1 
2 /*
3  * Copyright 2012 Google Inc.
4  *
5  * Use of this source code is governed by a BSD-style license that can be
6  * found in the LICENSE file.
7  */
8 
9 #include "SkSweepGradient.h"
10 
translate(SkScalar dx,SkScalar dy)11 static SkMatrix translate(SkScalar dx, SkScalar dy) {
12     SkMatrix matrix;
13     matrix.setTranslate(dx, dy);
14     return matrix;
15 }
16 
SkSweepGradient(SkScalar cx,SkScalar cy,const Descriptor & desc)17 SkSweepGradient::SkSweepGradient(SkScalar cx, SkScalar cy, const Descriptor& desc)
18     : SkGradientShaderBase(desc, translate(-cx, -cy))
19     , fCenter(SkPoint::Make(cx, cy))
20 {
21     // overwrite the tilemode to a canonical value (since sweep ignores it)
22     fTileMode = SkShader::kClamp_TileMode;
23 }
24 
asAGradient(GradientInfo * info) const25 SkShader::GradientType SkSweepGradient::asAGradient(GradientInfo* info) const {
26     if (info) {
27         commonAsAGradient(info);
28         info->fPoint[0] = fCenter;
29     }
30     return kSweep_GradientType;
31 }
32 
CreateProc(SkReadBuffer & buffer)33 SkFlattenable* SkSweepGradient::CreateProc(SkReadBuffer& buffer) {
34     DescriptorScope desc;
35     if (!desc.unflatten(buffer)) {
36         return nullptr;
37     }
38     const SkPoint center = buffer.readPoint();
39     return SkGradientShader::CreateSweep(center.x(), center.y(), desc.fColors, desc.fPos,
40                                          desc.fCount, desc.fGradFlags, desc.fLocalMatrix);
41 }
42 
flatten(SkWriteBuffer & buffer) const43 void SkSweepGradient::flatten(SkWriteBuffer& buffer) const {
44     this->INHERITED::flatten(buffer);
45     buffer.writePoint(fCenter);
46 }
47 
contextSize(const ContextRec &) const48 size_t SkSweepGradient::contextSize(const ContextRec&) const {
49     return sizeof(SweepGradientContext);
50 }
51 
onCreateContext(const ContextRec & rec,void * storage) const52 SkShader::Context* SkSweepGradient::onCreateContext(const ContextRec& rec, void* storage) const {
53     return new (storage) SweepGradientContext(*this, rec);
54 }
55 
SweepGradientContext(const SkSweepGradient & shader,const ContextRec & rec)56 SkSweepGradient::SweepGradientContext::SweepGradientContext(
57         const SkSweepGradient& shader, const ContextRec& rec)
58     : INHERITED(shader, rec) {}
59 
60 //  returns angle in a circle [0..2PI) -> [0..255]
SkATan2_255(float y,float x)61 static unsigned SkATan2_255(float y, float x) {
62     //    static const float g255Over2PI = 255 / (2 * SK_ScalarPI);
63     static const float g255Over2PI = 40.584510488433314f;
64 
65     float result = sk_float_atan2(y, x);
66     if (!SkScalarIsFinite(result)) {
67         return 0;
68     }
69     if (result < 0) {
70         result += 2 * SK_ScalarPI;
71     }
72     SkASSERT(result >= 0);
73     // since our value is always >= 0, we can cast to int, which is faster than
74     // calling floorf()
75     int ir = (int)(result * g255Over2PI);
76     SkASSERT(ir >= 0 && ir <= 255);
77     return ir;
78 }
79 
shadeSpan(int x,int y,SkPMColor * SK_RESTRICT dstC,int count)80 void SkSweepGradient::SweepGradientContext::shadeSpan(int x, int y, SkPMColor* SK_RESTRICT dstC,
81                                                       int count) {
82     SkMatrix::MapXYProc proc = fDstToIndexProc;
83     const SkMatrix&     matrix = fDstToIndex;
84     const SkPMColor* SK_RESTRICT cache = fCache->getCache32();
85     int                 toggle = init_dither_toggle(x, y);
86     SkPoint             srcPt;
87 
88     if (fDstToIndexClass != kPerspective_MatrixClass) {
89         proc(matrix, SkIntToScalar(x) + SK_ScalarHalf,
90                      SkIntToScalar(y) + SK_ScalarHalf, &srcPt);
91         SkScalar dx, fx = srcPt.fX;
92         SkScalar dy, fy = srcPt.fY;
93 
94         if (fDstToIndexClass == kFixedStepInX_MatrixClass) {
95             const auto step = matrix.fixedStepInX(SkIntToScalar(y) + SK_ScalarHalf);
96             dx = step.fX;
97             dy = step.fY;
98         } else {
99             SkASSERT(fDstToIndexClass == kLinear_MatrixClass);
100             dx = matrix.getScaleX();
101             dy = matrix.getSkewY();
102         }
103 
104         for (; count > 0; --count) {
105             *dstC++ = cache[toggle + SkATan2_255(fy, fx)];
106             fx += dx;
107             fy += dy;
108             toggle = next_dither_toggle(toggle);
109         }
110     } else {  // perspective case
111         for (int stop = x + count; x < stop; x++) {
112             proc(matrix, SkIntToScalar(x) + SK_ScalarHalf,
113                          SkIntToScalar(y) + SK_ScalarHalf, &srcPt);
114             *dstC++ = cache[toggle + SkATan2_255(srcPt.fY, srcPt.fX)];
115             toggle = next_dither_toggle(toggle);
116         }
117     }
118 }
119 
120 /////////////////////////////////////////////////////////////////////
121 
122 #if SK_SUPPORT_GPU
123 
124 #include "SkGr.h"
125 #include "gl/GrGLContext.h"
126 #include "glsl/GrGLSLCaps.h"
127 #include "glsl/GrGLSLFragmentShaderBuilder.h"
128 
129 class GrGLSweepGradient : public GrGLGradientEffect {
130 public:
131 
GrGLSweepGradient(const GrProcessor &)132     GrGLSweepGradient(const GrProcessor&) {}
~GrGLSweepGradient()133     virtual ~GrGLSweepGradient() { }
134 
135     virtual void emitCode(EmitArgs&) override;
136 
GenKey(const GrProcessor & processor,const GrGLSLCaps &,GrProcessorKeyBuilder * b)137     static void GenKey(const GrProcessor& processor, const GrGLSLCaps&, GrProcessorKeyBuilder* b) {
138         b->add32(GenBaseGradientKey(processor));
139     }
140 
141 private:
142 
143     typedef GrGLGradientEffect INHERITED;
144 
145 };
146 
147 /////////////////////////////////////////////////////////////////////
148 
149 class GrSweepGradient : public GrGradientEffect {
150 public:
Create(GrContext * ctx,const SkSweepGradient & shader,const SkMatrix & m)151     static GrFragmentProcessor* Create(GrContext* ctx, const SkSweepGradient& shader,
152                                        const SkMatrix& m) {
153         return new GrSweepGradient(ctx, shader, m);
154     }
~GrSweepGradient()155     virtual ~GrSweepGradient() { }
156 
name() const157     const char* name() const override { return "Sweep Gradient"; }
158 
159 private:
GrSweepGradient(GrContext * ctx,const SkSweepGradient & shader,const SkMatrix & matrix)160     GrSweepGradient(GrContext* ctx,
161                     const SkSweepGradient& shader,
162                     const SkMatrix& matrix)
163     : INHERITED(ctx, shader, matrix, SkShader::kClamp_TileMode) {
164         this->initClassID<GrSweepGradient>();
165     }
166 
onCreateGLSLInstance() const167     GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
168         return new GrGLSweepGradient(*this);
169     }
170 
onGetGLSLProcessorKey(const GrGLSLCaps & caps,GrProcessorKeyBuilder * b) const171     virtual void onGetGLSLProcessorKey(const GrGLSLCaps& caps,
172                                        GrProcessorKeyBuilder* b) const override {
173         GrGLSweepGradient::GenKey(*this, caps, b);
174     }
175 
176     GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
177 
178     typedef GrGradientEffect INHERITED;
179 };
180 
181 /////////////////////////////////////////////////////////////////////
182 
183 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrSweepGradient);
184 
TestCreate(GrProcessorTestData * d)185 const GrFragmentProcessor* GrSweepGradient::TestCreate(GrProcessorTestData* d) {
186     SkPoint center = {d->fRandom->nextUScalar1(), d->fRandom->nextUScalar1()};
187 
188     SkColor colors[kMaxRandomGradientColors];
189     SkScalar stopsArray[kMaxRandomGradientColors];
190     SkScalar* stops = stopsArray;
191     SkShader::TileMode tmIgnored;
192     int colorCount = RandomGradientParams(d->fRandom, colors, &stops, &tmIgnored);
193     SkAutoTUnref<SkShader> shader(SkGradientShader::CreateSweep(center.fX, center.fY,
194                                                                 colors, stops, colorCount));
195     const GrFragmentProcessor* fp = shader->asFragmentProcessor(d->fContext,
196                                                                 GrTest::TestMatrix(d->fRandom),
197                                                                 NULL, kNone_SkFilterQuality);
198     GrAlwaysAssert(fp);
199     return fp;
200 }
201 
202 /////////////////////////////////////////////////////////////////////
203 
emitCode(EmitArgs & args)204 void GrGLSweepGradient::emitCode(EmitArgs& args) {
205     const GrSweepGradient& ge = args.fFp.cast<GrSweepGradient>();
206     this->emitUniforms(args.fUniformHandler, ge);
207     SkString coords2D = args.fFragBuilder->ensureFSCoords2D(args.fCoords, 0);
208     SkString t;
209     // 0.1591549430918 is 1/(2*pi), used since atan returns values [-pi, pi]
210     // On Intel GPU there is an issue where it reads the second arguement to atan "- %s.x" as an int
211     // thus must us -1.0 * %s.x to work correctly
212     if (args.fGLSLCaps->mustForceNegatedAtanParamToFloat()){
213         t.printf("atan(- %s.y, -1.0 * %s.x) * 0.1591549430918 + 0.5",
214                  coords2D.c_str(), coords2D.c_str());
215     } else {
216         t.printf("atan(- %s.y, - %s.x) * 0.1591549430918 + 0.5",
217                  coords2D.c_str(), coords2D.c_str());
218     }
219     this->emitColor(args.fFragBuilder,
220                     args.fUniformHandler,
221                     args.fGLSLCaps,
222                     ge, t.c_str(),
223                     args.fOutputColor,
224                     args.fInputColor,
225                     args.fSamplers);
226 }
227 
228 /////////////////////////////////////////////////////////////////////
229 
asFragmentProcessor(GrContext * context,const SkMatrix & viewM,const SkMatrix * localMatrix,SkFilterQuality) const230 const GrFragmentProcessor* SkSweepGradient::asFragmentProcessor(
231                                                     GrContext* context,
232                                                     const SkMatrix& viewM,
233                                                     const SkMatrix* localMatrix,
234                                                     SkFilterQuality) const {
235 
236     SkMatrix matrix;
237     if (!this->getLocalMatrix().invert(&matrix)) {
238         return nullptr;
239     }
240     if (localMatrix) {
241         SkMatrix inv;
242         if (!localMatrix->invert(&inv)) {
243             return nullptr;
244         }
245         matrix.postConcat(inv);
246     }
247     matrix.postConcat(fPtsToUnit);
248 
249     SkAutoTUnref<const GrFragmentProcessor> inner(
250         GrSweepGradient::Create(context, *this, matrix));
251     return GrFragmentProcessor::MulOutputByInputAlpha(inner);
252 }
253 
254 #endif
255 
256 #ifndef SK_IGNORE_TO_STRING
toString(SkString * str) const257 void SkSweepGradient::toString(SkString* str) const {
258     str->append("SkSweepGradient: (");
259 
260     str->append("center: (");
261     str->appendScalar(fCenter.fX);
262     str->append(", ");
263     str->appendScalar(fCenter.fY);
264     str->append(") ");
265 
266     this->INHERITED::toString(str);
267 
268     str->append(")");
269 }
270 #endif
271