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