blob: 47de924b997e41b34bf902ee1174f7313e514cfe [file] [log] [blame]
sugoi@google.come3b4c502013-04-05 13:47:09 +00001/*
2 * Copyright 2013 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkDither.h"
9#include "SkPerlinNoiseShader.h"
commit-bot@chromium.orgc2a0ea62013-11-06 10:08:38 +000010#include "SkColorFilter.h"
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +000011#include "SkReadBuffer.h"
12#include "SkWriteBuffer.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000013#include "SkShader.h"
14#include "SkUnPreMultiply.h"
15#include "SkString.h"
16
17#if SK_SUPPORT_GPU
18#include "GrContext.h"
bsalomon@google.com77af6802013-10-02 13:04:56 +000019#include "GrCoordTransform.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000020#include "gl/GrGLEffect.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000021#include "GrTBackendEffectFactory.h"
22#include "SkGr.h"
23#endif
24
25static const int kBlockSize = 256;
26static const int kBlockMask = kBlockSize - 1;
27static const int kPerlinNoise = 4096;
28static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
29
30namespace {
31
32// noiseValue is the color component's value (or color)
33// limitValue is the maximum perlin noise array index value allowed
34// newValue is the current noise dimension (either width or height)
35inline int checkNoise(int noiseValue, int limitValue, int newValue) {
36 // If the noise value would bring us out of bounds of the current noise array while we are
37 // stiching noise tiles together, wrap the noise around the current dimension of the noise to
38 // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
39 if (noiseValue >= limitValue) {
40 noiseValue -= newValue;
41 }
42 if (noiseValue >= limitValue - 1) {
43 noiseValue -= newValue - 1;
44 }
45 return noiseValue;
46}
47
48inline SkScalar smoothCurve(SkScalar t) {
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +000049 static const SkScalar SK_Scalar3 = 3.0f;
sugoi@google.come3b4c502013-04-05 13:47:09 +000050
51 // returns t * t * (3 - 2 * t)
52 return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
53}
54
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +000055bool perlin_noise_type_is_valid(SkPerlinNoiseShader::Type type) {
56 return (SkPerlinNoiseShader::kFractalNoise_Type == type) ||
57 (SkPerlinNoiseShader::kTurbulence_Type == type);
58}
59
sugoi@google.come3b4c502013-04-05 13:47:09 +000060} // end namespace
61
62struct SkPerlinNoiseShader::StitchData {
63 StitchData()
64 : fWidth(0)
65 , fWrapX(0)
66 , fHeight(0)
67 , fWrapY(0)
68 {}
69
70 bool operator==(const StitchData& other) const {
71 return fWidth == other.fWidth &&
72 fWrapX == other.fWrapX &&
73 fHeight == other.fHeight &&
74 fWrapY == other.fWrapY;
75 }
76
77 int fWidth; // How much to subtract to wrap for stitching.
78 int fWrapX; // Minimum value to wrap.
79 int fHeight;
80 int fWrapY;
81};
82
83struct SkPerlinNoiseShader::PaintingData {
84 PaintingData(const SkISize& tileSize)
85 : fSeed(0)
86 , fTileSize(tileSize)
87 , fPermutationsBitmap(NULL)
88 , fNoiseBitmap(NULL)
89 {}
90
91 ~PaintingData()
92 {
93 SkDELETE(fPermutationsBitmap);
94 SkDELETE(fNoiseBitmap);
95 }
96
97 int fSeed;
98 uint8_t fLatticeSelector[kBlockSize];
99 uint16_t fNoise[4][kBlockSize][2];
100 SkPoint fGradient[4][kBlockSize];
101 SkISize fTileSize;
102 SkVector fBaseFrequency;
103 StitchData fStitchDataInit;
104
105private:
106
107 SkBitmap* fPermutationsBitmap;
108 SkBitmap* fNoiseBitmap;
109
110public:
111
112 inline int random() {
113 static const int gRandAmplitude = 16807; // 7**5; primitive root of m
114 static const int gRandQ = 127773; // m / a
115 static const int gRandR = 2836; // m % a
116
117 int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
118 if (result <= 0)
119 result += kRandMaximum;
120 fSeed = result;
121 return result;
122 }
123
124 void init(SkScalar seed)
125 {
126 static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
127
senorblanco@chromium.org857e3202014-01-09 17:41:42 +0000128 // According to the SVG spec, we must truncate (not round) the seed value.
129 fSeed = SkScalarTruncToInt(seed);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000130 // The seed value clamp to the range [1, kRandMaximum - 1].
sugoi@google.come3b4c502013-04-05 13:47:09 +0000131 if (fSeed <= 0) {
132 fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
133 }
134 if (fSeed > kRandMaximum - 1) {
135 fSeed = kRandMaximum - 1;
136 }
137 for (int channel = 0; channel < 4; ++channel) {
138 for (int i = 0; i < kBlockSize; ++i) {
139 fLatticeSelector[i] = i;
140 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
141 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
142 }
143 }
144 for (int i = kBlockSize - 1; i > 0; --i) {
145 int k = fLatticeSelector[i];
146 int j = random() % kBlockSize;
147 SkASSERT(j >= 0);
148 SkASSERT(j < kBlockSize);
149 fLatticeSelector[i] = fLatticeSelector[j];
150 fLatticeSelector[j] = k;
151 }
152
153 // Perform the permutations now
154 {
155 // Copy noise data
156 uint16_t noise[4][kBlockSize][2];
157 for (int i = 0; i < kBlockSize; ++i) {
158 for (int channel = 0; channel < 4; ++channel) {
159 for (int j = 0; j < 2; ++j) {
160 noise[channel][i][j] = fNoise[channel][i][j];
161 }
162 }
163 }
164 // Do permutations on noise data
165 for (int i = 0; i < kBlockSize; ++i) {
166 for (int channel = 0; channel < 4; ++channel) {
167 for (int j = 0; j < 2; ++j) {
168 fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
169 }
170 }
171 }
172 }
173
174 // Half of the largest possible value for 16 bit unsigned int
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +0000175 static const SkScalar gHalfMax16bits = 32767.5f;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000176
177 // Compute gradients from permutated noise data
178 for (int channel = 0; channel < 4; ++channel) {
179 for (int i = 0; i < kBlockSize; ++i) {
180 fGradient[channel][i] = SkPoint::Make(
181 SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
182 gInvBlockSizef),
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000183 SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
sugoi@google.come3b4c502013-04-05 13:47:09 +0000184 gInvBlockSizef));
185 fGradient[channel][i].normalize();
186 // Put the normalized gradient back into the noise data
187 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000188 fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000189 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000190 fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000191 }
192 }
193
194 // Invalidate bitmaps
195 SkDELETE(fPermutationsBitmap);
196 fPermutationsBitmap = NULL;
197 SkDELETE(fNoiseBitmap);
198 fNoiseBitmap = NULL;
199 }
200
201 void stitch() {
202 SkScalar tileWidth = SkIntToScalar(fTileSize.width());
203 SkScalar tileHeight = SkIntToScalar(fTileSize.height());
204 SkASSERT(tileWidth > 0 && tileHeight > 0);
205 // When stitching tiled turbulence, the frequencies must be adjusted
206 // so that the tile borders will be continuous.
207 if (fBaseFrequency.fX) {
reed@google.com8015cdd2013-12-18 15:49:32 +0000208 SkScalar lowFrequencx =
209 SkScalarFloorToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
210 SkScalar highFrequencx =
211 SkScalarCeilToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000212 // BaseFrequency should be non-negative according to the standard.
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000213 if (SkScalarDiv(fBaseFrequency.fX, lowFrequencx) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000214 SkScalarDiv(highFrequencx, fBaseFrequency.fX)) {
215 fBaseFrequency.fX = lowFrequencx;
216 } else {
217 fBaseFrequency.fX = highFrequencx;
218 }
219 }
220 if (fBaseFrequency.fY) {
reed@google.com8015cdd2013-12-18 15:49:32 +0000221 SkScalar lowFrequency =
222 SkScalarFloorToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
223 SkScalar highFrequency =
224 SkScalarCeilToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000225 if (SkScalarDiv(fBaseFrequency.fY, lowFrequency) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000226 SkScalarDiv(highFrequency, fBaseFrequency.fY)) {
227 fBaseFrequency.fY = lowFrequency;
228 } else {
229 fBaseFrequency.fY = highFrequency;
230 }
231 }
232 // Set up TurbulenceInitial stitch values.
233 fStitchDataInit.fWidth =
reed@google.com8015cdd2013-12-18 15:49:32 +0000234 SkScalarRoundToInt(tileWidth * fBaseFrequency.fX);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000235 fStitchDataInit.fWrapX = kPerlinNoise + fStitchDataInit.fWidth;
236 fStitchDataInit.fHeight =
reed@google.com8015cdd2013-12-18 15:49:32 +0000237 SkScalarRoundToInt(tileHeight * fBaseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000238 fStitchDataInit.fWrapY = kPerlinNoise + fStitchDataInit.fHeight;
239 }
240
241 SkBitmap* getPermutationsBitmap()
242 {
243 if (!fPermutationsBitmap) {
244 fPermutationsBitmap = SkNEW(SkBitmap);
reed@google.com9ebcac52014-01-24 18:53:42 +0000245 fPermutationsBitmap->allocPixels(SkImageInfo::MakeA8(kBlockSize, 1));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000246 uint8_t* bitmapPixels = fPermutationsBitmap->getAddr8(0, 0);
247 memcpy(bitmapPixels, fLatticeSelector, sizeof(uint8_t) * kBlockSize);
248 }
249 return fPermutationsBitmap;
250 }
251
252 SkBitmap* getNoiseBitmap()
253 {
254 if (!fNoiseBitmap) {
255 fNoiseBitmap = SkNEW(SkBitmap);
reed@google.com9ebcac52014-01-24 18:53:42 +0000256 fNoiseBitmap->allocPixels(SkImageInfo::MakeN32Premul(kBlockSize, 4));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000257 uint32_t* bitmapPixels = fNoiseBitmap->getAddr32(0, 0);
258 memcpy(bitmapPixels, fNoise[0][0], sizeof(uint16_t) * kBlockSize * 4 * 2);
259 }
260 return fNoiseBitmap;
261 }
262};
263
264SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
265 int numOctaves, SkScalar seed,
266 const SkISize* tileSize) {
267 return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY,
268 numOctaves, seed, tileSize));
269}
270
271SkShader* SkPerlinNoiseShader::CreateTubulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
272 int numOctaves, SkScalar seed,
273 const SkISize* tileSize) {
274 return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY,
275 numOctaves, seed, tileSize));
276}
277
278SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
279 SkScalar baseFrequencyX,
280 SkScalar baseFrequencyY,
281 int numOctaves,
282 SkScalar seed,
283 const SkISize* tileSize)
284 : fType(type)
285 , fBaseFrequencyX(baseFrequencyX)
286 , fBaseFrequencyY(baseFrequencyY)
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +0000287 , fNumOctaves(numOctaves > 255 ? 255 : numOctaves/*[0,255] octaves allowed*/)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000288 , fSeed(seed)
289 , fStitchTiles((tileSize != NULL) && !tileSize->isEmpty())
290 , fPaintingData(NULL)
291{
292 SkASSERT(numOctaves >= 0 && numOctaves < 256);
293 setTileSize(fStitchTiles ? *tileSize : SkISize::Make(0,0));
294 fMatrix.reset();
295}
296
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000297SkPerlinNoiseShader::SkPerlinNoiseShader(SkReadBuffer& buffer) :
sugoi@google.come3b4c502013-04-05 13:47:09 +0000298 INHERITED(buffer), fPaintingData(NULL) {
299 fType = (SkPerlinNoiseShader::Type) buffer.readInt();
300 fBaseFrequencyX = buffer.readScalar();
301 fBaseFrequencyY = buffer.readScalar();
302 fNumOctaves = buffer.readInt();
303 fSeed = buffer.readScalar();
304 fStitchTiles = buffer.readBool();
305 fTileSize.fWidth = buffer.readInt();
306 fTileSize.fHeight = buffer.readInt();
307 setTileSize(fTileSize);
308 fMatrix.reset();
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +0000309 buffer.validate(perlin_noise_type_is_valid(fType) &&
310 (fNumOctaves >= 0) && (fNumOctaves <= 255));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000311}
312
313SkPerlinNoiseShader::~SkPerlinNoiseShader() {
314 // Safety, should have been done in endContext()
315 SkDELETE(fPaintingData);
316}
317
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000318void SkPerlinNoiseShader::flatten(SkWriteBuffer& buffer) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000319 this->INHERITED::flatten(buffer);
320 buffer.writeInt((int) fType);
321 buffer.writeScalar(fBaseFrequencyX);
322 buffer.writeScalar(fBaseFrequencyY);
323 buffer.writeInt(fNumOctaves);
324 buffer.writeScalar(fSeed);
325 buffer.writeBool(fStitchTiles);
326 buffer.writeInt(fTileSize.fWidth);
327 buffer.writeInt(fTileSize.fHeight);
328}
329
330void SkPerlinNoiseShader::initPaint(PaintingData& paintingData)
331{
332 paintingData.init(fSeed);
333
334 // Set frequencies to original values
335 paintingData.fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
336 // Adjust frequecies based on size if stitching is enabled
337 if (fStitchTiles) {
338 paintingData.stitch();
339 }
340}
341
342void SkPerlinNoiseShader::setTileSize(const SkISize& tileSize) {
343 fTileSize = tileSize;
344
345 if (NULL == fPaintingData) {
346 fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize));
347 initPaint(*fPaintingData);
348 } else {
349 // Set Size
350 fPaintingData->fTileSize = fTileSize;
351 // Set frequencies to original values
352 fPaintingData->fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
353 // Adjust frequecies based on size if stitching is enabled
354 if (fStitchTiles) {
355 fPaintingData->stitch();
356 }
357 }
358}
359
360SkScalar SkPerlinNoiseShader::noise2D(int channel, const PaintingData& paintingData,
361 const StitchData& stitchData, const SkPoint& noiseVector)
362{
363 struct Noise {
364 int noisePositionIntegerValue;
365 SkScalar noisePositionFractionValue;
366 Noise(SkScalar component)
367 {
368 SkScalar position = component + kPerlinNoise;
369 noisePositionIntegerValue = SkScalarFloorToInt(position);
370 noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
371 }
372 };
373 Noise noiseX(noiseVector.x());
374 Noise noiseY(noiseVector.y());
375 SkScalar u, v;
376 // If stitching, adjust lattice points accordingly.
377 if (fStitchTiles) {
378 noiseX.noisePositionIntegerValue =
379 checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
380 noiseY.noisePositionIntegerValue =
381 checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
382 }
383 noiseX.noisePositionIntegerValue &= kBlockMask;
384 noiseY.noisePositionIntegerValue &= kBlockMask;
385 int latticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000386 paintingData.fLatticeSelector[noiseX.noisePositionIntegerValue] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000387 noiseY.noisePositionIntegerValue;
388 int nextLatticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000389 paintingData.fLatticeSelector[(noiseX.noisePositionIntegerValue + 1) & kBlockMask] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000390 noiseY.noisePositionIntegerValue;
391 SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
392 SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
393 // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
394 SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
395 noiseY.noisePositionFractionValue); // Offset (0,0)
396 u = paintingData.fGradient[channel][latticeIndex & kBlockMask].dot(fractionValue);
397 fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
398 v = paintingData.fGradient[channel][nextLatticeIndex & kBlockMask].dot(fractionValue);
399 SkScalar a = SkScalarInterp(u, v, sx);
400 fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
401 v = paintingData.fGradient[channel][(nextLatticeIndex + 1) & kBlockMask].dot(fractionValue);
402 fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
403 u = paintingData.fGradient[channel][(latticeIndex + 1) & kBlockMask].dot(fractionValue);
404 SkScalar b = SkScalarInterp(u, v, sx);
405 return SkScalarInterp(a, b, sy);
406}
407
408SkScalar SkPerlinNoiseShader::calculateTurbulenceValueForPoint(
409 int channel, const PaintingData& paintingData, StitchData& stitchData, const SkPoint& point)
410{
411 if (fStitchTiles) {
412 // Set up TurbulenceInitial stitch values.
413 stitchData = paintingData.fStitchDataInit;
414 }
415 SkScalar turbulenceFunctionResult = 0;
416 SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), paintingData.fBaseFrequency.fX),
417 SkScalarMul(point.y(), paintingData.fBaseFrequency.fY)));
418 SkScalar ratio = SK_Scalar1;
419 for (int octave = 0; octave < fNumOctaves; ++octave) {
420 SkScalar noise = noise2D(channel, paintingData, stitchData, noiseVector);
421 turbulenceFunctionResult += SkScalarDiv(
422 (fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio);
423 noiseVector.fX *= 2;
424 noiseVector.fY *= 2;
425 ratio *= 2;
426 if (fStitchTiles) {
427 // Update stitch values
428 stitchData.fWidth *= 2;
429 stitchData.fWrapX = stitchData.fWidth + kPerlinNoise;
430 stitchData.fHeight *= 2;
431 stitchData.fWrapY = stitchData.fHeight + kPerlinNoise;
432 }
433 }
434
435 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
436 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
437 if (fType == kFractalNoise_Type) {
438 turbulenceFunctionResult =
439 SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
440 }
441
442 if (channel == 3) { // Scale alpha by paint value
443 turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult,
444 SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255)));
445 }
446
447 // Clamp result
448 return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
449}
450
451SkPMColor SkPerlinNoiseShader::shade(const SkPoint& point, StitchData& stitchData) {
452 SkMatrix matrix = fMatrix;
senorblanco@chromium.org47d98c82014-03-03 14:58:09 +0000453 matrix.postConcat(getLocalMatrix());
sugoi@google.come3b4c502013-04-05 13:47:09 +0000454 SkMatrix invMatrix;
455 if (!matrix.invert(&invMatrix)) {
456 invMatrix.reset();
457 } else {
458 invMatrix.postConcat(invMatrix); // Square the matrix
459 }
460 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
461 // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
462 matrix.postTranslate(SK_Scalar1, SK_Scalar1);
463 SkPoint newPoint;
464 matrix.mapPoints(&newPoint, &point, 1);
465 invMatrix.mapPoints(&newPoint, &newPoint, 1);
466 newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
467 newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
468
469 U8CPU rgba[4];
470 for (int channel = 3; channel >= 0; --channel) {
471 rgba[channel] = SkScalarFloorToInt(255 *
472 calculateTurbulenceValueForPoint(channel, *fPaintingData, stitchData, newPoint));
473 }
474 return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
475}
476
477bool SkPerlinNoiseShader::setContext(const SkBitmap& device, const SkPaint& paint,
478 const SkMatrix& matrix) {
479 fMatrix = matrix;
480 return INHERITED::setContext(device, paint, matrix);
481}
482
483void SkPerlinNoiseShader::shadeSpan(int x, int y, SkPMColor result[], int count) {
484 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
485 StitchData stitchData;
486 for (int i = 0; i < count; ++i) {
487 result[i] = shade(point, stitchData);
488 point.fX += SK_Scalar1;
489 }
490}
491
492void SkPerlinNoiseShader::shadeSpan16(int x, int y, uint16_t result[], int count) {
493 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
494 StitchData stitchData;
495 DITHER_565_SCAN(y);
496 for (int i = 0; i < count; ++i) {
497 unsigned dither = DITHER_VALUE(x);
498 result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
499 DITHER_INC_X(x);
500 point.fX += SK_Scalar1;
501 }
502}
503
504/////////////////////////////////////////////////////////////////////
505
commit-bot@chromium.org344cf452013-06-17 14:19:01 +0000506#if SK_SUPPORT_GPU
sugoi@google.come3b4c502013-04-05 13:47:09 +0000507
508#include "GrTBackendEffectFactory.h"
509
sugoi@google.com4775cba2013-04-17 13:46:56 +0000510class GrGLNoise : public GrGLEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000511public:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000512 GrGLNoise(const GrBackendEffectFactory& factory,
513 const GrDrawEffect& drawEffect);
514 virtual ~GrGLNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000515
sugoi@google.com4775cba2013-04-17 13:46:56 +0000516 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
517
518 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
519
520protected:
521 SkPerlinNoiseShader::Type fType;
522 bool fStitchTiles;
523 int fNumOctaves;
524 GrGLUniformManager::UniformHandle fBaseFrequencyUni;
525 GrGLUniformManager::UniformHandle fAlphaUni;
526 GrGLUniformManager::UniformHandle fInvMatrixUni;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000527
528private:
529 typedef GrGLEffect INHERITED;
530};
531
532class GrGLPerlinNoise : public GrGLNoise {
533public:
sugoi@google.come3b4c502013-04-05 13:47:09 +0000534 GrGLPerlinNoise(const GrBackendEffectFactory& factory,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000535 const GrDrawEffect& drawEffect)
536 : GrGLNoise(factory, drawEffect) {}
537 virtual ~GrGLPerlinNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000538
539 virtual void emitCode(GrGLShaderBuilder*,
540 const GrDrawEffect&,
541 EffectKey,
542 const char* outputColor,
543 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000544 const TransformedCoordsArray&,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000545 const TextureSamplerArray&) SK_OVERRIDE;
546
sugoi@google.com4775cba2013-04-17 13:46:56 +0000547 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000548
549private:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000550 GrGLUniformManager::UniformHandle fStitchDataUni;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000551
sugoi@google.com4775cba2013-04-17 13:46:56 +0000552 typedef GrGLNoise INHERITED;
553};
554
555class GrGLSimplexNoise : public GrGLNoise {
556 // Note : This is for reference only. GrGLPerlinNoise is used for processing.
557public:
558 GrGLSimplexNoise(const GrBackendEffectFactory& factory,
559 const GrDrawEffect& drawEffect)
560 : GrGLNoise(factory, drawEffect) {}
561
562 virtual ~GrGLSimplexNoise() {}
563
564 virtual void emitCode(GrGLShaderBuilder*,
565 const GrDrawEffect&,
566 EffectKey,
567 const char* outputColor,
568 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000569 const TransformedCoordsArray&,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000570 const TextureSamplerArray&) SK_OVERRIDE;
571
572 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
573
574private:
575 GrGLUniformManager::UniformHandle fSeedUni;
576
577 typedef GrGLNoise INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000578};
579
580/////////////////////////////////////////////////////////////////////
581
sugoi@google.com4775cba2013-04-17 13:46:56 +0000582class GrNoiseEffect : public GrEffect {
583public:
584 virtual ~GrNoiseEffect() { }
585
586 SkPerlinNoiseShader::Type type() const { return fType; }
587 bool stitchTiles() const { return fStitchTiles; }
588 const SkVector& baseFrequency() const { return fBaseFrequency; }
589 int numOctaves() const { return fNumOctaves; }
bsalomon@google.com77af6802013-10-02 13:04:56 +0000590 const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000591 uint8_t alpha() const { return fAlpha; }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000592
593 void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE {
594 *validFlags = 0; // This is noise. Nothing is constant.
595 }
596
597protected:
598 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
599 const GrNoiseEffect& s = CastEffect<GrNoiseEffect>(sBase);
600 return fType == s.fType &&
601 fBaseFrequency == s.fBaseFrequency &&
602 fNumOctaves == s.fNumOctaves &&
603 fStitchTiles == s.fStitchTiles &&
bsalomon@google.com77af6802013-10-02 13:04:56 +0000604 fCoordTransform.getMatrix() == s.fCoordTransform.getMatrix() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000605 fAlpha == s.fAlpha;
606 }
607
608 GrNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, int numOctaves,
609 bool stitchTiles, const SkMatrix& matrix, uint8_t alpha)
610 : fType(type)
611 , fBaseFrequency(baseFrequency)
612 , fNumOctaves(numOctaves)
613 , fStitchTiles(stitchTiles)
614 , fMatrix(matrix)
615 , fAlpha(alpha) {
bsalomon@google.com77af6802013-10-02 13:04:56 +0000616 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
617 // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions.
618 SkMatrix m = matrix;
619 m.postTranslate(SK_Scalar1, SK_Scalar1);
620 fCoordTransform.reset(kLocal_GrCoordSet, m);
621 this->addCoordTransform(&fCoordTransform);
commit-bot@chromium.orga34995e2013-10-23 05:42:03 +0000622 this->setWillNotUseInputColor();
sugoi@google.com4775cba2013-04-17 13:46:56 +0000623 }
624
625 SkPerlinNoiseShader::Type fType;
bsalomon@google.com77af6802013-10-02 13:04:56 +0000626 GrCoordTransform fCoordTransform;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000627 SkVector fBaseFrequency;
628 int fNumOctaves;
629 bool fStitchTiles;
630 SkMatrix fMatrix;
631 uint8_t fAlpha;
632
633private:
634 typedef GrEffect INHERITED;
635};
636
637class GrPerlinNoiseEffect : public GrNoiseEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000638public:
639 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
640 int numOctaves, bool stitchTiles,
641 const SkPerlinNoiseShader::StitchData& stitchData,
642 GrTexture* permutationsTexture, GrTexture* noiseTexture,
643 const SkMatrix& matrix, uint8_t alpha) {
644 AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves,
645 stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha)));
646 return CreateEffectRef(effect);
647 }
648
649 virtual ~GrPerlinNoiseEffect() { }
650
651 static const char* Name() { return "PerlinNoise"; }
652 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
653 return GrTBackendEffectFactory<GrPerlinNoiseEffect>::getInstance();
654 }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000655 const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000656
657 typedef GrGLPerlinNoise GLEffect;
658
sugoi@google.come3b4c502013-04-05 13:47:09 +0000659private:
660 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
661 const GrPerlinNoiseEffect& s = CastEffect<GrPerlinNoiseEffect>(sBase);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000662 return INHERITED::onIsEqual(sBase) &&
663 fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() &&
sugoi@google.come3b4c502013-04-05 13:47:09 +0000664 fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000665 fStitchData == s.fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000666 }
667
668 GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
669 int numOctaves, bool stitchTiles,
670 const SkPerlinNoiseShader::StitchData& stitchData,
671 GrTexture* permutationsTexture, GrTexture* noiseTexture,
672 const SkMatrix& matrix, uint8_t alpha)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000673 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
674 , fPermutationsAccess(permutationsTexture)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000675 , fNoiseAccess(noiseTexture)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000676 , fStitchData(stitchData) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000677 this->addTextureAccess(&fPermutationsAccess);
678 this->addTextureAccess(&fNoiseAccess);
679 }
680
sugoi@google.com4775cba2013-04-17 13:46:56 +0000681 GR_DECLARE_EFFECT_TEST;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000682
683 GrTextureAccess fPermutationsAccess;
684 GrTextureAccess fNoiseAccess;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000685 SkPerlinNoiseShader::StitchData fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000686
sugoi@google.com4775cba2013-04-17 13:46:56 +0000687 typedef GrNoiseEffect INHERITED;
688};
689
690class GrSimplexNoiseEffect : public GrNoiseEffect {
691 // Note : This is for reference only. GrPerlinNoiseEffect is used for processing.
692public:
693 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
694 int numOctaves, bool stitchTiles, const SkScalar seed,
695 const SkMatrix& matrix, uint8_t alpha) {
696 AutoEffectUnref effect(SkNEW_ARGS(GrSimplexNoiseEffect, (type, baseFrequency, numOctaves,
697 stitchTiles, seed, matrix, alpha)));
698 return CreateEffectRef(effect);
699 }
700
701 virtual ~GrSimplexNoiseEffect() { }
702
703 static const char* Name() { return "SimplexNoise"; }
704 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
705 return GrTBackendEffectFactory<GrSimplexNoiseEffect>::getInstance();
706 }
707 const SkScalar& seed() const { return fSeed; }
708
709 typedef GrGLSimplexNoise GLEffect;
710
711private:
712 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
713 const GrSimplexNoiseEffect& s = CastEffect<GrSimplexNoiseEffect>(sBase);
714 return INHERITED::onIsEqual(sBase) && fSeed == s.fSeed;
715 }
716
717 GrSimplexNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
718 int numOctaves, bool stitchTiles, const SkScalar seed,
719 const SkMatrix& matrix, uint8_t alpha)
720 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
721 , fSeed(seed) {
722 }
723
724 SkScalar fSeed;
725
726 typedef GrNoiseEffect INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000727};
728
729/////////////////////////////////////////////////////////////////////
sugoi@google.come3b4c502013-04-05 13:47:09 +0000730GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect);
731
commit-bot@chromium.orge0e7cfe2013-09-09 20:09:12 +0000732GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkRandom* random,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000733 GrContext* context,
734 const GrDrawTargetCaps&,
735 GrTexture**) {
sugoi@google.com423ac132013-04-18 14:04:57 +0000736 int numOctaves = random->nextRangeU(2, 10);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000737 bool stitchTiles = random->nextBool();
738 SkScalar seed = SkIntToScalar(random->nextU());
739 SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +0000740 SkScalar baseFrequencyX = random->nextRangeScalar(0.01f,
741 0.99f);
742 SkScalar baseFrequencyY = random->nextRangeScalar(0.01f,
743 0.99f);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000744
745 SkShader* shader = random->nextBool() ?
746 SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
747 stitchTiles ? &tileSize : NULL) :
748 SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
749 stitchTiles ? &tileSize : NULL);
750
751 SkPaint paint;
752 GrEffectRef* effect = shader->asNewEffect(context, paint);
753
754 SkDELETE(shader);
755
756 return effect;
757}
sugoi@google.com4775cba2013-04-17 13:46:56 +0000758
sugoi@google.come3b4c502013-04-05 13:47:09 +0000759/////////////////////////////////////////////////////////////////////
760
sugoi@google.com4775cba2013-04-17 13:46:56 +0000761void GrGLSimplexNoise::emitCode(GrGLShaderBuilder* builder,
762 const GrDrawEffect&,
763 EffectKey key,
764 const char* outputColor,
765 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000766 const TransformedCoordsArray& coords,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000767 const TextureSamplerArray&) {
768 sk_ignore_unused_variable(inputColor);
769
bsalomon@google.com77af6802013-10-02 13:04:56 +0000770 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000771
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000772 fSeedUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000773 kFloat_GrSLType, "seed");
774 const char* seedUni = builder->getUniformCStr(fSeedUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000775 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000776 kMat33f_GrSLType, "invMatrix");
777 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000778 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000779 kVec2f_GrSLType, "baseFrequency");
780 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000781 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000782 kFloat_GrSLType, "alpha");
783 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
784
785 // Add vec3 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000786 static const GrGLShaderVar gVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000787 GrGLShaderVar("x", kVec3f_GrSLType)
788 };
789
790 SkString mod289_3_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000791 builder->fsEmitFunction(kVec3f_GrSLType,
792 "mod289", SK_ARRAY_COUNT(gVec3Args), gVec3Args,
793 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
794 "return x - floor(x * C.xxx) * C.yyy;", &mod289_3_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000795
796 // Add vec4 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000797 static const GrGLShaderVar gVec4Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000798 GrGLShaderVar("x", kVec4f_GrSLType)
799 };
800
801 SkString mod289_4_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000802 builder->fsEmitFunction(kVec4f_GrSLType,
803 "mod289", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
804 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
805 "return x - floor(x * C.xxxx) * C.yyyy;", &mod289_4_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000806
807 // Add vec4 permute function
sugoi@google.comd537af52013-06-10 13:59:25 +0000808 SkString permuteCode;
809 permuteCode.appendf("const vec2 C = vec2(34.0, 1.0);\n"
810 "return %s(((x * C.xxxx) + C.yyyy) * x);", mod289_4_funcName.c_str());
811 SkString permuteFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000812 builder->fsEmitFunction(kVec4f_GrSLType,
813 "permute", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
814 permuteCode.c_str(), &permuteFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000815
816 // Add vec4 taylorInvSqrt function
sugoi@google.comd537af52013-06-10 13:59:25 +0000817 SkString taylorInvSqrtFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000818 builder->fsEmitFunction(kVec4f_GrSLType,
819 "taylorInvSqrt", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
820 "const vec2 C = vec2(-0.85373472095314, 1.79284291400159);\n"
821 "return x * C.xxxx + C.yyyy;", &taylorInvSqrtFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000822
823 // Add vec3 noise function
sugoi@google.comd537af52013-06-10 13:59:25 +0000824 static const GrGLShaderVar gNoiseVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000825 GrGLShaderVar("v", kVec3f_GrSLType)
826 };
827
sugoi@google.comd537af52013-06-10 13:59:25 +0000828 SkString noiseCode;
829 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000830 "const vec2 C = vec2(1.0/6.0, 1.0/3.0);\n"
831 "const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n"
832
833 // First corner
834 "vec3 i = floor(v + dot(v, C.yyy));\n"
835 "vec3 x0 = v - i + dot(i, C.xxx);\n"
836
837 // Other corners
838 "vec3 g = step(x0.yzx, x0.xyz);\n"
839 "vec3 l = 1.0 - g;\n"
840 "vec3 i1 = min(g.xyz, l.zxy);\n"
841 "vec3 i2 = max(g.xyz, l.zxy);\n"
842
843 "vec3 x1 = x0 - i1 + C.xxx;\n"
844 "vec3 x2 = x0 - i2 + C.yyy;\n" // 2.0*C.x = 1/3 = C.y
845 "vec3 x3 = x0 - D.yyy;\n" // -1.0+3.0*C.x = -0.5 = -D.y
846 );
847
sugoi@google.comd537af52013-06-10 13:59:25 +0000848 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000849 // Permutations
850 "i = %s(i);\n"
851 "vec4 p = %s(%s(%s(\n"
852 " i.z + vec4(0.0, i1.z, i2.z, 1.0)) +\n"
853 " i.y + vec4(0.0, i1.y, i2.y, 1.0)) +\n"
854 " i.x + vec4(0.0, i1.x, i2.x, 1.0));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000855 mod289_3_funcName.c_str(), permuteFuncName.c_str(), permuteFuncName.c_str(),
856 permuteFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000857
sugoi@google.comd537af52013-06-10 13:59:25 +0000858 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000859 // Gradients: 7x7 points over a square, mapped onto an octahedron.
860 // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
861 "float n_ = 0.142857142857;\n" // 1.0/7.0
862 "vec3 ns = n_ * D.wyz - D.xzx;\n"
863
864 "vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\n" // mod(p,7*7)
865
866 "vec4 x_ = floor(j * ns.z);\n"
867 "vec4 y_ = floor(j - 7.0 * x_);" // mod(j,N)
868
869 "vec4 x = x_ *ns.x + ns.yyyy;\n"
870 "vec4 y = y_ *ns.x + ns.yyyy;\n"
871 "vec4 h = 1.0 - abs(x) - abs(y);\n"
872
873 "vec4 b0 = vec4(x.xy, y.xy);\n"
874 "vec4 b1 = vec4(x.zw, y.zw);\n"
875 );
876
sugoi@google.comd537af52013-06-10 13:59:25 +0000877 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000878 "vec4 s0 = floor(b0) * 2.0 + 1.0;\n"
879 "vec4 s1 = floor(b1) * 2.0 + 1.0;\n"
880 "vec4 sh = -step(h, vec4(0.0));\n"
881
882 "vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;\n"
883 "vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;\n"
884
885 "vec3 p0 = vec3(a0.xy, h.x);\n"
886 "vec3 p1 = vec3(a0.zw, h.y);\n"
887 "vec3 p2 = vec3(a1.xy, h.z);\n"
888 "vec3 p3 = vec3(a1.zw, h.w);\n"
889 );
890
sugoi@google.comd537af52013-06-10 13:59:25 +0000891 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000892 // Normalise gradients
893 "vec4 norm = %s(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n"
894 "p0 *= norm.x;\n"
895 "p1 *= norm.y;\n"
896 "p2 *= norm.z;\n"
897 "p3 *= norm.w;\n"
898
899 // Mix final noise value
900 "vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n"
901 "m = m * m;\n"
902 "return 42.0 * dot(m*m, vec4(dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3)));",
sugoi@google.comd537af52013-06-10 13:59:25 +0000903 taylorInvSqrtFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000904
sugoi@google.comd537af52013-06-10 13:59:25 +0000905 SkString noiseFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000906 builder->fsEmitFunction(kFloat_GrSLType,
907 "snoise", SK_ARRAY_COUNT(gNoiseVec3Args), gNoiseVec3Args,
908 noiseCode.c_str(), &noiseFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000909
910 const char* noiseVecIni = "noiseVecIni";
911 const char* factors = "factors";
912 const char* sum = "sum";
913 const char* xOffsets = "xOffsets";
914 const char* yOffsets = "yOffsets";
915 const char* channel = "channel";
916
917 // Fill with some prime numbers
918 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(13.0, 53.0, 101.0, 151.0);\n", xOffsets);
919 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(109.0, 167.0, 23.0, 67.0);\n", yOffsets);
920
921 // There are rounding errors if the floor operation is not performed here
922 builder->fsCodeAppendf(
923 "\t\tvec3 %s = vec3(floor((%s*vec3(%s, 1.0)).xy) * vec2(0.66) * %s, 0.0);\n",
commit-bot@chromium.org7ab7ca42013-08-28 15:59:13 +0000924 noiseVecIni, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000925
926 // Perturb the texcoords with three components of noise
927 builder->fsCodeAppendf("\t\t%s += 0.1 * vec3(%s(%s + vec3( 0.0, 0.0, %s)),"
928 "%s(%s + vec3( 43.0, 17.0, %s)),"
929 "%s(%s + vec3(-17.0, -43.0, %s)));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000930 noiseVecIni, noiseFuncName.c_str(), noiseVecIni, seedUni,
931 noiseFuncName.c_str(), noiseVecIni, seedUni,
932 noiseFuncName.c_str(), noiseVecIni, seedUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000933
934 builder->fsCodeAppendf("\t\t%s = vec4(0.0);\n", outputColor);
935
936 builder->fsCodeAppendf("\t\tvec3 %s = vec3(1.0);\n", factors);
937 builder->fsCodeAppendf("\t\tfloat %s = 0.0;\n", sum);
938
939 // Loop over all octaves
940 builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {\n", fNumOctaves);
941
942 // Loop over the 4 channels
943 builder->fsCodeAppendf("\t\t\tfor (int %s = 3; %s >= 0; --%s) {\n", channel, channel, channel);
944
945 builder->fsCodeAppendf(
946 "\t\t\t\t%s[channel] += %s.x * %s(%s * %s.yyy - vec3(%s[%s], %s[%s], %s * %s.z));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000947 outputColor, factors, noiseFuncName.c_str(), noiseVecIni, factors, xOffsets, channel,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000948 yOffsets, channel, seedUni, factors);
949
950 builder->fsCodeAppend("\t\t\t}\n"); // end of the for loop on channels
951
952 builder->fsCodeAppendf("\t\t\t%s += %s.x;\n", sum, factors);
953 builder->fsCodeAppendf("\t\t\t%s *= vec3(0.5, 2.0, 0.75);\n", factors);
954
955 builder->fsCodeAppend("\t\t}\n"); // end of the for loop on octaves
956
957 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
958 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
959 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
960 builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5 / %s) + vec4(0.5);\n",
961 outputColor, outputColor, sum);
962 } else {
963 builder->fsCodeAppendf("\t\t%s = abs(%s / vec4(%s));\n",
964 outputColor, outputColor, sum);
965 }
966
967 builder->fsCodeAppendf("\t\t%s.a *= %s;\n", outputColor, alphaUni);
968
969 // Clamp values
970 builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);\n", outputColor, outputColor);
971
972 // Pre-multiply the result
973 builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
974 outputColor, outputColor, outputColor, outputColor);
975}
976
sugoi@google.come3b4c502013-04-05 13:47:09 +0000977void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder,
978 const GrDrawEffect&,
979 EffectKey key,
980 const char* outputColor,
981 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000982 const TransformedCoordsArray& coords,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000983 const TextureSamplerArray& samplers) {
984 sk_ignore_unused_variable(inputColor);
985
bsalomon@google.com77af6802013-10-02 13:04:56 +0000986 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000987
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000988 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000989 kMat33f_GrSLType, "invMatrix");
990 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000991 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000992 kVec2f_GrSLType, "baseFrequency");
993 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000994 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000995 kFloat_GrSLType, "alpha");
996 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
997
998 const char* stitchDataUni = NULL;
999 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001000 fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001001 kVec2f_GrSLType, "stitchData");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001002 stitchDataUni = builder->getUniformCStr(fStitchDataUni);
1003 }
1004
sugoi@google.comd537af52013-06-10 13:59:25 +00001005 // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
1006 const char* chanCoordR = "0.125";
1007 const char* chanCoordG = "0.375";
1008 const char* chanCoordB = "0.625";
1009 const char* chanCoordA = "0.875";
1010 const char* chanCoord = "chanCoord";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001011 const char* stitchData = "stitchData";
1012 const char* ratio = "ratio";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001013 const char* noiseXY = "noiseXY";
1014 const char* noiseVec = "noiseVec";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001015 const char* noiseSmooth = "noiseSmooth";
1016 const char* fractVal = "fractVal";
1017 const char* uv = "uv";
1018 const char* ab = "ab";
1019 const char* latticeIdx = "latticeIdx";
1020 const char* lattice = "lattice";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001021 const char* inc8bit = "0.00390625"; // 1.0 / 256.0
1022 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
1023 // [-1,1] vector and perform a dot product between that vector and the provided vector.
1024 const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
1025
sugoi@google.comd537af52013-06-10 13:59:25 +00001026 // Add noise function
1027 static const GrGLShaderVar gPerlinNoiseArgs[] = {
1028 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001029 GrGLShaderVar(noiseVec, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001030 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001031
sugoi@google.comd537af52013-06-10 13:59:25 +00001032 static const GrGLShaderVar gPerlinNoiseStitchArgs[] = {
1033 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001034 GrGLShaderVar(noiseVec, kVec2f_GrSLType),
1035 GrGLShaderVar(stitchData, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001036 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001037
sugoi@google.comd537af52013-06-10 13:59:25 +00001038 SkString noiseCode;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001039
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001040 noiseCode.appendf("\tvec4 %s = vec4(floor(%s), fract(%s));", noiseXY, noiseVec, noiseVec);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001041
1042 // smooth curve : t * t * (3 - 2 * t)
sugoi@google.comd537af52013-06-10 13:59:25 +00001043 noiseCode.appendf("\n\tvec2 %s = %s.zw * %s.zw * (vec2(3.0) - vec2(2.0) * %s.zw);",
1044 noiseSmooth, noiseXY, noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001045
1046 // Adjust frequencies if we're stitching tiles
1047 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001048 noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001049 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001050 noiseCode.appendf("\n\tif(%s.x >= (%s.x - 1.0)) { %s.x -= (%s.x - 1.0); }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001051 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001052 noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001053 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001054 noiseCode.appendf("\n\tif(%s.y >= (%s.y - 1.0)) { %s.y -= (%s.y - 1.0); }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001055 noiseXY, stitchData, noiseXY, stitchData);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001056 }
1057
1058 // Get texture coordinates and normalize
sugoi@google.comd537af52013-06-10 13:59:25 +00001059 noiseCode.appendf("\n\t%s.xy = fract(floor(mod(%s.xy, 256.0)) / vec2(256.0));\n",
1060 noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001061
1062 // Get permutation for x
1063 {
1064 SkString xCoords("");
1065 xCoords.appendf("vec2(%s.x, 0.5)", noiseXY);
1066
sugoi@google.comd537af52013-06-10 13:59:25 +00001067 noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
1068 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1069 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001070 }
1071
1072 // Get permutation for x + 1
1073 {
1074 SkString xCoords("");
1075 xCoords.appendf("vec2(fract(%s.x + %s), 0.5)", noiseXY, inc8bit);
1076
sugoi@google.comd537af52013-06-10 13:59:25 +00001077 noiseCode.appendf("\n\t%s.y = ", latticeIdx);
1078 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1079 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001080 }
1081
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001082#if defined(SK_BUILD_FOR_ANDROID)
1083 // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
1084 // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
1085 // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
1086 // (or 0.484368 here). The following rounding operation prevents these precision issues from
1087 // affecting the result of the noise by making sure that we only have multiples of 1/255.
1088 // (Note that 1/255 is about 0.003921569, which is the value used here).
1089 noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);",
1090 latticeIdx, latticeIdx);
1091#endif
1092
sugoi@google.come3b4c502013-04-05 13:47:09 +00001093 // Get (x,y) coordinates with the permutated x
sugoi@google.comd537af52013-06-10 13:59:25 +00001094 noiseCode.appendf("\n\t%s = fract(%s + %s.yy);", latticeIdx, latticeIdx, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001095
sugoi@google.comd537af52013-06-10 13:59:25 +00001096 noiseCode.appendf("\n\tvec2 %s = %s.zw;", fractVal, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001097
sugoi@google.comd537af52013-06-10 13:59:25 +00001098 noiseCode.appendf("\n\n\tvec2 %s;", uv);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001099 // Compute u, at offset (0,0)
1100 {
1101 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001102 latticeCoords.appendf("vec2(%s.x, %s)", latticeIdx, chanCoord);
1103 noiseCode.appendf("\n\tvec4 %s = ", lattice);
1104 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1105 kVec2f_GrSLType);
1106 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1107 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001108 }
1109
sugoi@google.comd537af52013-06-10 13:59:25 +00001110 noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001111 // Compute v, at offset (-1,0)
1112 {
1113 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001114 latticeCoords.appendf("vec2(%s.y, %s)", latticeIdx, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001115 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001116 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1117 kVec2f_GrSLType);
1118 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1119 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001120 }
1121
1122 // Compute 'a' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001123 noiseCode.appendf("\n\tvec2 %s;", ab);
1124 noiseCode.appendf("\n\t%s.x = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001125
sugoi@google.comd537af52013-06-10 13:59:25 +00001126 noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001127 // Compute v, at offset (-1,-1)
1128 {
1129 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001130 latticeCoords.appendf("vec2(fract(%s.y + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001131 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001132 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1133 kVec2f_GrSLType);
1134 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1135 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001136 }
1137
sugoi@google.comd537af52013-06-10 13:59:25 +00001138 noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001139 // Compute u, at offset (0,-1)
1140 {
1141 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001142 latticeCoords.appendf("vec2(fract(%s.x + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001143 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001144 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1145 kVec2f_GrSLType);
1146 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1147 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001148 }
1149
1150 // Compute 'b' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001151 noiseCode.appendf("\n\t%s.y = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001152 // Compute the noise as a linear interpolation of 'a' and 'b'
sugoi@google.comd537af52013-06-10 13:59:25 +00001153 noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001154
sugoi@google.comd537af52013-06-10 13:59:25 +00001155 SkString noiseFuncName;
1156 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001157 builder->fsEmitFunction(kFloat_GrSLType,
1158 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
1159 gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001160 } else {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001161 builder->fsEmitFunction(kFloat_GrSLType,
1162 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
1163 gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001164 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001165
sugoi@google.comd537af52013-06-10 13:59:25 +00001166 // There are rounding errors if the floor operation is not performed here
1167 builder->fsCodeAppendf("\n\t\tvec2 %s = floor((%s * vec3(%s, 1.0)).xy) * %s;",
commit-bot@chromium.org7ab7ca42013-08-28 15:59:13 +00001168 noiseVec, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.comd537af52013-06-10 13:59:25 +00001169
1170 // Clear the color accumulator
1171 builder->fsCodeAppendf("\n\t\t%s = vec4(0.0);", outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001172
1173 if (fStitchTiles) {
sugoi@google.comd537af52013-06-10 13:59:25 +00001174 // Set up TurbulenceInitial stitch values.
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001175 builder->fsCodeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001176 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001177
sugoi@google.comd537af52013-06-10 13:59:25 +00001178 builder->fsCodeAppendf("\n\t\tfloat %s = 1.0;", ratio);
1179
1180 // Loop over all octaves
1181 builder->fsCodeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
1182
1183 builder->fsCodeAppendf("\n\t\t\t%s += ", outputColor);
1184 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1185 builder->fsCodeAppend("abs(");
1186 }
1187 if (fStitchTiles) {
1188 builder->fsCodeAppendf(
1189 "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
1190 "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
1191 noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
1192 noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
1193 noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
1194 noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
1195 } else {
1196 builder->fsCodeAppendf(
1197 "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
1198 "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
1199 noiseFuncName.c_str(), chanCoordR, noiseVec,
1200 noiseFuncName.c_str(), chanCoordG, noiseVec,
1201 noiseFuncName.c_str(), chanCoordB, noiseVec,
1202 noiseFuncName.c_str(), chanCoordA, noiseVec);
1203 }
1204 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1205 builder->fsCodeAppendf(")"); // end of "abs("
1206 }
1207 builder->fsCodeAppendf(" * %s;", ratio);
1208
1209 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
1210 builder->fsCodeAppendf("\n\t\t\t%s *= 0.5;", ratio);
1211
1212 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001213 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData);
sugoi@google.comd537af52013-06-10 13:59:25 +00001214 }
1215 builder->fsCodeAppend("\n\t\t}"); // end of the for loop on octaves
sugoi@google.come3b4c502013-04-05 13:47:09 +00001216
1217 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
1218 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
1219 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
sugoi@google.comd537af52013-06-10 13:59:25 +00001220 builder->fsCodeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001221 }
1222
sugoi@google.comd537af52013-06-10 13:59:25 +00001223 builder->fsCodeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001224
1225 // Clamp values
sugoi@google.comd537af52013-06-10 13:59:25 +00001226 builder->fsCodeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001227
1228 // Pre-multiply the result
sugoi@google.comd537af52013-06-10 13:59:25 +00001229 builder->fsCodeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
sugoi@google.come3b4c502013-04-05 13:47:09 +00001230 outputColor, outputColor, outputColor, outputColor);
1231}
1232
sugoi@google.com4775cba2013-04-17 13:46:56 +00001233GrGLNoise::GrGLNoise(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect)
sugoi@google.come3b4c502013-04-05 13:47:09 +00001234 : INHERITED (factory)
1235 , fType(drawEffect.castEffect<GrPerlinNoiseEffect>().type())
1236 , fStitchTiles(drawEffect.castEffect<GrPerlinNoiseEffect>().stitchTiles())
bsalomon@google.com77af6802013-10-02 13:04:56 +00001237 , fNumOctaves(drawEffect.castEffect<GrPerlinNoiseEffect>().numOctaves()) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001238}
1239
sugoi@google.com4775cba2013-04-17 13:46:56 +00001240GrGLEffect::EffectKey GrGLNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001241 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1242
1243 EffectKey key = turbulence.numOctaves();
1244
1245 key = key << 3; // Make room for next 3 bits
1246
1247 switch (turbulence.type()) {
1248 case SkPerlinNoiseShader::kFractalNoise_Type:
1249 key |= 0x1;
1250 break;
1251 case SkPerlinNoiseShader::kTurbulence_Type:
1252 key |= 0x2;
1253 break;
1254 default:
1255 // leave key at 0
1256 break;
1257 }
1258
1259 if (turbulence.stitchTiles()) {
1260 key |= 0x4; // Flip the 3rd bit if tile stitching is on
1261 }
1262
bsalomon@google.com77af6802013-10-02 13:04:56 +00001263 return key;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001264}
1265
sugoi@google.com4775cba2013-04-17 13:46:56 +00001266void GrGLNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001267 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1268
1269 const SkVector& baseFrequency = turbulence.baseFrequency();
1270 uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001271 uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
1272
1273 SkMatrix m = turbulence.matrix();
bsalomon@google.com77af6802013-10-02 13:04:56 +00001274 m.postTranslate(-SK_Scalar1, -SK_Scalar1);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001275 SkMatrix invM;
1276 if (!m.invert(&invM)) {
1277 invM.reset();
1278 } else {
1279 invM.postConcat(invM); // Square the matrix
1280 }
1281 uman.setSkMatrix(fInvMatrixUni, invM);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001282}
1283
sugoi@google.com4775cba2013-04-17 13:46:56 +00001284void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1285 INHERITED::setData(uman, drawEffect);
1286
1287 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1288 if (turbulence.stitchTiles()) {
1289 const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001290 uman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
1291 SkIntToScalar(stitchData.fHeight));
sugoi@google.com4775cba2013-04-17 13:46:56 +00001292 }
1293}
1294
1295void GrGLSimplexNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1296 INHERITED::setData(uman, drawEffect);
1297
1298 const GrSimplexNoiseEffect& turbulence = drawEffect.castEffect<GrSimplexNoiseEffect>();
1299 uman.set1f(fSeedUni, turbulence.seed());
1300}
1301
sugoi@google.come3b4c502013-04-05 13:47:09 +00001302/////////////////////////////////////////////////////////////////////
1303
1304GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001305 SkASSERT(NULL != context);
1306
commit-bot@chromium.orgc2a0ea62013-11-06 10:08:38 +00001307 if (0 == fNumOctaves) {
1308 SkColor clearColor = 0;
1309 if (kFractalNoise_Type == fType) {
1310 clearColor = SkColorSetARGB(paint.getAlpha() / 2, 127, 127, 127);
1311 }
1312 SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(
1313 clearColor, SkXfermode::kSrc_Mode));
1314 return cf->asNewEffect(context);
1315 }
1316
sugoi@google.come3b4c502013-04-05 13:47:09 +00001317 // Either we don't stitch tiles, either we have a valid tile size
1318 SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
1319
sugoi@google.com4775cba2013-04-17 13:46:56 +00001320#ifdef SK_USE_SIMPLEX_NOISE
1321 // Simplex noise is currently disabled but can be enabled by defining SK_USE_SIMPLEX_NOISE
1322 sk_ignore_unused_variable(context);
1323 GrEffectRef* effect =
1324 GrSimplexNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
1325 fNumOctaves, fStitchTiles, fSeed,
1326 this->getLocalMatrix(), paint.getAlpha());
1327#else
sugoi@google.come3b4c502013-04-05 13:47:09 +00001328 GrTexture* permutationsTexture = GrLockAndRefCachedBitmapTexture(
1329 context, *fPaintingData->getPermutationsBitmap(), NULL);
1330 GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture(
1331 context, *fPaintingData->getNoiseBitmap(), NULL);
1332
1333 GrEffectRef* effect = (NULL != permutationsTexture) && (NULL != noiseTexture) ?
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001334 GrPerlinNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001335 fNumOctaves, fStitchTiles,
1336 fPaintingData->fStitchDataInit,
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001337 permutationsTexture, noiseTexture,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001338 this->getLocalMatrix(), paint.getAlpha()) :
1339 NULL;
1340
1341 // Unlock immediately, this is not great, but we don't have a way of
1342 // knowing when else to unlock it currently. TODO: Remove this when
1343 // unref becomes the unlock replacement for all types of textures.
1344 if (NULL != permutationsTexture) {
1345 GrUnlockAndUnrefCachedBitmapTexture(permutationsTexture);
1346 }
1347 if (NULL != noiseTexture) {
1348 GrUnlockAndUnrefCachedBitmapTexture(noiseTexture);
1349 }
sugoi@google.com4775cba2013-04-17 13:46:56 +00001350#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +00001351
1352 return effect;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001353}
1354
1355#else
1356
1357GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext*, const SkPaint&) const {
1358 SkDEBUGFAIL("Should not call in GPU-less build");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001359 return NULL;
1360}
1361
1362#endif
1363
1364#ifdef SK_DEVELOPER
1365void SkPerlinNoiseShader::toString(SkString* str) const {
1366 str->append("SkPerlinNoiseShader: (");
1367
1368 str->append("type: ");
1369 switch (fType) {
1370 case kFractalNoise_Type:
1371 str->append("\"fractal noise\"");
1372 break;
1373 case kTurbulence_Type:
1374 str->append("\"turbulence\"");
1375 break;
1376 default:
1377 str->append("\"unknown\"");
1378 break;
1379 }
1380 str->append(" base frequency: (");
1381 str->appendScalar(fBaseFrequencyX);
1382 str->append(", ");
1383 str->appendScalar(fBaseFrequencyY);
1384 str->append(") number of octaves: ");
1385 str->appendS32(fNumOctaves);
1386 str->append(" seed: ");
1387 str->appendScalar(fSeed);
1388 str->append(" stitch tiles: ");
1389 str->append(fStitchTiles ? "true " : "false ");
1390
1391 this->INHERITED::toString(str);
1392
1393 str->append(")");
1394}
1395#endif