Home | History | Annotate | Download | only in effects
      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 "SkFlattenableBuffers.h"
     11 #include "SkShader.h"
     12 #include "SkUnPreMultiply.h"
     13 #include "SkString.h"
     14 
     15 #if SK_SUPPORT_GPU
     16 #include "GrContext.h"
     17 #include "gl/GrGLEffect.h"
     18 #include "gl/GrGLEffectMatrix.h"
     19 #include "GrTBackendEffectFactory.h"
     20 #include "SkGr.h"
     21 #endif
     22 
     23 static const int kBlockSize = 256;
     24 static const int kBlockMask = kBlockSize - 1;
     25 static const int kPerlinNoise = 4096;
     26 static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
     27 
     28 namespace {
     29 
     30 // noiseValue is the color component's value (or color)
     31 // limitValue is the maximum perlin noise array index value allowed
     32 // newValue is the current noise dimension (either width or height)
     33 inline int checkNoise(int noiseValue, int limitValue, int newValue) {
     34     // If the noise value would bring us out of bounds of the current noise array while we are
     35     // stiching noise tiles together, wrap the noise around the current dimension of the noise to
     36     // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
     37     if (noiseValue >= limitValue) {
     38         noiseValue -= newValue;
     39     }
     40     if (noiseValue >= limitValue - 1) {
     41         noiseValue -= newValue - 1;
     42     }
     43     return noiseValue;
     44 }
     45 
     46 inline SkScalar smoothCurve(SkScalar t) {
     47     static const SkScalar SK_Scalar3 = SkFloatToScalar(3.0f);
     48 
     49     // returns t * t * (3 - 2 * t)
     50     return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
     51 }
     52 
     53 } // end namespace
     54 
     55 struct SkPerlinNoiseShader::StitchData {
     56     StitchData()
     57       : fWidth(0)
     58       , fWrapX(0)
     59       , fHeight(0)
     60       , fWrapY(0)
     61     {}
     62 
     63     bool operator==(const StitchData& other) const {
     64         return fWidth == other.fWidth &&
     65                fWrapX == other.fWrapX &&
     66                fHeight == other.fHeight &&
     67                fWrapY == other.fWrapY;
     68     }
     69 
     70     int fWidth; // How much to subtract to wrap for stitching.
     71     int fWrapX; // Minimum value to wrap.
     72     int fHeight;
     73     int fWrapY;
     74 };
     75 
     76 struct SkPerlinNoiseShader::PaintingData {
     77     PaintingData(const SkISize& tileSize)
     78       : fSeed(0)
     79       , fTileSize(tileSize)
     80       , fPermutationsBitmap(NULL)
     81       , fNoiseBitmap(NULL)
     82     {}
     83 
     84     ~PaintingData()
     85     {
     86         SkDELETE(fPermutationsBitmap);
     87         SkDELETE(fNoiseBitmap);
     88     }
     89 
     90     int         fSeed;
     91     uint8_t     fLatticeSelector[kBlockSize];
     92     uint16_t    fNoise[4][kBlockSize][2];
     93     SkPoint     fGradient[4][kBlockSize];
     94     SkISize     fTileSize;
     95     SkVector    fBaseFrequency;
     96     StitchData  fStitchDataInit;
     97 
     98 private:
     99 
    100     SkBitmap*    fPermutationsBitmap;
    101     SkBitmap*    fNoiseBitmap;
    102 
    103 public:
    104 
    105     inline int random()  {
    106         static const int gRandAmplitude = 16807; // 7**5; primitive root of m
    107         static const int gRandQ = 127773; // m / a
    108         static const int gRandR = 2836; // m % a
    109 
    110         int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
    111         if (result <= 0)
    112             result += kRandMaximum;
    113         fSeed = result;
    114         return result;
    115     }
    116 
    117     void init(SkScalar seed)
    118     {
    119         static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
    120 
    121         // The seed value clamp to the range [1, kRandMaximum - 1].
    122         fSeed = SkScalarRoundToInt(seed);
    123         if (fSeed <= 0) {
    124             fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
    125         }
    126         if (fSeed > kRandMaximum - 1) {
    127             fSeed = kRandMaximum - 1;
    128         }
    129         for (int channel = 0; channel < 4; ++channel) {
    130             for (int i = 0; i < kBlockSize; ++i) {
    131                 fLatticeSelector[i] = i;
    132                 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
    133                 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
    134             }
    135         }
    136         for (int i = kBlockSize - 1; i > 0; --i) {
    137             int k = fLatticeSelector[i];
    138             int j = random() % kBlockSize;
    139             SkASSERT(j >= 0);
    140             SkASSERT(j < kBlockSize);
    141             fLatticeSelector[i] = fLatticeSelector[j];
    142             fLatticeSelector[j] = k;
    143         }
    144 
    145         // Perform the permutations now
    146         {
    147             // Copy noise data
    148             uint16_t noise[4][kBlockSize][2];
    149             for (int i = 0; i < kBlockSize; ++i) {
    150                 for (int channel = 0; channel < 4; ++channel) {
    151                     for (int j = 0; j < 2; ++j) {
    152                         noise[channel][i][j] = fNoise[channel][i][j];
    153                     }
    154                 }
    155             }
    156             // Do permutations on noise data
    157             for (int i = 0; i < kBlockSize; ++i) {
    158                 for (int channel = 0; channel < 4; ++channel) {
    159                     for (int j = 0; j < 2; ++j) {
    160                         fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
    161                     }
    162                 }
    163             }
    164         }
    165 
    166         // Half of the largest possible value for 16 bit unsigned int
    167         static const SkScalar gHalfMax16bits = SkFloatToScalar(32767.5f);
    168 
    169         // Compute gradients from permutated noise data
    170         for (int channel = 0; channel < 4; ++channel) {
    171             for (int i = 0; i < kBlockSize; ++i) {
    172                 fGradient[channel][i] = SkPoint::Make(
    173                     SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
    174                                 gInvBlockSizef),
    175                     SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
    176                                 gInvBlockSizef));
    177                 fGradient[channel][i].normalize();
    178                 // Put the normalized gradient back into the noise data
    179                 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
    180                     fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
    181                 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
    182                     fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
    183             }
    184         }
    185 
    186         // Invalidate bitmaps
    187         SkDELETE(fPermutationsBitmap);
    188         fPermutationsBitmap = NULL;
    189         SkDELETE(fNoiseBitmap);
    190         fNoiseBitmap = NULL;
    191     }
    192 
    193     void stitch() {
    194         SkScalar tileWidth  = SkIntToScalar(fTileSize.width());
    195         SkScalar tileHeight = SkIntToScalar(fTileSize.height());
    196         SkASSERT(tileWidth > 0 && tileHeight > 0);
    197         // When stitching tiled turbulence, the frequencies must be adjusted
    198         // so that the tile borders will be continuous.
    199         if (fBaseFrequency.fX) {
    200             SkScalar lowFrequencx = SkScalarDiv(
    201                 SkScalarMulFloor(tileWidth, fBaseFrequency.fX), tileWidth);
    202             SkScalar highFrequencx = SkScalarDiv(
    203                 SkScalarMulCeil(tileWidth, fBaseFrequency.fX), tileWidth);
    204             // BaseFrequency should be non-negative according to the standard.
    205             if (SkScalarDiv(fBaseFrequency.fX, lowFrequencx) <
    206                 SkScalarDiv(highFrequencx, fBaseFrequency.fX)) {
    207                 fBaseFrequency.fX = lowFrequencx;
    208             } else {
    209                 fBaseFrequency.fX = highFrequencx;
    210             }
    211         }
    212         if (fBaseFrequency.fY) {
    213             SkScalar lowFrequency = SkScalarDiv(
    214                 SkScalarMulFloor(tileHeight, fBaseFrequency.fY), tileHeight);
    215             SkScalar highFrequency = SkScalarDiv(
    216                 SkScalarMulCeil(tileHeight, fBaseFrequency.fY), tileHeight);
    217             if (SkScalarDiv(fBaseFrequency.fY, lowFrequency) <
    218                 SkScalarDiv(highFrequency, fBaseFrequency.fY)) {
    219                 fBaseFrequency.fY = lowFrequency;
    220             } else {
    221                 fBaseFrequency.fY = highFrequency;
    222             }
    223         }
    224         // Set up TurbulenceInitial stitch values.
    225         fStitchDataInit.fWidth  =
    226             SkScalarMulRound(tileWidth, fBaseFrequency.fX);
    227         fStitchDataInit.fWrapX  = kPerlinNoise + fStitchDataInit.fWidth;
    228         fStitchDataInit.fHeight =
    229             SkScalarMulRound(tileHeight, fBaseFrequency.fY);
    230         fStitchDataInit.fWrapY  = kPerlinNoise + fStitchDataInit.fHeight;
    231     }
    232 
    233     SkBitmap* getPermutationsBitmap()
    234     {
    235         if (!fPermutationsBitmap) {
    236             fPermutationsBitmap = SkNEW(SkBitmap);
    237             fPermutationsBitmap->setConfig(SkBitmap::kA8_Config, kBlockSize, 1);
    238             fPermutationsBitmap->allocPixels();
    239             uint8_t* bitmapPixels = fPermutationsBitmap->getAddr8(0, 0);
    240             memcpy(bitmapPixels, fLatticeSelector, sizeof(uint8_t) * kBlockSize);
    241         }
    242         return fPermutationsBitmap;
    243     }
    244 
    245     SkBitmap* getNoiseBitmap()
    246     {
    247         if (!fNoiseBitmap) {
    248             fNoiseBitmap = SkNEW(SkBitmap);
    249             fNoiseBitmap->setConfig(SkBitmap::kARGB_8888_Config, kBlockSize, 4);
    250             fNoiseBitmap->allocPixels();
    251             uint32_t* bitmapPixels = fNoiseBitmap->getAddr32(0, 0);
    252             memcpy(bitmapPixels, fNoise[0][0], sizeof(uint16_t) * kBlockSize * 4 * 2);
    253         }
    254         return fNoiseBitmap;
    255     }
    256 };
    257 
    258 SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
    259                                                   int numOctaves, SkScalar seed,
    260                                                   const SkISize* tileSize) {
    261     return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY,
    262                                             numOctaves, seed, tileSize));
    263 }
    264 
    265 SkShader* SkPerlinNoiseShader::CreateTubulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
    266                                               int numOctaves, SkScalar seed,
    267                                               const SkISize* tileSize) {
    268     return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY,
    269                                             numOctaves, seed, tileSize));
    270 }
    271 
    272 SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
    273                                          SkScalar baseFrequencyX,
    274                                          SkScalar baseFrequencyY,
    275                                          int numOctaves,
    276                                          SkScalar seed,
    277                                          const SkISize* tileSize)
    278   : fType(type)
    279   , fBaseFrequencyX(baseFrequencyX)
    280   , fBaseFrequencyY(baseFrequencyY)
    281   , fNumOctaves(numOctaves & 0xFF /*[0,255] octaves allowed*/)
    282   , fSeed(seed)
    283   , fStitchTiles((tileSize != NULL) && !tileSize->isEmpty())
    284   , fPaintingData(NULL)
    285 {
    286     SkASSERT(numOctaves >= 0 && numOctaves < 256);
    287     setTileSize(fStitchTiles ? *tileSize : SkISize::Make(0,0));
    288     fMatrix.reset();
    289 }
    290 
    291 SkPerlinNoiseShader::SkPerlinNoiseShader(SkFlattenableReadBuffer& buffer) :
    292         INHERITED(buffer), fPaintingData(NULL) {
    293     fType           = (SkPerlinNoiseShader::Type) buffer.readInt();
    294     fBaseFrequencyX = buffer.readScalar();
    295     fBaseFrequencyY = buffer.readScalar();
    296     fNumOctaves     = buffer.readInt();
    297     fSeed           = buffer.readScalar();
    298     fStitchTiles    = buffer.readBool();
    299     fTileSize.fWidth  = buffer.readInt();
    300     fTileSize.fHeight = buffer.readInt();
    301     setTileSize(fTileSize);
    302     fMatrix.reset();
    303 }
    304 
    305 SkPerlinNoiseShader::~SkPerlinNoiseShader() {
    306     // Safety, should have been done in endContext()
    307     SkDELETE(fPaintingData);
    308 }
    309 
    310 void SkPerlinNoiseShader::flatten(SkFlattenableWriteBuffer& buffer) const {
    311     this->INHERITED::flatten(buffer);
    312     buffer.writeInt((int) fType);
    313     buffer.writeScalar(fBaseFrequencyX);
    314     buffer.writeScalar(fBaseFrequencyY);
    315     buffer.writeInt(fNumOctaves);
    316     buffer.writeScalar(fSeed);
    317     buffer.writeBool(fStitchTiles);
    318     buffer.writeInt(fTileSize.fWidth);
    319     buffer.writeInt(fTileSize.fHeight);
    320 }
    321 
    322 void SkPerlinNoiseShader::initPaint(PaintingData& paintingData)
    323 {
    324     paintingData.init(fSeed);
    325 
    326     // Set frequencies to original values
    327     paintingData.fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
    328     // Adjust frequecies based on size if stitching is enabled
    329     if (fStitchTiles) {
    330         paintingData.stitch();
    331     }
    332 }
    333 
    334 void SkPerlinNoiseShader::setTileSize(const SkISize& tileSize) {
    335     fTileSize = tileSize;
    336 
    337     if (NULL == fPaintingData) {
    338         fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize));
    339         initPaint(*fPaintingData);
    340     } else {
    341         // Set Size
    342         fPaintingData->fTileSize = fTileSize;
    343         // Set frequencies to original values
    344         fPaintingData->fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
    345         // Adjust frequecies based on size if stitching is enabled
    346         if (fStitchTiles) {
    347             fPaintingData->stitch();
    348         }
    349     }
    350 }
    351 
    352 SkScalar SkPerlinNoiseShader::noise2D(int channel, const PaintingData& paintingData,
    353                                      const StitchData& stitchData, const SkPoint& noiseVector)
    354 {
    355     struct Noise {
    356         int noisePositionIntegerValue;
    357         SkScalar noisePositionFractionValue;
    358         Noise(SkScalar component)
    359         {
    360             SkScalar position = component + kPerlinNoise;
    361             noisePositionIntegerValue = SkScalarFloorToInt(position);
    362             noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
    363         }
    364     };
    365     Noise noiseX(noiseVector.x());
    366     Noise noiseY(noiseVector.y());
    367     SkScalar u, v;
    368     // If stitching, adjust lattice points accordingly.
    369     if (fStitchTiles) {
    370         noiseX.noisePositionIntegerValue =
    371             checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
    372         noiseY.noisePositionIntegerValue =
    373             checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
    374     }
    375     noiseX.noisePositionIntegerValue &= kBlockMask;
    376     noiseY.noisePositionIntegerValue &= kBlockMask;
    377     int latticeIndex =
    378         paintingData.fLatticeSelector[noiseX.noisePositionIntegerValue] +
    379         noiseY.noisePositionIntegerValue;
    380     int nextLatticeIndex =
    381         paintingData.fLatticeSelector[(noiseX.noisePositionIntegerValue + 1) & kBlockMask] +
    382         noiseY.noisePositionIntegerValue;
    383     SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
    384     SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
    385     // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
    386     SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
    387                                           noiseY.noisePositionFractionValue); // Offset (0,0)
    388     u = paintingData.fGradient[channel][latticeIndex & kBlockMask].dot(fractionValue);
    389     fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
    390     v = paintingData.fGradient[channel][nextLatticeIndex & kBlockMask].dot(fractionValue);
    391     SkScalar a = SkScalarInterp(u, v, sx);
    392     fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
    393     v = paintingData.fGradient[channel][(nextLatticeIndex + 1) & kBlockMask].dot(fractionValue);
    394     fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
    395     u = paintingData.fGradient[channel][(latticeIndex + 1) & kBlockMask].dot(fractionValue);
    396     SkScalar b = SkScalarInterp(u, v, sx);
    397     return SkScalarInterp(a, b, sy);
    398 }
    399 
    400 SkScalar SkPerlinNoiseShader::calculateTurbulenceValueForPoint(
    401     int channel, const PaintingData& paintingData, StitchData& stitchData, const SkPoint& point)
    402 {
    403     if (fStitchTiles) {
    404         // Set up TurbulenceInitial stitch values.
    405         stitchData = paintingData.fStitchDataInit;
    406     }
    407     SkScalar turbulenceFunctionResult = 0;
    408     SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), paintingData.fBaseFrequency.fX),
    409                                       SkScalarMul(point.y(), paintingData.fBaseFrequency.fY)));
    410     SkScalar ratio = SK_Scalar1;
    411     for (int octave = 0; octave < fNumOctaves; ++octave) {
    412         SkScalar noise = noise2D(channel, paintingData, stitchData, noiseVector);
    413         turbulenceFunctionResult += SkScalarDiv(
    414             (fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio);
    415         noiseVector.fX *= 2;
    416         noiseVector.fY *= 2;
    417         ratio *= 2;
    418         if (fStitchTiles) {
    419             // Update stitch values
    420             stitchData.fWidth  *= 2;
    421             stitchData.fWrapX   = stitchData.fWidth + kPerlinNoise;
    422             stitchData.fHeight *= 2;
    423             stitchData.fWrapY   = stitchData.fHeight + kPerlinNoise;
    424         }
    425     }
    426 
    427     // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
    428     // by fractalNoise and (turbulenceFunctionResult) by turbulence.
    429     if (fType == kFractalNoise_Type) {
    430         turbulenceFunctionResult =
    431             SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
    432     }
    433 
    434     if (channel == 3) { // Scale alpha by paint value
    435         turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult,
    436             SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255)));
    437     }
    438 
    439     // Clamp result
    440     return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
    441 }
    442 
    443 SkPMColor SkPerlinNoiseShader::shade(const SkPoint& point, StitchData& stitchData) {
    444     SkMatrix matrix = fMatrix;
    445     SkMatrix invMatrix;
    446     if (!matrix.invert(&invMatrix)) {
    447         invMatrix.reset();
    448     } else {
    449         invMatrix.postConcat(invMatrix); // Square the matrix
    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     matrix.postTranslate(SK_Scalar1, SK_Scalar1);
    454     SkPoint newPoint;
    455     matrix.mapPoints(&newPoint, &point, 1);
    456     invMatrix.mapPoints(&newPoint, &newPoint, 1);
    457     newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
    458     newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
    459 
    460     U8CPU rgba[4];
    461     for (int channel = 3; channel >= 0; --channel) {
    462         rgba[channel] = SkScalarFloorToInt(255 *
    463             calculateTurbulenceValueForPoint(channel, *fPaintingData, stitchData, newPoint));
    464     }
    465     return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
    466 }
    467 
    468 bool SkPerlinNoiseShader::setContext(const SkBitmap& device, const SkPaint& paint,
    469                                      const SkMatrix& matrix) {
    470     fMatrix = matrix;
    471     return INHERITED::setContext(device, paint, matrix);
    472 }
    473 
    474 void SkPerlinNoiseShader::shadeSpan(int x, int y, SkPMColor result[], int count) {
    475     SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
    476     StitchData stitchData;
    477     for (int i = 0; i < count; ++i) {
    478         result[i] = shade(point, stitchData);
    479         point.fX += SK_Scalar1;
    480     }
    481 }
    482 
    483 void SkPerlinNoiseShader::shadeSpan16(int x, int y, uint16_t result[], int count) {
    484     SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
    485     StitchData stitchData;
    486     DITHER_565_SCAN(y);
    487     for (int i = 0; i < count; ++i) {
    488         unsigned dither = DITHER_VALUE(x);
    489         result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
    490         DITHER_INC_X(x);
    491         point.fX += SK_Scalar1;
    492     }
    493 }
    494 
    495 /////////////////////////////////////////////////////////////////////
    496 
    497 #if SK_SUPPORT_GPU
    498 
    499 #include "GrTBackendEffectFactory.h"
    500 
    501 class GrGLNoise : public GrGLEffect {
    502 public:
    503     GrGLNoise(const GrBackendEffectFactory& factory,
    504               const GrDrawEffect& drawEffect);
    505     virtual ~GrGLNoise() {}
    506 
    507     static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
    508 
    509     virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
    510 
    511 protected:
    512     SkPerlinNoiseShader::Type           fType;
    513     bool                                fStitchTiles;
    514     int                                 fNumOctaves;
    515     GrGLUniformManager::UniformHandle   fBaseFrequencyUni;
    516     GrGLUniformManager::UniformHandle   fAlphaUni;
    517     GrGLUniformManager::UniformHandle   fInvMatrixUni;
    518     GrGLEffectMatrix                    fEffectMatrix;
    519 
    520 private:
    521     typedef GrGLEffect INHERITED;
    522 };
    523 
    524 class GrGLPerlinNoise : public GrGLNoise {
    525 public:
    526     GrGLPerlinNoise(const GrBackendEffectFactory& factory,
    527                     const GrDrawEffect& drawEffect)
    528       : GrGLNoise(factory, drawEffect) {}
    529     virtual ~GrGLPerlinNoise() {}
    530 
    531     virtual void emitCode(GrGLShaderBuilder*,
    532                           const GrDrawEffect&,
    533                           EffectKey,
    534                           const char* outputColor,
    535                           const char* inputColor,
    536                           const TextureSamplerArray&) SK_OVERRIDE;
    537 
    538     virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
    539 
    540 private:
    541     GrGLUniformManager::UniformHandle fStitchDataUni;
    542 
    543     typedef GrGLNoise INHERITED;
    544 };
    545 
    546 class GrGLSimplexNoise : public GrGLNoise {
    547     // Note : This is for reference only. GrGLPerlinNoise is used for processing.
    548 public:
    549     GrGLSimplexNoise(const GrBackendEffectFactory& factory,
    550                      const GrDrawEffect& drawEffect)
    551       : GrGLNoise(factory, drawEffect) {}
    552 
    553     virtual ~GrGLSimplexNoise() {}
    554 
    555     virtual void emitCode(GrGLShaderBuilder*,
    556                           const GrDrawEffect&,
    557                           EffectKey,
    558                           const char* outputColor,
    559                           const char* inputColor,
    560                           const TextureSamplerArray&) SK_OVERRIDE;
    561 
    562     virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
    563 
    564 private:
    565     GrGLUniformManager::UniformHandle fSeedUni;
    566 
    567     typedef GrGLNoise INHERITED;
    568 };
    569 
    570 /////////////////////////////////////////////////////////////////////
    571 
    572 class GrNoiseEffect : public GrEffect {
    573 public:
    574     virtual ~GrNoiseEffect() { }
    575 
    576     SkPerlinNoiseShader::Type type() const { return fType; }
    577     bool stitchTiles() const { return fStitchTiles; }
    578     const SkVector& baseFrequency() const { return fBaseFrequency; }
    579     int numOctaves() const { return fNumOctaves; }
    580     const SkMatrix& matrix() const { return fMatrix; }
    581     uint8_t alpha() const { return fAlpha; }
    582     GrGLEffectMatrix::CoordsType coordsType() const { return GrEffect::kLocal_CoordsType; }
    583 
    584     void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE {
    585         *validFlags = 0; // This is noise. Nothing is constant.
    586     }
    587 
    588 protected:
    589     virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
    590         const GrNoiseEffect& s = CastEffect<GrNoiseEffect>(sBase);
    591         return fType == s.fType &&
    592                fBaseFrequency == s.fBaseFrequency &&
    593                fNumOctaves == s.fNumOctaves &&
    594                fStitchTiles == s.fStitchTiles &&
    595                fMatrix == s.fMatrix &&
    596                fAlpha == s.fAlpha;
    597     }
    598 
    599     GrNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, int numOctaves,
    600                   bool stitchTiles, const SkMatrix& matrix, uint8_t alpha)
    601       : fType(type)
    602       , fBaseFrequency(baseFrequency)
    603       , fNumOctaves(numOctaves)
    604       , fStitchTiles(stitchTiles)
    605       , fMatrix(matrix)
    606       , fAlpha(alpha) {
    607     }
    608 
    609     SkPerlinNoiseShader::Type       fType;
    610     SkVector                        fBaseFrequency;
    611     int                             fNumOctaves;
    612     bool                            fStitchTiles;
    613     SkMatrix                        fMatrix;
    614     uint8_t                         fAlpha;
    615 
    616 private:
    617     typedef GrEffect INHERITED;
    618 };
    619 
    620 class GrPerlinNoiseEffect : public GrNoiseEffect {
    621 public:
    622     static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
    623                                int numOctaves, bool stitchTiles,
    624                                const SkPerlinNoiseShader::StitchData& stitchData,
    625                                GrTexture* permutationsTexture, GrTexture* noiseTexture,
    626                                const SkMatrix& matrix, uint8_t alpha) {
    627         AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves,
    628             stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha)));
    629         return CreateEffectRef(effect);
    630     }
    631 
    632     virtual ~GrPerlinNoiseEffect() { }
    633 
    634     static const char* Name() { return "PerlinNoise"; }
    635     virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
    636         return GrTBackendEffectFactory<GrPerlinNoiseEffect>::getInstance();
    637     }
    638     const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; }
    639 
    640     typedef GrGLPerlinNoise GLEffect;
    641 
    642 private:
    643     virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
    644         const GrPerlinNoiseEffect& s = CastEffect<GrPerlinNoiseEffect>(sBase);
    645         return INHERITED::onIsEqual(sBase) &&
    646                fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() &&
    647                fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() &&
    648                fStitchData == s.fStitchData;
    649     }
    650 
    651     GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
    652                         int numOctaves, bool stitchTiles,
    653                         const SkPerlinNoiseShader::StitchData& stitchData,
    654                         GrTexture* permutationsTexture, GrTexture* noiseTexture,
    655                         const SkMatrix& matrix, uint8_t alpha)
    656       : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
    657       , fPermutationsAccess(permutationsTexture)
    658       , fNoiseAccess(noiseTexture)
    659       , fStitchData(stitchData) {
    660         this->addTextureAccess(&fPermutationsAccess);
    661         this->addTextureAccess(&fNoiseAccess);
    662     }
    663 
    664     GR_DECLARE_EFFECT_TEST;
    665 
    666     GrTextureAccess                 fPermutationsAccess;
    667     GrTextureAccess                 fNoiseAccess;
    668     SkPerlinNoiseShader::StitchData fStitchData;
    669 
    670     typedef GrNoiseEffect INHERITED;
    671 };
    672 
    673 class GrSimplexNoiseEffect : public GrNoiseEffect {
    674     // Note : This is for reference only. GrPerlinNoiseEffect is used for processing.
    675 public:
    676     static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
    677                                int numOctaves, bool stitchTiles, const SkScalar seed,
    678                                const SkMatrix& matrix, uint8_t alpha) {
    679         AutoEffectUnref effect(SkNEW_ARGS(GrSimplexNoiseEffect, (type, baseFrequency, numOctaves,
    680             stitchTiles, seed, matrix, alpha)));
    681         return CreateEffectRef(effect);
    682     }
    683 
    684     virtual ~GrSimplexNoiseEffect() { }
    685 
    686     static const char* Name() { return "SimplexNoise"; }
    687     virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
    688         return GrTBackendEffectFactory<GrSimplexNoiseEffect>::getInstance();
    689     }
    690     const SkScalar& seed() const { return fSeed; }
    691 
    692     typedef GrGLSimplexNoise GLEffect;
    693 
    694 private:
    695     virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
    696         const GrSimplexNoiseEffect& s = CastEffect<GrSimplexNoiseEffect>(sBase);
    697         return INHERITED::onIsEqual(sBase) && fSeed == s.fSeed;
    698     }
    699 
    700     GrSimplexNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
    701                          int numOctaves, bool stitchTiles, const SkScalar seed,
    702                          const SkMatrix& matrix, uint8_t alpha)
    703       : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
    704       , fSeed(seed) {
    705     }
    706 
    707     SkScalar fSeed;
    708 
    709     typedef GrNoiseEffect INHERITED;
    710 };
    711 
    712 /////////////////////////////////////////////////////////////////////
    713 GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect);
    714 
    715 GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkMWCRandom* random,
    716                                              GrContext* context,
    717                                              const GrDrawTargetCaps&,
    718                                              GrTexture**) {
    719     int      numOctaves = random->nextRangeU(2, 10);
    720     bool     stitchTiles = random->nextBool();
    721     SkScalar seed = SkIntToScalar(random->nextU());
    722     SkISize  tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
    723     SkScalar baseFrequencyX = random->nextRangeScalar(SkFloatToScalar(0.01f),
    724                                                       SkFloatToScalar(0.99f));
    725     SkScalar baseFrequencyY = random->nextRangeScalar(SkFloatToScalar(0.01f),
    726                                                       SkFloatToScalar(0.99f));
    727 
    728     SkShader* shader = random->nextBool() ?
    729         SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
    730                                                 stitchTiles ? &tileSize : NULL) :
    731         SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
    732                                              stitchTiles ? &tileSize : NULL);
    733 
    734     SkPaint paint;
    735     GrEffectRef* effect = shader->asNewEffect(context, paint);
    736 
    737     SkDELETE(shader);
    738 
    739     return effect;
    740 }
    741 
    742 /////////////////////////////////////////////////////////////////////
    743 
    744 void GrGLSimplexNoise::emitCode(GrGLShaderBuilder* builder,
    745                                 const GrDrawEffect&,
    746                                 EffectKey key,
    747                                 const char* outputColor,
    748                                 const char* inputColor,
    749                                 const TextureSamplerArray&) {
    750     sk_ignore_unused_variable(inputColor);
    751 
    752     const char* vCoords;
    753     fEffectMatrix.emitCodeMakeFSCoords2D(builder, key, &vCoords);
    754 
    755     fSeedUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
    756                                    kFloat_GrSLType, "seed");
    757     const char* seedUni = builder->getUniformCStr(fSeedUni);
    758     fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
    759                                         kMat33f_GrSLType, "invMatrix");
    760     const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
    761     fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
    762                                             kVec2f_GrSLType, "baseFrequency");
    763     const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
    764     fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
    765                                     kFloat_GrSLType, "alpha");
    766     const char* alphaUni = builder->getUniformCStr(fAlphaUni);
    767 
    768     // Add vec3 modulo 289 function
    769     static const GrGLShaderVar gVec3Args[] =  {
    770         GrGLShaderVar("x", kVec3f_GrSLType)
    771     };
    772 
    773     SkString mod289_3_funcName;
    774     builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kVec3f_GrSLType,
    775                           "mod289", SK_ARRAY_COUNT(gVec3Args), gVec3Args,
    776                           "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
    777                           "return x - floor(x * C.xxx) * C.yyy;", &mod289_3_funcName);
    778 
    779     // Add vec4 modulo 289 function
    780     static const GrGLShaderVar gVec4Args[] =  {
    781         GrGLShaderVar("x", kVec4f_GrSLType)
    782     };
    783 
    784     SkString mod289_4_funcName;
    785     builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kVec4f_GrSLType,
    786                           "mod289", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
    787                           "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
    788                           "return x - floor(x * C.xxxx) * C.yyyy;", &mod289_4_funcName);
    789 
    790     // Add vec4 permute function
    791     SkString permuteCode;
    792     permuteCode.appendf("const vec2 C = vec2(34.0, 1.0);\n"
    793                         "return %s(((x * C.xxxx) + C.yyyy) * x);", mod289_4_funcName.c_str());
    794     SkString permuteFuncName;
    795     builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kVec4f_GrSLType,
    796                           "permute", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
    797                           permuteCode.c_str(), &permuteFuncName);
    798 
    799     // Add vec4 taylorInvSqrt function
    800     SkString taylorInvSqrtFuncName;
    801     builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kVec4f_GrSLType,
    802                           "taylorInvSqrt", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
    803                           "const vec2 C = vec2(-0.85373472095314, 1.79284291400159);\n"
    804                           "return x * C.xxxx + C.yyyy;", &taylorInvSqrtFuncName);
    805 
    806     // Add vec3 noise function
    807     static const GrGLShaderVar gNoiseVec3Args[] =  {
    808         GrGLShaderVar("v", kVec3f_GrSLType)
    809     };
    810 
    811     SkString noiseCode;
    812     noiseCode.append(
    813         "const vec2 C = vec2(1.0/6.0, 1.0/3.0);\n"
    814         "const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n"
    815 
    816         // First corner
    817         "vec3 i = floor(v + dot(v, C.yyy));\n"
    818         "vec3 x0 = v - i + dot(i, C.xxx);\n"
    819 
    820         // Other corners
    821         "vec3 g = step(x0.yzx, x0.xyz);\n"
    822         "vec3 l = 1.0 - g;\n"
    823         "vec3 i1 = min(g.xyz, l.zxy);\n"
    824         "vec3 i2 = max(g.xyz, l.zxy);\n"
    825 
    826         "vec3 x1 = x0 - i1 + C.xxx;\n"
    827         "vec3 x2 = x0 - i2 + C.yyy;\n" // 2.0*C.x = 1/3 = C.y
    828         "vec3 x3 = x0 - D.yyy;\n" // -1.0+3.0*C.x = -0.5 = -D.y
    829     );
    830 
    831     noiseCode.appendf(
    832         // Permutations
    833         "i = %s(i);\n"
    834         "vec4 p = %s(%s(%s(\n"
    835         "         i.z + vec4(0.0, i1.z, i2.z, 1.0)) +\n"
    836         "         i.y + vec4(0.0, i1.y, i2.y, 1.0)) +\n"
    837         "         i.x + vec4(0.0, i1.x, i2.x, 1.0));\n",
    838         mod289_3_funcName.c_str(), permuteFuncName.c_str(), permuteFuncName.c_str(),
    839         permuteFuncName.c_str());
    840 
    841     noiseCode.append(
    842         // Gradients: 7x7 points over a square, mapped onto an octahedron.
    843         // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
    844         "float n_ = 0.142857142857;\n" // 1.0/7.0
    845         "vec3  ns = n_ * D.wyz - D.xzx;\n"
    846 
    847         "vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\n" // mod(p,7*7)
    848 
    849         "vec4 x_ = floor(j * ns.z);\n"
    850         "vec4 y_ = floor(j - 7.0 * x_);" // mod(j,N)
    851 
    852         "vec4 x = x_ *ns.x + ns.yyyy;\n"
    853         "vec4 y = y_ *ns.x + ns.yyyy;\n"
    854         "vec4 h = 1.0 - abs(x) - abs(y);\n"
    855 
    856         "vec4 b0 = vec4(x.xy, y.xy);\n"
    857         "vec4 b1 = vec4(x.zw, y.zw);\n"
    858     );
    859 
    860     noiseCode.append(
    861         "vec4 s0 = floor(b0) * 2.0 + 1.0;\n"
    862         "vec4 s1 = floor(b1) * 2.0 + 1.0;\n"
    863         "vec4 sh = -step(h, vec4(0.0));\n"
    864 
    865         "vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;\n"
    866         "vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;\n"
    867 
    868         "vec3 p0 = vec3(a0.xy, h.x);\n"
    869         "vec3 p1 = vec3(a0.zw, h.y);\n"
    870         "vec3 p2 = vec3(a1.xy, h.z);\n"
    871         "vec3 p3 = vec3(a1.zw, h.w);\n"
    872     );
    873 
    874     noiseCode.appendf(
    875         // Normalise gradients
    876         "vec4 norm = %s(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n"
    877         "p0 *= norm.x;\n"
    878         "p1 *= norm.y;\n"
    879         "p2 *= norm.z;\n"
    880         "p3 *= norm.w;\n"
    881 
    882         // Mix final noise value
    883         "vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n"
    884         "m = m * m;\n"
    885         "return 42.0 * dot(m*m, vec4(dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3)));",
    886         taylorInvSqrtFuncName.c_str());
    887 
    888     SkString noiseFuncName;
    889     builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kFloat_GrSLType,
    890                           "snoise", SK_ARRAY_COUNT(gNoiseVec3Args), gNoiseVec3Args,
    891                           noiseCode.c_str(), &noiseFuncName);
    892 
    893     const char* noiseVecIni = "noiseVecIni";
    894     const char* factors     = "factors";
    895     const char* sum         = "sum";
    896     const char* xOffsets    = "xOffsets";
    897     const char* yOffsets    = "yOffsets";
    898     const char* channel     = "channel";
    899 
    900     // Fill with some prime numbers
    901     builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(13.0, 53.0, 101.0, 151.0);\n", xOffsets);
    902     builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(109.0, 167.0, 23.0, 67.0);\n", yOffsets);
    903 
    904     // There are rounding errors if the floor operation is not performed here
    905     builder->fsCodeAppendf(
    906         "\t\tvec3 %s = vec3(floor((%s*vec3(%s, 1.0)).xy) * vec2(0.66) * %s, 0.0);\n",
    907         noiseVecIni, invMatrixUni, vCoords, baseFrequencyUni);
    908 
    909     // Perturb the texcoords with three components of noise
    910     builder->fsCodeAppendf("\t\t%s += 0.1 * vec3(%s(%s + vec3(  0.0,   0.0, %s)),"
    911                                                 "%s(%s + vec3( 43.0,  17.0, %s)),"
    912                                                 "%s(%s + vec3(-17.0, -43.0, %s)));\n",
    913                            noiseVecIni, noiseFuncName.c_str(), noiseVecIni, seedUni,
    914                                         noiseFuncName.c_str(), noiseVecIni, seedUni,
    915                                         noiseFuncName.c_str(), noiseVecIni, seedUni);
    916 
    917     builder->fsCodeAppendf("\t\t%s = vec4(0.0);\n", outputColor);
    918 
    919     builder->fsCodeAppendf("\t\tvec3 %s = vec3(1.0);\n", factors);
    920     builder->fsCodeAppendf("\t\tfloat %s = 0.0;\n", sum);
    921 
    922     // Loop over all octaves
    923     builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {\n", fNumOctaves);
    924 
    925     // Loop over the 4 channels
    926     builder->fsCodeAppendf("\t\t\tfor (int %s = 3; %s >= 0; --%s) {\n", channel, channel, channel);
    927 
    928     builder->fsCodeAppendf(
    929         "\t\t\t\t%s[channel] += %s.x * %s(%s * %s.yyy - vec3(%s[%s], %s[%s], %s * %s.z));\n",
    930         outputColor, factors, noiseFuncName.c_str(), noiseVecIni, factors, xOffsets, channel,
    931         yOffsets, channel, seedUni, factors);
    932 
    933     builder->fsCodeAppend("\t\t\t}\n"); // end of the for loop on channels
    934 
    935     builder->fsCodeAppendf("\t\t\t%s += %s.x;\n", sum, factors);
    936     builder->fsCodeAppendf("\t\t\t%s *= vec3(0.5, 2.0, 0.75);\n", factors);
    937 
    938     builder->fsCodeAppend("\t\t}\n"); // end of the for loop on octaves
    939 
    940     if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
    941         // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
    942         // by fractalNoise and (turbulenceFunctionResult) by turbulence.
    943         builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5 / %s) + vec4(0.5);\n",
    944                                outputColor, outputColor, sum);
    945     } else {
    946         builder->fsCodeAppendf("\t\t%s = abs(%s / vec4(%s));\n",
    947                                outputColor, outputColor, sum);
    948     }
    949 
    950     builder->fsCodeAppendf("\t\t%s.a *= %s;\n", outputColor, alphaUni);
    951 
    952     // Clamp values
    953     builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);\n", outputColor, outputColor);
    954 
    955     // Pre-multiply the result
    956     builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
    957                            outputColor, outputColor, outputColor, outputColor);
    958 }
    959 
    960 void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder,
    961                                const GrDrawEffect&,
    962                                EffectKey key,
    963                                const char* outputColor,
    964                                const char* inputColor,
    965                                const TextureSamplerArray& samplers) {
    966     sk_ignore_unused_variable(inputColor);
    967 
    968     const char* vCoords;
    969     fEffectMatrix.emitCodeMakeFSCoords2D(builder, key, &vCoords);
    970 
    971     fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
    972                                         kMat33f_GrSLType, "invMatrix");
    973     const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
    974     fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
    975                                             kVec2f_GrSLType, "baseFrequency");
    976     const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
    977     fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
    978                                     kFloat_GrSLType, "alpha");
    979     const char* alphaUni = builder->getUniformCStr(fAlphaUni);
    980 
    981     const char* stitchDataUni = NULL;
    982     if (fStitchTiles) {
    983         fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
    984                                              kVec2f_GrSLType, "stitchData");
    985         stitchDataUni = builder->getUniformCStr(fStitchDataUni);
    986     }
    987 
    988     // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
    989     const char* chanCoordR  = "0.125";
    990     const char* chanCoordG  = "0.375";
    991     const char* chanCoordB  = "0.625";
    992     const char* chanCoordA  = "0.875";
    993     const char* chanCoord   = "chanCoord";
    994     const char* stitchData  = "stitchData";
    995     const char* ratio       = "ratio";
    996     const char* noiseXY     = "noiseXY";
    997     const char* noiseVec    = "noiseVec";
    998     const char* noiseSmooth = "noiseSmooth";
    999     const char* fractVal    = "fractVal";
   1000     const char* uv          = "uv";
   1001     const char* ab          = "ab";
   1002     const char* latticeIdx  = "latticeIdx";
   1003     const char* lattice     = "lattice";
   1004     const char* inc8bit     = "0.00390625";  // 1.0 / 256.0
   1005     // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
   1006     // [-1,1] vector and perform a dot product between that vector and the provided vector.
   1007     const char* dotLattice  = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
   1008 
   1009     // Add noise function
   1010     static const GrGLShaderVar gPerlinNoiseArgs[] =  {
   1011         GrGLShaderVar(chanCoord, kFloat_GrSLType),
   1012         GrGLShaderVar(noiseVec, kVec2f_GrSLType)
   1013     };
   1014 
   1015     static const GrGLShaderVar gPerlinNoiseStitchArgs[] =  {
   1016         GrGLShaderVar(chanCoord, kFloat_GrSLType),
   1017         GrGLShaderVar(noiseVec, kVec2f_GrSLType),
   1018         GrGLShaderVar(stitchData, kVec2f_GrSLType)
   1019     };
   1020 
   1021     SkString noiseCode;
   1022 
   1023     noiseCode.appendf("\tvec4 %s = vec4(floor(%s), fract(%s));", noiseXY, noiseVec, noiseVec);
   1024 
   1025     // smooth curve : t * t * (3 - 2 * t)
   1026     noiseCode.appendf("\n\tvec2 %s = %s.zw * %s.zw * (vec2(3.0) - vec2(2.0) * %s.zw);",
   1027         noiseSmooth, noiseXY, noiseXY, noiseXY);
   1028 
   1029     // Adjust frequencies if we're stitching tiles
   1030     if (fStitchTiles) {
   1031         noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
   1032             noiseXY, stitchData, noiseXY, stitchData);
   1033         noiseCode.appendf("\n\tif(%s.x >= (%s.x - 1.0)) { %s.x -= (%s.x - 1.0); }",
   1034             noiseXY, stitchData, noiseXY, stitchData);
   1035         noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }",
   1036             noiseXY, stitchData, noiseXY, stitchData);
   1037         noiseCode.appendf("\n\tif(%s.y >= (%s.y - 1.0)) { %s.y -= (%s.y - 1.0); }",
   1038             noiseXY, stitchData, noiseXY, stitchData);
   1039     }
   1040 
   1041     // Get texture coordinates and normalize
   1042     noiseCode.appendf("\n\t%s.xy = fract(floor(mod(%s.xy, 256.0)) / vec2(256.0));\n",
   1043         noiseXY, noiseXY);
   1044 
   1045     // Get permutation for x
   1046     {
   1047         SkString xCoords("");
   1048         xCoords.appendf("vec2(%s.x, 0.5)", noiseXY);
   1049 
   1050         noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
   1051         builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
   1052         noiseCode.append(".r;");
   1053     }
   1054 
   1055     // Get permutation for x + 1
   1056     {
   1057         SkString xCoords("");
   1058         xCoords.appendf("vec2(fract(%s.x + %s), 0.5)", noiseXY, inc8bit);
   1059 
   1060         noiseCode.appendf("\n\t%s.y = ", latticeIdx);
   1061         builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
   1062         noiseCode.append(".r;");
   1063     }
   1064 
   1065 #if defined(SK_BUILD_FOR_ANDROID)
   1066     // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
   1067     // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
   1068     // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
   1069     // (or 0.484368 here). The following rounding operation prevents these precision issues from
   1070     // affecting the result of the noise by making sure that we only have multiples of 1/255.
   1071     // (Note that 1/255 is about 0.003921569, which is the value used here).
   1072     noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);",
   1073                       latticeIdx, latticeIdx);
   1074 #endif
   1075 
   1076     // Get (x,y) coordinates with the permutated x
   1077     noiseCode.appendf("\n\t%s = fract(%s + %s.yy);", latticeIdx, latticeIdx, noiseXY);
   1078 
   1079     noiseCode.appendf("\n\tvec2 %s = %s.zw;", fractVal, noiseXY);
   1080 
   1081     noiseCode.appendf("\n\n\tvec2 %s;", uv);
   1082     // Compute u, at offset (0,0)
   1083     {
   1084         SkString latticeCoords("");
   1085         latticeCoords.appendf("vec2(%s.x, %s)", latticeIdx, chanCoord);
   1086         noiseCode.appendf("\n\tvec4 %s = ", lattice);
   1087         builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
   1088             kVec2f_GrSLType);
   1089         noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
   1090         noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
   1091     }
   1092 
   1093     noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
   1094     // Compute v, at offset (-1,0)
   1095     {
   1096         SkString latticeCoords("");
   1097         latticeCoords.appendf("vec2(%s.y, %s)", latticeIdx, chanCoord);
   1098         noiseCode.append("\n\tlattice = ");
   1099         builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
   1100             kVec2f_GrSLType);
   1101         noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
   1102         noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
   1103     }
   1104 
   1105     // Compute 'a' as a linear interpolation of 'u' and 'v'
   1106     noiseCode.appendf("\n\tvec2 %s;", ab);
   1107     noiseCode.appendf("\n\t%s.x = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
   1108 
   1109     noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
   1110     // Compute v, at offset (-1,-1)
   1111     {
   1112         SkString latticeCoords("");
   1113         latticeCoords.appendf("vec2(fract(%s.y + %s), %s)", latticeIdx, inc8bit, chanCoord);
   1114         noiseCode.append("\n\tlattice = ");
   1115         builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
   1116             kVec2f_GrSLType);
   1117         noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
   1118         noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
   1119     }
   1120 
   1121     noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
   1122     // Compute u, at offset (0,-1)
   1123     {
   1124         SkString latticeCoords("");
   1125         latticeCoords.appendf("vec2(fract(%s.x + %s), %s)", latticeIdx, inc8bit, chanCoord);
   1126         noiseCode.append("\n\tlattice = ");
   1127         builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
   1128             kVec2f_GrSLType);
   1129         noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
   1130         noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
   1131     }
   1132 
   1133     // Compute 'b' as a linear interpolation of 'u' and 'v'
   1134     noiseCode.appendf("\n\t%s.y = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
   1135     // Compute the noise as a linear interpolation of 'a' and 'b'
   1136     noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
   1137 
   1138     SkString noiseFuncName;
   1139     if (fStitchTiles) {
   1140         builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kFloat_GrSLType,
   1141                               "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
   1142                               gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
   1143     } else {
   1144         builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kFloat_GrSLType,
   1145                               "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
   1146                               gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
   1147     }
   1148 
   1149     // There are rounding errors if the floor operation is not performed here
   1150     builder->fsCodeAppendf("\n\t\tvec2 %s = floor((%s * vec3(%s, 1.0)).xy) * %s;",
   1151                            noiseVec, invMatrixUni, vCoords, baseFrequencyUni);
   1152 
   1153     // Clear the color accumulator
   1154     builder->fsCodeAppendf("\n\t\t%s = vec4(0.0);", outputColor);
   1155 
   1156     if (fStitchTiles) {
   1157         // Set up TurbulenceInitial stitch values.
   1158         builder->fsCodeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni);
   1159     }
   1160 
   1161     builder->fsCodeAppendf("\n\t\tfloat %s = 1.0;", ratio);
   1162 
   1163     // Loop over all octaves
   1164     builder->fsCodeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
   1165 
   1166     builder->fsCodeAppendf("\n\t\t\t%s += ", outputColor);
   1167     if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
   1168         builder->fsCodeAppend("abs(");
   1169     }
   1170     if (fStitchTiles) {
   1171         builder->fsCodeAppendf(
   1172             "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
   1173                  "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
   1174             noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
   1175             noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
   1176             noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
   1177             noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
   1178     } else {
   1179         builder->fsCodeAppendf(
   1180             "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
   1181                  "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
   1182             noiseFuncName.c_str(), chanCoordR, noiseVec,
   1183             noiseFuncName.c_str(), chanCoordG, noiseVec,
   1184             noiseFuncName.c_str(), chanCoordB, noiseVec,
   1185             noiseFuncName.c_str(), chanCoordA, noiseVec);
   1186     }
   1187     if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
   1188         builder->fsCodeAppendf(")"); // end of "abs("
   1189     }
   1190     builder->fsCodeAppendf(" * %s;", ratio);
   1191 
   1192     builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
   1193     builder->fsCodeAppendf("\n\t\t\t%s *= 0.5;", ratio);
   1194 
   1195     if (fStitchTiles) {
   1196         builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData);
   1197     }
   1198     builder->fsCodeAppend("\n\t\t}"); // end of the for loop on octaves
   1199 
   1200     if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
   1201         // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
   1202         // by fractalNoise and (turbulenceFunctionResult) by turbulence.
   1203         builder->fsCodeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
   1204     }
   1205 
   1206     builder->fsCodeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni);
   1207 
   1208     // Clamp values
   1209     builder->fsCodeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
   1210 
   1211     // Pre-multiply the result
   1212     builder->fsCodeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
   1213                   outputColor, outputColor, outputColor, outputColor);
   1214 }
   1215 
   1216 GrGLNoise::GrGLNoise(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect)
   1217   : INHERITED (factory)
   1218   , fType(drawEffect.castEffect<GrPerlinNoiseEffect>().type())
   1219   , fStitchTiles(drawEffect.castEffect<GrPerlinNoiseEffect>().stitchTiles())
   1220   , fNumOctaves(drawEffect.castEffect<GrPerlinNoiseEffect>().numOctaves())
   1221   , fEffectMatrix(drawEffect.castEffect<GrPerlinNoiseEffect>().coordsType()) {
   1222 }
   1223 
   1224 GrGLEffect::EffectKey GrGLNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) {
   1225     const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
   1226 
   1227     EffectKey key = turbulence.numOctaves();
   1228 
   1229     key = key << 3; // Make room for next 3 bits
   1230 
   1231     switch (turbulence.type()) {
   1232         case SkPerlinNoiseShader::kFractalNoise_Type:
   1233             key |= 0x1;
   1234             break;
   1235         case SkPerlinNoiseShader::kTurbulence_Type:
   1236             key |= 0x2;
   1237             break;
   1238         default:
   1239             // leave key at 0
   1240             break;
   1241     }
   1242 
   1243     if (turbulence.stitchTiles()) {
   1244         key |= 0x4; // Flip the 3rd bit if tile stitching is on
   1245     }
   1246 
   1247     key = key << GrGLEffectMatrix::kKeyBits;
   1248 
   1249     SkMatrix m = turbulence.matrix();
   1250     m.postTranslate(SK_Scalar1, SK_Scalar1);
   1251     return key | GrGLEffectMatrix::GenKey(m, drawEffect,
   1252                  drawEffect.castEffect<GrPerlinNoiseEffect>().coordsType(), NULL);
   1253 }
   1254 
   1255 void GrGLNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
   1256     const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
   1257 
   1258     const SkVector& baseFrequency = turbulence.baseFrequency();
   1259     uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
   1260     uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
   1261 
   1262     SkMatrix m = turbulence.matrix();
   1263     SkMatrix invM;
   1264     if (!m.invert(&invM)) {
   1265         invM.reset();
   1266     } else {
   1267         invM.postConcat(invM); // Square the matrix
   1268     }
   1269     uman.setSkMatrix(fInvMatrixUni, invM);
   1270 
   1271     // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
   1272     // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions.
   1273     m.postTranslate(SK_Scalar1, SK_Scalar1);
   1274     fEffectMatrix.setData(uman, m, drawEffect, NULL);
   1275 }
   1276 
   1277 void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
   1278     INHERITED::setData(uman, drawEffect);
   1279 
   1280     const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
   1281     if (turbulence.stitchTiles()) {
   1282         const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
   1283         uman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
   1284                                    SkIntToScalar(stitchData.fHeight));
   1285     }
   1286 }
   1287 
   1288 void GrGLSimplexNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
   1289     INHERITED::setData(uman, drawEffect);
   1290 
   1291     const GrSimplexNoiseEffect& turbulence = drawEffect.castEffect<GrSimplexNoiseEffect>();
   1292     uman.set1f(fSeedUni, turbulence.seed());
   1293 }
   1294 
   1295 /////////////////////////////////////////////////////////////////////
   1296 
   1297 GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
   1298     SkASSERT(NULL != context);
   1299 
   1300     // Either we don't stitch tiles, either we have a valid tile size
   1301     SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
   1302 
   1303 #ifdef SK_USE_SIMPLEX_NOISE
   1304     // Simplex noise is currently disabled but can be enabled by defining SK_USE_SIMPLEX_NOISE
   1305     sk_ignore_unused_variable(context);
   1306     GrEffectRef* effect =
   1307         GrSimplexNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
   1308                                      fNumOctaves, fStitchTiles, fSeed,
   1309                                      this->getLocalMatrix(), paint.getAlpha());
   1310 #else
   1311     GrTexture* permutationsTexture = GrLockAndRefCachedBitmapTexture(
   1312         context, *fPaintingData->getPermutationsBitmap(), NULL);
   1313     GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture(
   1314         context, *fPaintingData->getNoiseBitmap(), NULL);
   1315 
   1316     GrEffectRef* effect = (NULL != permutationsTexture) && (NULL != noiseTexture) ?
   1317         GrPerlinNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
   1318                                     fNumOctaves, fStitchTiles,
   1319                                     fPaintingData->fStitchDataInit,
   1320                                     permutationsTexture, noiseTexture,
   1321                                     this->getLocalMatrix(), paint.getAlpha()) :
   1322         NULL;
   1323 
   1324     // Unlock immediately, this is not great, but we don't have a way of
   1325     // knowing when else to unlock it currently. TODO: Remove this when
   1326     // unref becomes the unlock replacement for all types of textures.
   1327     if (NULL != permutationsTexture) {
   1328         GrUnlockAndUnrefCachedBitmapTexture(permutationsTexture);
   1329     }
   1330     if (NULL != noiseTexture) {
   1331         GrUnlockAndUnrefCachedBitmapTexture(noiseTexture);
   1332     }
   1333 #endif
   1334 
   1335     return effect;
   1336 }
   1337 
   1338 #else
   1339 
   1340 GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext*, const SkPaint&) const {
   1341     SkDEBUGFAIL("Should not call in GPU-less build");
   1342     return NULL;
   1343 }
   1344 
   1345 #endif
   1346 
   1347 #ifdef SK_DEVELOPER
   1348 void SkPerlinNoiseShader::toString(SkString* str) const {
   1349     str->append("SkPerlinNoiseShader: (");
   1350 
   1351     str->append("type: ");
   1352     switch (fType) {
   1353         case kFractalNoise_Type:
   1354             str->append("\"fractal noise\"");
   1355             break;
   1356         case kTurbulence_Type:
   1357             str->append("\"turbulence\"");
   1358             break;
   1359         default:
   1360             str->append("\"unknown\"");
   1361             break;
   1362     }
   1363     str->append(" base frequency: (");
   1364     str->appendScalar(fBaseFrequencyX);
   1365     str->append(", ");
   1366     str->appendScalar(fBaseFrequencyY);
   1367     str->append(") number of octaves: ");
   1368     str->appendS32(fNumOctaves);
   1369     str->append(" seed: ");
   1370     str->appendScalar(fSeed);
   1371     str->append(" stitch tiles: ");
   1372     str->append(fStitchTiles ? "true " : "false ");
   1373 
   1374     this->INHERITED::toString(str);
   1375 
   1376     str->append(")");
   1377 }
   1378 #endif
   1379