Make all GrFragmentProcessors GL independent.
[platform/upstream/libSkiaSharp.git] / src / effects / SkPerlinNoiseShader.cpp
1 /*
2  * Copyright 2013 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7
8 #include "SkDither.h"
9 #include "SkPerlinNoiseShader.h"
10 #include "SkColorFilter.h"
11 #include "SkReadBuffer.h"
12 #include "SkWriteBuffer.h"
13 #include "SkShader.h"
14 #include "SkUnPreMultiply.h"
15 #include "SkString.h"
16
17 #if SK_SUPPORT_GPU
18 #include "GrContext.h"
19 #include "GrCoordTransform.h"
20 #include "GrInvariantOutput.h"
21 #include "SkGr.h"
22 #include "effects/GrConstColorProcessor.h"
23 #include "glsl/GrGLSLFragmentProcessor.h"
24 #include "glsl/GrGLSLFragmentShaderBuilder.h"
25 #include "glsl/GrGLSLProgramBuilder.h"
26 #include "glsl/GrGLSLProgramDataManager.h"
27 #endif
28
29 static const int kBlockSize = 256;
30 static const int kBlockMask = kBlockSize - 1;
31 static const int kPerlinNoise = 4096;
32 static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
33
34 namespace {
35
36 // noiseValue is the color component's value (or color)
37 // limitValue is the maximum perlin noise array index value allowed
38 // newValue is the current noise dimension (either width or height)
39 inline int checkNoise(int noiseValue, int limitValue, int newValue) {
40     // If the noise value would bring us out of bounds of the current noise array while we are
41     // stiching noise tiles together, wrap the noise around the current dimension of the noise to
42     // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
43     if (noiseValue >= limitValue) {
44         noiseValue -= newValue;
45     }
46     return noiseValue;
47 }
48
49 inline SkScalar smoothCurve(SkScalar t) {
50     static const SkScalar SK_Scalar3 = 3.0f;
51
52     // returns t * t * (3 - 2 * t)
53     return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
54 }
55
56 } // end namespace
57
58 struct SkPerlinNoiseShader::StitchData {
59     StitchData()
60       : fWidth(0)
61       , fWrapX(0)
62       , fHeight(0)
63       , fWrapY(0)
64     {}
65
66     bool operator==(const StitchData& other) const {
67         return fWidth == other.fWidth &&
68                fWrapX == other.fWrapX &&
69                fHeight == other.fHeight &&
70                fWrapY == other.fWrapY;
71     }
72
73     int fWidth; // How much to subtract to wrap for stitching.
74     int fWrapX; // Minimum value to wrap.
75     int fHeight;
76     int fWrapY;
77 };
78
79 struct SkPerlinNoiseShader::PaintingData {
80     PaintingData(const SkISize& tileSize, SkScalar seed,
81                  SkScalar baseFrequencyX, SkScalar baseFrequencyY,
82                  const SkMatrix& matrix)
83     {
84         SkVector vec[2] = {
85             { SkScalarInvert(baseFrequencyX),   SkScalarInvert(baseFrequencyY)  },
86             { SkIntToScalar(tileSize.fWidth),   SkIntToScalar(tileSize.fHeight) },
87         };
88         matrix.mapVectors(vec, 2);
89
90         fBaseFrequency.set(SkScalarInvert(vec[0].fX), SkScalarInvert(vec[0].fY));
91         fTileSize.set(SkScalarRoundToInt(vec[1].fX), SkScalarRoundToInt(vec[1].fY));
92         this->init(seed);
93         if (!fTileSize.isEmpty()) {
94             this->stitch();
95         }
96
97 #if SK_SUPPORT_GPU
98         fPermutationsBitmap.setInfo(SkImageInfo::MakeA8(kBlockSize, 1));
99         fPermutationsBitmap.setPixels(fLatticeSelector);
100
101         fNoiseBitmap.setInfo(SkImageInfo::MakeN32Premul(kBlockSize, 4));
102         fNoiseBitmap.setPixels(fNoise[0][0]);
103 #endif
104     }
105
106     int         fSeed;
107     uint8_t     fLatticeSelector[kBlockSize];
108     uint16_t    fNoise[4][kBlockSize][2];
109     SkPoint     fGradient[4][kBlockSize];
110     SkISize     fTileSize;
111     SkVector    fBaseFrequency;
112     StitchData  fStitchDataInit;
113
114 private:
115
116 #if SK_SUPPORT_GPU
117     SkBitmap   fPermutationsBitmap;
118     SkBitmap   fNoiseBitmap;
119 #endif
120
121     inline int random()  {
122         static const int gRandAmplitude = 16807; // 7**5; primitive root of m
123         static const int gRandQ = 127773; // m / a
124         static const int gRandR = 2836; // m % a
125
126         int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
127         if (result <= 0)
128             result += kRandMaximum;
129         fSeed = result;
130         return result;
131     }
132
133     // Only called once. Could be part of the constructor.
134     void init(SkScalar seed)
135     {
136         static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
137
138         // According to the SVG spec, we must truncate (not round) the seed value.
139         fSeed = SkScalarTruncToInt(seed);
140         // The seed value clamp to the range [1, kRandMaximum - 1].
141         if (fSeed <= 0) {
142             fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
143         }
144         if (fSeed > kRandMaximum - 1) {
145             fSeed = kRandMaximum - 1;
146         }
147         for (int channel = 0; channel < 4; ++channel) {
148             for (int i = 0; i < kBlockSize; ++i) {
149                 fLatticeSelector[i] = i;
150                 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
151                 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
152             }
153         }
154         for (int i = kBlockSize - 1; i > 0; --i) {
155             int k = fLatticeSelector[i];
156             int j = random() % kBlockSize;
157             SkASSERT(j >= 0);
158             SkASSERT(j < kBlockSize);
159             fLatticeSelector[i] = fLatticeSelector[j];
160             fLatticeSelector[j] = k;
161         }
162
163         // Perform the permutations now
164         {
165             // Copy noise data
166             uint16_t noise[4][kBlockSize][2];
167             for (int i = 0; i < kBlockSize; ++i) {
168                 for (int channel = 0; channel < 4; ++channel) {
169                     for (int j = 0; j < 2; ++j) {
170                         noise[channel][i][j] = fNoise[channel][i][j];
171                     }
172                 }
173             }
174             // Do permutations on noise data
175             for (int i = 0; i < kBlockSize; ++i) {
176                 for (int channel = 0; channel < 4; ++channel) {
177                     for (int j = 0; j < 2; ++j) {
178                         fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
179                     }
180                 }
181             }
182         }
183
184         // Half of the largest possible value for 16 bit unsigned int
185         static const SkScalar gHalfMax16bits = 32767.5f;
186
187         // Compute gradients from permutated noise data
188         for (int channel = 0; channel < 4; ++channel) {
189             for (int i = 0; i < kBlockSize; ++i) {
190                 fGradient[channel][i] = SkPoint::Make(
191                     SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
192                                 gInvBlockSizef),
193                     SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
194                                 gInvBlockSizef));
195                 fGradient[channel][i].normalize();
196                 // Put the normalized gradient back into the noise data
197                 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
198                     fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
199                 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
200                     fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
201             }
202         }
203     }
204
205     // Only called once. Could be part of the constructor.
206     void stitch() {
207         SkScalar tileWidth  = SkIntToScalar(fTileSize.width());
208         SkScalar tileHeight = SkIntToScalar(fTileSize.height());
209         SkASSERT(tileWidth > 0 && tileHeight > 0);
210         // When stitching tiled turbulence, the frequencies must be adjusted
211         // so that the tile borders will be continuous.
212         if (fBaseFrequency.fX) {
213             SkScalar lowFrequencx =
214                 SkScalarFloorToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
215             SkScalar highFrequencx =
216                 SkScalarCeilToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
217             // BaseFrequency should be non-negative according to the standard.
218             if (fBaseFrequency.fX / lowFrequencx < highFrequencx / fBaseFrequency.fX) {
219                 fBaseFrequency.fX = lowFrequencx;
220             } else {
221                 fBaseFrequency.fX = highFrequencx;
222             }
223         }
224         if (fBaseFrequency.fY) {
225             SkScalar lowFrequency =
226                 SkScalarFloorToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
227             SkScalar highFrequency =
228                 SkScalarCeilToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
229             if (fBaseFrequency.fY / lowFrequency < highFrequency / fBaseFrequency.fY) {
230                 fBaseFrequency.fY = lowFrequency;
231             } else {
232                 fBaseFrequency.fY = highFrequency;
233             }
234         }
235         // Set up TurbulenceInitial stitch values.
236         fStitchDataInit.fWidth  =
237             SkScalarRoundToInt(tileWidth * fBaseFrequency.fX);
238         fStitchDataInit.fWrapX  = kPerlinNoise + fStitchDataInit.fWidth;
239         fStitchDataInit.fHeight =
240             SkScalarRoundToInt(tileHeight * fBaseFrequency.fY);
241         fStitchDataInit.fWrapY  = kPerlinNoise + fStitchDataInit.fHeight;
242     }
243
244 public:
245
246 #if SK_SUPPORT_GPU
247     const SkBitmap& getPermutationsBitmap() const { return fPermutationsBitmap; }
248
249     const SkBitmap& getNoiseBitmap() const { return fNoiseBitmap; }
250 #endif
251 };
252
253 SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
254                                                   int numOctaves, SkScalar seed,
255                                                   const SkISize* tileSize) {
256     return new SkPerlinNoiseShader(kFractalNoise_Type, baseFrequencyX, baseFrequencyY, numOctaves,
257                                    seed, tileSize);
258 }
259
260 SkShader* SkPerlinNoiseShader::CreateTurbulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
261                                               int numOctaves, SkScalar seed,
262                                               const SkISize* tileSize) {
263     return new SkPerlinNoiseShader(kTurbulence_Type, baseFrequencyX, baseFrequencyY, numOctaves,
264                                    seed, tileSize);
265 }
266
267 SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
268                                          SkScalar baseFrequencyX,
269                                          SkScalar baseFrequencyY,
270                                          int numOctaves,
271                                          SkScalar seed,
272                                          const SkISize* tileSize)
273   : fType(type)
274   , fBaseFrequencyX(baseFrequencyX)
275   , fBaseFrequencyY(baseFrequencyY)
276   , fNumOctaves(numOctaves > 255 ? 255 : numOctaves/*[0,255] octaves allowed*/)
277   , fSeed(seed)
278   , fTileSize(nullptr == tileSize ? SkISize::Make(0, 0) : *tileSize)
279   , fStitchTiles(!fTileSize.isEmpty())
280 {
281     SkASSERT(numOctaves >= 0 && numOctaves < 256);
282 }
283
284 SkPerlinNoiseShader::~SkPerlinNoiseShader() {
285 }
286
287 SkFlattenable* SkPerlinNoiseShader::CreateProc(SkReadBuffer& buffer) {
288     Type type = (Type)buffer.readInt();
289     SkScalar freqX = buffer.readScalar();
290     SkScalar freqY = buffer.readScalar();
291     int octaves = buffer.readInt();
292     SkScalar seed = buffer.readScalar();
293     SkISize tileSize;
294     tileSize.fWidth = buffer.readInt();
295     tileSize.fHeight = buffer.readInt();
296
297     switch (type) {
298         case kFractalNoise_Type:
299             return SkPerlinNoiseShader::CreateFractalNoise(freqX, freqY, octaves, seed, &tileSize);
300         case kTurbulence_Type:
301             return SkPerlinNoiseShader::CreateTubulence(freqX, freqY, octaves, seed, &tileSize);
302         default:
303             return nullptr;
304     }
305 }
306
307 void SkPerlinNoiseShader::flatten(SkWriteBuffer& buffer) const {
308     buffer.writeInt((int) fType);
309     buffer.writeScalar(fBaseFrequencyX);
310     buffer.writeScalar(fBaseFrequencyY);
311     buffer.writeInt(fNumOctaves);
312     buffer.writeScalar(fSeed);
313     buffer.writeInt(fTileSize.fWidth);
314     buffer.writeInt(fTileSize.fHeight);
315 }
316
317 SkScalar SkPerlinNoiseShader::PerlinNoiseShaderContext::noise2D(
318         int channel, const StitchData& stitchData, const SkPoint& noiseVector) const {
319     struct Noise {
320         int noisePositionIntegerValue;
321         int nextNoisePositionIntegerValue;
322         SkScalar noisePositionFractionValue;
323         Noise(SkScalar component)
324         {
325             SkScalar position = component + kPerlinNoise;
326             noisePositionIntegerValue = SkScalarFloorToInt(position);
327             noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
328             nextNoisePositionIntegerValue = noisePositionIntegerValue + 1;
329         }
330     };
331     Noise noiseX(noiseVector.x());
332     Noise noiseY(noiseVector.y());
333     SkScalar u, v;
334     const SkPerlinNoiseShader& perlinNoiseShader = static_cast<const SkPerlinNoiseShader&>(fShader);
335     // If stitching, adjust lattice points accordingly.
336     if (perlinNoiseShader.fStitchTiles) {
337         noiseX.noisePositionIntegerValue =
338             checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
339         noiseY.noisePositionIntegerValue =
340             checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
341         noiseX.nextNoisePositionIntegerValue =
342             checkNoise(noiseX.nextNoisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
343         noiseY.nextNoisePositionIntegerValue =
344             checkNoise(noiseY.nextNoisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
345     }
346     noiseX.noisePositionIntegerValue &= kBlockMask;
347     noiseY.noisePositionIntegerValue &= kBlockMask;
348     noiseX.nextNoisePositionIntegerValue &= kBlockMask;
349     noiseY.nextNoisePositionIntegerValue &= kBlockMask;
350     int i =
351         fPaintingData->fLatticeSelector[noiseX.noisePositionIntegerValue];
352     int j =
353         fPaintingData->fLatticeSelector[noiseX.nextNoisePositionIntegerValue];
354     int b00 = (i + noiseY.noisePositionIntegerValue) & kBlockMask;
355     int b10 = (j + noiseY.noisePositionIntegerValue) & kBlockMask;
356     int b01 = (i + noiseY.nextNoisePositionIntegerValue) & kBlockMask;
357     int b11 = (j + noiseY.nextNoisePositionIntegerValue) & kBlockMask;
358     SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
359     SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
360     // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
361     SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
362                                           noiseY.noisePositionFractionValue); // Offset (0,0)
363     u = fPaintingData->fGradient[channel][b00].dot(fractionValue);
364     fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
365     v = fPaintingData->fGradient[channel][b10].dot(fractionValue);
366     SkScalar a = SkScalarInterp(u, v, sx);
367     fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
368     v = fPaintingData->fGradient[channel][b11].dot(fractionValue);
369     fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
370     u = fPaintingData->fGradient[channel][b01].dot(fractionValue);
371     SkScalar b = SkScalarInterp(u, v, sx);
372     return SkScalarInterp(a, b, sy);
373 }
374
375 SkScalar SkPerlinNoiseShader::PerlinNoiseShaderContext::calculateTurbulenceValueForPoint(
376         int channel, StitchData& stitchData, const SkPoint& point) const {
377     const SkPerlinNoiseShader& perlinNoiseShader = static_cast<const SkPerlinNoiseShader&>(fShader);
378     if (perlinNoiseShader.fStitchTiles) {
379         // Set up TurbulenceInitial stitch values.
380         stitchData = fPaintingData->fStitchDataInit;
381     }
382     SkScalar turbulenceFunctionResult = 0;
383     SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), fPaintingData->fBaseFrequency.fX),
384                                       SkScalarMul(point.y(), fPaintingData->fBaseFrequency.fY)));
385     SkScalar ratio = SK_Scalar1;
386     for (int octave = 0; octave < perlinNoiseShader.fNumOctaves; ++octave) {
387         SkScalar noise = noise2D(channel, stitchData, noiseVector);
388         SkScalar numer = (perlinNoiseShader.fType == kFractalNoise_Type) ?
389                             noise : SkScalarAbs(noise);
390         turbulenceFunctionResult += numer / ratio;
391         noiseVector.fX *= 2;
392         noiseVector.fY *= 2;
393         ratio *= 2;
394         if (perlinNoiseShader.fStitchTiles) {
395             // Update stitch values
396             stitchData.fWidth  *= 2;
397             stitchData.fWrapX   = stitchData.fWidth + kPerlinNoise;
398             stitchData.fHeight *= 2;
399             stitchData.fWrapY   = stitchData.fHeight + kPerlinNoise;
400         }
401     }
402
403     // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
404     // by fractalNoise and (turbulenceFunctionResult) by turbulence.
405     if (perlinNoiseShader.fType == kFractalNoise_Type) {
406         turbulenceFunctionResult =
407             SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
408     }
409
410     if (channel == 3) { // Scale alpha by paint value
411         turbulenceFunctionResult *= SkIntToScalar(getPaintAlpha()) / 255;
412     }
413
414     // Clamp result
415     return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
416 }
417
418 SkPMColor SkPerlinNoiseShader::PerlinNoiseShaderContext::shade(
419         const SkPoint& point, StitchData& stitchData) const {
420     SkPoint newPoint;
421     fMatrix.mapPoints(&newPoint, &point, 1);
422     newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
423     newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
424
425     U8CPU rgba[4];
426     for (int channel = 3; channel >= 0; --channel) {
427         rgba[channel] = SkScalarFloorToInt(255 *
428             calculateTurbulenceValueForPoint(channel, stitchData, newPoint));
429     }
430     return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
431 }
432
433 SkShader::Context* SkPerlinNoiseShader::onCreateContext(const ContextRec& rec,
434                                                         void* storage) const {
435     return new (storage) PerlinNoiseShaderContext(*this, rec);
436 }
437
438 size_t SkPerlinNoiseShader::contextSize() const {
439     return sizeof(PerlinNoiseShaderContext);
440 }
441
442 SkPerlinNoiseShader::PerlinNoiseShaderContext::PerlinNoiseShaderContext(
443         const SkPerlinNoiseShader& shader, const ContextRec& rec)
444     : INHERITED(shader, rec)
445 {
446     SkMatrix newMatrix = *rec.fMatrix;
447     newMatrix.preConcat(shader.getLocalMatrix());
448     if (rec.fLocalMatrix) {
449         newMatrix.preConcat(*rec.fLocalMatrix);
450     }
451     // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
452     // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
453     fMatrix.setTranslate(-newMatrix.getTranslateX() + SK_Scalar1, -newMatrix.getTranslateY() + SK_Scalar1);
454     fPaintingData = new PaintingData(shader.fTileSize, shader.fSeed, shader.fBaseFrequencyX,
455                                      shader.fBaseFrequencyY, newMatrix);
456 }
457
458 SkPerlinNoiseShader::PerlinNoiseShaderContext::~PerlinNoiseShaderContext() { delete fPaintingData; }
459
460 void SkPerlinNoiseShader::PerlinNoiseShaderContext::shadeSpan(
461         int x, int y, SkPMColor result[], int count) {
462     SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
463     StitchData stitchData;
464     for (int i = 0; i < count; ++i) {
465         result[i] = shade(point, stitchData);
466         point.fX += SK_Scalar1;
467     }
468 }
469
470 void SkPerlinNoiseShader::PerlinNoiseShaderContext::shadeSpan16(
471         int x, int y, uint16_t result[], int count) {
472     SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
473     StitchData stitchData;
474     DITHER_565_SCAN(y);
475     for (int i = 0; i < count; ++i) {
476         unsigned dither = DITHER_VALUE(x);
477         result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
478         DITHER_INC_X(x);
479         point.fX += SK_Scalar1;
480     }
481 }
482
483 /////////////////////////////////////////////////////////////////////
484
485 #if SK_SUPPORT_GPU
486
487 class GrGLPerlinNoise : public GrGLSLFragmentProcessor {
488 public:
489     GrGLPerlinNoise(const GrProcessor&);
490     virtual ~GrGLPerlinNoise() {}
491
492     virtual void emitCode(EmitArgs&) override;
493
494     static inline void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder* b);
495
496 protected:
497     void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override;
498
499 private:
500
501     GrGLSLProgramDataManager::UniformHandle fStitchDataUni;
502     SkPerlinNoiseShader::Type               fType;
503     bool                                    fStitchTiles;
504     int                                     fNumOctaves;
505     GrGLSLProgramDataManager::UniformHandle fBaseFrequencyUni;
506
507 private:
508     typedef GrGLSLFragmentProcessor INHERITED;
509 };
510
511 /////////////////////////////////////////////////////////////////////
512
513 class GrPerlinNoiseEffect : public GrFragmentProcessor {
514 public:
515     static GrFragmentProcessor* Create(SkPerlinNoiseShader::Type type,
516                                        int numOctaves, bool stitchTiles,
517                                        SkPerlinNoiseShader::PaintingData* paintingData,
518                                        GrTexture* permutationsTexture, GrTexture* noiseTexture,
519                                        const SkMatrix& matrix) {
520         return new GrPerlinNoiseEffect(type, numOctaves, stitchTiles, paintingData,
521                                        permutationsTexture, noiseTexture, matrix);
522     }
523
524     virtual ~GrPerlinNoiseEffect() { delete fPaintingData; }
525
526     const char* name() const override { return "PerlinNoise"; }
527
528     const SkPerlinNoiseShader::StitchData& stitchData() const { return fPaintingData->fStitchDataInit; }
529
530     SkPerlinNoiseShader::Type type() const { return fType; }
531     bool stitchTiles() const { return fStitchTiles; }
532     const SkVector& baseFrequency() const { return fPaintingData->fBaseFrequency; }
533     int numOctaves() const { return fNumOctaves; }
534     const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
535
536 private:
537     GrGLSLFragmentProcessor* onCreateGLInstance() const override {
538         return new GrGLPerlinNoise(*this);
539     }
540
541     virtual void onGetGLProcessorKey(const GrGLSLCaps& caps,
542                                      GrProcessorKeyBuilder* b) const override {
543         GrGLPerlinNoise::GenKey(*this, caps, b);
544     }
545
546     bool onIsEqual(const GrFragmentProcessor& sBase) const override {
547         const GrPerlinNoiseEffect& s = sBase.cast<GrPerlinNoiseEffect>();
548         return fType == s.fType &&
549                fPaintingData->fBaseFrequency == s.fPaintingData->fBaseFrequency &&
550                fNumOctaves == s.fNumOctaves &&
551                fStitchTiles == s.fStitchTiles &&
552                fPaintingData->fStitchDataInit == s.fPaintingData->fStitchDataInit;
553     }
554
555     void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
556         inout->setToUnknown(GrInvariantOutput::kWillNot_ReadInput);
557     }
558
559     GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type,
560                         int numOctaves, bool stitchTiles,
561                         SkPerlinNoiseShader::PaintingData* paintingData,
562                         GrTexture* permutationsTexture, GrTexture* noiseTexture,
563                         const SkMatrix& matrix)
564       : fType(type)
565       , fNumOctaves(numOctaves)
566       , fStitchTiles(stitchTiles)
567       , fPermutationsAccess(permutationsTexture)
568       , fNoiseAccess(noiseTexture)
569       , fPaintingData(paintingData) {
570         this->initClassID<GrPerlinNoiseEffect>();
571         this->addTextureAccess(&fPermutationsAccess);
572         this->addTextureAccess(&fNoiseAccess);
573         fCoordTransform.reset(kLocal_GrCoordSet, matrix);
574         this->addCoordTransform(&fCoordTransform);
575     }
576
577     GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
578
579     SkPerlinNoiseShader::Type       fType;
580     GrCoordTransform                fCoordTransform;
581     int                             fNumOctaves;
582     bool                            fStitchTiles;
583     GrTextureAccess                 fPermutationsAccess;
584     GrTextureAccess                 fNoiseAccess;
585     SkPerlinNoiseShader::PaintingData *fPaintingData;
586
587 private:
588     typedef GrFragmentProcessor INHERITED;
589 };
590
591 /////////////////////////////////////////////////////////////////////
592 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrPerlinNoiseEffect);
593
594 const GrFragmentProcessor* GrPerlinNoiseEffect::TestCreate(GrProcessorTestData* d) {
595     int      numOctaves = d->fRandom->nextRangeU(2, 10);
596     bool     stitchTiles = d->fRandom->nextBool();
597     SkScalar seed = SkIntToScalar(d->fRandom->nextU());
598     SkISize  tileSize = SkISize::Make(d->fRandom->nextRangeU(4, 4096),
599                                       d->fRandom->nextRangeU(4, 4096));
600     SkScalar baseFrequencyX = d->fRandom->nextRangeScalar(0.01f,
601                                                           0.99f);
602     SkScalar baseFrequencyY = d->fRandom->nextRangeScalar(0.01f,
603                                                           0.99f);
604
605     SkAutoTUnref<SkShader> shader(d->fRandom->nextBool() ?
606         SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
607                                                 stitchTiles ? &tileSize : nullptr) :
608         SkPerlinNoiseShader::CreateTurbulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
609                                              stitchTiles ? &tileSize : nullptr));
610
611     GrPaint grPaint;
612     return shader->asFragmentProcessor(d->fContext,
613                                        GrTest::TestMatrix(d->fRandom), nullptr,
614                                        kNone_SkFilterQuality);
615 }
616
617 GrGLPerlinNoise::GrGLPerlinNoise(const GrProcessor& processor)
618   : fType(processor.cast<GrPerlinNoiseEffect>().type())
619   , fStitchTiles(processor.cast<GrPerlinNoiseEffect>().stitchTiles())
620   , fNumOctaves(processor.cast<GrPerlinNoiseEffect>().numOctaves()) {
621 }
622
623 void GrGLPerlinNoise::emitCode(EmitArgs& args) {
624     GrGLSLFragmentBuilder* fsBuilder = args.fBuilder->getFragmentShaderBuilder();
625     SkString vCoords = fsBuilder->ensureFSCoords2D(args.fCoords, 0);
626
627     fBaseFrequencyUni = args.fBuilder->addUniform(GrGLSLProgramBuilder::kFragment_Visibility,
628                                             kVec2f_GrSLType, kDefault_GrSLPrecision,
629                                             "baseFrequency");
630     const char* baseFrequencyUni = args.fBuilder->getUniformCStr(fBaseFrequencyUni);
631
632     const char* stitchDataUni = nullptr;
633     if (fStitchTiles) {
634         fStitchDataUni = args.fBuilder->addUniform(GrGLSLProgramBuilder::kFragment_Visibility,
635                                              kVec2f_GrSLType, kDefault_GrSLPrecision,
636                                              "stitchData");
637         stitchDataUni = args.fBuilder->getUniformCStr(fStitchDataUni);
638     }
639
640     // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
641     const char* chanCoordR  = "0.125";
642     const char* chanCoordG  = "0.375";
643     const char* chanCoordB  = "0.625";
644     const char* chanCoordA  = "0.875";
645     const char* chanCoord   = "chanCoord";
646     const char* stitchData  = "stitchData";
647     const char* ratio       = "ratio";
648     const char* noiseVec    = "noiseVec";
649     const char* noiseSmooth = "noiseSmooth";
650     const char* floorVal    = "floorVal";
651     const char* fractVal    = "fractVal";
652     const char* uv          = "uv";
653     const char* ab          = "ab";
654     const char* latticeIdx  = "latticeIdx";
655     const char* bcoords     = "bcoords";
656     const char* lattice     = "lattice";
657     const char* inc8bit     = "0.00390625";  // 1.0 / 256.0
658     // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
659     // [-1,1] vector and perform a dot product between that vector and the provided vector.
660     const char* dotLattice  = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
661
662     // Add noise function
663     static const GrGLSLShaderVar gPerlinNoiseArgs[] =  {
664         GrGLSLShaderVar(chanCoord, kFloat_GrSLType),
665         GrGLSLShaderVar(noiseVec, kVec2f_GrSLType)
666     };
667
668     static const GrGLSLShaderVar gPerlinNoiseStitchArgs[] =  {
669         GrGLSLShaderVar(chanCoord, kFloat_GrSLType),
670         GrGLSLShaderVar(noiseVec, kVec2f_GrSLType),
671         GrGLSLShaderVar(stitchData, kVec2f_GrSLType)
672     };
673
674     SkString noiseCode;
675
676     noiseCode.appendf("\tvec4 %s;\n", floorVal);
677     noiseCode.appendf("\t%s.xy = floor(%s);\n", floorVal, noiseVec);
678     noiseCode.appendf("\t%s.zw = %s.xy + vec2(1.0);\n", floorVal, floorVal);
679     noiseCode.appendf("\tvec2 %s = fract(%s);\n", fractVal, noiseVec);
680
681     // smooth curve : t * t * (3 - 2 * t)
682     noiseCode.appendf("\n\tvec2 %s = %s * %s * (vec2(3.0) - vec2(2.0) * %s);",
683         noiseSmooth, fractVal, fractVal, fractVal);
684
685     // Adjust frequencies if we're stitching tiles
686     if (fStitchTiles) {
687         noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
688             floorVal, stitchData, floorVal, stitchData);
689         noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }",
690             floorVal, stitchData, floorVal, stitchData);
691         noiseCode.appendf("\n\tif(%s.z >= %s.x) { %s.z -= %s.x; }",
692             floorVal, stitchData, floorVal, stitchData);
693         noiseCode.appendf("\n\tif(%s.w >= %s.y) { %s.w -= %s.y; }",
694             floorVal, stitchData, floorVal, stitchData);
695     }
696
697     // Get texture coordinates and normalize
698     noiseCode.appendf("\n\t%s = fract(floor(mod(%s, 256.0)) / vec4(256.0));\n",
699         floorVal, floorVal);
700
701     // Get permutation for x
702     {
703         SkString xCoords("");
704         xCoords.appendf("vec2(%s.x, 0.5)", floorVal);
705
706         noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
707         fsBuilder->appendTextureLookup(&noiseCode, args.fSamplers[0], xCoords.c_str(),
708                                        kVec2f_GrSLType);
709         noiseCode.append(".r;");
710     }
711
712     // Get permutation for x + 1
713     {
714         SkString xCoords("");
715         xCoords.appendf("vec2(%s.z, 0.5)", floorVal);
716
717         noiseCode.appendf("\n\t%s.y = ", latticeIdx);
718         fsBuilder->appendTextureLookup(&noiseCode, args.fSamplers[0], xCoords.c_str(),
719                                        kVec2f_GrSLType);
720         noiseCode.append(".r;");
721     }
722
723 #if defined(SK_BUILD_FOR_ANDROID)
724     // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
725     // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
726     // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
727     // (or 0.484368 here). The following rounding operation prevents these precision issues from
728     // affecting the result of the noise by making sure that we only have multiples of 1/255.
729     // (Note that 1/255 is about 0.003921569, which is the value used here).
730     noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);",
731                       latticeIdx, latticeIdx);
732 #endif
733
734     // Get (x,y) coordinates with the permutated x
735     noiseCode.appendf("\n\tvec4 %s = fract(%s.xyxy + %s.yyww);", bcoords, latticeIdx, floorVal);
736
737     noiseCode.appendf("\n\n\tvec2 %s;", uv);
738     // Compute u, at offset (0,0)
739     {
740         SkString latticeCoords("");
741         latticeCoords.appendf("vec2(%s.x, %s)", bcoords, chanCoord);
742         noiseCode.appendf("\n\tvec4 %s = ", lattice);
743         fsBuilder->appendTextureLookup(&noiseCode, args.fSamplers[1], latticeCoords.c_str(),
744             kVec2f_GrSLType);
745         noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
746         noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
747     }
748
749     noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
750     // Compute v, at offset (-1,0)
751     {
752         SkString latticeCoords("");
753         latticeCoords.appendf("vec2(%s.y, %s)", bcoords, chanCoord);
754         noiseCode.append("\n\tlattice = ");
755         fsBuilder->appendTextureLookup(&noiseCode, args.fSamplers[1], latticeCoords.c_str(),
756             kVec2f_GrSLType);
757         noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
758         noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
759     }
760
761     // Compute 'a' as a linear interpolation of 'u' and 'v'
762     noiseCode.appendf("\n\tvec2 %s;", ab);
763     noiseCode.appendf("\n\t%s.x = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
764
765     noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
766     // Compute v, at offset (-1,-1)
767     {
768         SkString latticeCoords("");
769         latticeCoords.appendf("vec2(%s.w, %s)", bcoords, chanCoord);
770         noiseCode.append("\n\tlattice = ");
771         fsBuilder->appendTextureLookup(&noiseCode, args.fSamplers[1], latticeCoords.c_str(),
772             kVec2f_GrSLType);
773         noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
774         noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
775     }
776
777     noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
778     // Compute u, at offset (0,-1)
779     {
780         SkString latticeCoords("");
781         latticeCoords.appendf("vec2(%s.z, %s)", bcoords, chanCoord);
782         noiseCode.append("\n\tlattice = ");
783         fsBuilder->appendTextureLookup(&noiseCode, args.fSamplers[1], latticeCoords.c_str(),
784             kVec2f_GrSLType);
785         noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
786         noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
787     }
788
789     // Compute 'b' as a linear interpolation of 'u' and 'v'
790     noiseCode.appendf("\n\t%s.y = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
791     // Compute the noise as a linear interpolation of 'a' and 'b'
792     noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
793
794     SkString noiseFuncName;
795     if (fStitchTiles) {
796         fsBuilder->emitFunction(kFloat_GrSLType,
797                                 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
798                                 gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
799     } else {
800         fsBuilder->emitFunction(kFloat_GrSLType,
801                                 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
802                                 gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
803     }
804
805     // There are rounding errors if the floor operation is not performed here
806     fsBuilder->codeAppendf("\n\t\tvec2 %s = floor(%s.xy) * %s;",
807                            noiseVec, vCoords.c_str(), baseFrequencyUni);
808
809     // Clear the color accumulator
810     fsBuilder->codeAppendf("\n\t\t%s = vec4(0.0);", args.fOutputColor);
811
812     if (fStitchTiles) {
813         // Set up TurbulenceInitial stitch values.
814         fsBuilder->codeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni);
815     }
816
817     fsBuilder->codeAppendf("\n\t\tfloat %s = 1.0;", ratio);
818
819     // Loop over all octaves
820     fsBuilder->codeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
821
822     fsBuilder->codeAppendf("\n\t\t\t%s += ", args.fOutputColor);
823     if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
824         fsBuilder->codeAppend("abs(");
825     }
826     if (fStitchTiles) {
827         fsBuilder->codeAppendf(
828             "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
829                  "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
830             noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
831             noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
832             noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
833             noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
834     } else {
835         fsBuilder->codeAppendf(
836             "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
837                  "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
838             noiseFuncName.c_str(), chanCoordR, noiseVec,
839             noiseFuncName.c_str(), chanCoordG, noiseVec,
840             noiseFuncName.c_str(), chanCoordB, noiseVec,
841             noiseFuncName.c_str(), chanCoordA, noiseVec);
842     }
843     if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
844         fsBuilder->codeAppendf(")"); // end of "abs("
845     }
846     fsBuilder->codeAppendf(" * %s;", ratio);
847
848     fsBuilder->codeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
849     fsBuilder->codeAppendf("\n\t\t\t%s *= 0.5;", ratio);
850
851     if (fStitchTiles) {
852         fsBuilder->codeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData);
853     }
854     fsBuilder->codeAppend("\n\t\t}"); // end of the for loop on octaves
855
856     if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
857         // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
858         // by fractalNoise and (turbulenceFunctionResult) by turbulence.
859         fsBuilder->codeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);",
860                                args.fOutputColor,args.fOutputColor);
861     }
862
863     // Clamp values
864     fsBuilder->codeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", args.fOutputColor, args.fOutputColor);
865
866     // Pre-multiply the result
867     fsBuilder->codeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
868                            args.fOutputColor, args.fOutputColor,
869                            args.fOutputColor, args.fOutputColor);
870 }
871
872 void GrGLPerlinNoise::GenKey(const GrProcessor& processor, const GrGLSLCaps&,
873                              GrProcessorKeyBuilder* b) {
874     const GrPerlinNoiseEffect& turbulence = processor.cast<GrPerlinNoiseEffect>();
875
876     uint32_t key = turbulence.numOctaves();
877
878     key = key << 3; // Make room for next 3 bits
879
880     switch (turbulence.type()) {
881         case SkPerlinNoiseShader::kFractalNoise_Type:
882             key |= 0x1;
883             break;
884         case SkPerlinNoiseShader::kTurbulence_Type:
885             key |= 0x2;
886             break;
887         default:
888             // leave key at 0
889             break;
890     }
891
892     if (turbulence.stitchTiles()) {
893         key |= 0x4; // Flip the 3rd bit if tile stitching is on
894     }
895
896     b->add32(key);
897 }
898
899 void GrGLPerlinNoise::onSetData(const GrGLSLProgramDataManager& pdman,
900                                 const GrProcessor& processor) {
901     INHERITED::onSetData(pdman, processor);
902
903     const GrPerlinNoiseEffect& turbulence = processor.cast<GrPerlinNoiseEffect>();
904
905     const SkVector& baseFrequency = turbulence.baseFrequency();
906     pdman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
907
908     if (turbulence.stitchTiles()) {
909         const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
910         pdman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
911                                    SkIntToScalar(stitchData.fHeight));
912     }
913 }
914
915 /////////////////////////////////////////////////////////////////////
916 const GrFragmentProcessor* SkPerlinNoiseShader::asFragmentProcessor(
917                                                     GrContext* context,
918                                                     const SkMatrix& viewM,
919                                                     const SkMatrix* externalLocalMatrix,
920                                                     SkFilterQuality) const {
921     SkASSERT(context);
922
923     SkMatrix localMatrix = this->getLocalMatrix();
924     if (externalLocalMatrix) {
925         localMatrix.preConcat(*externalLocalMatrix);
926     }
927
928     SkMatrix matrix = viewM;
929     matrix.preConcat(localMatrix);
930
931     if (0 == fNumOctaves) {
932         if (kFractalNoise_Type == fType) {
933             // Extract the incoming alpha and emit rgba = (a/4, a/4, a/4, a/2)
934             SkAutoTUnref<const GrFragmentProcessor> inner(
935                 GrConstColorProcessor::Create(0x80404040,
936                                               GrConstColorProcessor::kModulateRGBA_InputMode));
937             return GrFragmentProcessor::MulOutputByInputAlpha(inner);
938         }
939         // Emit zero.
940         return GrConstColorProcessor::Create(0x0, GrConstColorProcessor::kIgnore_InputMode);
941     }
942
943     // Either we don't stitch tiles, either we have a valid tile size
944     SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
945
946     SkPerlinNoiseShader::PaintingData* paintingData =
947             new PaintingData(fTileSize, fSeed, fBaseFrequencyX, fBaseFrequencyY, matrix);
948     SkAutoTUnref<GrTexture> permutationsTexture(
949         GrRefCachedBitmapTexture(context, paintingData->getPermutationsBitmap(),
950                                  GrTextureParams::ClampNoFilter()));
951     SkAutoTUnref<GrTexture> noiseTexture(
952         GrRefCachedBitmapTexture(context, paintingData->getNoiseBitmap(),
953                                  GrTextureParams::ClampNoFilter()));
954
955     SkMatrix m = viewM;
956     m.setTranslateX(-localMatrix.getTranslateX() + SK_Scalar1);
957     m.setTranslateY(-localMatrix.getTranslateY() + SK_Scalar1);
958     if ((permutationsTexture) && (noiseTexture)) {
959         SkAutoTUnref<GrFragmentProcessor> inner(
960             GrPerlinNoiseEffect::Create(fType,
961                                         fNumOctaves,
962                                         fStitchTiles,
963                                         paintingData,
964                                         permutationsTexture, noiseTexture,
965                                         m));
966         return GrFragmentProcessor::MulOutputByInputAlpha(inner);
967     }
968     delete paintingData;
969     return nullptr;
970 }
971
972 #endif
973
974 #ifndef SK_IGNORE_TO_STRING
975 void SkPerlinNoiseShader::toString(SkString* str) const {
976     str->append("SkPerlinNoiseShader: (");
977
978     str->append("type: ");
979     switch (fType) {
980         case kFractalNoise_Type:
981             str->append("\"fractal noise\"");
982             break;
983         case kTurbulence_Type:
984             str->append("\"turbulence\"");
985             break;
986         default:
987             str->append("\"unknown\"");
988             break;
989     }
990     str->append(" base frequency: (");
991     str->appendScalar(fBaseFrequencyX);
992     str->append(", ");
993     str->appendScalar(fBaseFrequencyY);
994     str->append(") number of octaves: ");
995     str->appendS32(fNumOctaves);
996     str->append(" seed: ");
997     str->appendScalar(fSeed);
998     str->append(" stitch tiles: ");
999     str->append(fStitchTiles ? "true " : "false ");
1000
1001     this->INHERITED::toString(str);
1002
1003     str->append(")");
1004 }
1005 #endif