michael@0: /* michael@0: * Copyright 2013 Google Inc. michael@0: * michael@0: * Use of this source code is governed by a BSD-style license that can be michael@0: * found in the LICENSE file. michael@0: */ michael@0: michael@0: #include "SkDither.h" michael@0: #include "SkPerlinNoiseShader.h" michael@0: #include "SkColorFilter.h" michael@0: #include "SkReadBuffer.h" michael@0: #include "SkWriteBuffer.h" michael@0: #include "SkShader.h" michael@0: #include "SkUnPreMultiply.h" michael@0: #include "SkString.h" michael@0: michael@0: #if SK_SUPPORT_GPU michael@0: #include "GrContext.h" michael@0: #include "GrCoordTransform.h" michael@0: #include "gl/GrGLEffect.h" michael@0: #include "GrTBackendEffectFactory.h" michael@0: #include "SkGr.h" michael@0: #endif michael@0: michael@0: static const int kBlockSize = 256; michael@0: static const int kBlockMask = kBlockSize - 1; michael@0: static const int kPerlinNoise = 4096; michael@0: static const int kRandMaximum = SK_MaxS32; // 2**31 - 1 michael@0: michael@0: namespace { michael@0: michael@0: // noiseValue is the color component's value (or color) michael@0: // limitValue is the maximum perlin noise array index value allowed michael@0: // newValue is the current noise dimension (either width or height) michael@0: inline int checkNoise(int noiseValue, int limitValue, int newValue) { michael@0: // If the noise value would bring us out of bounds of the current noise array while we are michael@0: // stiching noise tiles together, wrap the noise around the current dimension of the noise to michael@0: // stay within the array bounds in a continuous fashion (so that tiling lines are not visible) michael@0: if (noiseValue >= limitValue) { michael@0: noiseValue -= newValue; michael@0: } michael@0: if (noiseValue >= limitValue - 1) { michael@0: noiseValue -= newValue - 1; michael@0: } michael@0: return noiseValue; michael@0: } michael@0: michael@0: inline SkScalar smoothCurve(SkScalar t) { michael@0: static const SkScalar SK_Scalar3 = 3.0f; michael@0: michael@0: // returns t * t * (3 - 2 * t) michael@0: return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t); michael@0: } michael@0: michael@0: bool perlin_noise_type_is_valid(SkPerlinNoiseShader::Type type) { michael@0: return (SkPerlinNoiseShader::kFractalNoise_Type == type) || michael@0: (SkPerlinNoiseShader::kTurbulence_Type == type); michael@0: } michael@0: michael@0: } // end namespace michael@0: michael@0: struct SkPerlinNoiseShader::StitchData { michael@0: StitchData() michael@0: : fWidth(0) michael@0: , fWrapX(0) michael@0: , fHeight(0) michael@0: , fWrapY(0) michael@0: {} michael@0: michael@0: bool operator==(const StitchData& other) const { michael@0: return fWidth == other.fWidth && michael@0: fWrapX == other.fWrapX && michael@0: fHeight == other.fHeight && michael@0: fWrapY == other.fWrapY; michael@0: } michael@0: michael@0: int fWidth; // How much to subtract to wrap for stitching. michael@0: int fWrapX; // Minimum value to wrap. michael@0: int fHeight; michael@0: int fWrapY; michael@0: }; michael@0: michael@0: struct SkPerlinNoiseShader::PaintingData { michael@0: PaintingData(const SkISize& tileSize, SkScalar seed, michael@0: SkScalar baseFrequencyX, SkScalar baseFrequencyY) michael@0: : fTileSize(tileSize) michael@0: , fBaseFrequency(SkPoint::Make(baseFrequencyX, baseFrequencyY)) michael@0: { michael@0: this->init(seed); michael@0: if (!fTileSize.isEmpty()) { michael@0: this->stitch(); michael@0: } michael@0: michael@0: #if SK_SUPPORT_GPU && !defined(SK_USE_SIMPLEX_NOISE) michael@0: fPermutationsBitmap.setConfig(SkImageInfo::MakeA8(kBlockSize, 1)); michael@0: fPermutationsBitmap.setPixels(fLatticeSelector); michael@0: michael@0: fNoiseBitmap.setConfig(SkImageInfo::MakeN32Premul(kBlockSize, 4)); michael@0: fNoiseBitmap.setPixels(fNoise[0][0]); michael@0: #endif michael@0: } michael@0: michael@0: int fSeed; michael@0: uint8_t fLatticeSelector[kBlockSize]; michael@0: uint16_t fNoise[4][kBlockSize][2]; michael@0: SkPoint fGradient[4][kBlockSize]; michael@0: SkISize fTileSize; michael@0: SkVector fBaseFrequency; michael@0: StitchData fStitchDataInit; michael@0: michael@0: private: michael@0: michael@0: #if SK_SUPPORT_GPU && !defined(SK_USE_SIMPLEX_NOISE) michael@0: SkBitmap fPermutationsBitmap; michael@0: SkBitmap fNoiseBitmap; michael@0: #endif michael@0: michael@0: inline int random() { michael@0: static const int gRandAmplitude = 16807; // 7**5; primitive root of m michael@0: static const int gRandQ = 127773; // m / a michael@0: static const int gRandR = 2836; // m % a michael@0: michael@0: int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ); michael@0: if (result <= 0) michael@0: result += kRandMaximum; michael@0: fSeed = result; michael@0: return result; michael@0: } michael@0: michael@0: // Only called once. Could be part of the constructor. michael@0: void init(SkScalar seed) michael@0: { michael@0: static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize)); michael@0: michael@0: // According to the SVG spec, we must truncate (not round) the seed value. michael@0: fSeed = SkScalarTruncToInt(seed); michael@0: // The seed value clamp to the range [1, kRandMaximum - 1]. michael@0: if (fSeed <= 0) { michael@0: fSeed = -(fSeed % (kRandMaximum - 1)) + 1; michael@0: } michael@0: if (fSeed > kRandMaximum - 1) { michael@0: fSeed = kRandMaximum - 1; michael@0: } michael@0: for (int channel = 0; channel < 4; ++channel) { michael@0: for (int i = 0; i < kBlockSize; ++i) { michael@0: fLatticeSelector[i] = i; michael@0: fNoise[channel][i][0] = (random() % (2 * kBlockSize)); michael@0: fNoise[channel][i][1] = (random() % (2 * kBlockSize)); michael@0: } michael@0: } michael@0: for (int i = kBlockSize - 1; i > 0; --i) { michael@0: int k = fLatticeSelector[i]; michael@0: int j = random() % kBlockSize; michael@0: SkASSERT(j >= 0); michael@0: SkASSERT(j < kBlockSize); michael@0: fLatticeSelector[i] = fLatticeSelector[j]; michael@0: fLatticeSelector[j] = k; michael@0: } michael@0: michael@0: // Perform the permutations now michael@0: { michael@0: // Copy noise data michael@0: uint16_t noise[4][kBlockSize][2]; michael@0: for (int i = 0; i < kBlockSize; ++i) { michael@0: for (int channel = 0; channel < 4; ++channel) { michael@0: for (int j = 0; j < 2; ++j) { michael@0: noise[channel][i][j] = fNoise[channel][i][j]; michael@0: } michael@0: } michael@0: } michael@0: // Do permutations on noise data michael@0: for (int i = 0; i < kBlockSize; ++i) { michael@0: for (int channel = 0; channel < 4; ++channel) { michael@0: for (int j = 0; j < 2; ++j) { michael@0: fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j]; michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Half of the largest possible value for 16 bit unsigned int michael@0: static const SkScalar gHalfMax16bits = 32767.5f; michael@0: michael@0: // Compute gradients from permutated noise data michael@0: for (int channel = 0; channel < 4; ++channel) { michael@0: for (int i = 0; i < kBlockSize; ++i) { michael@0: fGradient[channel][i] = SkPoint::Make( michael@0: SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize), michael@0: gInvBlockSizef), michael@0: SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize), michael@0: gInvBlockSizef)); michael@0: fGradient[channel][i].normalize(); michael@0: // Put the normalized gradient back into the noise data michael@0: fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul( michael@0: fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits)); michael@0: fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul( michael@0: fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits)); michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Only called once. Could be part of the constructor. michael@0: void stitch() { michael@0: SkScalar tileWidth = SkIntToScalar(fTileSize.width()); michael@0: SkScalar tileHeight = SkIntToScalar(fTileSize.height()); michael@0: SkASSERT(tileWidth > 0 && tileHeight > 0); michael@0: // When stitching tiled turbulence, the frequencies must be adjusted michael@0: // so that the tile borders will be continuous. michael@0: if (fBaseFrequency.fX) { michael@0: SkScalar lowFrequencx = michael@0: SkScalarFloorToScalar(tileWidth * fBaseFrequency.fX) / tileWidth; michael@0: SkScalar highFrequencx = michael@0: SkScalarCeilToScalar(tileWidth * fBaseFrequency.fX) / tileWidth; michael@0: // BaseFrequency should be non-negative according to the standard. michael@0: if (SkScalarDiv(fBaseFrequency.fX, lowFrequencx) < michael@0: SkScalarDiv(highFrequencx, fBaseFrequency.fX)) { michael@0: fBaseFrequency.fX = lowFrequencx; michael@0: } else { michael@0: fBaseFrequency.fX = highFrequencx; michael@0: } michael@0: } michael@0: if (fBaseFrequency.fY) { michael@0: SkScalar lowFrequency = michael@0: SkScalarFloorToScalar(tileHeight * fBaseFrequency.fY) / tileHeight; michael@0: SkScalar highFrequency = michael@0: SkScalarCeilToScalar(tileHeight * fBaseFrequency.fY) / tileHeight; michael@0: if (SkScalarDiv(fBaseFrequency.fY, lowFrequency) < michael@0: SkScalarDiv(highFrequency, fBaseFrequency.fY)) { michael@0: fBaseFrequency.fY = lowFrequency; michael@0: } else { michael@0: fBaseFrequency.fY = highFrequency; michael@0: } michael@0: } michael@0: // Set up TurbulenceInitial stitch values. michael@0: fStitchDataInit.fWidth = michael@0: SkScalarRoundToInt(tileWidth * fBaseFrequency.fX); michael@0: fStitchDataInit.fWrapX = kPerlinNoise + fStitchDataInit.fWidth; michael@0: fStitchDataInit.fHeight = michael@0: SkScalarRoundToInt(tileHeight * fBaseFrequency.fY); michael@0: fStitchDataInit.fWrapY = kPerlinNoise + fStitchDataInit.fHeight; michael@0: } michael@0: michael@0: public: michael@0: michael@0: #if SK_SUPPORT_GPU && !defined(SK_USE_SIMPLEX_NOISE) michael@0: const SkBitmap& getPermutationsBitmap() const { return fPermutationsBitmap; } michael@0: michael@0: const SkBitmap& getNoiseBitmap() const { return fNoiseBitmap; } michael@0: #endif michael@0: }; michael@0: michael@0: SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY, michael@0: int numOctaves, SkScalar seed, michael@0: const SkISize* tileSize) { michael@0: return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY, michael@0: numOctaves, seed, tileSize)); michael@0: } michael@0: michael@0: SkShader* SkPerlinNoiseShader::CreateTubulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY, michael@0: int numOctaves, SkScalar seed, michael@0: const SkISize* tileSize) { michael@0: return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY, michael@0: numOctaves, seed, tileSize)); michael@0: } michael@0: michael@0: SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type, michael@0: SkScalar baseFrequencyX, michael@0: SkScalar baseFrequencyY, michael@0: int numOctaves, michael@0: SkScalar seed, michael@0: const SkISize* tileSize) michael@0: : fType(type) michael@0: , fBaseFrequencyX(baseFrequencyX) michael@0: , fBaseFrequencyY(baseFrequencyY) michael@0: , fNumOctaves(numOctaves > 255 ? 255 : numOctaves/*[0,255] octaves allowed*/) michael@0: , fSeed(seed) michael@0: , fTileSize(NULL == tileSize ? SkISize::Make(0, 0) : *tileSize) michael@0: , fStitchTiles(!fTileSize.isEmpty()) michael@0: { michael@0: SkASSERT(numOctaves >= 0 && numOctaves < 256); michael@0: fMatrix.reset(); michael@0: fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize, fSeed, fBaseFrequencyX, fBaseFrequencyY)); michael@0: } michael@0: michael@0: SkPerlinNoiseShader::SkPerlinNoiseShader(SkReadBuffer& buffer) michael@0: : INHERITED(buffer) michael@0: { michael@0: fType = (SkPerlinNoiseShader::Type) buffer.readInt(); michael@0: fBaseFrequencyX = buffer.readScalar(); michael@0: fBaseFrequencyY = buffer.readScalar(); michael@0: fNumOctaves = buffer.readInt(); michael@0: fSeed = buffer.readScalar(); michael@0: fStitchTiles = buffer.readBool(); michael@0: fTileSize.fWidth = buffer.readInt(); michael@0: fTileSize.fHeight = buffer.readInt(); michael@0: fMatrix.reset(); michael@0: fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize, fSeed, fBaseFrequencyX, fBaseFrequencyY)); michael@0: buffer.validate(perlin_noise_type_is_valid(fType) && michael@0: (fNumOctaves >= 0) && (fNumOctaves <= 255) && michael@0: (fStitchTiles != fTileSize.isEmpty())); michael@0: } michael@0: michael@0: SkPerlinNoiseShader::~SkPerlinNoiseShader() { michael@0: // Safety, should have been done in endContext() michael@0: SkDELETE(fPaintingData); michael@0: } michael@0: michael@0: void SkPerlinNoiseShader::flatten(SkWriteBuffer& buffer) const { michael@0: this->INHERITED::flatten(buffer); michael@0: buffer.writeInt((int) fType); michael@0: buffer.writeScalar(fBaseFrequencyX); michael@0: buffer.writeScalar(fBaseFrequencyY); michael@0: buffer.writeInt(fNumOctaves); michael@0: buffer.writeScalar(fSeed); michael@0: buffer.writeBool(fStitchTiles); michael@0: buffer.writeInt(fTileSize.fWidth); michael@0: buffer.writeInt(fTileSize.fHeight); michael@0: } michael@0: michael@0: SkScalar SkPerlinNoiseShader::noise2D(int channel, const PaintingData& paintingData, michael@0: const StitchData& stitchData, michael@0: const SkPoint& noiseVector) const { michael@0: struct Noise { michael@0: int noisePositionIntegerValue; michael@0: SkScalar noisePositionFractionValue; michael@0: Noise(SkScalar component) michael@0: { michael@0: SkScalar position = component + kPerlinNoise; michael@0: noisePositionIntegerValue = SkScalarFloorToInt(position); michael@0: noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue); michael@0: } michael@0: }; michael@0: Noise noiseX(noiseVector.x()); michael@0: Noise noiseY(noiseVector.y()); michael@0: SkScalar u, v; michael@0: // If stitching, adjust lattice points accordingly. michael@0: if (fStitchTiles) { michael@0: noiseX.noisePositionIntegerValue = michael@0: checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth); michael@0: noiseY.noisePositionIntegerValue = michael@0: checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight); michael@0: } michael@0: noiseX.noisePositionIntegerValue &= kBlockMask; michael@0: noiseY.noisePositionIntegerValue &= kBlockMask; michael@0: int latticeIndex = michael@0: paintingData.fLatticeSelector[noiseX.noisePositionIntegerValue] + michael@0: noiseY.noisePositionIntegerValue; michael@0: int nextLatticeIndex = michael@0: paintingData.fLatticeSelector[(noiseX.noisePositionIntegerValue + 1) & kBlockMask] + michael@0: noiseY.noisePositionIntegerValue; michael@0: SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue); michael@0: SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue); michael@0: // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement michael@0: SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue, michael@0: noiseY.noisePositionFractionValue); // Offset (0,0) michael@0: u = paintingData.fGradient[channel][latticeIndex & kBlockMask].dot(fractionValue); michael@0: fractionValue.fX -= SK_Scalar1; // Offset (-1,0) michael@0: v = paintingData.fGradient[channel][nextLatticeIndex & kBlockMask].dot(fractionValue); michael@0: SkScalar a = SkScalarInterp(u, v, sx); michael@0: fractionValue.fY -= SK_Scalar1; // Offset (-1,-1) michael@0: v = paintingData.fGradient[channel][(nextLatticeIndex + 1) & kBlockMask].dot(fractionValue); michael@0: fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1) michael@0: u = paintingData.fGradient[channel][(latticeIndex + 1) & kBlockMask].dot(fractionValue); michael@0: SkScalar b = SkScalarInterp(u, v, sx); michael@0: return SkScalarInterp(a, b, sy); michael@0: } michael@0: michael@0: SkScalar SkPerlinNoiseShader::calculateTurbulenceValueForPoint(int channel, michael@0: const PaintingData& paintingData, michael@0: StitchData& stitchData, michael@0: const SkPoint& point) const { michael@0: if (fStitchTiles) { michael@0: // Set up TurbulenceInitial stitch values. michael@0: stitchData = paintingData.fStitchDataInit; michael@0: } michael@0: SkScalar turbulenceFunctionResult = 0; michael@0: SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), paintingData.fBaseFrequency.fX), michael@0: SkScalarMul(point.y(), paintingData.fBaseFrequency.fY))); michael@0: SkScalar ratio = SK_Scalar1; michael@0: for (int octave = 0; octave < fNumOctaves; ++octave) { michael@0: SkScalar noise = noise2D(channel, paintingData, stitchData, noiseVector); michael@0: turbulenceFunctionResult += SkScalarDiv( michael@0: (fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio); michael@0: noiseVector.fX *= 2; michael@0: noiseVector.fY *= 2; michael@0: ratio *= 2; michael@0: if (fStitchTiles) { michael@0: // Update stitch values michael@0: stitchData.fWidth *= 2; michael@0: stitchData.fWrapX = stitchData.fWidth + kPerlinNoise; michael@0: stitchData.fHeight *= 2; michael@0: stitchData.fWrapY = stitchData.fHeight + kPerlinNoise; michael@0: } michael@0: } michael@0: michael@0: // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2 michael@0: // by fractalNoise and (turbulenceFunctionResult) by turbulence. michael@0: if (fType == kFractalNoise_Type) { michael@0: turbulenceFunctionResult = michael@0: SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf; michael@0: } michael@0: michael@0: if (channel == 3) { // Scale alpha by paint value michael@0: turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult, michael@0: SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255))); michael@0: } michael@0: michael@0: // Clamp result michael@0: return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1); michael@0: } michael@0: michael@0: SkPMColor SkPerlinNoiseShader::shade(const SkPoint& point, StitchData& stitchData) const { michael@0: SkMatrix matrix = fMatrix; michael@0: matrix.postConcat(getLocalMatrix()); michael@0: SkMatrix invMatrix; michael@0: if (!matrix.invert(&invMatrix)) { michael@0: invMatrix.reset(); michael@0: } else { michael@0: invMatrix.postConcat(invMatrix); // Square the matrix michael@0: } michael@0: // This (1,1) translation is due to WebKit's 1 based coordinates for the noise michael@0: // (as opposed to 0 based, usually). The same adjustment is in the setData() function. michael@0: matrix.postTranslate(SK_Scalar1, SK_Scalar1); michael@0: SkPoint newPoint; michael@0: matrix.mapPoints(&newPoint, &point, 1); michael@0: invMatrix.mapPoints(&newPoint, &newPoint, 1); michael@0: newPoint.fX = SkScalarRoundToScalar(newPoint.fX); michael@0: newPoint.fY = SkScalarRoundToScalar(newPoint.fY); michael@0: michael@0: U8CPU rgba[4]; michael@0: for (int channel = 3; channel >= 0; --channel) { michael@0: rgba[channel] = SkScalarFloorToInt(255 * michael@0: calculateTurbulenceValueForPoint(channel, *fPaintingData, stitchData, newPoint)); michael@0: } michael@0: return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]); michael@0: } michael@0: michael@0: bool SkPerlinNoiseShader::setContext(const SkBitmap& device, const SkPaint& paint, michael@0: const SkMatrix& matrix) { michael@0: fMatrix = matrix; michael@0: return INHERITED::setContext(device, paint, matrix); michael@0: } michael@0: michael@0: void SkPerlinNoiseShader::shadeSpan(int x, int y, SkPMColor result[], int count) { michael@0: SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y)); michael@0: StitchData stitchData; michael@0: for (int i = 0; i < count; ++i) { michael@0: result[i] = shade(point, stitchData); michael@0: point.fX += SK_Scalar1; michael@0: } michael@0: } michael@0: michael@0: void SkPerlinNoiseShader::shadeSpan16(int x, int y, uint16_t result[], int count) { michael@0: SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y)); michael@0: StitchData stitchData; michael@0: DITHER_565_SCAN(y); michael@0: for (int i = 0; i < count; ++i) { michael@0: unsigned dither = DITHER_VALUE(x); michael@0: result[i] = SkDitherRGB32To565(shade(point, stitchData), dither); michael@0: DITHER_INC_X(x); michael@0: point.fX += SK_Scalar1; michael@0: } michael@0: } michael@0: michael@0: ///////////////////////////////////////////////////////////////////// michael@0: michael@0: #if SK_SUPPORT_GPU michael@0: michael@0: #include "GrTBackendEffectFactory.h" michael@0: michael@0: class GrGLNoise : public GrGLEffect { michael@0: public: michael@0: GrGLNoise(const GrBackendEffectFactory& factory, michael@0: const GrDrawEffect& drawEffect); michael@0: virtual ~GrGLNoise() {} michael@0: michael@0: static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&); michael@0: michael@0: virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE; michael@0: michael@0: protected: michael@0: SkPerlinNoiseShader::Type fType; michael@0: bool fStitchTiles; michael@0: int fNumOctaves; michael@0: GrGLUniformManager::UniformHandle fBaseFrequencyUni; michael@0: GrGLUniformManager::UniformHandle fAlphaUni; michael@0: GrGLUniformManager::UniformHandle fInvMatrixUni; michael@0: michael@0: private: michael@0: typedef GrGLEffect INHERITED; michael@0: }; michael@0: michael@0: class GrGLPerlinNoise : public GrGLNoise { michael@0: public: michael@0: GrGLPerlinNoise(const GrBackendEffectFactory& factory, michael@0: const GrDrawEffect& drawEffect) michael@0: : GrGLNoise(factory, drawEffect) {} michael@0: virtual ~GrGLPerlinNoise() {} michael@0: michael@0: virtual void emitCode(GrGLShaderBuilder*, michael@0: const GrDrawEffect&, michael@0: EffectKey, michael@0: const char* outputColor, michael@0: const char* inputColor, michael@0: const TransformedCoordsArray&, michael@0: const TextureSamplerArray&) SK_OVERRIDE; michael@0: michael@0: virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE; michael@0: michael@0: private: michael@0: GrGLUniformManager::UniformHandle fStitchDataUni; michael@0: michael@0: typedef GrGLNoise INHERITED; michael@0: }; michael@0: michael@0: class GrGLSimplexNoise : public GrGLNoise { michael@0: // Note : This is for reference only. GrGLPerlinNoise is used for processing. michael@0: public: michael@0: GrGLSimplexNoise(const GrBackendEffectFactory& factory, michael@0: const GrDrawEffect& drawEffect) michael@0: : GrGLNoise(factory, drawEffect) {} michael@0: michael@0: virtual ~GrGLSimplexNoise() {} michael@0: michael@0: virtual void emitCode(GrGLShaderBuilder*, michael@0: const GrDrawEffect&, michael@0: EffectKey, michael@0: const char* outputColor, michael@0: const char* inputColor, michael@0: const TransformedCoordsArray&, michael@0: const TextureSamplerArray&) SK_OVERRIDE; michael@0: michael@0: virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE; michael@0: michael@0: private: michael@0: GrGLUniformManager::UniformHandle fSeedUni; michael@0: michael@0: typedef GrGLNoise INHERITED; michael@0: }; michael@0: michael@0: ///////////////////////////////////////////////////////////////////// michael@0: michael@0: class GrNoiseEffect : public GrEffect { michael@0: public: michael@0: virtual ~GrNoiseEffect() { } michael@0: michael@0: SkPerlinNoiseShader::Type type() const { return fType; } michael@0: bool stitchTiles() const { return fStitchTiles; } michael@0: const SkVector& baseFrequency() const { return fBaseFrequency; } michael@0: int numOctaves() const { return fNumOctaves; } michael@0: const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); } michael@0: uint8_t alpha() const { return fAlpha; } michael@0: michael@0: void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE { michael@0: *validFlags = 0; // This is noise. Nothing is constant. michael@0: } michael@0: michael@0: protected: michael@0: virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE { michael@0: const GrNoiseEffect& s = CastEffect(sBase); michael@0: return fType == s.fType && michael@0: fBaseFrequency == s.fBaseFrequency && michael@0: fNumOctaves == s.fNumOctaves && michael@0: fStitchTiles == s.fStitchTiles && michael@0: fCoordTransform.getMatrix() == s.fCoordTransform.getMatrix() && michael@0: fAlpha == s.fAlpha; michael@0: } michael@0: michael@0: GrNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, int numOctaves, michael@0: bool stitchTiles, const SkMatrix& matrix, uint8_t alpha) michael@0: : fType(type) michael@0: , fBaseFrequency(baseFrequency) michael@0: , fNumOctaves(numOctaves) michael@0: , fStitchTiles(stitchTiles) michael@0: , fMatrix(matrix) michael@0: , fAlpha(alpha) { michael@0: // This (1,1) translation is due to WebKit's 1 based coordinates for the noise michael@0: // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions. michael@0: SkMatrix m = matrix; michael@0: m.postTranslate(SK_Scalar1, SK_Scalar1); michael@0: fCoordTransform.reset(kLocal_GrCoordSet, m); michael@0: this->addCoordTransform(&fCoordTransform); michael@0: this->setWillNotUseInputColor(); michael@0: } michael@0: michael@0: SkPerlinNoiseShader::Type fType; michael@0: GrCoordTransform fCoordTransform; michael@0: SkVector fBaseFrequency; michael@0: int fNumOctaves; michael@0: bool fStitchTiles; michael@0: SkMatrix fMatrix; michael@0: uint8_t fAlpha; michael@0: michael@0: private: michael@0: typedef GrEffect INHERITED; michael@0: }; michael@0: michael@0: class GrPerlinNoiseEffect : public GrNoiseEffect { michael@0: public: michael@0: static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, michael@0: int numOctaves, bool stitchTiles, michael@0: const SkPerlinNoiseShader::StitchData& stitchData, michael@0: GrTexture* permutationsTexture, GrTexture* noiseTexture, michael@0: const SkMatrix& matrix, uint8_t alpha) { michael@0: AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves, michael@0: stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha))); michael@0: return CreateEffectRef(effect); michael@0: } michael@0: michael@0: virtual ~GrPerlinNoiseEffect() { } michael@0: michael@0: static const char* Name() { return "PerlinNoise"; } michael@0: virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE { michael@0: return GrTBackendEffectFactory::getInstance(); michael@0: } michael@0: const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; } michael@0: michael@0: typedef GrGLPerlinNoise GLEffect; michael@0: michael@0: private: michael@0: virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE { michael@0: const GrPerlinNoiseEffect& s = CastEffect(sBase); michael@0: return INHERITED::onIsEqual(sBase) && michael@0: fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() && michael@0: fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() && michael@0: fStitchData == s.fStitchData; michael@0: } michael@0: michael@0: GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, michael@0: int numOctaves, bool stitchTiles, michael@0: const SkPerlinNoiseShader::StitchData& stitchData, michael@0: GrTexture* permutationsTexture, GrTexture* noiseTexture, michael@0: const SkMatrix& matrix, uint8_t alpha) michael@0: : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha) michael@0: , fPermutationsAccess(permutationsTexture) michael@0: , fNoiseAccess(noiseTexture) michael@0: , fStitchData(stitchData) { michael@0: this->addTextureAccess(&fPermutationsAccess); michael@0: this->addTextureAccess(&fNoiseAccess); michael@0: } michael@0: michael@0: GR_DECLARE_EFFECT_TEST; michael@0: michael@0: GrTextureAccess fPermutationsAccess; michael@0: GrTextureAccess fNoiseAccess; michael@0: SkPerlinNoiseShader::StitchData fStitchData; michael@0: michael@0: typedef GrNoiseEffect INHERITED; michael@0: }; michael@0: michael@0: class GrSimplexNoiseEffect : public GrNoiseEffect { michael@0: // Note : This is for reference only. GrPerlinNoiseEffect is used for processing. michael@0: public: michael@0: static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, michael@0: int numOctaves, bool stitchTiles, const SkScalar seed, michael@0: const SkMatrix& matrix, uint8_t alpha) { michael@0: AutoEffectUnref effect(SkNEW_ARGS(GrSimplexNoiseEffect, (type, baseFrequency, numOctaves, michael@0: stitchTiles, seed, matrix, alpha))); michael@0: return CreateEffectRef(effect); michael@0: } michael@0: michael@0: virtual ~GrSimplexNoiseEffect() { } michael@0: michael@0: static const char* Name() { return "SimplexNoise"; } michael@0: virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE { michael@0: return GrTBackendEffectFactory::getInstance(); michael@0: } michael@0: const SkScalar& seed() const { return fSeed; } michael@0: michael@0: typedef GrGLSimplexNoise GLEffect; michael@0: michael@0: private: michael@0: virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE { michael@0: const GrSimplexNoiseEffect& s = CastEffect(sBase); michael@0: return INHERITED::onIsEqual(sBase) && fSeed == s.fSeed; michael@0: } michael@0: michael@0: GrSimplexNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, michael@0: int numOctaves, bool stitchTiles, const SkScalar seed, michael@0: const SkMatrix& matrix, uint8_t alpha) michael@0: : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha) michael@0: , fSeed(seed) { michael@0: } michael@0: michael@0: SkScalar fSeed; michael@0: michael@0: typedef GrNoiseEffect INHERITED; michael@0: }; michael@0: michael@0: ///////////////////////////////////////////////////////////////////// michael@0: GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect); michael@0: michael@0: GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkRandom* random, michael@0: GrContext* context, michael@0: const GrDrawTargetCaps&, michael@0: GrTexture**) { michael@0: int numOctaves = random->nextRangeU(2, 10); michael@0: bool stitchTiles = random->nextBool(); michael@0: SkScalar seed = SkIntToScalar(random->nextU()); michael@0: SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096)); michael@0: SkScalar baseFrequencyX = random->nextRangeScalar(0.01f, michael@0: 0.99f); michael@0: SkScalar baseFrequencyY = random->nextRangeScalar(0.01f, michael@0: 0.99f); michael@0: michael@0: SkShader* shader = random->nextBool() ? michael@0: SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed, michael@0: stitchTiles ? &tileSize : NULL) : michael@0: SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed, michael@0: stitchTiles ? &tileSize : NULL); michael@0: michael@0: SkPaint paint; michael@0: GrEffectRef* effect = shader->asNewEffect(context, paint); michael@0: michael@0: SkDELETE(shader); michael@0: michael@0: return effect; michael@0: } michael@0: michael@0: ///////////////////////////////////////////////////////////////////// michael@0: michael@0: void GrGLSimplexNoise::emitCode(GrGLShaderBuilder* builder, michael@0: const GrDrawEffect&, michael@0: EffectKey key, michael@0: const char* outputColor, michael@0: const char* inputColor, michael@0: const TransformedCoordsArray& coords, michael@0: const TextureSamplerArray&) { michael@0: sk_ignore_unused_variable(inputColor); michael@0: michael@0: SkString vCoords = builder->ensureFSCoords2D(coords, 0); michael@0: michael@0: fSeedUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, michael@0: kFloat_GrSLType, "seed"); michael@0: const char* seedUni = builder->getUniformCStr(fSeedUni); michael@0: fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, michael@0: kMat33f_GrSLType, "invMatrix"); michael@0: const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni); michael@0: fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, michael@0: kVec2f_GrSLType, "baseFrequency"); michael@0: const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni); michael@0: fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, michael@0: kFloat_GrSLType, "alpha"); michael@0: const char* alphaUni = builder->getUniformCStr(fAlphaUni); michael@0: michael@0: // Add vec3 modulo 289 function michael@0: static const GrGLShaderVar gVec3Args[] = { michael@0: GrGLShaderVar("x", kVec3f_GrSLType) michael@0: }; michael@0: michael@0: SkString mod289_3_funcName; michael@0: builder->fsEmitFunction(kVec3f_GrSLType, michael@0: "mod289", SK_ARRAY_COUNT(gVec3Args), gVec3Args, michael@0: "const vec2 C = vec2(1.0 / 289.0, 289.0);\n" michael@0: "return x - floor(x * C.xxx) * C.yyy;", &mod289_3_funcName); michael@0: michael@0: // Add vec4 modulo 289 function michael@0: static const GrGLShaderVar gVec4Args[] = { michael@0: GrGLShaderVar("x", kVec4f_GrSLType) michael@0: }; michael@0: michael@0: SkString mod289_4_funcName; michael@0: builder->fsEmitFunction(kVec4f_GrSLType, michael@0: "mod289", SK_ARRAY_COUNT(gVec4Args), gVec4Args, michael@0: "const vec2 C = vec2(1.0 / 289.0, 289.0);\n" michael@0: "return x - floor(x * C.xxxx) * C.yyyy;", &mod289_4_funcName); michael@0: michael@0: // Add vec4 permute function michael@0: SkString permuteCode; michael@0: permuteCode.appendf("const vec2 C = vec2(34.0, 1.0);\n" michael@0: "return %s(((x * C.xxxx) + C.yyyy) * x);", mod289_4_funcName.c_str()); michael@0: SkString permuteFuncName; michael@0: builder->fsEmitFunction(kVec4f_GrSLType, michael@0: "permute", SK_ARRAY_COUNT(gVec4Args), gVec4Args, michael@0: permuteCode.c_str(), &permuteFuncName); michael@0: michael@0: // Add vec4 taylorInvSqrt function michael@0: SkString taylorInvSqrtFuncName; michael@0: builder->fsEmitFunction(kVec4f_GrSLType, michael@0: "taylorInvSqrt", SK_ARRAY_COUNT(gVec4Args), gVec4Args, michael@0: "const vec2 C = vec2(-0.85373472095314, 1.79284291400159);\n" michael@0: "return x * C.xxxx + C.yyyy;", &taylorInvSqrtFuncName); michael@0: michael@0: // Add vec3 noise function michael@0: static const GrGLShaderVar gNoiseVec3Args[] = { michael@0: GrGLShaderVar("v", kVec3f_GrSLType) michael@0: }; michael@0: michael@0: SkString noiseCode; michael@0: noiseCode.append( michael@0: "const vec2 C = vec2(1.0/6.0, 1.0/3.0);\n" michael@0: "const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n" michael@0: michael@0: // First corner michael@0: "vec3 i = floor(v + dot(v, C.yyy));\n" michael@0: "vec3 x0 = v - i + dot(i, C.xxx);\n" michael@0: michael@0: // Other corners michael@0: "vec3 g = step(x0.yzx, x0.xyz);\n" michael@0: "vec3 l = 1.0 - g;\n" michael@0: "vec3 i1 = min(g.xyz, l.zxy);\n" michael@0: "vec3 i2 = max(g.xyz, l.zxy);\n" michael@0: michael@0: "vec3 x1 = x0 - i1 + C.xxx;\n" michael@0: "vec3 x2 = x0 - i2 + C.yyy;\n" // 2.0*C.x = 1/3 = C.y michael@0: "vec3 x3 = x0 - D.yyy;\n" // -1.0+3.0*C.x = -0.5 = -D.y michael@0: ); michael@0: michael@0: noiseCode.appendf( michael@0: // Permutations michael@0: "i = %s(i);\n" michael@0: "vec4 p = %s(%s(%s(\n" michael@0: " i.z + vec4(0.0, i1.z, i2.z, 1.0)) +\n" michael@0: " i.y + vec4(0.0, i1.y, i2.y, 1.0)) +\n" michael@0: " i.x + vec4(0.0, i1.x, i2.x, 1.0));\n", michael@0: mod289_3_funcName.c_str(), permuteFuncName.c_str(), permuteFuncName.c_str(), michael@0: permuteFuncName.c_str()); michael@0: michael@0: noiseCode.append( michael@0: // Gradients: 7x7 points over a square, mapped onto an octahedron. michael@0: // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294) michael@0: "float n_ = 0.142857142857;\n" // 1.0/7.0 michael@0: "vec3 ns = n_ * D.wyz - D.xzx;\n" michael@0: michael@0: "vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\n" // mod(p,7*7) michael@0: michael@0: "vec4 x_ = floor(j * ns.z);\n" michael@0: "vec4 y_ = floor(j - 7.0 * x_);" // mod(j,N) michael@0: michael@0: "vec4 x = x_ *ns.x + ns.yyyy;\n" michael@0: "vec4 y = y_ *ns.x + ns.yyyy;\n" michael@0: "vec4 h = 1.0 - abs(x) - abs(y);\n" michael@0: michael@0: "vec4 b0 = vec4(x.xy, y.xy);\n" michael@0: "vec4 b1 = vec4(x.zw, y.zw);\n" michael@0: ); michael@0: michael@0: noiseCode.append( michael@0: "vec4 s0 = floor(b0) * 2.0 + 1.0;\n" michael@0: "vec4 s1 = floor(b1) * 2.0 + 1.0;\n" michael@0: "vec4 sh = -step(h, vec4(0.0));\n" michael@0: michael@0: "vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;\n" michael@0: "vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;\n" michael@0: michael@0: "vec3 p0 = vec3(a0.xy, h.x);\n" michael@0: "vec3 p1 = vec3(a0.zw, h.y);\n" michael@0: "vec3 p2 = vec3(a1.xy, h.z);\n" michael@0: "vec3 p3 = vec3(a1.zw, h.w);\n" michael@0: ); michael@0: michael@0: noiseCode.appendf( michael@0: // Normalise gradients michael@0: "vec4 norm = %s(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n" michael@0: "p0 *= norm.x;\n" michael@0: "p1 *= norm.y;\n" michael@0: "p2 *= norm.z;\n" michael@0: "p3 *= norm.w;\n" michael@0: michael@0: // Mix final noise value michael@0: "vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n" michael@0: "m = m * m;\n" michael@0: "return 42.0 * dot(m*m, vec4(dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3)));", michael@0: taylorInvSqrtFuncName.c_str()); michael@0: michael@0: SkString noiseFuncName; michael@0: builder->fsEmitFunction(kFloat_GrSLType, michael@0: "snoise", SK_ARRAY_COUNT(gNoiseVec3Args), gNoiseVec3Args, michael@0: noiseCode.c_str(), &noiseFuncName); michael@0: michael@0: const char* noiseVecIni = "noiseVecIni"; michael@0: const char* factors = "factors"; michael@0: const char* sum = "sum"; michael@0: const char* xOffsets = "xOffsets"; michael@0: const char* yOffsets = "yOffsets"; michael@0: const char* channel = "channel"; michael@0: michael@0: // Fill with some prime numbers michael@0: builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(13.0, 53.0, 101.0, 151.0);\n", xOffsets); michael@0: builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(109.0, 167.0, 23.0, 67.0);\n", yOffsets); michael@0: michael@0: // There are rounding errors if the floor operation is not performed here michael@0: builder->fsCodeAppendf( michael@0: "\t\tvec3 %s = vec3(floor((%s*vec3(%s, 1.0)).xy) * vec2(0.66) * %s, 0.0);\n", michael@0: noiseVecIni, invMatrixUni, vCoords.c_str(), baseFrequencyUni); michael@0: michael@0: // Perturb the texcoords with three components of noise michael@0: builder->fsCodeAppendf("\t\t%s += 0.1 * vec3(%s(%s + vec3( 0.0, 0.0, %s))," michael@0: "%s(%s + vec3( 43.0, 17.0, %s))," michael@0: "%s(%s + vec3(-17.0, -43.0, %s)));\n", michael@0: noiseVecIni, noiseFuncName.c_str(), noiseVecIni, seedUni, michael@0: noiseFuncName.c_str(), noiseVecIni, seedUni, michael@0: noiseFuncName.c_str(), noiseVecIni, seedUni); michael@0: michael@0: builder->fsCodeAppendf("\t\t%s = vec4(0.0);\n", outputColor); michael@0: michael@0: builder->fsCodeAppendf("\t\tvec3 %s = vec3(1.0);\n", factors); michael@0: builder->fsCodeAppendf("\t\tfloat %s = 0.0;\n", sum); michael@0: michael@0: // Loop over all octaves michael@0: builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {\n", fNumOctaves); michael@0: michael@0: // Loop over the 4 channels michael@0: builder->fsCodeAppendf("\t\t\tfor (int %s = 3; %s >= 0; --%s) {\n", channel, channel, channel); michael@0: michael@0: builder->fsCodeAppendf( michael@0: "\t\t\t\t%s[channel] += %s.x * %s(%s * %s.yyy - vec3(%s[%s], %s[%s], %s * %s.z));\n", michael@0: outputColor, factors, noiseFuncName.c_str(), noiseVecIni, factors, xOffsets, channel, michael@0: yOffsets, channel, seedUni, factors); michael@0: michael@0: builder->fsCodeAppend("\t\t\t}\n"); // end of the for loop on channels michael@0: michael@0: builder->fsCodeAppendf("\t\t\t%s += %s.x;\n", sum, factors); michael@0: builder->fsCodeAppendf("\t\t\t%s *= vec3(0.5, 2.0, 0.75);\n", factors); michael@0: michael@0: builder->fsCodeAppend("\t\t}\n"); // end of the for loop on octaves michael@0: michael@0: if (fType == SkPerlinNoiseShader::kFractalNoise_Type) { michael@0: // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2 michael@0: // by fractalNoise and (turbulenceFunctionResult) by turbulence. michael@0: builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5 / %s) + vec4(0.5);\n", michael@0: outputColor, outputColor, sum); michael@0: } else { michael@0: builder->fsCodeAppendf("\t\t%s = abs(%s / vec4(%s));\n", michael@0: outputColor, outputColor, sum); michael@0: } michael@0: michael@0: builder->fsCodeAppendf("\t\t%s.a *= %s;\n", outputColor, alphaUni); michael@0: michael@0: // Clamp values michael@0: builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);\n", outputColor, outputColor); michael@0: michael@0: // Pre-multiply the result michael@0: builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n", michael@0: outputColor, outputColor, outputColor, outputColor); michael@0: } michael@0: michael@0: void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder, michael@0: const GrDrawEffect&, michael@0: EffectKey key, michael@0: const char* outputColor, michael@0: const char* inputColor, michael@0: const TransformedCoordsArray& coords, michael@0: const TextureSamplerArray& samplers) { michael@0: sk_ignore_unused_variable(inputColor); michael@0: michael@0: SkString vCoords = builder->ensureFSCoords2D(coords, 0); michael@0: michael@0: fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, michael@0: kMat33f_GrSLType, "invMatrix"); michael@0: const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni); michael@0: fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, michael@0: kVec2f_GrSLType, "baseFrequency"); michael@0: const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni); michael@0: fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, michael@0: kFloat_GrSLType, "alpha"); michael@0: const char* alphaUni = builder->getUniformCStr(fAlphaUni); michael@0: michael@0: const char* stitchDataUni = NULL; michael@0: if (fStitchTiles) { michael@0: fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, michael@0: kVec2f_GrSLType, "stitchData"); michael@0: stitchDataUni = builder->getUniformCStr(fStitchDataUni); michael@0: } michael@0: michael@0: // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8 michael@0: const char* chanCoordR = "0.125"; michael@0: const char* chanCoordG = "0.375"; michael@0: const char* chanCoordB = "0.625"; michael@0: const char* chanCoordA = "0.875"; michael@0: const char* chanCoord = "chanCoord"; michael@0: const char* stitchData = "stitchData"; michael@0: const char* ratio = "ratio"; michael@0: const char* noiseXY = "noiseXY"; michael@0: const char* noiseVec = "noiseVec"; michael@0: const char* noiseSmooth = "noiseSmooth"; michael@0: const char* fractVal = "fractVal"; michael@0: const char* uv = "uv"; michael@0: const char* ab = "ab"; michael@0: const char* latticeIdx = "latticeIdx"; michael@0: const char* lattice = "lattice"; michael@0: const char* inc8bit = "0.00390625"; // 1.0 / 256.0 michael@0: // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a michael@0: // [-1,1] vector and perform a dot product between that vector and the provided vector. michael@0: const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);"; michael@0: michael@0: // Add noise function michael@0: static const GrGLShaderVar gPerlinNoiseArgs[] = { michael@0: GrGLShaderVar(chanCoord, kFloat_GrSLType), michael@0: GrGLShaderVar(noiseVec, kVec2f_GrSLType) michael@0: }; michael@0: michael@0: static const GrGLShaderVar gPerlinNoiseStitchArgs[] = { michael@0: GrGLShaderVar(chanCoord, kFloat_GrSLType), michael@0: GrGLShaderVar(noiseVec, kVec2f_GrSLType), michael@0: GrGLShaderVar(stitchData, kVec2f_GrSLType) michael@0: }; michael@0: michael@0: SkString noiseCode; michael@0: michael@0: noiseCode.appendf("\tvec4 %s = vec4(floor(%s), fract(%s));", noiseXY, noiseVec, noiseVec); michael@0: michael@0: // smooth curve : t * t * (3 - 2 * t) michael@0: noiseCode.appendf("\n\tvec2 %s = %s.zw * %s.zw * (vec2(3.0) - vec2(2.0) * %s.zw);", michael@0: noiseSmooth, noiseXY, noiseXY, noiseXY); michael@0: michael@0: // Adjust frequencies if we're stitching tiles michael@0: if (fStitchTiles) { michael@0: noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }", michael@0: noiseXY, stitchData, noiseXY, stitchData); michael@0: noiseCode.appendf("\n\tif(%s.x >= (%s.x - 1.0)) { %s.x -= (%s.x - 1.0); }", michael@0: noiseXY, stitchData, noiseXY, stitchData); michael@0: noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }", michael@0: noiseXY, stitchData, noiseXY, stitchData); michael@0: noiseCode.appendf("\n\tif(%s.y >= (%s.y - 1.0)) { %s.y -= (%s.y - 1.0); }", michael@0: noiseXY, stitchData, noiseXY, stitchData); michael@0: } michael@0: michael@0: // Get texture coordinates and normalize michael@0: noiseCode.appendf("\n\t%s.xy = fract(floor(mod(%s.xy, 256.0)) / vec2(256.0));\n", michael@0: noiseXY, noiseXY); michael@0: michael@0: // Get permutation for x michael@0: { michael@0: SkString xCoords(""); michael@0: xCoords.appendf("vec2(%s.x, 0.5)", noiseXY); michael@0: michael@0: noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx); michael@0: builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType); michael@0: noiseCode.append(".r;"); michael@0: } michael@0: michael@0: // Get permutation for x + 1 michael@0: { michael@0: SkString xCoords(""); michael@0: xCoords.appendf("vec2(fract(%s.x + %s), 0.5)", noiseXY, inc8bit); michael@0: michael@0: noiseCode.appendf("\n\t%s.y = ", latticeIdx); michael@0: builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType); michael@0: noiseCode.append(".r;"); michael@0: } michael@0: michael@0: #if defined(SK_BUILD_FOR_ANDROID) michael@0: // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3). michael@0: // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit michael@0: // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725 michael@0: // (or 0.484368 here). The following rounding operation prevents these precision issues from michael@0: // affecting the result of the noise by making sure that we only have multiples of 1/255. michael@0: // (Note that 1/255 is about 0.003921569, which is the value used here). michael@0: noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);", michael@0: latticeIdx, latticeIdx); michael@0: #endif michael@0: michael@0: // Get (x,y) coordinates with the permutated x michael@0: noiseCode.appendf("\n\t%s = fract(%s + %s.yy);", latticeIdx, latticeIdx, noiseXY); michael@0: michael@0: noiseCode.appendf("\n\tvec2 %s = %s.zw;", fractVal, noiseXY); michael@0: michael@0: noiseCode.appendf("\n\n\tvec2 %s;", uv); michael@0: // Compute u, at offset (0,0) michael@0: { michael@0: SkString latticeCoords(""); michael@0: latticeCoords.appendf("vec2(%s.x, %s)", latticeIdx, chanCoord); michael@0: noiseCode.appendf("\n\tvec4 %s = ", lattice); michael@0: builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(), michael@0: kVec2f_GrSLType); michael@0: noiseCode.appendf(".bgra;\n\t%s.x = ", uv); michael@0: noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal); michael@0: } michael@0: michael@0: noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal); michael@0: // Compute v, at offset (-1,0) michael@0: { michael@0: SkString latticeCoords(""); michael@0: latticeCoords.appendf("vec2(%s.y, %s)", latticeIdx, chanCoord); michael@0: noiseCode.append("\n\tlattice = "); michael@0: builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(), michael@0: kVec2f_GrSLType); michael@0: noiseCode.appendf(".bgra;\n\t%s.y = ", uv); michael@0: noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal); michael@0: } michael@0: michael@0: // Compute 'a' as a linear interpolation of 'u' and 'v' michael@0: noiseCode.appendf("\n\tvec2 %s;", ab); michael@0: noiseCode.appendf("\n\t%s.x = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth); michael@0: michael@0: noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal); michael@0: // Compute v, at offset (-1,-1) michael@0: { michael@0: SkString latticeCoords(""); michael@0: latticeCoords.appendf("vec2(fract(%s.y + %s), %s)", latticeIdx, inc8bit, chanCoord); michael@0: noiseCode.append("\n\tlattice = "); michael@0: builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(), michael@0: kVec2f_GrSLType); michael@0: noiseCode.appendf(".bgra;\n\t%s.y = ", uv); michael@0: noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal); michael@0: } michael@0: michael@0: noiseCode.appendf("\n\t%s.x += 1.0;", fractVal); michael@0: // Compute u, at offset (0,-1) michael@0: { michael@0: SkString latticeCoords(""); michael@0: latticeCoords.appendf("vec2(fract(%s.x + %s), %s)", latticeIdx, inc8bit, chanCoord); michael@0: noiseCode.append("\n\tlattice = "); michael@0: builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(), michael@0: kVec2f_GrSLType); michael@0: noiseCode.appendf(".bgra;\n\t%s.x = ", uv); michael@0: noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal); michael@0: } michael@0: michael@0: // Compute 'b' as a linear interpolation of 'u' and 'v' michael@0: noiseCode.appendf("\n\t%s.y = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth); michael@0: // Compute the noise as a linear interpolation of 'a' and 'b' michael@0: noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth); michael@0: michael@0: SkString noiseFuncName; michael@0: if (fStitchTiles) { michael@0: builder->fsEmitFunction(kFloat_GrSLType, michael@0: "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs), michael@0: gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName); michael@0: } else { michael@0: builder->fsEmitFunction(kFloat_GrSLType, michael@0: "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs), michael@0: gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName); michael@0: } michael@0: michael@0: // There are rounding errors if the floor operation is not performed here michael@0: builder->fsCodeAppendf("\n\t\tvec2 %s = floor((%s * vec3(%s, 1.0)).xy) * %s;", michael@0: noiseVec, invMatrixUni, vCoords.c_str(), baseFrequencyUni); michael@0: michael@0: // Clear the color accumulator michael@0: builder->fsCodeAppendf("\n\t\t%s = vec4(0.0);", outputColor); michael@0: michael@0: if (fStitchTiles) { michael@0: // Set up TurbulenceInitial stitch values. michael@0: builder->fsCodeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni); michael@0: } michael@0: michael@0: builder->fsCodeAppendf("\n\t\tfloat %s = 1.0;", ratio); michael@0: michael@0: // Loop over all octaves michael@0: builder->fsCodeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves); michael@0: michael@0: builder->fsCodeAppendf("\n\t\t\t%s += ", outputColor); michael@0: if (fType != SkPerlinNoiseShader::kFractalNoise_Type) { michael@0: builder->fsCodeAppend("abs("); michael@0: } michael@0: if (fStitchTiles) { michael@0: builder->fsCodeAppendf( michael@0: "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s)," michael@0: "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))", michael@0: noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData, michael@0: noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData, michael@0: noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData, michael@0: noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData); michael@0: } else { michael@0: builder->fsCodeAppendf( michael@0: "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s)," michael@0: "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))", michael@0: noiseFuncName.c_str(), chanCoordR, noiseVec, michael@0: noiseFuncName.c_str(), chanCoordG, noiseVec, michael@0: noiseFuncName.c_str(), chanCoordB, noiseVec, michael@0: noiseFuncName.c_str(), chanCoordA, noiseVec); michael@0: } michael@0: if (fType != SkPerlinNoiseShader::kFractalNoise_Type) { michael@0: builder->fsCodeAppendf(")"); // end of "abs(" michael@0: } michael@0: builder->fsCodeAppendf(" * %s;", ratio); michael@0: michael@0: builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec); michael@0: builder->fsCodeAppendf("\n\t\t\t%s *= 0.5;", ratio); michael@0: michael@0: if (fStitchTiles) { michael@0: builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData); michael@0: } michael@0: builder->fsCodeAppend("\n\t\t}"); // end of the for loop on octaves michael@0: michael@0: if (fType == SkPerlinNoiseShader::kFractalNoise_Type) { michael@0: // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2 michael@0: // by fractalNoise and (turbulenceFunctionResult) by turbulence. michael@0: builder->fsCodeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor); michael@0: } michael@0: michael@0: builder->fsCodeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni); michael@0: michael@0: // Clamp values michael@0: builder->fsCodeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor); michael@0: michael@0: // Pre-multiply the result michael@0: builder->fsCodeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n", michael@0: outputColor, outputColor, outputColor, outputColor); michael@0: } michael@0: michael@0: GrGLNoise::GrGLNoise(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect) michael@0: : INHERITED (factory) michael@0: , fType(drawEffect.castEffect().type()) michael@0: , fStitchTiles(drawEffect.castEffect().stitchTiles()) michael@0: , fNumOctaves(drawEffect.castEffect().numOctaves()) { michael@0: } michael@0: michael@0: GrGLEffect::EffectKey GrGLNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) { michael@0: const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect(); michael@0: michael@0: EffectKey key = turbulence.numOctaves(); michael@0: michael@0: key = key << 3; // Make room for next 3 bits michael@0: michael@0: switch (turbulence.type()) { michael@0: case SkPerlinNoiseShader::kFractalNoise_Type: michael@0: key |= 0x1; michael@0: break; michael@0: case SkPerlinNoiseShader::kTurbulence_Type: michael@0: key |= 0x2; michael@0: break; michael@0: default: michael@0: // leave key at 0 michael@0: break; michael@0: } michael@0: michael@0: if (turbulence.stitchTiles()) { michael@0: key |= 0x4; // Flip the 3rd bit if tile stitching is on michael@0: } michael@0: michael@0: return key; michael@0: } michael@0: michael@0: void GrGLNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) { michael@0: const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect(); michael@0: michael@0: const SkVector& baseFrequency = turbulence.baseFrequency(); michael@0: uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY); michael@0: uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255))); michael@0: michael@0: SkMatrix m = turbulence.matrix(); michael@0: m.postTranslate(-SK_Scalar1, -SK_Scalar1); michael@0: SkMatrix invM; michael@0: if (!m.invert(&invM)) { michael@0: invM.reset(); michael@0: } else { michael@0: invM.postConcat(invM); // Square the matrix michael@0: } michael@0: uman.setSkMatrix(fInvMatrixUni, invM); michael@0: } michael@0: michael@0: void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) { michael@0: INHERITED::setData(uman, drawEffect); michael@0: michael@0: const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect(); michael@0: if (turbulence.stitchTiles()) { michael@0: const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData(); michael@0: uman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth), michael@0: SkIntToScalar(stitchData.fHeight)); michael@0: } michael@0: } michael@0: michael@0: void GrGLSimplexNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) { michael@0: INHERITED::setData(uman, drawEffect); michael@0: michael@0: const GrSimplexNoiseEffect& turbulence = drawEffect.castEffect(); michael@0: uman.set1f(fSeedUni, turbulence.seed()); michael@0: } michael@0: michael@0: ///////////////////////////////////////////////////////////////////// michael@0: michael@0: GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint) const { michael@0: SkASSERT(NULL != context); michael@0: michael@0: if (0 == fNumOctaves) { michael@0: SkColor clearColor = 0; michael@0: if (kFractalNoise_Type == fType) { michael@0: clearColor = SkColorSetARGB(paint.getAlpha() / 2, 127, 127, 127); michael@0: } michael@0: SkAutoTUnref cf(SkColorFilter::CreateModeFilter( michael@0: clearColor, SkXfermode::kSrc_Mode)); michael@0: return cf->asNewEffect(context); michael@0: } michael@0: michael@0: // Either we don't stitch tiles, either we have a valid tile size michael@0: SkASSERT(!fStitchTiles || !fTileSize.isEmpty()); michael@0: michael@0: #ifdef SK_USE_SIMPLEX_NOISE michael@0: // Simplex noise is currently disabled but can be enabled by defining SK_USE_SIMPLEX_NOISE michael@0: sk_ignore_unused_variable(context); michael@0: GrEffectRef* effect = michael@0: GrSimplexNoiseEffect::Create(fType, fPaintingData->fBaseFrequency, michael@0: fNumOctaves, fStitchTiles, fSeed, michael@0: this->getLocalMatrix(), paint.getAlpha()); michael@0: #else michael@0: GrTexture* permutationsTexture = GrLockAndRefCachedBitmapTexture( michael@0: context, fPaintingData->getPermutationsBitmap(), NULL); michael@0: GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture( michael@0: context, fPaintingData->getNoiseBitmap(), NULL); michael@0: michael@0: GrEffectRef* effect = (NULL != permutationsTexture) && (NULL != noiseTexture) ? michael@0: GrPerlinNoiseEffect::Create(fType, fPaintingData->fBaseFrequency, michael@0: fNumOctaves, fStitchTiles, michael@0: fPaintingData->fStitchDataInit, michael@0: permutationsTexture, noiseTexture, michael@0: this->getLocalMatrix(), paint.getAlpha()) : michael@0: NULL; michael@0: michael@0: // Unlock immediately, this is not great, but we don't have a way of michael@0: // knowing when else to unlock it currently. TODO: Remove this when michael@0: // unref becomes the unlock replacement for all types of textures. michael@0: if (NULL != permutationsTexture) { michael@0: GrUnlockAndUnrefCachedBitmapTexture(permutationsTexture); michael@0: } michael@0: if (NULL != noiseTexture) { michael@0: GrUnlockAndUnrefCachedBitmapTexture(noiseTexture); michael@0: } michael@0: #endif michael@0: michael@0: return effect; michael@0: } michael@0: michael@0: #else michael@0: michael@0: GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext*, const SkPaint&) const { michael@0: SkDEBUGFAIL("Should not call in GPU-less build"); michael@0: return NULL; michael@0: } michael@0: michael@0: #endif michael@0: michael@0: #ifndef SK_IGNORE_TO_STRING michael@0: void SkPerlinNoiseShader::toString(SkString* str) const { michael@0: str->append("SkPerlinNoiseShader: ("); michael@0: michael@0: str->append("type: "); michael@0: switch (fType) { michael@0: case kFractalNoise_Type: michael@0: str->append("\"fractal noise\""); michael@0: break; michael@0: case kTurbulence_Type: michael@0: str->append("\"turbulence\""); michael@0: break; michael@0: default: michael@0: str->append("\"unknown\""); michael@0: break; michael@0: } michael@0: str->append(" base frequency: ("); michael@0: str->appendScalar(fBaseFrequencyX); michael@0: str->append(", "); michael@0: str->appendScalar(fBaseFrequencyY); michael@0: str->append(") number of octaves: "); michael@0: str->appendS32(fNumOctaves); michael@0: str->append(" seed: "); michael@0: str->appendScalar(fSeed); michael@0: str->append(" stitch tiles: "); michael@0: str->append(fStitchTiles ? "true " : "false "); michael@0: michael@0: this->INHERITED::toString(str); michael@0: michael@0: str->append(")"); michael@0: } michael@0: #endif