2 * Copyright 2013 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
9 #include "SkPerlinNoiseShader.h"
10 #include "SkColorFilter.h"
11 #include "SkReadBuffer.h"
12 #include "SkWriteBuffer.h"
14 #include "SkUnPreMultiply.h"
18 #include "GrContext.h"
19 #include "GrCoordTransform.h"
20 #include "GrInvariantOutput.h"
22 #include "gl/GrGLProcessor.h"
23 #include "gl/builders/GrGLProgramBuilder.h"
26 static const int kBlockSize = 256;
27 static const int kBlockMask = kBlockSize - 1;
28 static const int kPerlinNoise = 4096;
29 static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
33 // noiseValue is the color component's value (or color)
34 // limitValue is the maximum perlin noise array index value allowed
35 // newValue is the current noise dimension (either width or height)
36 inline int checkNoise(int noiseValue, int limitValue, int newValue) {
37 // If the noise value would bring us out of bounds of the current noise array while we are
38 // stiching noise tiles together, wrap the noise around the current dimension of the noise to
39 // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
40 if (noiseValue >= limitValue) {
41 noiseValue -= newValue;
46 inline SkScalar smoothCurve(SkScalar t) {
47 static const SkScalar SK_Scalar3 = 3.0f;
49 // returns t * t * (3 - 2 * t)
50 return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
55 struct SkPerlinNoiseShader::StitchData {
63 bool operator==(const StitchData& other) const {
64 return fWidth == other.fWidth &&
65 fWrapX == other.fWrapX &&
66 fHeight == other.fHeight &&
67 fWrapY == other.fWrapY;
70 int fWidth; // How much to subtract to wrap for stitching.
71 int fWrapX; // Minimum value to wrap.
76 struct SkPerlinNoiseShader::PaintingData {
77 PaintingData(const SkISize& tileSize, SkScalar seed,
78 SkScalar baseFrequencyX, SkScalar baseFrequencyY,
79 const SkMatrix& matrix)
82 { SkScalarInvert(baseFrequencyX), SkScalarInvert(baseFrequencyY) },
83 { SkIntToScalar(tileSize.fWidth), SkIntToScalar(tileSize.fHeight) },
85 matrix.mapVectors(vec, 2);
87 fBaseFrequency.set(SkScalarInvert(vec[0].fX), SkScalarInvert(vec[0].fY));
88 fTileSize.set(SkScalarRoundToInt(vec[1].fX), SkScalarRoundToInt(vec[1].fY));
90 if (!fTileSize.isEmpty()) {
95 fPermutationsBitmap.setInfo(SkImageInfo::MakeA8(kBlockSize, 1));
96 fPermutationsBitmap.setPixels(fLatticeSelector);
98 fNoiseBitmap.setInfo(SkImageInfo::MakeN32Premul(kBlockSize, 4));
99 fNoiseBitmap.setPixels(fNoise[0][0]);
104 uint8_t fLatticeSelector[kBlockSize];
105 uint16_t fNoise[4][kBlockSize][2];
106 SkPoint fGradient[4][kBlockSize];
108 SkVector fBaseFrequency;
109 StitchData fStitchDataInit;
114 SkBitmap fPermutationsBitmap;
115 SkBitmap fNoiseBitmap;
118 inline int random() {
119 static const int gRandAmplitude = 16807; // 7**5; primitive root of m
120 static const int gRandQ = 127773; // m / a
121 static const int gRandR = 2836; // m % a
123 int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
125 result += kRandMaximum;
130 // Only called once. Could be part of the constructor.
131 void init(SkScalar seed)
133 static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
135 // According to the SVG spec, we must truncate (not round) the seed value.
136 fSeed = SkScalarTruncToInt(seed);
137 // The seed value clamp to the range [1, kRandMaximum - 1].
139 fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
141 if (fSeed > kRandMaximum - 1) {
142 fSeed = kRandMaximum - 1;
144 for (int channel = 0; channel < 4; ++channel) {
145 for (int i = 0; i < kBlockSize; ++i) {
146 fLatticeSelector[i] = i;
147 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
148 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
151 for (int i = kBlockSize - 1; i > 0; --i) {
152 int k = fLatticeSelector[i];
153 int j = random() % kBlockSize;
155 SkASSERT(j < kBlockSize);
156 fLatticeSelector[i] = fLatticeSelector[j];
157 fLatticeSelector[j] = k;
160 // Perform the permutations now
163 uint16_t noise[4][kBlockSize][2];
164 for (int i = 0; i < kBlockSize; ++i) {
165 for (int channel = 0; channel < 4; ++channel) {
166 for (int j = 0; j < 2; ++j) {
167 noise[channel][i][j] = fNoise[channel][i][j];
171 // Do permutations on noise data
172 for (int i = 0; i < kBlockSize; ++i) {
173 for (int channel = 0; channel < 4; ++channel) {
174 for (int j = 0; j < 2; ++j) {
175 fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
181 // Half of the largest possible value for 16 bit unsigned int
182 static const SkScalar gHalfMax16bits = 32767.5f;
184 // Compute gradients from permutated noise data
185 for (int channel = 0; channel < 4; ++channel) {
186 for (int i = 0; i < kBlockSize; ++i) {
187 fGradient[channel][i] = SkPoint::Make(
188 SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
190 SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
192 fGradient[channel][i].normalize();
193 // Put the normalized gradient back into the noise data
194 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
195 fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
196 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
197 fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
202 // Only called once. Could be part of the constructor.
204 SkScalar tileWidth = SkIntToScalar(fTileSize.width());
205 SkScalar tileHeight = SkIntToScalar(fTileSize.height());
206 SkASSERT(tileWidth > 0 && tileHeight > 0);
207 // When stitching tiled turbulence, the frequencies must be adjusted
208 // so that the tile borders will be continuous.
209 if (fBaseFrequency.fX) {
210 SkScalar lowFrequencx =
211 SkScalarFloorToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
212 SkScalar highFrequencx =
213 SkScalarCeilToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
214 // BaseFrequency should be non-negative according to the standard.
215 if (SkScalarDiv(fBaseFrequency.fX, lowFrequencx) <
216 SkScalarDiv(highFrequencx, fBaseFrequency.fX)) {
217 fBaseFrequency.fX = lowFrequencx;
219 fBaseFrequency.fX = highFrequencx;
222 if (fBaseFrequency.fY) {
223 SkScalar lowFrequency =
224 SkScalarFloorToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
225 SkScalar highFrequency =
226 SkScalarCeilToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
227 if (SkScalarDiv(fBaseFrequency.fY, lowFrequency) <
228 SkScalarDiv(highFrequency, fBaseFrequency.fY)) {
229 fBaseFrequency.fY = lowFrequency;
231 fBaseFrequency.fY = highFrequency;
234 // Set up TurbulenceInitial stitch values.
235 fStitchDataInit.fWidth =
236 SkScalarRoundToInt(tileWidth * fBaseFrequency.fX);
237 fStitchDataInit.fWrapX = kPerlinNoise + fStitchDataInit.fWidth;
238 fStitchDataInit.fHeight =
239 SkScalarRoundToInt(tileHeight * fBaseFrequency.fY);
240 fStitchDataInit.fWrapY = kPerlinNoise + fStitchDataInit.fHeight;
246 const SkBitmap& getPermutationsBitmap() const { return fPermutationsBitmap; }
248 const SkBitmap& getNoiseBitmap() const { return fNoiseBitmap; }
252 SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
253 int numOctaves, SkScalar seed,
254 const SkISize* tileSize) {
255 return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY,
256 numOctaves, seed, tileSize));
259 SkShader* SkPerlinNoiseShader::CreateTurbulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
260 int numOctaves, SkScalar seed,
261 const SkISize* tileSize) {
262 return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY,
263 numOctaves, seed, tileSize));
266 SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
267 SkScalar baseFrequencyX,
268 SkScalar baseFrequencyY,
271 const SkISize* tileSize)
273 , fBaseFrequencyX(baseFrequencyX)
274 , fBaseFrequencyY(baseFrequencyY)
275 , fNumOctaves(numOctaves > 255 ? 255 : numOctaves/*[0,255] octaves allowed*/)
277 , fTileSize(NULL == tileSize ? SkISize::Make(0, 0) : *tileSize)
278 , fStitchTiles(!fTileSize.isEmpty())
280 SkASSERT(numOctaves >= 0 && numOctaves < 256);
283 SkPerlinNoiseShader::~SkPerlinNoiseShader() {
286 SkFlattenable* SkPerlinNoiseShader::CreateProc(SkReadBuffer& buffer) {
287 Type type = (Type)buffer.readInt();
288 SkScalar freqX = buffer.readScalar();
289 SkScalar freqY = buffer.readScalar();
290 int octaves = buffer.readInt();
291 SkScalar seed = buffer.readScalar();
293 tileSize.fWidth = buffer.readInt();
294 tileSize.fHeight = buffer.readInt();
297 case kFractalNoise_Type:
298 return SkPerlinNoiseShader::CreateFractalNoise(freqX, freqY, octaves, seed, &tileSize);
299 case kTurbulence_Type:
300 return SkPerlinNoiseShader::CreateTubulence(freqX, freqY, octaves, seed, &tileSize);
306 void SkPerlinNoiseShader::flatten(SkWriteBuffer& buffer) const {
307 buffer.writeInt((int) fType);
308 buffer.writeScalar(fBaseFrequencyX);
309 buffer.writeScalar(fBaseFrequencyY);
310 buffer.writeInt(fNumOctaves);
311 buffer.writeScalar(fSeed);
312 buffer.writeInt(fTileSize.fWidth);
313 buffer.writeInt(fTileSize.fHeight);
316 SkScalar SkPerlinNoiseShader::PerlinNoiseShaderContext::noise2D(
317 int channel, const StitchData& stitchData, const SkPoint& noiseVector) const {
319 int noisePositionIntegerValue;
320 int nextNoisePositionIntegerValue;
321 SkScalar noisePositionFractionValue;
322 Noise(SkScalar component)
324 SkScalar position = component + kPerlinNoise;
325 noisePositionIntegerValue = SkScalarFloorToInt(position);
326 noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
327 nextNoisePositionIntegerValue = noisePositionIntegerValue + 1;
330 Noise noiseX(noiseVector.x());
331 Noise noiseY(noiseVector.y());
333 const SkPerlinNoiseShader& perlinNoiseShader = static_cast<const SkPerlinNoiseShader&>(fShader);
334 // If stitching, adjust lattice points accordingly.
335 if (perlinNoiseShader.fStitchTiles) {
336 noiseX.noisePositionIntegerValue =
337 checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
338 noiseY.noisePositionIntegerValue =
339 checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
340 noiseX.nextNoisePositionIntegerValue =
341 checkNoise(noiseX.nextNoisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
342 noiseY.nextNoisePositionIntegerValue =
343 checkNoise(noiseY.nextNoisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
345 noiseX.noisePositionIntegerValue &= kBlockMask;
346 noiseY.noisePositionIntegerValue &= kBlockMask;
347 noiseX.nextNoisePositionIntegerValue &= kBlockMask;
348 noiseY.nextNoisePositionIntegerValue &= kBlockMask;
350 fPaintingData->fLatticeSelector[noiseX.noisePositionIntegerValue];
352 fPaintingData->fLatticeSelector[noiseX.nextNoisePositionIntegerValue];
353 int b00 = (i + noiseY.noisePositionIntegerValue) & kBlockMask;
354 int b10 = (j + noiseY.noisePositionIntegerValue) & kBlockMask;
355 int b01 = (i + noiseY.nextNoisePositionIntegerValue) & kBlockMask;
356 int b11 = (j + noiseY.nextNoisePositionIntegerValue) & kBlockMask;
357 SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
358 SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
359 // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
360 SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
361 noiseY.noisePositionFractionValue); // Offset (0,0)
362 u = fPaintingData->fGradient[channel][b00].dot(fractionValue);
363 fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
364 v = fPaintingData->fGradient[channel][b10].dot(fractionValue);
365 SkScalar a = SkScalarInterp(u, v, sx);
366 fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
367 v = fPaintingData->fGradient[channel][b11].dot(fractionValue);
368 fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
369 u = fPaintingData->fGradient[channel][b01].dot(fractionValue);
370 SkScalar b = SkScalarInterp(u, v, sx);
371 return SkScalarInterp(a, b, sy);
374 SkScalar SkPerlinNoiseShader::PerlinNoiseShaderContext::calculateTurbulenceValueForPoint(
375 int channel, StitchData& stitchData, const SkPoint& point) const {
376 const SkPerlinNoiseShader& perlinNoiseShader = static_cast<const SkPerlinNoiseShader&>(fShader);
377 if (perlinNoiseShader.fStitchTiles) {
378 // Set up TurbulenceInitial stitch values.
379 stitchData = fPaintingData->fStitchDataInit;
381 SkScalar turbulenceFunctionResult = 0;
382 SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), fPaintingData->fBaseFrequency.fX),
383 SkScalarMul(point.y(), fPaintingData->fBaseFrequency.fY)));
384 SkScalar ratio = SK_Scalar1;
385 for (int octave = 0; octave < perlinNoiseShader.fNumOctaves; ++octave) {
386 SkScalar noise = noise2D(channel, stitchData, noiseVector);
387 turbulenceFunctionResult += SkScalarDiv(
388 (perlinNoiseShader.fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio);
392 if (perlinNoiseShader.fStitchTiles) {
393 // Update stitch values
394 stitchData.fWidth *= 2;
395 stitchData.fWrapX = stitchData.fWidth + kPerlinNoise;
396 stitchData.fHeight *= 2;
397 stitchData.fWrapY = stitchData.fHeight + kPerlinNoise;
401 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
402 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
403 if (perlinNoiseShader.fType == kFractalNoise_Type) {
404 turbulenceFunctionResult =
405 SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
408 if (channel == 3) { // Scale alpha by paint value
409 turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult,
410 SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255)));
414 return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
417 SkPMColor SkPerlinNoiseShader::PerlinNoiseShaderContext::shade(
418 const SkPoint& point, StitchData& stitchData) const {
420 fMatrix.mapPoints(&newPoint, &point, 1);
421 newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
422 newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
425 for (int channel = 3; channel >= 0; --channel) {
426 rgba[channel] = SkScalarFloorToInt(255 *
427 calculateTurbulenceValueForPoint(channel, stitchData, newPoint));
429 return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
432 SkShader::Context* SkPerlinNoiseShader::onCreateContext(const ContextRec& rec,
433 void* storage) const {
434 return SkNEW_PLACEMENT_ARGS(storage, PerlinNoiseShaderContext, (*this, rec));
437 size_t SkPerlinNoiseShader::contextSize() const {
438 return sizeof(PerlinNoiseShaderContext);
441 SkPerlinNoiseShader::PerlinNoiseShaderContext::PerlinNoiseShaderContext(
442 const SkPerlinNoiseShader& shader, const ContextRec& rec)
443 : INHERITED(shader, rec)
445 SkMatrix newMatrix = *rec.fMatrix;
446 newMatrix.preConcat(shader.getLocalMatrix());
447 if (rec.fLocalMatrix) {
448 newMatrix.preConcat(*rec.fLocalMatrix);
450 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
451 // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
452 fMatrix.setTranslate(-newMatrix.getTranslateX() + SK_Scalar1, -newMatrix.getTranslateY() + SK_Scalar1);
453 fPaintingData = SkNEW_ARGS(PaintingData, (shader.fTileSize, shader.fSeed, shader.fBaseFrequencyX, shader.fBaseFrequencyY, newMatrix));
456 SkPerlinNoiseShader::PerlinNoiseShaderContext::~PerlinNoiseShaderContext() {
457 SkDELETE(fPaintingData);
460 void SkPerlinNoiseShader::PerlinNoiseShaderContext::shadeSpan(
461 int x, int y, SkPMColor result[], int count) {
462 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
463 StitchData stitchData;
464 for (int i = 0; i < count; ++i) {
465 result[i] = shade(point, stitchData);
466 point.fX += SK_Scalar1;
470 void SkPerlinNoiseShader::PerlinNoiseShaderContext::shadeSpan16(
471 int x, int y, uint16_t result[], int count) {
472 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
473 StitchData stitchData;
475 for (int i = 0; i < count; ++i) {
476 unsigned dither = DITHER_VALUE(x);
477 result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
479 point.fX += SK_Scalar1;
483 /////////////////////////////////////////////////////////////////////
487 class GrGLPerlinNoise : public GrGLFragmentProcessor {
489 GrGLPerlinNoise(const GrProcessor&);
490 virtual ~GrGLPerlinNoise() {}
492 virtual void emitCode(GrGLFPBuilder*,
493 const GrFragmentProcessor&,
494 const char* outputColor,
495 const char* inputColor,
496 const TransformedCoordsArray&,
497 const TextureSamplerArray&) SK_OVERRIDE;
499 void setData(const GrGLProgramDataManager&, const GrProcessor&) SK_OVERRIDE;
501 static inline void GenKey(const GrProcessor&, const GrGLCaps&, GrProcessorKeyBuilder* b);
505 GrGLProgramDataManager::UniformHandle fStitchDataUni;
506 SkPerlinNoiseShader::Type fType;
509 GrGLProgramDataManager::UniformHandle fBaseFrequencyUni;
510 GrGLProgramDataManager::UniformHandle fAlphaUni;
513 typedef GrGLFragmentProcessor INHERITED;
516 /////////////////////////////////////////////////////////////////////
518 class GrPerlinNoiseEffect : public GrFragmentProcessor {
520 static GrFragmentProcessor* Create(SkPerlinNoiseShader::Type type,
521 int numOctaves, bool stitchTiles,
522 SkPerlinNoiseShader::PaintingData* paintingData,
523 GrTexture* permutationsTexture, GrTexture* noiseTexture,
524 const SkMatrix& matrix, uint8_t alpha) {
525 return SkNEW_ARGS(GrPerlinNoiseEffect, (type, numOctaves, stitchTiles, paintingData,
526 permutationsTexture, noiseTexture, matrix, alpha));
529 virtual ~GrPerlinNoiseEffect() {
530 SkDELETE(fPaintingData);
533 const char* name() const SK_OVERRIDE { return "PerlinNoise"; }
535 virtual void getGLProcessorKey(const GrGLCaps& caps,
536 GrProcessorKeyBuilder* b) const SK_OVERRIDE {
537 GrGLPerlinNoise::GenKey(*this, caps, b);
540 GrGLFragmentProcessor* createGLInstance() const SK_OVERRIDE {
541 return SkNEW_ARGS(GrGLPerlinNoise, (*this));
544 const SkPerlinNoiseShader::StitchData& stitchData() const { return fPaintingData->fStitchDataInit; }
546 SkPerlinNoiseShader::Type type() const { return fType; }
547 bool stitchTiles() const { return fStitchTiles; }
548 const SkVector& baseFrequency() const { return fPaintingData->fBaseFrequency; }
549 int numOctaves() const { return fNumOctaves; }
550 const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
551 uint8_t alpha() const { return fAlpha; }
554 bool onIsEqual(const GrFragmentProcessor& sBase) const SK_OVERRIDE {
555 const GrPerlinNoiseEffect& s = sBase.cast<GrPerlinNoiseEffect>();
556 return fType == s.fType &&
557 fPaintingData->fBaseFrequency == s.fPaintingData->fBaseFrequency &&
558 fNumOctaves == s.fNumOctaves &&
559 fStitchTiles == s.fStitchTiles &&
560 fAlpha == s.fAlpha &&
561 fPaintingData->fStitchDataInit == s.fPaintingData->fStitchDataInit;
564 void onComputeInvariantOutput(GrInvariantOutput* inout) const SK_OVERRIDE {
565 inout->setToUnknown(GrInvariantOutput::kWillNot_ReadInput);
568 GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type,
569 int numOctaves, bool stitchTiles,
570 SkPerlinNoiseShader::PaintingData* paintingData,
571 GrTexture* permutationsTexture, GrTexture* noiseTexture,
572 const SkMatrix& matrix, uint8_t alpha)
574 , fNumOctaves(numOctaves)
575 , fStitchTiles(stitchTiles)
577 , fPermutationsAccess(permutationsTexture)
578 , fNoiseAccess(noiseTexture)
579 , fPaintingData(paintingData) {
580 this->initClassID<GrPerlinNoiseEffect>();
581 this->addTextureAccess(&fPermutationsAccess);
582 this->addTextureAccess(&fNoiseAccess);
583 fCoordTransform.reset(kLocal_GrCoordSet, matrix);
584 this->addCoordTransform(&fCoordTransform);
587 GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
589 SkPerlinNoiseShader::Type fType;
590 GrCoordTransform fCoordTransform;
594 GrTextureAccess fPermutationsAccess;
595 GrTextureAccess fNoiseAccess;
596 SkPerlinNoiseShader::PaintingData *fPaintingData;
599 typedef GrFragmentProcessor INHERITED;
602 /////////////////////////////////////////////////////////////////////
603 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrPerlinNoiseEffect);
605 GrFragmentProcessor* GrPerlinNoiseEffect::TestCreate(SkRandom* random,
607 const GrDrawTargetCaps&,
609 int numOctaves = random->nextRangeU(2, 10);
610 bool stitchTiles = random->nextBool();
611 SkScalar seed = SkIntToScalar(random->nextU());
612 SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
613 SkScalar baseFrequencyX = random->nextRangeScalar(0.01f,
615 SkScalar baseFrequencyY = random->nextRangeScalar(0.01f,
618 SkShader* shader = random->nextBool() ?
619 SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
620 stitchTiles ? &tileSize : NULL) :
621 SkPerlinNoiseShader::CreateTurbulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
622 stitchTiles ? &tileSize : NULL);
626 GrFragmentProcessor* effect;
627 SkAssertResult(shader->asFragmentProcessor(context, paint,
628 GrProcessorUnitTest::TestMatrix(random), NULL,
629 &paintColor, &effect));
636 GrGLPerlinNoise::GrGLPerlinNoise(const GrProcessor& processor)
637 : fType(processor.cast<GrPerlinNoiseEffect>().type())
638 , fStitchTiles(processor.cast<GrPerlinNoiseEffect>().stitchTiles())
639 , fNumOctaves(processor.cast<GrPerlinNoiseEffect>().numOctaves()) {
642 void GrGLPerlinNoise::emitCode(GrGLFPBuilder* builder,
643 const GrFragmentProcessor&,
644 const char* outputColor,
645 const char* inputColor,
646 const TransformedCoordsArray& coords,
647 const TextureSamplerArray& samplers) {
648 sk_ignore_unused_variable(inputColor);
650 GrGLFPFragmentBuilder* fsBuilder = builder->getFragmentShaderBuilder();
651 SkString vCoords = fsBuilder->ensureFSCoords2D(coords, 0);
653 fBaseFrequencyUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
654 kVec2f_GrSLType, kDefault_GrSLPrecision,
656 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
657 fAlphaUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
658 kFloat_GrSLType, kDefault_GrSLPrecision,
660 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
662 const char* stitchDataUni = NULL;
664 fStitchDataUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
665 kVec2f_GrSLType, kDefault_GrSLPrecision,
667 stitchDataUni = builder->getUniformCStr(fStitchDataUni);
670 // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
671 const char* chanCoordR = "0.125";
672 const char* chanCoordG = "0.375";
673 const char* chanCoordB = "0.625";
674 const char* chanCoordA = "0.875";
675 const char* chanCoord = "chanCoord";
676 const char* stitchData = "stitchData";
677 const char* ratio = "ratio";
678 const char* noiseVec = "noiseVec";
679 const char* noiseSmooth = "noiseSmooth";
680 const char* floorVal = "floorVal";
681 const char* fractVal = "fractVal";
682 const char* uv = "uv";
683 const char* ab = "ab";
684 const char* latticeIdx = "latticeIdx";
685 const char* bcoords = "bcoords";
686 const char* lattice = "lattice";
687 const char* inc8bit = "0.00390625"; // 1.0 / 256.0
688 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
689 // [-1,1] vector and perform a dot product between that vector and the provided vector.
690 const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
692 // Add noise function
693 static const GrGLShaderVar gPerlinNoiseArgs[] = {
694 GrGLShaderVar(chanCoord, kFloat_GrSLType),
695 GrGLShaderVar(noiseVec, kVec2f_GrSLType)
698 static const GrGLShaderVar gPerlinNoiseStitchArgs[] = {
699 GrGLShaderVar(chanCoord, kFloat_GrSLType),
700 GrGLShaderVar(noiseVec, kVec2f_GrSLType),
701 GrGLShaderVar(stitchData, kVec2f_GrSLType)
706 noiseCode.appendf("\tvec4 %s;\n", floorVal);
707 noiseCode.appendf("\t%s.xy = floor(%s);\n", floorVal, noiseVec);
708 noiseCode.appendf("\t%s.zw = %s.xy + vec2(1.0);\n", floorVal, floorVal);
709 noiseCode.appendf("\tvec2 %s = fract(%s);\n", fractVal, noiseVec);
711 // smooth curve : t * t * (3 - 2 * t)
712 noiseCode.appendf("\n\tvec2 %s = %s * %s * (vec2(3.0) - vec2(2.0) * %s);",
713 noiseSmooth, fractVal, fractVal, fractVal);
715 // Adjust frequencies if we're stitching tiles
717 noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
718 floorVal, stitchData, floorVal, stitchData);
719 noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }",
720 floorVal, stitchData, floorVal, stitchData);
721 noiseCode.appendf("\n\tif(%s.z >= %s.x) { %s.z -= %s.x; }",
722 floorVal, stitchData, floorVal, stitchData);
723 noiseCode.appendf("\n\tif(%s.w >= %s.y) { %s.w -= %s.y; }",
724 floorVal, stitchData, floorVal, stitchData);
727 // Get texture coordinates and normalize
728 noiseCode.appendf("\n\t%s = fract(floor(mod(%s, 256.0)) / vec4(256.0));\n",
731 // Get permutation for x
733 SkString xCoords("");
734 xCoords.appendf("vec2(%s.x, 0.5)", floorVal);
736 noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
737 fsBuilder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
738 noiseCode.append(".r;");
741 // Get permutation for x + 1
743 SkString xCoords("");
744 xCoords.appendf("vec2(%s.z, 0.5)", floorVal);
746 noiseCode.appendf("\n\t%s.y = ", latticeIdx);
747 fsBuilder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
748 noiseCode.append(".r;");
751 #if defined(SK_BUILD_FOR_ANDROID)
752 // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
753 // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
754 // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
755 // (or 0.484368 here). The following rounding operation prevents these precision issues from
756 // affecting the result of the noise by making sure that we only have multiples of 1/255.
757 // (Note that 1/255 is about 0.003921569, which is the value used here).
758 noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);",
759 latticeIdx, latticeIdx);
762 // Get (x,y) coordinates with the permutated x
763 noiseCode.appendf("\n\tvec4 %s = fract(%s.xyxy + %s.yyww);", bcoords, latticeIdx, floorVal);
765 noiseCode.appendf("\n\n\tvec2 %s;", uv);
766 // Compute u, at offset (0,0)
768 SkString latticeCoords("");
769 latticeCoords.appendf("vec2(%s.x, %s)", bcoords, chanCoord);
770 noiseCode.appendf("\n\tvec4 %s = ", lattice);
771 fsBuilder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
773 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
774 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
777 noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
778 // Compute v, at offset (-1,0)
780 SkString latticeCoords("");
781 latticeCoords.appendf("vec2(%s.y, %s)", bcoords, chanCoord);
782 noiseCode.append("\n\tlattice = ");
783 fsBuilder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
785 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
786 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
789 // Compute 'a' as a linear interpolation of 'u' and 'v'
790 noiseCode.appendf("\n\tvec2 %s;", ab);
791 noiseCode.appendf("\n\t%s.x = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
793 noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
794 // Compute v, at offset (-1,-1)
796 SkString latticeCoords("");
797 latticeCoords.appendf("vec2(%s.w, %s)", bcoords, chanCoord);
798 noiseCode.append("\n\tlattice = ");
799 fsBuilder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
801 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
802 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
805 noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
806 // Compute u, at offset (0,-1)
808 SkString latticeCoords("");
809 latticeCoords.appendf("vec2(%s.z, %s)", bcoords, chanCoord);
810 noiseCode.append("\n\tlattice = ");
811 fsBuilder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
813 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
814 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
817 // Compute 'b' as a linear interpolation of 'u' and 'v'
818 noiseCode.appendf("\n\t%s.y = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
819 // Compute the noise as a linear interpolation of 'a' and 'b'
820 noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
822 SkString noiseFuncName;
824 fsBuilder->emitFunction(kFloat_GrSLType,
825 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
826 gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
828 fsBuilder->emitFunction(kFloat_GrSLType,
829 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
830 gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
833 // There are rounding errors if the floor operation is not performed here
834 fsBuilder->codeAppendf("\n\t\tvec2 %s = floor(%s.xy) * %s;",
835 noiseVec, vCoords.c_str(), baseFrequencyUni);
837 // Clear the color accumulator
838 fsBuilder->codeAppendf("\n\t\t%s = vec4(0.0);", outputColor);
841 // Set up TurbulenceInitial stitch values.
842 fsBuilder->codeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni);
845 fsBuilder->codeAppendf("\n\t\tfloat %s = 1.0;", ratio);
847 // Loop over all octaves
848 fsBuilder->codeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
850 fsBuilder->codeAppendf("\n\t\t\t%s += ", outputColor);
851 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
852 fsBuilder->codeAppend("abs(");
855 fsBuilder->codeAppendf(
856 "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
857 "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
858 noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
859 noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
860 noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
861 noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
863 fsBuilder->codeAppendf(
864 "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
865 "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
866 noiseFuncName.c_str(), chanCoordR, noiseVec,
867 noiseFuncName.c_str(), chanCoordG, noiseVec,
868 noiseFuncName.c_str(), chanCoordB, noiseVec,
869 noiseFuncName.c_str(), chanCoordA, noiseVec);
871 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
872 fsBuilder->codeAppendf(")"); // end of "abs("
874 fsBuilder->codeAppendf(" * %s;", ratio);
876 fsBuilder->codeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
877 fsBuilder->codeAppendf("\n\t\t\t%s *= 0.5;", ratio);
880 fsBuilder->codeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData);
882 fsBuilder->codeAppend("\n\t\t}"); // end of the for loop on octaves
884 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
885 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
886 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
887 fsBuilder->codeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
890 fsBuilder->codeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni);
893 fsBuilder->codeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
895 // Pre-multiply the result
896 fsBuilder->codeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
897 outputColor, outputColor, outputColor, outputColor);
900 void GrGLPerlinNoise::GenKey(const GrProcessor& processor, const GrGLCaps&,
901 GrProcessorKeyBuilder* b) {
902 const GrPerlinNoiseEffect& turbulence = processor.cast<GrPerlinNoiseEffect>();
904 uint32_t key = turbulence.numOctaves();
906 key = key << 3; // Make room for next 3 bits
908 switch (turbulence.type()) {
909 case SkPerlinNoiseShader::kFractalNoise_Type:
912 case SkPerlinNoiseShader::kTurbulence_Type:
920 if (turbulence.stitchTiles()) {
921 key |= 0x4; // Flip the 3rd bit if tile stitching is on
927 void GrGLPerlinNoise::setData(const GrGLProgramDataManager& pdman, const GrProcessor& processor) {
928 INHERITED::setData(pdman, processor);
930 const GrPerlinNoiseEffect& turbulence = processor.cast<GrPerlinNoiseEffect>();
932 const SkVector& baseFrequency = turbulence.baseFrequency();
933 pdman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
934 pdman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
936 if (turbulence.stitchTiles()) {
937 const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
938 pdman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
939 SkIntToScalar(stitchData.fHeight));
943 /////////////////////////////////////////////////////////////////////
945 bool SkPerlinNoiseShader::asFragmentProcessor(GrContext* context, const SkPaint& paint,
946 const SkMatrix& viewM,
947 const SkMatrix* externalLocalMatrix,
948 GrColor* paintColor, GrFragmentProcessor** fp) const {
951 *paintColor = SkColor2GrColorJustAlpha(paint.getColor());
953 SkMatrix localMatrix = this->getLocalMatrix();
954 if (externalLocalMatrix) {
955 localMatrix.preConcat(*externalLocalMatrix);
958 SkMatrix matrix = viewM;
959 matrix.preConcat(localMatrix);
961 if (0 == fNumOctaves) {
962 if (kFractalNoise_Type == fType) {
963 uint32_t alpha = paint.getAlpha() >> 1;
964 uint32_t rgb = alpha >> 1;
965 *paintColor = GrColorPackRGBA(rgb, rgb, rgb, alpha);
972 // Either we don't stitch tiles, either we have a valid tile size
973 SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
975 SkPerlinNoiseShader::PaintingData* paintingData =
976 SkNEW_ARGS(PaintingData, (fTileSize, fSeed, fBaseFrequencyX, fBaseFrequencyY, matrix));
977 SkAutoTUnref<GrTexture> permutationsTexture(
978 GrRefCachedBitmapTexture(context, paintingData->getPermutationsBitmap(), NULL));
979 SkAutoTUnref<GrTexture> noiseTexture(
980 GrRefCachedBitmapTexture(context, paintingData->getNoiseBitmap(), NULL));
983 m.setTranslateX(-localMatrix.getTranslateX() + SK_Scalar1);
984 m.setTranslateY(-localMatrix.getTranslateY() + SK_Scalar1);
985 if ((permutationsTexture) && (noiseTexture)) {
986 *fp = GrPerlinNoiseEffect::Create(fType,
990 permutationsTexture, noiseTexture,
991 m, paint.getAlpha());
993 SkDELETE(paintingData);
1001 bool SkPerlinNoiseShader::asFragmentProcessor(GrContext*, const SkPaint&, const SkMatrix&,
1002 const SkMatrix*, GrColor*,
1003 GrFragmentProcessor**) const {
1004 SkDEBUGFAIL("Should not call in GPU-less build");
1010 #ifndef SK_IGNORE_TO_STRING
1011 void SkPerlinNoiseShader::toString(SkString* str) const {
1012 str->append("SkPerlinNoiseShader: (");
1014 str->append("type: ");
1016 case kFractalNoise_Type:
1017 str->append("\"fractal noise\"");
1019 case kTurbulence_Type:
1020 str->append("\"turbulence\"");
1023 str->append("\"unknown\"");
1026 str->append(" base frequency: (");
1027 str->appendScalar(fBaseFrequencyX);
1029 str->appendScalar(fBaseFrequencyY);
1030 str->append(") number of octaves: ");
1031 str->appendS32(fNumOctaves);
1032 str->append(" seed: ");
1033 str->appendScalar(fSeed);
1034 str->append(" stitch tiles: ");
1035 str->append(fStitchTiles ? "true " : "false ");
1037 this->INHERITED::toString(str);