blob: cdf8baf682198eb406074ef21ceb150f6dae6fa6 [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"
sugoi@google.come3b4c502013-04-05 13:47:09 +000011#include "SkFlattenableBuffers.h"
12#include "SkShader.h"
13#include "SkUnPreMultiply.h"
14#include "SkString.h"
15
16#if SK_SUPPORT_GPU
17#include "GrContext.h"
bsalomon@google.com77af6802013-10-02 13:04:56 +000018#include "GrCoordTransform.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000019#include "gl/GrGLEffect.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000020#include "GrTBackendEffectFactory.h"
21#include "SkGr.h"
22#endif
23
24static const int kBlockSize = 256;
25static const int kBlockMask = kBlockSize - 1;
26static const int kPerlinNoise = 4096;
27static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
28
29namespace {
30
31// noiseValue is the color component's value (or color)
32// limitValue is the maximum perlin noise array index value allowed
33// newValue is the current noise dimension (either width or height)
34inline int checkNoise(int noiseValue, int limitValue, int newValue) {
35 // If the noise value would bring us out of bounds of the current noise array while we are
36 // stiching noise tiles together, wrap the noise around the current dimension of the noise to
37 // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
38 if (noiseValue >= limitValue) {
39 noiseValue -= newValue;
40 }
41 if (noiseValue >= limitValue - 1) {
42 noiseValue -= newValue - 1;
43 }
44 return noiseValue;
45}
46
47inline SkScalar smoothCurve(SkScalar t) {
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +000048 static const SkScalar SK_Scalar3 = 3.0f;
sugoi@google.come3b4c502013-04-05 13:47:09 +000049
50 // returns t * t * (3 - 2 * t)
51 return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
52}
53
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +000054bool perlin_noise_type_is_valid(SkPerlinNoiseShader::Type type) {
55 return (SkPerlinNoiseShader::kFractalNoise_Type == type) ||
56 (SkPerlinNoiseShader::kTurbulence_Type == type);
57}
58
sugoi@google.come3b4c502013-04-05 13:47:09 +000059} // end namespace
60
61struct SkPerlinNoiseShader::StitchData {
62 StitchData()
63 : fWidth(0)
64 , fWrapX(0)
65 , fHeight(0)
66 , fWrapY(0)
67 {}
68
69 bool operator==(const StitchData& other) const {
70 return fWidth == other.fWidth &&
71 fWrapX == other.fWrapX &&
72 fHeight == other.fHeight &&
73 fWrapY == other.fWrapY;
74 }
75
76 int fWidth; // How much to subtract to wrap for stitching.
77 int fWrapX; // Minimum value to wrap.
78 int fHeight;
79 int fWrapY;
80};
81
82struct SkPerlinNoiseShader::PaintingData {
83 PaintingData(const SkISize& tileSize)
84 : fSeed(0)
85 , fTileSize(tileSize)
86 , fPermutationsBitmap(NULL)
87 , fNoiseBitmap(NULL)
88 {}
89
90 ~PaintingData()
91 {
92 SkDELETE(fPermutationsBitmap);
93 SkDELETE(fNoiseBitmap);
94 }
95
96 int fSeed;
97 uint8_t fLatticeSelector[kBlockSize];
98 uint16_t fNoise[4][kBlockSize][2];
99 SkPoint fGradient[4][kBlockSize];
100 SkISize fTileSize;
101 SkVector fBaseFrequency;
102 StitchData fStitchDataInit;
103
104private:
105
106 SkBitmap* fPermutationsBitmap;
107 SkBitmap* fNoiseBitmap;
108
109public:
110
111 inline int random() {
112 static const int gRandAmplitude = 16807; // 7**5; primitive root of m
113 static const int gRandQ = 127773; // m / a
114 static const int gRandR = 2836; // m % a
115
116 int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
117 if (result <= 0)
118 result += kRandMaximum;
119 fSeed = result;
120 return result;
121 }
122
123 void init(SkScalar seed)
124 {
125 static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
126
senorblanco@chromium.org857e3202014-01-09 17:41:42 +0000127 // According to the SVG spec, we must truncate (not round) the seed value.
128 fSeed = SkScalarTruncToInt(seed);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000129 // The seed value clamp to the range [1, kRandMaximum - 1].
sugoi@google.come3b4c502013-04-05 13:47:09 +0000130 if (fSeed <= 0) {
131 fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
132 }
133 if (fSeed > kRandMaximum - 1) {
134 fSeed = kRandMaximum - 1;
135 }
136 for (int channel = 0; channel < 4; ++channel) {
137 for (int i = 0; i < kBlockSize; ++i) {
138 fLatticeSelector[i] = i;
139 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
140 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
141 }
142 }
143 for (int i = kBlockSize - 1; i > 0; --i) {
144 int k = fLatticeSelector[i];
145 int j = random() % kBlockSize;
146 SkASSERT(j >= 0);
147 SkASSERT(j < kBlockSize);
148 fLatticeSelector[i] = fLatticeSelector[j];
149 fLatticeSelector[j] = k;
150 }
151
152 // Perform the permutations now
153 {
154 // Copy noise data
155 uint16_t noise[4][kBlockSize][2];
156 for (int i = 0; i < kBlockSize; ++i) {
157 for (int channel = 0; channel < 4; ++channel) {
158 for (int j = 0; j < 2; ++j) {
159 noise[channel][i][j] = fNoise[channel][i][j];
160 }
161 }
162 }
163 // Do permutations on noise data
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 fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
168 }
169 }
170 }
171 }
172
173 // Half of the largest possible value for 16 bit unsigned int
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +0000174 static const SkScalar gHalfMax16bits = 32767.5f;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000175
176 // Compute gradients from permutated noise data
177 for (int channel = 0; channel < 4; ++channel) {
178 for (int i = 0; i < kBlockSize; ++i) {
179 fGradient[channel][i] = SkPoint::Make(
180 SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
181 gInvBlockSizef),
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000182 SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
sugoi@google.come3b4c502013-04-05 13:47:09 +0000183 gInvBlockSizef));
184 fGradient[channel][i].normalize();
185 // Put the normalized gradient back into the noise data
186 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000187 fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000188 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000189 fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000190 }
191 }
192
193 // Invalidate bitmaps
194 SkDELETE(fPermutationsBitmap);
195 fPermutationsBitmap = NULL;
196 SkDELETE(fNoiseBitmap);
197 fNoiseBitmap = NULL;
198 }
199
200 void stitch() {
201 SkScalar tileWidth = SkIntToScalar(fTileSize.width());
202 SkScalar tileHeight = SkIntToScalar(fTileSize.height());
203 SkASSERT(tileWidth > 0 && tileHeight > 0);
204 // When stitching tiled turbulence, the frequencies must be adjusted
205 // so that the tile borders will be continuous.
206 if (fBaseFrequency.fX) {
reed@google.com8015cdd2013-12-18 15:49:32 +0000207 SkScalar lowFrequencx =
208 SkScalarFloorToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
209 SkScalar highFrequencx =
210 SkScalarCeilToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000211 // BaseFrequency should be non-negative according to the standard.
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000212 if (SkScalarDiv(fBaseFrequency.fX, lowFrequencx) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000213 SkScalarDiv(highFrequencx, fBaseFrequency.fX)) {
214 fBaseFrequency.fX = lowFrequencx;
215 } else {
216 fBaseFrequency.fX = highFrequencx;
217 }
218 }
219 if (fBaseFrequency.fY) {
reed@google.com8015cdd2013-12-18 15:49:32 +0000220 SkScalar lowFrequency =
221 SkScalarFloorToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
222 SkScalar highFrequency =
223 SkScalarCeilToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000224 if (SkScalarDiv(fBaseFrequency.fY, lowFrequency) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000225 SkScalarDiv(highFrequency, fBaseFrequency.fY)) {
226 fBaseFrequency.fY = lowFrequency;
227 } else {
228 fBaseFrequency.fY = highFrequency;
229 }
230 }
231 // Set up TurbulenceInitial stitch values.
232 fStitchDataInit.fWidth =
reed@google.com8015cdd2013-12-18 15:49:32 +0000233 SkScalarRoundToInt(tileWidth * fBaseFrequency.fX);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000234 fStitchDataInit.fWrapX = kPerlinNoise + fStitchDataInit.fWidth;
235 fStitchDataInit.fHeight =
reed@google.com8015cdd2013-12-18 15:49:32 +0000236 SkScalarRoundToInt(tileHeight * fBaseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000237 fStitchDataInit.fWrapY = kPerlinNoise + fStitchDataInit.fHeight;
238 }
239
240 SkBitmap* getPermutationsBitmap()
241 {
242 if (!fPermutationsBitmap) {
243 fPermutationsBitmap = SkNEW(SkBitmap);
reed@google.com9ebcac52014-01-24 18:53:42 +0000244 fPermutationsBitmap->allocPixels(SkImageInfo::MakeA8(kBlockSize, 1));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000245 uint8_t* bitmapPixels = fPermutationsBitmap->getAddr8(0, 0);
246 memcpy(bitmapPixels, fLatticeSelector, sizeof(uint8_t) * kBlockSize);
247 }
248 return fPermutationsBitmap;
249 }
250
251 SkBitmap* getNoiseBitmap()
252 {
253 if (!fNoiseBitmap) {
254 fNoiseBitmap = SkNEW(SkBitmap);
reed@google.com9ebcac52014-01-24 18:53:42 +0000255 fNoiseBitmap->allocPixels(SkImageInfo::MakeN32Premul(kBlockSize, 4));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000256 uint32_t* bitmapPixels = fNoiseBitmap->getAddr32(0, 0);
257 memcpy(bitmapPixels, fNoise[0][0], sizeof(uint16_t) * kBlockSize * 4 * 2);
258 }
259 return fNoiseBitmap;
260 }
261};
262
263SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
264 int numOctaves, SkScalar seed,
265 const SkISize* tileSize) {
266 return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY,
267 numOctaves, seed, tileSize));
268}
269
270SkShader* SkPerlinNoiseShader::CreateTubulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
271 int numOctaves, SkScalar seed,
272 const SkISize* tileSize) {
273 return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY,
274 numOctaves, seed, tileSize));
275}
276
277SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
278 SkScalar baseFrequencyX,
279 SkScalar baseFrequencyY,
280 int numOctaves,
281 SkScalar seed,
282 const SkISize* tileSize)
283 : fType(type)
284 , fBaseFrequencyX(baseFrequencyX)
285 , fBaseFrequencyY(baseFrequencyY)
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +0000286 , fNumOctaves(numOctaves > 255 ? 255 : numOctaves/*[0,255] octaves allowed*/)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000287 , fSeed(seed)
288 , fStitchTiles((tileSize != NULL) && !tileSize->isEmpty())
289 , fPaintingData(NULL)
290{
291 SkASSERT(numOctaves >= 0 && numOctaves < 256);
292 setTileSize(fStitchTiles ? *tileSize : SkISize::Make(0,0));
293 fMatrix.reset();
294}
295
296SkPerlinNoiseShader::SkPerlinNoiseShader(SkFlattenableReadBuffer& buffer) :
297 INHERITED(buffer), fPaintingData(NULL) {
298 fType = (SkPerlinNoiseShader::Type) buffer.readInt();
299 fBaseFrequencyX = buffer.readScalar();
300 fBaseFrequencyY = buffer.readScalar();
301 fNumOctaves = buffer.readInt();
302 fSeed = buffer.readScalar();
303 fStitchTiles = buffer.readBool();
304 fTileSize.fWidth = buffer.readInt();
305 fTileSize.fHeight = buffer.readInt();
306 setTileSize(fTileSize);
307 fMatrix.reset();
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +0000308 buffer.validate(perlin_noise_type_is_valid(fType) &&
309 (fNumOctaves >= 0) && (fNumOctaves <= 255));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000310}
311
312SkPerlinNoiseShader::~SkPerlinNoiseShader() {
313 // Safety, should have been done in endContext()
314 SkDELETE(fPaintingData);
315}
316
317void SkPerlinNoiseShader::flatten(SkFlattenableWriteBuffer& buffer) const {
318 this->INHERITED::flatten(buffer);
319 buffer.writeInt((int) fType);
320 buffer.writeScalar(fBaseFrequencyX);
321 buffer.writeScalar(fBaseFrequencyY);
322 buffer.writeInt(fNumOctaves);
323 buffer.writeScalar(fSeed);
324 buffer.writeBool(fStitchTiles);
325 buffer.writeInt(fTileSize.fWidth);
326 buffer.writeInt(fTileSize.fHeight);
327}
328
329void SkPerlinNoiseShader::initPaint(PaintingData& paintingData)
330{
331 paintingData.init(fSeed);
332
333 // Set frequencies to original values
334 paintingData.fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
335 // Adjust frequecies based on size if stitching is enabled
336 if (fStitchTiles) {
337 paintingData.stitch();
338 }
339}
340
341void SkPerlinNoiseShader::setTileSize(const SkISize& tileSize) {
342 fTileSize = tileSize;
343
344 if (NULL == fPaintingData) {
345 fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize));
346 initPaint(*fPaintingData);
347 } else {
348 // Set Size
349 fPaintingData->fTileSize = fTileSize;
350 // Set frequencies to original values
351 fPaintingData->fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
352 // Adjust frequecies based on size if stitching is enabled
353 if (fStitchTiles) {
354 fPaintingData->stitch();
355 }
356 }
357}
358
359SkScalar SkPerlinNoiseShader::noise2D(int channel, const PaintingData& paintingData,
360 const StitchData& stitchData, const SkPoint& noiseVector)
361{
362 struct Noise {
363 int noisePositionIntegerValue;
364 SkScalar noisePositionFractionValue;
365 Noise(SkScalar component)
366 {
367 SkScalar position = component + kPerlinNoise;
368 noisePositionIntegerValue = SkScalarFloorToInt(position);
369 noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
370 }
371 };
372 Noise noiseX(noiseVector.x());
373 Noise noiseY(noiseVector.y());
374 SkScalar u, v;
375 // If stitching, adjust lattice points accordingly.
376 if (fStitchTiles) {
377 noiseX.noisePositionIntegerValue =
378 checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
379 noiseY.noisePositionIntegerValue =
380 checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
381 }
382 noiseX.noisePositionIntegerValue &= kBlockMask;
383 noiseY.noisePositionIntegerValue &= kBlockMask;
384 int latticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000385 paintingData.fLatticeSelector[noiseX.noisePositionIntegerValue] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000386 noiseY.noisePositionIntegerValue;
387 int nextLatticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000388 paintingData.fLatticeSelector[(noiseX.noisePositionIntegerValue + 1) & kBlockMask] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000389 noiseY.noisePositionIntegerValue;
390 SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
391 SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
392 // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
393 SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
394 noiseY.noisePositionFractionValue); // Offset (0,0)
395 u = paintingData.fGradient[channel][latticeIndex & kBlockMask].dot(fractionValue);
396 fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
397 v = paintingData.fGradient[channel][nextLatticeIndex & kBlockMask].dot(fractionValue);
398 SkScalar a = SkScalarInterp(u, v, sx);
399 fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
400 v = paintingData.fGradient[channel][(nextLatticeIndex + 1) & kBlockMask].dot(fractionValue);
401 fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
402 u = paintingData.fGradient[channel][(latticeIndex + 1) & kBlockMask].dot(fractionValue);
403 SkScalar b = SkScalarInterp(u, v, sx);
404 return SkScalarInterp(a, b, sy);
405}
406
407SkScalar SkPerlinNoiseShader::calculateTurbulenceValueForPoint(
408 int channel, const PaintingData& paintingData, StitchData& stitchData, const SkPoint& point)
409{
410 if (fStitchTiles) {
411 // Set up TurbulenceInitial stitch values.
412 stitchData = paintingData.fStitchDataInit;
413 }
414 SkScalar turbulenceFunctionResult = 0;
415 SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), paintingData.fBaseFrequency.fX),
416 SkScalarMul(point.y(), paintingData.fBaseFrequency.fY)));
417 SkScalar ratio = SK_Scalar1;
418 for (int octave = 0; octave < fNumOctaves; ++octave) {
419 SkScalar noise = noise2D(channel, paintingData, stitchData, noiseVector);
420 turbulenceFunctionResult += SkScalarDiv(
421 (fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio);
422 noiseVector.fX *= 2;
423 noiseVector.fY *= 2;
424 ratio *= 2;
425 if (fStitchTiles) {
426 // Update stitch values
427 stitchData.fWidth *= 2;
428 stitchData.fWrapX = stitchData.fWidth + kPerlinNoise;
429 stitchData.fHeight *= 2;
430 stitchData.fWrapY = stitchData.fHeight + kPerlinNoise;
431 }
432 }
433
434 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
435 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
436 if (fType == kFractalNoise_Type) {
437 turbulenceFunctionResult =
438 SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
439 }
440
441 if (channel == 3) { // Scale alpha by paint value
442 turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult,
443 SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255)));
444 }
445
446 // Clamp result
447 return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
448}
449
450SkPMColor SkPerlinNoiseShader::shade(const SkPoint& point, StitchData& stitchData) {
451 SkMatrix matrix = fMatrix;
452 SkMatrix invMatrix;
453 if (!matrix.invert(&invMatrix)) {
454 invMatrix.reset();
455 } else {
456 invMatrix.postConcat(invMatrix); // Square the matrix
457 }
458 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
459 // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
460 matrix.postTranslate(SK_Scalar1, SK_Scalar1);
461 SkPoint newPoint;
462 matrix.mapPoints(&newPoint, &point, 1);
463 invMatrix.mapPoints(&newPoint, &newPoint, 1);
464 newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
465 newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
466
467 U8CPU rgba[4];
468 for (int channel = 3; channel >= 0; --channel) {
469 rgba[channel] = SkScalarFloorToInt(255 *
470 calculateTurbulenceValueForPoint(channel, *fPaintingData, stitchData, newPoint));
471 }
472 return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
473}
474
475bool SkPerlinNoiseShader::setContext(const SkBitmap& device, const SkPaint& paint,
476 const SkMatrix& matrix) {
477 fMatrix = matrix;
478 return INHERITED::setContext(device, paint, matrix);
479}
480
481void SkPerlinNoiseShader::shadeSpan(int x, int y, SkPMColor result[], int count) {
482 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
483 StitchData stitchData;
484 for (int i = 0; i < count; ++i) {
485 result[i] = shade(point, stitchData);
486 point.fX += SK_Scalar1;
487 }
488}
489
490void SkPerlinNoiseShader::shadeSpan16(int x, int y, uint16_t result[], int count) {
491 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
492 StitchData stitchData;
493 DITHER_565_SCAN(y);
494 for (int i = 0; i < count; ++i) {
495 unsigned dither = DITHER_VALUE(x);
496 result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
497 DITHER_INC_X(x);
498 point.fX += SK_Scalar1;
499 }
500}
501
502/////////////////////////////////////////////////////////////////////
503
commit-bot@chromium.org344cf452013-06-17 14:19:01 +0000504#if SK_SUPPORT_GPU
sugoi@google.come3b4c502013-04-05 13:47:09 +0000505
506#include "GrTBackendEffectFactory.h"
507
sugoi@google.com4775cba2013-04-17 13:46:56 +0000508class GrGLNoise : public GrGLEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000509public:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000510 GrGLNoise(const GrBackendEffectFactory& factory,
511 const GrDrawEffect& drawEffect);
512 virtual ~GrGLNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000513
sugoi@google.com4775cba2013-04-17 13:46:56 +0000514 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
515
516 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
517
518protected:
519 SkPerlinNoiseShader::Type fType;
520 bool fStitchTiles;
521 int fNumOctaves;
522 GrGLUniformManager::UniformHandle fBaseFrequencyUni;
523 GrGLUniformManager::UniformHandle fAlphaUni;
524 GrGLUniformManager::UniformHandle fInvMatrixUni;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000525
526private:
527 typedef GrGLEffect INHERITED;
528};
529
530class GrGLPerlinNoise : public GrGLNoise {
531public:
sugoi@google.come3b4c502013-04-05 13:47:09 +0000532 GrGLPerlinNoise(const GrBackendEffectFactory& factory,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000533 const GrDrawEffect& drawEffect)
534 : GrGLNoise(factory, drawEffect) {}
535 virtual ~GrGLPerlinNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000536
537 virtual void emitCode(GrGLShaderBuilder*,
538 const GrDrawEffect&,
539 EffectKey,
540 const char* outputColor,
541 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000542 const TransformedCoordsArray&,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000543 const TextureSamplerArray&) SK_OVERRIDE;
544
sugoi@google.com4775cba2013-04-17 13:46:56 +0000545 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000546
547private:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000548 GrGLUniformManager::UniformHandle fStitchDataUni;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000549
sugoi@google.com4775cba2013-04-17 13:46:56 +0000550 typedef GrGLNoise INHERITED;
551};
552
553class GrGLSimplexNoise : public GrGLNoise {
554 // Note : This is for reference only. GrGLPerlinNoise is used for processing.
555public:
556 GrGLSimplexNoise(const GrBackendEffectFactory& factory,
557 const GrDrawEffect& drawEffect)
558 : GrGLNoise(factory, drawEffect) {}
559
560 virtual ~GrGLSimplexNoise() {}
561
562 virtual void emitCode(GrGLShaderBuilder*,
563 const GrDrawEffect&,
564 EffectKey,
565 const char* outputColor,
566 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000567 const TransformedCoordsArray&,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000568 const TextureSamplerArray&) SK_OVERRIDE;
569
570 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
571
572private:
573 GrGLUniformManager::UniformHandle fSeedUni;
574
575 typedef GrGLNoise INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000576};
577
578/////////////////////////////////////////////////////////////////////
579
sugoi@google.com4775cba2013-04-17 13:46:56 +0000580class GrNoiseEffect : public GrEffect {
581public:
582 virtual ~GrNoiseEffect() { }
583
584 SkPerlinNoiseShader::Type type() const { return fType; }
585 bool stitchTiles() const { return fStitchTiles; }
586 const SkVector& baseFrequency() const { return fBaseFrequency; }
587 int numOctaves() const { return fNumOctaves; }
bsalomon@google.com77af6802013-10-02 13:04:56 +0000588 const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000589 uint8_t alpha() const { return fAlpha; }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000590
591 void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE {
592 *validFlags = 0; // This is noise. Nothing is constant.
593 }
594
595protected:
596 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
597 const GrNoiseEffect& s = CastEffect<GrNoiseEffect>(sBase);
598 return fType == s.fType &&
599 fBaseFrequency == s.fBaseFrequency &&
600 fNumOctaves == s.fNumOctaves &&
601 fStitchTiles == s.fStitchTiles &&
bsalomon@google.com77af6802013-10-02 13:04:56 +0000602 fCoordTransform.getMatrix() == s.fCoordTransform.getMatrix() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000603 fAlpha == s.fAlpha;
604 }
605
606 GrNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, int numOctaves,
607 bool stitchTiles, const SkMatrix& matrix, uint8_t alpha)
608 : fType(type)
609 , fBaseFrequency(baseFrequency)
610 , fNumOctaves(numOctaves)
611 , fStitchTiles(stitchTiles)
612 , fMatrix(matrix)
613 , fAlpha(alpha) {
bsalomon@google.com77af6802013-10-02 13:04:56 +0000614 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
615 // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions.
616 SkMatrix m = matrix;
617 m.postTranslate(SK_Scalar1, SK_Scalar1);
618 fCoordTransform.reset(kLocal_GrCoordSet, m);
619 this->addCoordTransform(&fCoordTransform);
commit-bot@chromium.orga34995e2013-10-23 05:42:03 +0000620 this->setWillNotUseInputColor();
sugoi@google.com4775cba2013-04-17 13:46:56 +0000621 }
622
623 SkPerlinNoiseShader::Type fType;
bsalomon@google.com77af6802013-10-02 13:04:56 +0000624 GrCoordTransform fCoordTransform;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000625 SkVector fBaseFrequency;
626 int fNumOctaves;
627 bool fStitchTiles;
628 SkMatrix fMatrix;
629 uint8_t fAlpha;
630
631private:
632 typedef GrEffect INHERITED;
633};
634
635class GrPerlinNoiseEffect : public GrNoiseEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000636public:
637 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
638 int numOctaves, bool stitchTiles,
639 const SkPerlinNoiseShader::StitchData& stitchData,
640 GrTexture* permutationsTexture, GrTexture* noiseTexture,
641 const SkMatrix& matrix, uint8_t alpha) {
642 AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves,
643 stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha)));
644 return CreateEffectRef(effect);
645 }
646
647 virtual ~GrPerlinNoiseEffect() { }
648
649 static const char* Name() { return "PerlinNoise"; }
650 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
651 return GrTBackendEffectFactory<GrPerlinNoiseEffect>::getInstance();
652 }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000653 const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000654
655 typedef GrGLPerlinNoise GLEffect;
656
sugoi@google.come3b4c502013-04-05 13:47:09 +0000657private:
658 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
659 const GrPerlinNoiseEffect& s = CastEffect<GrPerlinNoiseEffect>(sBase);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000660 return INHERITED::onIsEqual(sBase) &&
661 fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() &&
sugoi@google.come3b4c502013-04-05 13:47:09 +0000662 fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000663 fStitchData == s.fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000664 }
665
666 GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
667 int numOctaves, bool stitchTiles,
668 const SkPerlinNoiseShader::StitchData& stitchData,
669 GrTexture* permutationsTexture, GrTexture* noiseTexture,
670 const SkMatrix& matrix, uint8_t alpha)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000671 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
672 , fPermutationsAccess(permutationsTexture)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000673 , fNoiseAccess(noiseTexture)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000674 , fStitchData(stitchData) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000675 this->addTextureAccess(&fPermutationsAccess);
676 this->addTextureAccess(&fNoiseAccess);
677 }
678
sugoi@google.com4775cba2013-04-17 13:46:56 +0000679 GR_DECLARE_EFFECT_TEST;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000680
681 GrTextureAccess fPermutationsAccess;
682 GrTextureAccess fNoiseAccess;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000683 SkPerlinNoiseShader::StitchData fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000684
sugoi@google.com4775cba2013-04-17 13:46:56 +0000685 typedef GrNoiseEffect INHERITED;
686};
687
688class GrSimplexNoiseEffect : public GrNoiseEffect {
689 // Note : This is for reference only. GrPerlinNoiseEffect is used for processing.
690public:
691 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
692 int numOctaves, bool stitchTiles, const SkScalar seed,
693 const SkMatrix& matrix, uint8_t alpha) {
694 AutoEffectUnref effect(SkNEW_ARGS(GrSimplexNoiseEffect, (type, baseFrequency, numOctaves,
695 stitchTiles, seed, matrix, alpha)));
696 return CreateEffectRef(effect);
697 }
698
699 virtual ~GrSimplexNoiseEffect() { }
700
701 static const char* Name() { return "SimplexNoise"; }
702 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
703 return GrTBackendEffectFactory<GrSimplexNoiseEffect>::getInstance();
704 }
705 const SkScalar& seed() const { return fSeed; }
706
707 typedef GrGLSimplexNoise GLEffect;
708
709private:
710 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
711 const GrSimplexNoiseEffect& s = CastEffect<GrSimplexNoiseEffect>(sBase);
712 return INHERITED::onIsEqual(sBase) && fSeed == s.fSeed;
713 }
714
715 GrSimplexNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
716 int numOctaves, bool stitchTiles, const SkScalar seed,
717 const SkMatrix& matrix, uint8_t alpha)
718 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
719 , fSeed(seed) {
720 }
721
722 SkScalar fSeed;
723
724 typedef GrNoiseEffect INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000725};
726
727/////////////////////////////////////////////////////////////////////
sugoi@google.come3b4c502013-04-05 13:47:09 +0000728GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect);
729
commit-bot@chromium.orge0e7cfe2013-09-09 20:09:12 +0000730GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkRandom* random,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000731 GrContext* context,
732 const GrDrawTargetCaps&,
733 GrTexture**) {
sugoi@google.com423ac132013-04-18 14:04:57 +0000734 int numOctaves = random->nextRangeU(2, 10);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000735 bool stitchTiles = random->nextBool();
736 SkScalar seed = SkIntToScalar(random->nextU());
737 SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +0000738 SkScalar baseFrequencyX = random->nextRangeScalar(0.01f,
739 0.99f);
740 SkScalar baseFrequencyY = random->nextRangeScalar(0.01f,
741 0.99f);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000742
743 SkShader* shader = random->nextBool() ?
744 SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
745 stitchTiles ? &tileSize : NULL) :
746 SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
747 stitchTiles ? &tileSize : NULL);
748
749 SkPaint paint;
750 GrEffectRef* effect = shader->asNewEffect(context, paint);
751
752 SkDELETE(shader);
753
754 return effect;
755}
sugoi@google.com4775cba2013-04-17 13:46:56 +0000756
sugoi@google.come3b4c502013-04-05 13:47:09 +0000757/////////////////////////////////////////////////////////////////////
758
sugoi@google.com4775cba2013-04-17 13:46:56 +0000759void GrGLSimplexNoise::emitCode(GrGLShaderBuilder* builder,
760 const GrDrawEffect&,
761 EffectKey key,
762 const char* outputColor,
763 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000764 const TransformedCoordsArray& coords,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000765 const TextureSamplerArray&) {
766 sk_ignore_unused_variable(inputColor);
767
bsalomon@google.com77af6802013-10-02 13:04:56 +0000768 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000769
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000770 fSeedUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000771 kFloat_GrSLType, "seed");
772 const char* seedUni = builder->getUniformCStr(fSeedUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000773 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000774 kMat33f_GrSLType, "invMatrix");
775 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000776 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000777 kVec2f_GrSLType, "baseFrequency");
778 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000779 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000780 kFloat_GrSLType, "alpha");
781 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
782
783 // Add vec3 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000784 static const GrGLShaderVar gVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000785 GrGLShaderVar("x", kVec3f_GrSLType)
786 };
787
788 SkString mod289_3_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000789 builder->fsEmitFunction(kVec3f_GrSLType,
790 "mod289", SK_ARRAY_COUNT(gVec3Args), gVec3Args,
791 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
792 "return x - floor(x * C.xxx) * C.yyy;", &mod289_3_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000793
794 // Add vec4 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000795 static const GrGLShaderVar gVec4Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000796 GrGLShaderVar("x", kVec4f_GrSLType)
797 };
798
799 SkString mod289_4_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000800 builder->fsEmitFunction(kVec4f_GrSLType,
801 "mod289", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
802 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
803 "return x - floor(x * C.xxxx) * C.yyyy;", &mod289_4_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000804
805 // Add vec4 permute function
sugoi@google.comd537af52013-06-10 13:59:25 +0000806 SkString permuteCode;
807 permuteCode.appendf("const vec2 C = vec2(34.0, 1.0);\n"
808 "return %s(((x * C.xxxx) + C.yyyy) * x);", mod289_4_funcName.c_str());
809 SkString permuteFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000810 builder->fsEmitFunction(kVec4f_GrSLType,
811 "permute", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
812 permuteCode.c_str(), &permuteFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000813
814 // Add vec4 taylorInvSqrt function
sugoi@google.comd537af52013-06-10 13:59:25 +0000815 SkString taylorInvSqrtFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000816 builder->fsEmitFunction(kVec4f_GrSLType,
817 "taylorInvSqrt", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
818 "const vec2 C = vec2(-0.85373472095314, 1.79284291400159);\n"
819 "return x * C.xxxx + C.yyyy;", &taylorInvSqrtFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000820
821 // Add vec3 noise function
sugoi@google.comd537af52013-06-10 13:59:25 +0000822 static const GrGLShaderVar gNoiseVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000823 GrGLShaderVar("v", kVec3f_GrSLType)
824 };
825
sugoi@google.comd537af52013-06-10 13:59:25 +0000826 SkString noiseCode;
827 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000828 "const vec2 C = vec2(1.0/6.0, 1.0/3.0);\n"
829 "const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n"
830
831 // First corner
832 "vec3 i = floor(v + dot(v, C.yyy));\n"
833 "vec3 x0 = v - i + dot(i, C.xxx);\n"
834
835 // Other corners
836 "vec3 g = step(x0.yzx, x0.xyz);\n"
837 "vec3 l = 1.0 - g;\n"
838 "vec3 i1 = min(g.xyz, l.zxy);\n"
839 "vec3 i2 = max(g.xyz, l.zxy);\n"
840
841 "vec3 x1 = x0 - i1 + C.xxx;\n"
842 "vec3 x2 = x0 - i2 + C.yyy;\n" // 2.0*C.x = 1/3 = C.y
843 "vec3 x3 = x0 - D.yyy;\n" // -1.0+3.0*C.x = -0.5 = -D.y
844 );
845
sugoi@google.comd537af52013-06-10 13:59:25 +0000846 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000847 // Permutations
848 "i = %s(i);\n"
849 "vec4 p = %s(%s(%s(\n"
850 " i.z + vec4(0.0, i1.z, i2.z, 1.0)) +\n"
851 " i.y + vec4(0.0, i1.y, i2.y, 1.0)) +\n"
852 " i.x + vec4(0.0, i1.x, i2.x, 1.0));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000853 mod289_3_funcName.c_str(), permuteFuncName.c_str(), permuteFuncName.c_str(),
854 permuteFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000855
sugoi@google.comd537af52013-06-10 13:59:25 +0000856 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000857 // Gradients: 7x7 points over a square, mapped onto an octahedron.
858 // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
859 "float n_ = 0.142857142857;\n" // 1.0/7.0
860 "vec3 ns = n_ * D.wyz - D.xzx;\n"
861
862 "vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\n" // mod(p,7*7)
863
864 "vec4 x_ = floor(j * ns.z);\n"
865 "vec4 y_ = floor(j - 7.0 * x_);" // mod(j,N)
866
867 "vec4 x = x_ *ns.x + ns.yyyy;\n"
868 "vec4 y = y_ *ns.x + ns.yyyy;\n"
869 "vec4 h = 1.0 - abs(x) - abs(y);\n"
870
871 "vec4 b0 = vec4(x.xy, y.xy);\n"
872 "vec4 b1 = vec4(x.zw, y.zw);\n"
873 );
874
sugoi@google.comd537af52013-06-10 13:59:25 +0000875 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000876 "vec4 s0 = floor(b0) * 2.0 + 1.0;\n"
877 "vec4 s1 = floor(b1) * 2.0 + 1.0;\n"
878 "vec4 sh = -step(h, vec4(0.0));\n"
879
880 "vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;\n"
881 "vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;\n"
882
883 "vec3 p0 = vec3(a0.xy, h.x);\n"
884 "vec3 p1 = vec3(a0.zw, h.y);\n"
885 "vec3 p2 = vec3(a1.xy, h.z);\n"
886 "vec3 p3 = vec3(a1.zw, h.w);\n"
887 );
888
sugoi@google.comd537af52013-06-10 13:59:25 +0000889 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000890 // Normalise gradients
891 "vec4 norm = %s(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n"
892 "p0 *= norm.x;\n"
893 "p1 *= norm.y;\n"
894 "p2 *= norm.z;\n"
895 "p3 *= norm.w;\n"
896
897 // Mix final noise value
898 "vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n"
899 "m = m * m;\n"
900 "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 +0000901 taylorInvSqrtFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000902
sugoi@google.comd537af52013-06-10 13:59:25 +0000903 SkString noiseFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000904 builder->fsEmitFunction(kFloat_GrSLType,
905 "snoise", SK_ARRAY_COUNT(gNoiseVec3Args), gNoiseVec3Args,
906 noiseCode.c_str(), &noiseFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000907
908 const char* noiseVecIni = "noiseVecIni";
909 const char* factors = "factors";
910 const char* sum = "sum";
911 const char* xOffsets = "xOffsets";
912 const char* yOffsets = "yOffsets";
913 const char* channel = "channel";
914
915 // Fill with some prime numbers
916 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(13.0, 53.0, 101.0, 151.0);\n", xOffsets);
917 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(109.0, 167.0, 23.0, 67.0);\n", yOffsets);
918
919 // There are rounding errors if the floor operation is not performed here
920 builder->fsCodeAppendf(
921 "\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 +0000922 noiseVecIni, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000923
924 // Perturb the texcoords with three components of noise
925 builder->fsCodeAppendf("\t\t%s += 0.1 * vec3(%s(%s + vec3( 0.0, 0.0, %s)),"
926 "%s(%s + vec3( 43.0, 17.0, %s)),"
927 "%s(%s + vec3(-17.0, -43.0, %s)));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000928 noiseVecIni, noiseFuncName.c_str(), noiseVecIni, seedUni,
929 noiseFuncName.c_str(), noiseVecIni, seedUni,
930 noiseFuncName.c_str(), noiseVecIni, seedUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000931
932 builder->fsCodeAppendf("\t\t%s = vec4(0.0);\n", outputColor);
933
934 builder->fsCodeAppendf("\t\tvec3 %s = vec3(1.0);\n", factors);
935 builder->fsCodeAppendf("\t\tfloat %s = 0.0;\n", sum);
936
937 // Loop over all octaves
938 builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {\n", fNumOctaves);
939
940 // Loop over the 4 channels
941 builder->fsCodeAppendf("\t\t\tfor (int %s = 3; %s >= 0; --%s) {\n", channel, channel, channel);
942
943 builder->fsCodeAppendf(
944 "\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 +0000945 outputColor, factors, noiseFuncName.c_str(), noiseVecIni, factors, xOffsets, channel,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000946 yOffsets, channel, seedUni, factors);
947
948 builder->fsCodeAppend("\t\t\t}\n"); // end of the for loop on channels
949
950 builder->fsCodeAppendf("\t\t\t%s += %s.x;\n", sum, factors);
951 builder->fsCodeAppendf("\t\t\t%s *= vec3(0.5, 2.0, 0.75);\n", factors);
952
953 builder->fsCodeAppend("\t\t}\n"); // end of the for loop on octaves
954
955 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
956 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
957 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
958 builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5 / %s) + vec4(0.5);\n",
959 outputColor, outputColor, sum);
960 } else {
961 builder->fsCodeAppendf("\t\t%s = abs(%s / vec4(%s));\n",
962 outputColor, outputColor, sum);
963 }
964
965 builder->fsCodeAppendf("\t\t%s.a *= %s;\n", outputColor, alphaUni);
966
967 // Clamp values
968 builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);\n", outputColor, outputColor);
969
970 // Pre-multiply the result
971 builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
972 outputColor, outputColor, outputColor, outputColor);
973}
974
sugoi@google.come3b4c502013-04-05 13:47:09 +0000975void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder,
976 const GrDrawEffect&,
977 EffectKey key,
978 const char* outputColor,
979 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000980 const TransformedCoordsArray& coords,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000981 const TextureSamplerArray& samplers) {
982 sk_ignore_unused_variable(inputColor);
983
bsalomon@google.com77af6802013-10-02 13:04:56 +0000984 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000985
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000986 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000987 kMat33f_GrSLType, "invMatrix");
988 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000989 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000990 kVec2f_GrSLType, "baseFrequency");
991 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000992 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000993 kFloat_GrSLType, "alpha");
994 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
995
996 const char* stitchDataUni = NULL;
997 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000998 fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
commit-bot@chromium.org98393202013-07-04 18:13:05 +0000999 kVec2f_GrSLType, "stitchData");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001000 stitchDataUni = builder->getUniformCStr(fStitchDataUni);
1001 }
1002
sugoi@google.comd537af52013-06-10 13:59:25 +00001003 // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
1004 const char* chanCoordR = "0.125";
1005 const char* chanCoordG = "0.375";
1006 const char* chanCoordB = "0.625";
1007 const char* chanCoordA = "0.875";
1008 const char* chanCoord = "chanCoord";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001009 const char* stitchData = "stitchData";
1010 const char* ratio = "ratio";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001011 const char* noiseXY = "noiseXY";
1012 const char* noiseVec = "noiseVec";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001013 const char* noiseSmooth = "noiseSmooth";
1014 const char* fractVal = "fractVal";
1015 const char* uv = "uv";
1016 const char* ab = "ab";
1017 const char* latticeIdx = "latticeIdx";
1018 const char* lattice = "lattice";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001019 const char* inc8bit = "0.00390625"; // 1.0 / 256.0
1020 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
1021 // [-1,1] vector and perform a dot product between that vector and the provided vector.
1022 const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
1023
sugoi@google.comd537af52013-06-10 13:59:25 +00001024 // Add noise function
1025 static const GrGLShaderVar gPerlinNoiseArgs[] = {
1026 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001027 GrGLShaderVar(noiseVec, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001028 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001029
sugoi@google.comd537af52013-06-10 13:59:25 +00001030 static const GrGLShaderVar gPerlinNoiseStitchArgs[] = {
1031 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001032 GrGLShaderVar(noiseVec, kVec2f_GrSLType),
1033 GrGLShaderVar(stitchData, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001034 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001035
sugoi@google.comd537af52013-06-10 13:59:25 +00001036 SkString noiseCode;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001037
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001038 noiseCode.appendf("\tvec4 %s = vec4(floor(%s), fract(%s));", noiseXY, noiseVec, noiseVec);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001039
1040 // smooth curve : t * t * (3 - 2 * t)
sugoi@google.comd537af52013-06-10 13:59:25 +00001041 noiseCode.appendf("\n\tvec2 %s = %s.zw * %s.zw * (vec2(3.0) - vec2(2.0) * %s.zw);",
1042 noiseSmooth, noiseXY, noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001043
1044 // Adjust frequencies if we're stitching tiles
1045 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001046 noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001047 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001048 noiseCode.appendf("\n\tif(%s.x >= (%s.x - 1.0)) { %s.x -= (%s.x - 1.0); }",
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.y >= %s.y) { %s.y -= %s.y; }",
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 - 1.0)) { %s.y -= (%s.y - 1.0); }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001053 noiseXY, stitchData, noiseXY, stitchData);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001054 }
1055
1056 // Get texture coordinates and normalize
sugoi@google.comd537af52013-06-10 13:59:25 +00001057 noiseCode.appendf("\n\t%s.xy = fract(floor(mod(%s.xy, 256.0)) / vec2(256.0));\n",
1058 noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001059
1060 // Get permutation for x
1061 {
1062 SkString xCoords("");
1063 xCoords.appendf("vec2(%s.x, 0.5)", noiseXY);
1064
sugoi@google.comd537af52013-06-10 13:59:25 +00001065 noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
1066 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1067 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001068 }
1069
1070 // Get permutation for x + 1
1071 {
1072 SkString xCoords("");
1073 xCoords.appendf("vec2(fract(%s.x + %s), 0.5)", noiseXY, inc8bit);
1074
sugoi@google.comd537af52013-06-10 13:59:25 +00001075 noiseCode.appendf("\n\t%s.y = ", latticeIdx);
1076 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1077 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001078 }
1079
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001080#if defined(SK_BUILD_FOR_ANDROID)
1081 // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
1082 // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
1083 // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
1084 // (or 0.484368 here). The following rounding operation prevents these precision issues from
1085 // affecting the result of the noise by making sure that we only have multiples of 1/255.
1086 // (Note that 1/255 is about 0.003921569, which is the value used here).
1087 noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);",
1088 latticeIdx, latticeIdx);
1089#endif
1090
sugoi@google.come3b4c502013-04-05 13:47:09 +00001091 // Get (x,y) coordinates with the permutated x
sugoi@google.comd537af52013-06-10 13:59:25 +00001092 noiseCode.appendf("\n\t%s = fract(%s + %s.yy);", latticeIdx, latticeIdx, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001093
sugoi@google.comd537af52013-06-10 13:59:25 +00001094 noiseCode.appendf("\n\tvec2 %s = %s.zw;", fractVal, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001095
sugoi@google.comd537af52013-06-10 13:59:25 +00001096 noiseCode.appendf("\n\n\tvec2 %s;", uv);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001097 // Compute u, at offset (0,0)
1098 {
1099 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001100 latticeCoords.appendf("vec2(%s.x, %s)", latticeIdx, chanCoord);
1101 noiseCode.appendf("\n\tvec4 %s = ", lattice);
1102 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1103 kVec2f_GrSLType);
1104 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1105 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001106 }
1107
sugoi@google.comd537af52013-06-10 13:59:25 +00001108 noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001109 // Compute v, at offset (-1,0)
1110 {
1111 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001112 latticeCoords.appendf("vec2(%s.y, %s)", latticeIdx, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001113 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001114 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1115 kVec2f_GrSLType);
1116 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1117 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001118 }
1119
1120 // Compute 'a' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001121 noiseCode.appendf("\n\tvec2 %s;", ab);
1122 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 +00001123
sugoi@google.comd537af52013-06-10 13:59:25 +00001124 noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001125 // Compute v, at offset (-1,-1)
1126 {
1127 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001128 latticeCoords.appendf("vec2(fract(%s.y + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001129 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001130 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1131 kVec2f_GrSLType);
1132 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1133 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001134 }
1135
sugoi@google.comd537af52013-06-10 13:59:25 +00001136 noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001137 // Compute u, at offset (0,-1)
1138 {
1139 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001140 latticeCoords.appendf("vec2(fract(%s.x + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001141 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001142 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1143 kVec2f_GrSLType);
1144 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1145 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001146 }
1147
1148 // Compute 'b' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001149 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 +00001150 // Compute the noise as a linear interpolation of 'a' and 'b'
sugoi@google.comd537af52013-06-10 13:59:25 +00001151 noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001152
sugoi@google.comd537af52013-06-10 13:59:25 +00001153 SkString noiseFuncName;
1154 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001155 builder->fsEmitFunction(kFloat_GrSLType,
1156 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
1157 gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001158 } else {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001159 builder->fsEmitFunction(kFloat_GrSLType,
1160 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
1161 gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001162 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001163
sugoi@google.comd537af52013-06-10 13:59:25 +00001164 // There are rounding errors if the floor operation is not performed here
1165 builder->fsCodeAppendf("\n\t\tvec2 %s = floor((%s * vec3(%s, 1.0)).xy) * %s;",
commit-bot@chromium.org7ab7ca42013-08-28 15:59:13 +00001166 noiseVec, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.comd537af52013-06-10 13:59:25 +00001167
1168 // Clear the color accumulator
1169 builder->fsCodeAppendf("\n\t\t%s = vec4(0.0);", outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001170
1171 if (fStitchTiles) {
sugoi@google.comd537af52013-06-10 13:59:25 +00001172 // Set up TurbulenceInitial stitch values.
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001173 builder->fsCodeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001174 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001175
sugoi@google.comd537af52013-06-10 13:59:25 +00001176 builder->fsCodeAppendf("\n\t\tfloat %s = 1.0;", ratio);
1177
1178 // Loop over all octaves
1179 builder->fsCodeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
1180
1181 builder->fsCodeAppendf("\n\t\t\t%s += ", outputColor);
1182 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1183 builder->fsCodeAppend("abs(");
1184 }
1185 if (fStitchTiles) {
1186 builder->fsCodeAppendf(
1187 "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
1188 "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
1189 noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
1190 noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
1191 noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
1192 noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
1193 } else {
1194 builder->fsCodeAppendf(
1195 "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
1196 "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
1197 noiseFuncName.c_str(), chanCoordR, noiseVec,
1198 noiseFuncName.c_str(), chanCoordG, noiseVec,
1199 noiseFuncName.c_str(), chanCoordB, noiseVec,
1200 noiseFuncName.c_str(), chanCoordA, noiseVec);
1201 }
1202 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1203 builder->fsCodeAppendf(")"); // end of "abs("
1204 }
1205 builder->fsCodeAppendf(" * %s;", ratio);
1206
1207 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
1208 builder->fsCodeAppendf("\n\t\t\t%s *= 0.5;", ratio);
1209
1210 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001211 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData);
sugoi@google.comd537af52013-06-10 13:59:25 +00001212 }
1213 builder->fsCodeAppend("\n\t\t}"); // end of the for loop on octaves
sugoi@google.come3b4c502013-04-05 13:47:09 +00001214
1215 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
1216 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
1217 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
sugoi@google.comd537af52013-06-10 13:59:25 +00001218 builder->fsCodeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001219 }
1220
sugoi@google.comd537af52013-06-10 13:59:25 +00001221 builder->fsCodeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001222
1223 // Clamp values
sugoi@google.comd537af52013-06-10 13:59:25 +00001224 builder->fsCodeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001225
1226 // Pre-multiply the result
sugoi@google.comd537af52013-06-10 13:59:25 +00001227 builder->fsCodeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
sugoi@google.come3b4c502013-04-05 13:47:09 +00001228 outputColor, outputColor, outputColor, outputColor);
1229}
1230
sugoi@google.com4775cba2013-04-17 13:46:56 +00001231GrGLNoise::GrGLNoise(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect)
sugoi@google.come3b4c502013-04-05 13:47:09 +00001232 : INHERITED (factory)
1233 , fType(drawEffect.castEffect<GrPerlinNoiseEffect>().type())
1234 , fStitchTiles(drawEffect.castEffect<GrPerlinNoiseEffect>().stitchTiles())
bsalomon@google.com77af6802013-10-02 13:04:56 +00001235 , fNumOctaves(drawEffect.castEffect<GrPerlinNoiseEffect>().numOctaves()) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001236}
1237
sugoi@google.com4775cba2013-04-17 13:46:56 +00001238GrGLEffect::EffectKey GrGLNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001239 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1240
1241 EffectKey key = turbulence.numOctaves();
1242
1243 key = key << 3; // Make room for next 3 bits
1244
1245 switch (turbulence.type()) {
1246 case SkPerlinNoiseShader::kFractalNoise_Type:
1247 key |= 0x1;
1248 break;
1249 case SkPerlinNoiseShader::kTurbulence_Type:
1250 key |= 0x2;
1251 break;
1252 default:
1253 // leave key at 0
1254 break;
1255 }
1256
1257 if (turbulence.stitchTiles()) {
1258 key |= 0x4; // Flip the 3rd bit if tile stitching is on
1259 }
1260
bsalomon@google.com77af6802013-10-02 13:04:56 +00001261 return key;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001262}
1263
sugoi@google.com4775cba2013-04-17 13:46:56 +00001264void GrGLNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001265 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1266
1267 const SkVector& baseFrequency = turbulence.baseFrequency();
1268 uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001269 uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
1270
1271 SkMatrix m = turbulence.matrix();
bsalomon@google.com77af6802013-10-02 13:04:56 +00001272 m.postTranslate(-SK_Scalar1, -SK_Scalar1);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001273 SkMatrix invM;
1274 if (!m.invert(&invM)) {
1275 invM.reset();
1276 } else {
1277 invM.postConcat(invM); // Square the matrix
1278 }
1279 uman.setSkMatrix(fInvMatrixUni, invM);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001280}
1281
sugoi@google.com4775cba2013-04-17 13:46:56 +00001282void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1283 INHERITED::setData(uman, drawEffect);
1284
1285 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1286 if (turbulence.stitchTiles()) {
1287 const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001288 uman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
1289 SkIntToScalar(stitchData.fHeight));
sugoi@google.com4775cba2013-04-17 13:46:56 +00001290 }
1291}
1292
1293void GrGLSimplexNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1294 INHERITED::setData(uman, drawEffect);
1295
1296 const GrSimplexNoiseEffect& turbulence = drawEffect.castEffect<GrSimplexNoiseEffect>();
1297 uman.set1f(fSeedUni, turbulence.seed());
1298}
1299
sugoi@google.come3b4c502013-04-05 13:47:09 +00001300/////////////////////////////////////////////////////////////////////
1301
1302GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001303 SkASSERT(NULL != context);
1304
commit-bot@chromium.orgc2a0ea62013-11-06 10:08:38 +00001305 if (0 == fNumOctaves) {
1306 SkColor clearColor = 0;
1307 if (kFractalNoise_Type == fType) {
1308 clearColor = SkColorSetARGB(paint.getAlpha() / 2, 127, 127, 127);
1309 }
1310 SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(
1311 clearColor, SkXfermode::kSrc_Mode));
1312 return cf->asNewEffect(context);
1313 }
1314
sugoi@google.come3b4c502013-04-05 13:47:09 +00001315 // Either we don't stitch tiles, either we have a valid tile size
1316 SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
1317
sugoi@google.com4775cba2013-04-17 13:46:56 +00001318#ifdef SK_USE_SIMPLEX_NOISE
1319 // Simplex noise is currently disabled but can be enabled by defining SK_USE_SIMPLEX_NOISE
1320 sk_ignore_unused_variable(context);
1321 GrEffectRef* effect =
1322 GrSimplexNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
1323 fNumOctaves, fStitchTiles, fSeed,
1324 this->getLocalMatrix(), paint.getAlpha());
1325#else
sugoi@google.come3b4c502013-04-05 13:47:09 +00001326 GrTexture* permutationsTexture = GrLockAndRefCachedBitmapTexture(
1327 context, *fPaintingData->getPermutationsBitmap(), NULL);
1328 GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture(
1329 context, *fPaintingData->getNoiseBitmap(), NULL);
1330
1331 GrEffectRef* effect = (NULL != permutationsTexture) && (NULL != noiseTexture) ?
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001332 GrPerlinNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001333 fNumOctaves, fStitchTiles,
1334 fPaintingData->fStitchDataInit,
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001335 permutationsTexture, noiseTexture,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001336 this->getLocalMatrix(), paint.getAlpha()) :
1337 NULL;
1338
1339 // Unlock immediately, this is not great, but we don't have a way of
1340 // knowing when else to unlock it currently. TODO: Remove this when
1341 // unref becomes the unlock replacement for all types of textures.
1342 if (NULL != permutationsTexture) {
1343 GrUnlockAndUnrefCachedBitmapTexture(permutationsTexture);
1344 }
1345 if (NULL != noiseTexture) {
1346 GrUnlockAndUnrefCachedBitmapTexture(noiseTexture);
1347 }
sugoi@google.com4775cba2013-04-17 13:46:56 +00001348#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +00001349
1350 return effect;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001351}
1352
1353#else
1354
1355GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext*, const SkPaint&) const {
1356 SkDEBUGFAIL("Should not call in GPU-less build");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001357 return NULL;
1358}
1359
1360#endif
1361
1362#ifdef SK_DEVELOPER
1363void SkPerlinNoiseShader::toString(SkString* str) const {
1364 str->append("SkPerlinNoiseShader: (");
1365
1366 str->append("type: ");
1367 switch (fType) {
1368 case kFractalNoise_Type:
1369 str->append("\"fractal noise\"");
1370 break;
1371 case kTurbulence_Type:
1372 str->append("\"turbulence\"");
1373 break;
1374 default:
1375 str->append("\"unknown\"");
1376 break;
1377 }
1378 str->append(" base frequency: (");
1379 str->appendScalar(fBaseFrequencyX);
1380 str->append(", ");
1381 str->appendScalar(fBaseFrequencyY);
1382 str->append(") number of octaves: ");
1383 str->appendS32(fNumOctaves);
1384 str->append(" seed: ");
1385 str->appendScalar(fSeed);
1386 str->append(" stitch tiles: ");
1387 str->append(fStitchTiles ? "true " : "false ");
1388
1389 this->INHERITED::toString(str);
1390
1391 str->append(")");
1392}
1393#endif