blob: af51afc0316f8438944239f76fe26f63c4a34904 [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"
10#include "SkFlattenableBuffers.h"
11#include "SkShader.h"
12#include "SkUnPreMultiply.h"
13#include "SkString.h"
14
15#if SK_SUPPORT_GPU
16#include "GrContext.h"
bsalomon@google.com77af6802013-10-02 13:04:56 +000017#include "GrCoordTransform.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000018#include "gl/GrGLEffect.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000019#include "GrTBackendEffectFactory.h"
20#include "SkGr.h"
21#endif
22
23static const int kBlockSize = 256;
24static const int kBlockMask = kBlockSize - 1;
25static const int kPerlinNoise = 4096;
26static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
27
28namespace {
29
30// noiseValue is the color component's value (or color)
31// limitValue is the maximum perlin noise array index value allowed
32// newValue is the current noise dimension (either width or height)
33inline int checkNoise(int noiseValue, int limitValue, int newValue) {
34 // If the noise value would bring us out of bounds of the current noise array while we are
35 // stiching noise tiles together, wrap the noise around the current dimension of the noise to
36 // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
37 if (noiseValue >= limitValue) {
38 noiseValue -= newValue;
39 }
40 if (noiseValue >= limitValue - 1) {
41 noiseValue -= newValue - 1;
42 }
43 return noiseValue;
44}
45
46inline SkScalar smoothCurve(SkScalar t) {
47 static const SkScalar SK_Scalar3 = SkFloatToScalar(3.0f);
48
49 // returns t * t * (3 - 2 * t)
50 return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
51}
52
53} // end namespace
54
55struct SkPerlinNoiseShader::StitchData {
56 StitchData()
57 : fWidth(0)
58 , fWrapX(0)
59 , fHeight(0)
60 , fWrapY(0)
61 {}
62
63 bool operator==(const StitchData& other) const {
64 return fWidth == other.fWidth &&
65 fWrapX == other.fWrapX &&
66 fHeight == other.fHeight &&
67 fWrapY == other.fWrapY;
68 }
69
70 int fWidth; // How much to subtract to wrap for stitching.
71 int fWrapX; // Minimum value to wrap.
72 int fHeight;
73 int fWrapY;
74};
75
76struct SkPerlinNoiseShader::PaintingData {
77 PaintingData(const SkISize& tileSize)
78 : fSeed(0)
79 , fTileSize(tileSize)
80 , fPermutationsBitmap(NULL)
81 , fNoiseBitmap(NULL)
82 {}
83
84 ~PaintingData()
85 {
86 SkDELETE(fPermutationsBitmap);
87 SkDELETE(fNoiseBitmap);
88 }
89
90 int fSeed;
91 uint8_t fLatticeSelector[kBlockSize];
92 uint16_t fNoise[4][kBlockSize][2];
93 SkPoint fGradient[4][kBlockSize];
94 SkISize fTileSize;
95 SkVector fBaseFrequency;
96 StitchData fStitchDataInit;
97
98private:
99
100 SkBitmap* fPermutationsBitmap;
101 SkBitmap* fNoiseBitmap;
102
103public:
104
105 inline int random() {
106 static const int gRandAmplitude = 16807; // 7**5; primitive root of m
107 static const int gRandQ = 127773; // m / a
108 static const int gRandR = 2836; // m % a
109
110 int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
111 if (result <= 0)
112 result += kRandMaximum;
113 fSeed = result;
114 return result;
115 }
116
117 void init(SkScalar seed)
118 {
119 static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
120
121 // The seed value clamp to the range [1, kRandMaximum - 1].
122 fSeed = SkScalarRoundToInt(seed);
123 if (fSeed <= 0) {
124 fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
125 }
126 if (fSeed > kRandMaximum - 1) {
127 fSeed = kRandMaximum - 1;
128 }
129 for (int channel = 0; channel < 4; ++channel) {
130 for (int i = 0; i < kBlockSize; ++i) {
131 fLatticeSelector[i] = i;
132 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
133 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
134 }
135 }
136 for (int i = kBlockSize - 1; i > 0; --i) {
137 int k = fLatticeSelector[i];
138 int j = random() % kBlockSize;
139 SkASSERT(j >= 0);
140 SkASSERT(j < kBlockSize);
141 fLatticeSelector[i] = fLatticeSelector[j];
142 fLatticeSelector[j] = k;
143 }
144
145 // Perform the permutations now
146 {
147 // Copy noise data
148 uint16_t noise[4][kBlockSize][2];
149 for (int i = 0; i < kBlockSize; ++i) {
150 for (int channel = 0; channel < 4; ++channel) {
151 for (int j = 0; j < 2; ++j) {
152 noise[channel][i][j] = fNoise[channel][i][j];
153 }
154 }
155 }
156 // Do permutations on noise data
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 fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
161 }
162 }
163 }
164 }
165
166 // Half of the largest possible value for 16 bit unsigned int
sugoi@google.comd537af52013-06-10 13:59:25 +0000167 static const SkScalar gHalfMax16bits = SkFloatToScalar(32767.5f);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000168
169 // Compute gradients from permutated noise data
170 for (int channel = 0; channel < 4; ++channel) {
171 for (int i = 0; i < kBlockSize; ++i) {
172 fGradient[channel][i] = SkPoint::Make(
173 SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
174 gInvBlockSizef),
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000175 SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
sugoi@google.come3b4c502013-04-05 13:47:09 +0000176 gInvBlockSizef));
177 fGradient[channel][i].normalize();
178 // Put the normalized gradient back into the noise data
179 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000180 fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000181 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000182 fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000183 }
184 }
185
186 // Invalidate bitmaps
187 SkDELETE(fPermutationsBitmap);
188 fPermutationsBitmap = NULL;
189 SkDELETE(fNoiseBitmap);
190 fNoiseBitmap = NULL;
191 }
192
193 void stitch() {
194 SkScalar tileWidth = SkIntToScalar(fTileSize.width());
195 SkScalar tileHeight = SkIntToScalar(fTileSize.height());
196 SkASSERT(tileWidth > 0 && tileHeight > 0);
197 // When stitching tiled turbulence, the frequencies must be adjusted
198 // so that the tile borders will be continuous.
199 if (fBaseFrequency.fX) {
200 SkScalar lowFrequencx = SkScalarDiv(
201 SkScalarMulFloor(tileWidth, fBaseFrequency.fX), tileWidth);
202 SkScalar highFrequencx = SkScalarDiv(
203 SkScalarMulCeil(tileWidth, fBaseFrequency.fX), tileWidth);
204 // BaseFrequency should be non-negative according to the standard.
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000205 if (SkScalarDiv(fBaseFrequency.fX, lowFrequencx) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000206 SkScalarDiv(highFrequencx, fBaseFrequency.fX)) {
207 fBaseFrequency.fX = lowFrequencx;
208 } else {
209 fBaseFrequency.fX = highFrequencx;
210 }
211 }
212 if (fBaseFrequency.fY) {
213 SkScalar lowFrequency = SkScalarDiv(
214 SkScalarMulFloor(tileHeight, fBaseFrequency.fY), tileHeight);
215 SkScalar highFrequency = SkScalarDiv(
216 SkScalarMulCeil(tileHeight, fBaseFrequency.fY), tileHeight);
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000217 if (SkScalarDiv(fBaseFrequency.fY, lowFrequency) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000218 SkScalarDiv(highFrequency, fBaseFrequency.fY)) {
219 fBaseFrequency.fY = lowFrequency;
220 } else {
221 fBaseFrequency.fY = highFrequency;
222 }
223 }
224 // Set up TurbulenceInitial stitch values.
225 fStitchDataInit.fWidth =
226 SkScalarMulRound(tileWidth, fBaseFrequency.fX);
227 fStitchDataInit.fWrapX = kPerlinNoise + fStitchDataInit.fWidth;
228 fStitchDataInit.fHeight =
229 SkScalarMulRound(tileHeight, fBaseFrequency.fY);
230 fStitchDataInit.fWrapY = kPerlinNoise + fStitchDataInit.fHeight;
231 }
232
233 SkBitmap* getPermutationsBitmap()
234 {
235 if (!fPermutationsBitmap) {
236 fPermutationsBitmap = SkNEW(SkBitmap);
237 fPermutationsBitmap->setConfig(SkBitmap::kA8_Config, kBlockSize, 1);
238 fPermutationsBitmap->allocPixels();
239 uint8_t* bitmapPixels = fPermutationsBitmap->getAddr8(0, 0);
240 memcpy(bitmapPixels, fLatticeSelector, sizeof(uint8_t) * kBlockSize);
241 }
242 return fPermutationsBitmap;
243 }
244
245 SkBitmap* getNoiseBitmap()
246 {
247 if (!fNoiseBitmap) {
248 fNoiseBitmap = SkNEW(SkBitmap);
249 fNoiseBitmap->setConfig(SkBitmap::kARGB_8888_Config, kBlockSize, 4);
250 fNoiseBitmap->allocPixels();
251 uint32_t* bitmapPixels = fNoiseBitmap->getAddr32(0, 0);
252 memcpy(bitmapPixels, fNoise[0][0], sizeof(uint16_t) * kBlockSize * 4 * 2);
253 }
254 return fNoiseBitmap;
255 }
256};
257
258SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
259 int numOctaves, SkScalar seed,
260 const SkISize* tileSize) {
261 return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY,
262 numOctaves, seed, tileSize));
263}
264
265SkShader* SkPerlinNoiseShader::CreateTubulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
266 int numOctaves, SkScalar seed,
267 const SkISize* tileSize) {
268 return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY,
269 numOctaves, seed, tileSize));
270}
271
272SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
273 SkScalar baseFrequencyX,
274 SkScalar baseFrequencyY,
275 int numOctaves,
276 SkScalar seed,
277 const SkISize* tileSize)
278 : fType(type)
279 , fBaseFrequencyX(baseFrequencyX)
280 , fBaseFrequencyY(baseFrequencyY)
281 , fNumOctaves(numOctaves & 0xFF /*[0,255] octaves allowed*/)
282 , fSeed(seed)
283 , fStitchTiles((tileSize != NULL) && !tileSize->isEmpty())
284 , fPaintingData(NULL)
285{
286 SkASSERT(numOctaves >= 0 && numOctaves < 256);
287 setTileSize(fStitchTiles ? *tileSize : SkISize::Make(0,0));
288 fMatrix.reset();
289}
290
291SkPerlinNoiseShader::SkPerlinNoiseShader(SkFlattenableReadBuffer& buffer) :
292 INHERITED(buffer), fPaintingData(NULL) {
293 fType = (SkPerlinNoiseShader::Type) buffer.readInt();
294 fBaseFrequencyX = buffer.readScalar();
295 fBaseFrequencyY = buffer.readScalar();
296 fNumOctaves = buffer.readInt();
297 fSeed = buffer.readScalar();
298 fStitchTiles = buffer.readBool();
299 fTileSize.fWidth = buffer.readInt();
300 fTileSize.fHeight = buffer.readInt();
301 setTileSize(fTileSize);
302 fMatrix.reset();
303}
304
305SkPerlinNoiseShader::~SkPerlinNoiseShader() {
306 // Safety, should have been done in endContext()
307 SkDELETE(fPaintingData);
308}
309
310void SkPerlinNoiseShader::flatten(SkFlattenableWriteBuffer& buffer) const {
311 this->INHERITED::flatten(buffer);
312 buffer.writeInt((int) fType);
313 buffer.writeScalar(fBaseFrequencyX);
314 buffer.writeScalar(fBaseFrequencyY);
315 buffer.writeInt(fNumOctaves);
316 buffer.writeScalar(fSeed);
317 buffer.writeBool(fStitchTiles);
318 buffer.writeInt(fTileSize.fWidth);
319 buffer.writeInt(fTileSize.fHeight);
320}
321
322void SkPerlinNoiseShader::initPaint(PaintingData& paintingData)
323{
324 paintingData.init(fSeed);
325
326 // Set frequencies to original values
327 paintingData.fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
328 // Adjust frequecies based on size if stitching is enabled
329 if (fStitchTiles) {
330 paintingData.stitch();
331 }
332}
333
334void SkPerlinNoiseShader::setTileSize(const SkISize& tileSize) {
335 fTileSize = tileSize;
336
337 if (NULL == fPaintingData) {
338 fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize));
339 initPaint(*fPaintingData);
340 } else {
341 // Set Size
342 fPaintingData->fTileSize = fTileSize;
343 // Set frequencies to original values
344 fPaintingData->fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
345 // Adjust frequecies based on size if stitching is enabled
346 if (fStitchTiles) {
347 fPaintingData->stitch();
348 }
349 }
350}
351
352SkScalar SkPerlinNoiseShader::noise2D(int channel, const PaintingData& paintingData,
353 const StitchData& stitchData, const SkPoint& noiseVector)
354{
355 struct Noise {
356 int noisePositionIntegerValue;
357 SkScalar noisePositionFractionValue;
358 Noise(SkScalar component)
359 {
360 SkScalar position = component + kPerlinNoise;
361 noisePositionIntegerValue = SkScalarFloorToInt(position);
362 noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
363 }
364 };
365 Noise noiseX(noiseVector.x());
366 Noise noiseY(noiseVector.y());
367 SkScalar u, v;
368 // If stitching, adjust lattice points accordingly.
369 if (fStitchTiles) {
370 noiseX.noisePositionIntegerValue =
371 checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
372 noiseY.noisePositionIntegerValue =
373 checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
374 }
375 noiseX.noisePositionIntegerValue &= kBlockMask;
376 noiseY.noisePositionIntegerValue &= kBlockMask;
377 int latticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000378 paintingData.fLatticeSelector[noiseX.noisePositionIntegerValue] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000379 noiseY.noisePositionIntegerValue;
380 int nextLatticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000381 paintingData.fLatticeSelector[(noiseX.noisePositionIntegerValue + 1) & kBlockMask] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000382 noiseY.noisePositionIntegerValue;
383 SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
384 SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
385 // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
386 SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
387 noiseY.noisePositionFractionValue); // Offset (0,0)
388 u = paintingData.fGradient[channel][latticeIndex & kBlockMask].dot(fractionValue);
389 fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
390 v = paintingData.fGradient[channel][nextLatticeIndex & kBlockMask].dot(fractionValue);
391 SkScalar a = SkScalarInterp(u, v, sx);
392 fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
393 v = paintingData.fGradient[channel][(nextLatticeIndex + 1) & kBlockMask].dot(fractionValue);
394 fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
395 u = paintingData.fGradient[channel][(latticeIndex + 1) & kBlockMask].dot(fractionValue);
396 SkScalar b = SkScalarInterp(u, v, sx);
397 return SkScalarInterp(a, b, sy);
398}
399
400SkScalar SkPerlinNoiseShader::calculateTurbulenceValueForPoint(
401 int channel, const PaintingData& paintingData, StitchData& stitchData, const SkPoint& point)
402{
403 if (fStitchTiles) {
404 // Set up TurbulenceInitial stitch values.
405 stitchData = paintingData.fStitchDataInit;
406 }
407 SkScalar turbulenceFunctionResult = 0;
408 SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), paintingData.fBaseFrequency.fX),
409 SkScalarMul(point.y(), paintingData.fBaseFrequency.fY)));
410 SkScalar ratio = SK_Scalar1;
411 for (int octave = 0; octave < fNumOctaves; ++octave) {
412 SkScalar noise = noise2D(channel, paintingData, stitchData, noiseVector);
413 turbulenceFunctionResult += SkScalarDiv(
414 (fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio);
415 noiseVector.fX *= 2;
416 noiseVector.fY *= 2;
417 ratio *= 2;
418 if (fStitchTiles) {
419 // Update stitch values
420 stitchData.fWidth *= 2;
421 stitchData.fWrapX = stitchData.fWidth + kPerlinNoise;
422 stitchData.fHeight *= 2;
423 stitchData.fWrapY = stitchData.fHeight + kPerlinNoise;
424 }
425 }
426
427 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
428 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
429 if (fType == kFractalNoise_Type) {
430 turbulenceFunctionResult =
431 SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
432 }
433
434 if (channel == 3) { // Scale alpha by paint value
435 turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult,
436 SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255)));
437 }
438
439 // Clamp result
440 return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
441}
442
443SkPMColor SkPerlinNoiseShader::shade(const SkPoint& point, StitchData& stitchData) {
444 SkMatrix matrix = fMatrix;
445 SkMatrix invMatrix;
446 if (!matrix.invert(&invMatrix)) {
447 invMatrix.reset();
448 } else {
449 invMatrix.postConcat(invMatrix); // Square the matrix
450 }
451 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
452 // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
453 matrix.postTranslate(SK_Scalar1, SK_Scalar1);
454 SkPoint newPoint;
455 matrix.mapPoints(&newPoint, &point, 1);
456 invMatrix.mapPoints(&newPoint, &newPoint, 1);
457 newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
458 newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
459
460 U8CPU rgba[4];
461 for (int channel = 3; channel >= 0; --channel) {
462 rgba[channel] = SkScalarFloorToInt(255 *
463 calculateTurbulenceValueForPoint(channel, *fPaintingData, stitchData, newPoint));
464 }
465 return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
466}
467
468bool SkPerlinNoiseShader::setContext(const SkBitmap& device, const SkPaint& paint,
469 const SkMatrix& matrix) {
470 fMatrix = matrix;
471 return INHERITED::setContext(device, paint, matrix);
472}
473
474void SkPerlinNoiseShader::shadeSpan(int x, int y, SkPMColor result[], int count) {
475 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
476 StitchData stitchData;
477 for (int i = 0; i < count; ++i) {
478 result[i] = shade(point, stitchData);
479 point.fX += SK_Scalar1;
480 }
481}
482
483void SkPerlinNoiseShader::shadeSpan16(int x, int y, uint16_t result[], int count) {
484 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
485 StitchData stitchData;
486 DITHER_565_SCAN(y);
487 for (int i = 0; i < count; ++i) {
488 unsigned dither = DITHER_VALUE(x);
489 result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
490 DITHER_INC_X(x);
491 point.fX += SK_Scalar1;
492 }
493}
494
495/////////////////////////////////////////////////////////////////////
496
commit-bot@chromium.org344cf452013-06-17 14:19:01 +0000497#if SK_SUPPORT_GPU
sugoi@google.come3b4c502013-04-05 13:47:09 +0000498
499#include "GrTBackendEffectFactory.h"
500
sugoi@google.com4775cba2013-04-17 13:46:56 +0000501class GrGLNoise : public GrGLEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000502public:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000503 GrGLNoise(const GrBackendEffectFactory& factory,
504 const GrDrawEffect& drawEffect);
505 virtual ~GrGLNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000506
sugoi@google.com4775cba2013-04-17 13:46:56 +0000507 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
508
509 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
510
511protected:
512 SkPerlinNoiseShader::Type fType;
513 bool fStitchTiles;
514 int fNumOctaves;
515 GrGLUniformManager::UniformHandle fBaseFrequencyUni;
516 GrGLUniformManager::UniformHandle fAlphaUni;
517 GrGLUniformManager::UniformHandle fInvMatrixUni;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000518
519private:
520 typedef GrGLEffect INHERITED;
521};
522
523class GrGLPerlinNoise : public GrGLNoise {
524public:
sugoi@google.come3b4c502013-04-05 13:47:09 +0000525 GrGLPerlinNoise(const GrBackendEffectFactory& factory,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000526 const GrDrawEffect& drawEffect)
527 : GrGLNoise(factory, drawEffect) {}
528 virtual ~GrGLPerlinNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000529
530 virtual void emitCode(GrGLShaderBuilder*,
531 const GrDrawEffect&,
532 EffectKey,
533 const char* outputColor,
534 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000535 const TransformedCoordsArray&,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000536 const TextureSamplerArray&) SK_OVERRIDE;
537
sugoi@google.com4775cba2013-04-17 13:46:56 +0000538 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000539
540private:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000541 GrGLUniformManager::UniformHandle fStitchDataUni;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000542
sugoi@google.com4775cba2013-04-17 13:46:56 +0000543 typedef GrGLNoise INHERITED;
544};
545
546class GrGLSimplexNoise : public GrGLNoise {
547 // Note : This is for reference only. GrGLPerlinNoise is used for processing.
548public:
549 GrGLSimplexNoise(const GrBackendEffectFactory& factory,
550 const GrDrawEffect& drawEffect)
551 : GrGLNoise(factory, drawEffect) {}
552
553 virtual ~GrGLSimplexNoise() {}
554
555 virtual void emitCode(GrGLShaderBuilder*,
556 const GrDrawEffect&,
557 EffectKey,
558 const char* outputColor,
559 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000560 const TransformedCoordsArray&,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000561 const TextureSamplerArray&) SK_OVERRIDE;
562
563 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
564
565private:
566 GrGLUniformManager::UniformHandle fSeedUni;
567
568 typedef GrGLNoise INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000569};
570
571/////////////////////////////////////////////////////////////////////
572
sugoi@google.com4775cba2013-04-17 13:46:56 +0000573class GrNoiseEffect : public GrEffect {
574public:
575 virtual ~GrNoiseEffect() { }
576
577 SkPerlinNoiseShader::Type type() const { return fType; }
578 bool stitchTiles() const { return fStitchTiles; }
579 const SkVector& baseFrequency() const { return fBaseFrequency; }
580 int numOctaves() const { return fNumOctaves; }
bsalomon@google.com77af6802013-10-02 13:04:56 +0000581 const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000582 uint8_t alpha() const { return fAlpha; }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000583
584 void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE {
585 *validFlags = 0; // This is noise. Nothing is constant.
586 }
587
588protected:
589 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
590 const GrNoiseEffect& s = CastEffect<GrNoiseEffect>(sBase);
591 return fType == s.fType &&
592 fBaseFrequency == s.fBaseFrequency &&
593 fNumOctaves == s.fNumOctaves &&
594 fStitchTiles == s.fStitchTiles &&
bsalomon@google.com77af6802013-10-02 13:04:56 +0000595 fCoordTransform.getMatrix() == s.fCoordTransform.getMatrix() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000596 fAlpha == s.fAlpha;
597 }
598
599 GrNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, int numOctaves,
600 bool stitchTiles, const SkMatrix& matrix, uint8_t alpha)
601 : fType(type)
602 , fBaseFrequency(baseFrequency)
603 , fNumOctaves(numOctaves)
604 , fStitchTiles(stitchTiles)
605 , fMatrix(matrix)
606 , fAlpha(alpha) {
bsalomon@google.com77af6802013-10-02 13:04:56 +0000607 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
608 // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions.
609 SkMatrix m = matrix;
610 m.postTranslate(SK_Scalar1, SK_Scalar1);
611 fCoordTransform.reset(kLocal_GrCoordSet, m);
612 this->addCoordTransform(&fCoordTransform);
commit-bot@chromium.orga34995e2013-10-23 05:42:03 +0000613 this->setWillNotUseInputColor();
sugoi@google.com4775cba2013-04-17 13:46:56 +0000614 }
615
616 SkPerlinNoiseShader::Type fType;
bsalomon@google.com77af6802013-10-02 13:04:56 +0000617 GrCoordTransform fCoordTransform;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000618 SkVector fBaseFrequency;
619 int fNumOctaves;
620 bool fStitchTiles;
621 SkMatrix fMatrix;
622 uint8_t fAlpha;
623
624private:
625 typedef GrEffect INHERITED;
626};
627
628class GrPerlinNoiseEffect : public GrNoiseEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000629public:
630 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
631 int numOctaves, bool stitchTiles,
632 const SkPerlinNoiseShader::StitchData& stitchData,
633 GrTexture* permutationsTexture, GrTexture* noiseTexture,
634 const SkMatrix& matrix, uint8_t alpha) {
635 AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves,
636 stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha)));
637 return CreateEffectRef(effect);
638 }
639
640 virtual ~GrPerlinNoiseEffect() { }
641
642 static const char* Name() { return "PerlinNoise"; }
643 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
644 return GrTBackendEffectFactory<GrPerlinNoiseEffect>::getInstance();
645 }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000646 const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000647
648 typedef GrGLPerlinNoise GLEffect;
649
sugoi@google.come3b4c502013-04-05 13:47:09 +0000650private:
651 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
652 const GrPerlinNoiseEffect& s = CastEffect<GrPerlinNoiseEffect>(sBase);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000653 return INHERITED::onIsEqual(sBase) &&
654 fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() &&
sugoi@google.come3b4c502013-04-05 13:47:09 +0000655 fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000656 fStitchData == s.fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000657 }
658
659 GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
660 int numOctaves, bool stitchTiles,
661 const SkPerlinNoiseShader::StitchData& stitchData,
662 GrTexture* permutationsTexture, GrTexture* noiseTexture,
663 const SkMatrix& matrix, uint8_t alpha)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000664 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
665 , fPermutationsAccess(permutationsTexture)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000666 , fNoiseAccess(noiseTexture)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000667 , fStitchData(stitchData) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000668 this->addTextureAccess(&fPermutationsAccess);
669 this->addTextureAccess(&fNoiseAccess);
670 }
671
sugoi@google.com4775cba2013-04-17 13:46:56 +0000672 GR_DECLARE_EFFECT_TEST;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000673
674 GrTextureAccess fPermutationsAccess;
675 GrTextureAccess fNoiseAccess;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000676 SkPerlinNoiseShader::StitchData fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000677
sugoi@google.com4775cba2013-04-17 13:46:56 +0000678 typedef GrNoiseEffect INHERITED;
679};
680
681class GrSimplexNoiseEffect : public GrNoiseEffect {
682 // Note : This is for reference only. GrPerlinNoiseEffect is used for processing.
683public:
684 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
685 int numOctaves, bool stitchTiles, const SkScalar seed,
686 const SkMatrix& matrix, uint8_t alpha) {
687 AutoEffectUnref effect(SkNEW_ARGS(GrSimplexNoiseEffect, (type, baseFrequency, numOctaves,
688 stitchTiles, seed, matrix, alpha)));
689 return CreateEffectRef(effect);
690 }
691
692 virtual ~GrSimplexNoiseEffect() { }
693
694 static const char* Name() { return "SimplexNoise"; }
695 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
696 return GrTBackendEffectFactory<GrSimplexNoiseEffect>::getInstance();
697 }
698 const SkScalar& seed() const { return fSeed; }
699
700 typedef GrGLSimplexNoise GLEffect;
701
702private:
703 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
704 const GrSimplexNoiseEffect& s = CastEffect<GrSimplexNoiseEffect>(sBase);
705 return INHERITED::onIsEqual(sBase) && fSeed == s.fSeed;
706 }
707
708 GrSimplexNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
709 int numOctaves, bool stitchTiles, const SkScalar seed,
710 const SkMatrix& matrix, uint8_t alpha)
711 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
712 , fSeed(seed) {
713 }
714
715 SkScalar fSeed;
716
717 typedef GrNoiseEffect INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000718};
719
720/////////////////////////////////////////////////////////////////////
sugoi@google.come3b4c502013-04-05 13:47:09 +0000721GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect);
722
commit-bot@chromium.orge0e7cfe2013-09-09 20:09:12 +0000723GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkRandom* random,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000724 GrContext* context,
725 const GrDrawTargetCaps&,
726 GrTexture**) {
sugoi@google.com423ac132013-04-18 14:04:57 +0000727 int numOctaves = random->nextRangeU(2, 10);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000728 bool stitchTiles = random->nextBool();
729 SkScalar seed = SkIntToScalar(random->nextU());
730 SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
731 SkScalar baseFrequencyX = random->nextRangeScalar(SkFloatToScalar(0.01f),
732 SkFloatToScalar(0.99f));
733 SkScalar baseFrequencyY = random->nextRangeScalar(SkFloatToScalar(0.01f),
734 SkFloatToScalar(0.99f));
735
736 SkShader* shader = random->nextBool() ?
737 SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
738 stitchTiles ? &tileSize : NULL) :
739 SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
740 stitchTiles ? &tileSize : NULL);
741
742 SkPaint paint;
743 GrEffectRef* effect = shader->asNewEffect(context, paint);
744
745 SkDELETE(shader);
746
747 return effect;
748}
sugoi@google.com4775cba2013-04-17 13:46:56 +0000749
sugoi@google.come3b4c502013-04-05 13:47:09 +0000750/////////////////////////////////////////////////////////////////////
751
sugoi@google.com4775cba2013-04-17 13:46:56 +0000752void GrGLSimplexNoise::emitCode(GrGLShaderBuilder* builder,
753 const GrDrawEffect&,
754 EffectKey key,
755 const char* outputColor,
756 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000757 const TransformedCoordsArray& coords,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000758 const TextureSamplerArray&) {
759 sk_ignore_unused_variable(inputColor);
760
bsalomon@google.com77af6802013-10-02 13:04:56 +0000761 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000762
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000763 fSeedUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000764 kFloat_GrSLType, "seed");
765 const char* seedUni = builder->getUniformCStr(fSeedUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000766 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000767 kMat33f_GrSLType, "invMatrix");
768 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000769 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000770 kVec2f_GrSLType, "baseFrequency");
771 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000772 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000773 kFloat_GrSLType, "alpha");
774 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
775
776 // Add vec3 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000777 static const GrGLShaderVar gVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000778 GrGLShaderVar("x", kVec3f_GrSLType)
779 };
780
781 SkString mod289_3_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000782 builder->fsEmitFunction(kVec3f_GrSLType,
783 "mod289", SK_ARRAY_COUNT(gVec3Args), gVec3Args,
784 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
785 "return x - floor(x * C.xxx) * C.yyy;", &mod289_3_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000786
787 // Add vec4 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000788 static const GrGLShaderVar gVec4Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000789 GrGLShaderVar("x", kVec4f_GrSLType)
790 };
791
792 SkString mod289_4_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000793 builder->fsEmitFunction(kVec4f_GrSLType,
794 "mod289", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
795 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
796 "return x - floor(x * C.xxxx) * C.yyyy;", &mod289_4_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000797
798 // Add vec4 permute function
sugoi@google.comd537af52013-06-10 13:59:25 +0000799 SkString permuteCode;
800 permuteCode.appendf("const vec2 C = vec2(34.0, 1.0);\n"
801 "return %s(((x * C.xxxx) + C.yyyy) * x);", mod289_4_funcName.c_str());
802 SkString permuteFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000803 builder->fsEmitFunction(kVec4f_GrSLType,
804 "permute", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
805 permuteCode.c_str(), &permuteFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000806
807 // Add vec4 taylorInvSqrt function
sugoi@google.comd537af52013-06-10 13:59:25 +0000808 SkString taylorInvSqrtFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000809 builder->fsEmitFunction(kVec4f_GrSLType,
810 "taylorInvSqrt", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
811 "const vec2 C = vec2(-0.85373472095314, 1.79284291400159);\n"
812 "return x * C.xxxx + C.yyyy;", &taylorInvSqrtFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000813
814 // Add vec3 noise function
sugoi@google.comd537af52013-06-10 13:59:25 +0000815 static const GrGLShaderVar gNoiseVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000816 GrGLShaderVar("v", kVec3f_GrSLType)
817 };
818
sugoi@google.comd537af52013-06-10 13:59:25 +0000819 SkString noiseCode;
820 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000821 "const vec2 C = vec2(1.0/6.0, 1.0/3.0);\n"
822 "const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n"
823
824 // First corner
825 "vec3 i = floor(v + dot(v, C.yyy));\n"
826 "vec3 x0 = v - i + dot(i, C.xxx);\n"
827
828 // Other corners
829 "vec3 g = step(x0.yzx, x0.xyz);\n"
830 "vec3 l = 1.0 - g;\n"
831 "vec3 i1 = min(g.xyz, l.zxy);\n"
832 "vec3 i2 = max(g.xyz, l.zxy);\n"
833
834 "vec3 x1 = x0 - i1 + C.xxx;\n"
835 "vec3 x2 = x0 - i2 + C.yyy;\n" // 2.0*C.x = 1/3 = C.y
836 "vec3 x3 = x0 - D.yyy;\n" // -1.0+3.0*C.x = -0.5 = -D.y
837 );
838
sugoi@google.comd537af52013-06-10 13:59:25 +0000839 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000840 // Permutations
841 "i = %s(i);\n"
842 "vec4 p = %s(%s(%s(\n"
843 " i.z + vec4(0.0, i1.z, i2.z, 1.0)) +\n"
844 " i.y + vec4(0.0, i1.y, i2.y, 1.0)) +\n"
845 " i.x + vec4(0.0, i1.x, i2.x, 1.0));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000846 mod289_3_funcName.c_str(), permuteFuncName.c_str(), permuteFuncName.c_str(),
847 permuteFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000848
sugoi@google.comd537af52013-06-10 13:59:25 +0000849 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000850 // Gradients: 7x7 points over a square, mapped onto an octahedron.
851 // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
852 "float n_ = 0.142857142857;\n" // 1.0/7.0
853 "vec3 ns = n_ * D.wyz - D.xzx;\n"
854
855 "vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\n" // mod(p,7*7)
856
857 "vec4 x_ = floor(j * ns.z);\n"
858 "vec4 y_ = floor(j - 7.0 * x_);" // mod(j,N)
859
860 "vec4 x = x_ *ns.x + ns.yyyy;\n"
861 "vec4 y = y_ *ns.x + ns.yyyy;\n"
862 "vec4 h = 1.0 - abs(x) - abs(y);\n"
863
864 "vec4 b0 = vec4(x.xy, y.xy);\n"
865 "vec4 b1 = vec4(x.zw, y.zw);\n"
866 );
867
sugoi@google.comd537af52013-06-10 13:59:25 +0000868 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000869 "vec4 s0 = floor(b0) * 2.0 + 1.0;\n"
870 "vec4 s1 = floor(b1) * 2.0 + 1.0;\n"
871 "vec4 sh = -step(h, vec4(0.0));\n"
872
873 "vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;\n"
874 "vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;\n"
875
876 "vec3 p0 = vec3(a0.xy, h.x);\n"
877 "vec3 p1 = vec3(a0.zw, h.y);\n"
878 "vec3 p2 = vec3(a1.xy, h.z);\n"
879 "vec3 p3 = vec3(a1.zw, h.w);\n"
880 );
881
sugoi@google.comd537af52013-06-10 13:59:25 +0000882 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000883 // Normalise gradients
884 "vec4 norm = %s(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n"
885 "p0 *= norm.x;\n"
886 "p1 *= norm.y;\n"
887 "p2 *= norm.z;\n"
888 "p3 *= norm.w;\n"
889
890 // Mix final noise value
891 "vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n"
892 "m = m * m;\n"
893 "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 +0000894 taylorInvSqrtFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000895
sugoi@google.comd537af52013-06-10 13:59:25 +0000896 SkString noiseFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000897 builder->fsEmitFunction(kFloat_GrSLType,
898 "snoise", SK_ARRAY_COUNT(gNoiseVec3Args), gNoiseVec3Args,
899 noiseCode.c_str(), &noiseFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000900
901 const char* noiseVecIni = "noiseVecIni";
902 const char* factors = "factors";
903 const char* sum = "sum";
904 const char* xOffsets = "xOffsets";
905 const char* yOffsets = "yOffsets";
906 const char* channel = "channel";
907
908 // Fill with some prime numbers
909 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(13.0, 53.0, 101.0, 151.0);\n", xOffsets);
910 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(109.0, 167.0, 23.0, 67.0);\n", yOffsets);
911
912 // There are rounding errors if the floor operation is not performed here
913 builder->fsCodeAppendf(
914 "\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 +0000915 noiseVecIni, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000916
917 // Perturb the texcoords with three components of noise
918 builder->fsCodeAppendf("\t\t%s += 0.1 * vec3(%s(%s + vec3( 0.0, 0.0, %s)),"
919 "%s(%s + vec3( 43.0, 17.0, %s)),"
920 "%s(%s + vec3(-17.0, -43.0, %s)));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000921 noiseVecIni, noiseFuncName.c_str(), noiseVecIni, seedUni,
922 noiseFuncName.c_str(), noiseVecIni, seedUni,
923 noiseFuncName.c_str(), noiseVecIni, seedUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000924
925 builder->fsCodeAppendf("\t\t%s = vec4(0.0);\n", outputColor);
926
927 builder->fsCodeAppendf("\t\tvec3 %s = vec3(1.0);\n", factors);
928 builder->fsCodeAppendf("\t\tfloat %s = 0.0;\n", sum);
929
930 // Loop over all octaves
931 builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {\n", fNumOctaves);
932
933 // Loop over the 4 channels
934 builder->fsCodeAppendf("\t\t\tfor (int %s = 3; %s >= 0; --%s) {\n", channel, channel, channel);
935
936 builder->fsCodeAppendf(
937 "\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 +0000938 outputColor, factors, noiseFuncName.c_str(), noiseVecIni, factors, xOffsets, channel,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000939 yOffsets, channel, seedUni, factors);
940
941 builder->fsCodeAppend("\t\t\t}\n"); // end of the for loop on channels
942
943 builder->fsCodeAppendf("\t\t\t%s += %s.x;\n", sum, factors);
944 builder->fsCodeAppendf("\t\t\t%s *= vec3(0.5, 2.0, 0.75);\n", factors);
945
946 builder->fsCodeAppend("\t\t}\n"); // end of the for loop on octaves
947
948 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
949 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
950 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
951 builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5 / %s) + vec4(0.5);\n",
952 outputColor, outputColor, sum);
953 } else {
954 builder->fsCodeAppendf("\t\t%s = abs(%s / vec4(%s));\n",
955 outputColor, outputColor, sum);
956 }
957
958 builder->fsCodeAppendf("\t\t%s.a *= %s;\n", outputColor, alphaUni);
959
960 // Clamp values
961 builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);\n", outputColor, outputColor);
962
963 // Pre-multiply the result
964 builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
965 outputColor, outputColor, outputColor, outputColor);
966}
967
sugoi@google.come3b4c502013-04-05 13:47:09 +0000968void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder,
969 const GrDrawEffect&,
970 EffectKey key,
971 const char* outputColor,
972 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000973 const TransformedCoordsArray& coords,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000974 const TextureSamplerArray& samplers) {
975 sk_ignore_unused_variable(inputColor);
976
bsalomon@google.com77af6802013-10-02 13:04:56 +0000977 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000978
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000979 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000980 kMat33f_GrSLType, "invMatrix");
981 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000982 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000983 kVec2f_GrSLType, "baseFrequency");
984 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000985 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000986 kFloat_GrSLType, "alpha");
987 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
988
989 const char* stitchDataUni = NULL;
990 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000991 fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
commit-bot@chromium.org98393202013-07-04 18:13:05 +0000992 kVec2f_GrSLType, "stitchData");
sugoi@google.come3b4c502013-04-05 13:47:09 +0000993 stitchDataUni = builder->getUniformCStr(fStitchDataUni);
994 }
995
sugoi@google.comd537af52013-06-10 13:59:25 +0000996 // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
997 const char* chanCoordR = "0.125";
998 const char* chanCoordG = "0.375";
999 const char* chanCoordB = "0.625";
1000 const char* chanCoordA = "0.875";
1001 const char* chanCoord = "chanCoord";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001002 const char* stitchData = "stitchData";
1003 const char* ratio = "ratio";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001004 const char* noiseXY = "noiseXY";
1005 const char* noiseVec = "noiseVec";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001006 const char* noiseSmooth = "noiseSmooth";
1007 const char* fractVal = "fractVal";
1008 const char* uv = "uv";
1009 const char* ab = "ab";
1010 const char* latticeIdx = "latticeIdx";
1011 const char* lattice = "lattice";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001012 const char* inc8bit = "0.00390625"; // 1.0 / 256.0
1013 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
1014 // [-1,1] vector and perform a dot product between that vector and the provided vector.
1015 const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
1016
sugoi@google.comd537af52013-06-10 13:59:25 +00001017 // Add noise function
1018 static const GrGLShaderVar gPerlinNoiseArgs[] = {
1019 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001020 GrGLShaderVar(noiseVec, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001021 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001022
sugoi@google.comd537af52013-06-10 13:59:25 +00001023 static const GrGLShaderVar gPerlinNoiseStitchArgs[] = {
1024 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001025 GrGLShaderVar(noiseVec, kVec2f_GrSLType),
1026 GrGLShaderVar(stitchData, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001027 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001028
sugoi@google.comd537af52013-06-10 13:59:25 +00001029 SkString noiseCode;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001030
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001031 noiseCode.appendf("\tvec4 %s = vec4(floor(%s), fract(%s));", noiseXY, noiseVec, noiseVec);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001032
1033 // smooth curve : t * t * (3 - 2 * t)
sugoi@google.comd537af52013-06-10 13:59:25 +00001034 noiseCode.appendf("\n\tvec2 %s = %s.zw * %s.zw * (vec2(3.0) - vec2(2.0) * %s.zw);",
1035 noiseSmooth, noiseXY, noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001036
1037 // Adjust frequencies if we're stitching tiles
1038 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001039 noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001040 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001041 noiseCode.appendf("\n\tif(%s.x >= (%s.x - 1.0)) { %s.x -= (%s.x - 1.0); }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001042 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001043 noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001044 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001045 noiseCode.appendf("\n\tif(%s.y >= (%s.y - 1.0)) { %s.y -= (%s.y - 1.0); }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001046 noiseXY, stitchData, noiseXY, stitchData);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001047 }
1048
1049 // Get texture coordinates and normalize
sugoi@google.comd537af52013-06-10 13:59:25 +00001050 noiseCode.appendf("\n\t%s.xy = fract(floor(mod(%s.xy, 256.0)) / vec2(256.0));\n",
1051 noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001052
1053 // Get permutation for x
1054 {
1055 SkString xCoords("");
1056 xCoords.appendf("vec2(%s.x, 0.5)", noiseXY);
1057
sugoi@google.comd537af52013-06-10 13:59:25 +00001058 noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
1059 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1060 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001061 }
1062
1063 // Get permutation for x + 1
1064 {
1065 SkString xCoords("");
1066 xCoords.appendf("vec2(fract(%s.x + %s), 0.5)", noiseXY, inc8bit);
1067
sugoi@google.comd537af52013-06-10 13:59:25 +00001068 noiseCode.appendf("\n\t%s.y = ", latticeIdx);
1069 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1070 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001071 }
1072
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001073#if defined(SK_BUILD_FOR_ANDROID)
1074 // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
1075 // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
1076 // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
1077 // (or 0.484368 here). The following rounding operation prevents these precision issues from
1078 // affecting the result of the noise by making sure that we only have multiples of 1/255.
1079 // (Note that 1/255 is about 0.003921569, which is the value used here).
1080 noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);",
1081 latticeIdx, latticeIdx);
1082#endif
1083
sugoi@google.come3b4c502013-04-05 13:47:09 +00001084 // Get (x,y) coordinates with the permutated x
sugoi@google.comd537af52013-06-10 13:59:25 +00001085 noiseCode.appendf("\n\t%s = fract(%s + %s.yy);", latticeIdx, latticeIdx, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001086
sugoi@google.comd537af52013-06-10 13:59:25 +00001087 noiseCode.appendf("\n\tvec2 %s = %s.zw;", fractVal, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001088
sugoi@google.comd537af52013-06-10 13:59:25 +00001089 noiseCode.appendf("\n\n\tvec2 %s;", uv);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001090 // Compute u, at offset (0,0)
1091 {
1092 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001093 latticeCoords.appendf("vec2(%s.x, %s)", latticeIdx, chanCoord);
1094 noiseCode.appendf("\n\tvec4 %s = ", lattice);
1095 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1096 kVec2f_GrSLType);
1097 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1098 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001099 }
1100
sugoi@google.comd537af52013-06-10 13:59:25 +00001101 noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001102 // Compute v, at offset (-1,0)
1103 {
1104 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001105 latticeCoords.appendf("vec2(%s.y, %s)", latticeIdx, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001106 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001107 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1108 kVec2f_GrSLType);
1109 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1110 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001111 }
1112
1113 // Compute 'a' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001114 noiseCode.appendf("\n\tvec2 %s;", ab);
1115 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 +00001116
sugoi@google.comd537af52013-06-10 13:59:25 +00001117 noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001118 // Compute v, at offset (-1,-1)
1119 {
1120 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001121 latticeCoords.appendf("vec2(fract(%s.y + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001122 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001123 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1124 kVec2f_GrSLType);
1125 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1126 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001127 }
1128
sugoi@google.comd537af52013-06-10 13:59:25 +00001129 noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001130 // Compute u, at offset (0,-1)
1131 {
1132 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001133 latticeCoords.appendf("vec2(fract(%s.x + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001134 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001135 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1136 kVec2f_GrSLType);
1137 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1138 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001139 }
1140
1141 // Compute 'b' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001142 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 +00001143 // Compute the noise as a linear interpolation of 'a' and 'b'
sugoi@google.comd537af52013-06-10 13:59:25 +00001144 noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001145
sugoi@google.comd537af52013-06-10 13:59:25 +00001146 SkString noiseFuncName;
1147 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001148 builder->fsEmitFunction(kFloat_GrSLType,
1149 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
1150 gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001151 } else {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001152 builder->fsEmitFunction(kFloat_GrSLType,
1153 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
1154 gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001155 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001156
sugoi@google.comd537af52013-06-10 13:59:25 +00001157 // There are rounding errors if the floor operation is not performed here
1158 builder->fsCodeAppendf("\n\t\tvec2 %s = floor((%s * vec3(%s, 1.0)).xy) * %s;",
commit-bot@chromium.org7ab7ca42013-08-28 15:59:13 +00001159 noiseVec, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.comd537af52013-06-10 13:59:25 +00001160
1161 // Clear the color accumulator
1162 builder->fsCodeAppendf("\n\t\t%s = vec4(0.0);", outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001163
1164 if (fStitchTiles) {
sugoi@google.comd537af52013-06-10 13:59:25 +00001165 // Set up TurbulenceInitial stitch values.
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001166 builder->fsCodeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001167 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001168
sugoi@google.comd537af52013-06-10 13:59:25 +00001169 builder->fsCodeAppendf("\n\t\tfloat %s = 1.0;", ratio);
1170
1171 // Loop over all octaves
1172 builder->fsCodeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
1173
1174 builder->fsCodeAppendf("\n\t\t\t%s += ", outputColor);
1175 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1176 builder->fsCodeAppend("abs(");
1177 }
1178 if (fStitchTiles) {
1179 builder->fsCodeAppendf(
1180 "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
1181 "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
1182 noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
1183 noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
1184 noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
1185 noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
1186 } else {
1187 builder->fsCodeAppendf(
1188 "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
1189 "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
1190 noiseFuncName.c_str(), chanCoordR, noiseVec,
1191 noiseFuncName.c_str(), chanCoordG, noiseVec,
1192 noiseFuncName.c_str(), chanCoordB, noiseVec,
1193 noiseFuncName.c_str(), chanCoordA, noiseVec);
1194 }
1195 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1196 builder->fsCodeAppendf(")"); // end of "abs("
1197 }
1198 builder->fsCodeAppendf(" * %s;", ratio);
1199
1200 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
1201 builder->fsCodeAppendf("\n\t\t\t%s *= 0.5;", ratio);
1202
1203 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001204 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData);
sugoi@google.comd537af52013-06-10 13:59:25 +00001205 }
1206 builder->fsCodeAppend("\n\t\t}"); // end of the for loop on octaves
sugoi@google.come3b4c502013-04-05 13:47:09 +00001207
1208 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
1209 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
1210 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
sugoi@google.comd537af52013-06-10 13:59:25 +00001211 builder->fsCodeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001212 }
1213
sugoi@google.comd537af52013-06-10 13:59:25 +00001214 builder->fsCodeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001215
1216 // Clamp values
sugoi@google.comd537af52013-06-10 13:59:25 +00001217 builder->fsCodeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001218
1219 // Pre-multiply the result
sugoi@google.comd537af52013-06-10 13:59:25 +00001220 builder->fsCodeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
sugoi@google.come3b4c502013-04-05 13:47:09 +00001221 outputColor, outputColor, outputColor, outputColor);
1222}
1223
sugoi@google.com4775cba2013-04-17 13:46:56 +00001224GrGLNoise::GrGLNoise(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect)
sugoi@google.come3b4c502013-04-05 13:47:09 +00001225 : INHERITED (factory)
1226 , fType(drawEffect.castEffect<GrPerlinNoiseEffect>().type())
1227 , fStitchTiles(drawEffect.castEffect<GrPerlinNoiseEffect>().stitchTiles())
bsalomon@google.com77af6802013-10-02 13:04:56 +00001228 , fNumOctaves(drawEffect.castEffect<GrPerlinNoiseEffect>().numOctaves()) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001229}
1230
sugoi@google.com4775cba2013-04-17 13:46:56 +00001231GrGLEffect::EffectKey GrGLNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001232 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1233
1234 EffectKey key = turbulence.numOctaves();
1235
1236 key = key << 3; // Make room for next 3 bits
1237
1238 switch (turbulence.type()) {
1239 case SkPerlinNoiseShader::kFractalNoise_Type:
1240 key |= 0x1;
1241 break;
1242 case SkPerlinNoiseShader::kTurbulence_Type:
1243 key |= 0x2;
1244 break;
1245 default:
1246 // leave key at 0
1247 break;
1248 }
1249
1250 if (turbulence.stitchTiles()) {
1251 key |= 0x4; // Flip the 3rd bit if tile stitching is on
1252 }
1253
bsalomon@google.com77af6802013-10-02 13:04:56 +00001254 return key;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001255}
1256
sugoi@google.com4775cba2013-04-17 13:46:56 +00001257void GrGLNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001258 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1259
1260 const SkVector& baseFrequency = turbulence.baseFrequency();
1261 uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001262 uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
1263
1264 SkMatrix m = turbulence.matrix();
bsalomon@google.com77af6802013-10-02 13:04:56 +00001265 m.postTranslate(-SK_Scalar1, -SK_Scalar1);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001266 SkMatrix invM;
1267 if (!m.invert(&invM)) {
1268 invM.reset();
1269 } else {
1270 invM.postConcat(invM); // Square the matrix
1271 }
1272 uman.setSkMatrix(fInvMatrixUni, invM);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001273}
1274
sugoi@google.com4775cba2013-04-17 13:46:56 +00001275void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1276 INHERITED::setData(uman, drawEffect);
1277
1278 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1279 if (turbulence.stitchTiles()) {
1280 const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001281 uman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
1282 SkIntToScalar(stitchData.fHeight));
sugoi@google.com4775cba2013-04-17 13:46:56 +00001283 }
1284}
1285
1286void GrGLSimplexNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1287 INHERITED::setData(uman, drawEffect);
1288
1289 const GrSimplexNoiseEffect& turbulence = drawEffect.castEffect<GrSimplexNoiseEffect>();
1290 uman.set1f(fSeedUni, turbulence.seed());
1291}
1292
sugoi@google.come3b4c502013-04-05 13:47:09 +00001293/////////////////////////////////////////////////////////////////////
1294
1295GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001296 SkASSERT(NULL != context);
1297
1298 // Either we don't stitch tiles, either we have a valid tile size
1299 SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
1300
sugoi@google.com4775cba2013-04-17 13:46:56 +00001301#ifdef SK_USE_SIMPLEX_NOISE
1302 // Simplex noise is currently disabled but can be enabled by defining SK_USE_SIMPLEX_NOISE
1303 sk_ignore_unused_variable(context);
1304 GrEffectRef* effect =
1305 GrSimplexNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
1306 fNumOctaves, fStitchTiles, fSeed,
1307 this->getLocalMatrix(), paint.getAlpha());
1308#else
sugoi@google.come3b4c502013-04-05 13:47:09 +00001309 GrTexture* permutationsTexture = GrLockAndRefCachedBitmapTexture(
1310 context, *fPaintingData->getPermutationsBitmap(), NULL);
1311 GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture(
1312 context, *fPaintingData->getNoiseBitmap(), NULL);
1313
1314 GrEffectRef* effect = (NULL != permutationsTexture) && (NULL != noiseTexture) ?
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001315 GrPerlinNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001316 fNumOctaves, fStitchTiles,
1317 fPaintingData->fStitchDataInit,
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001318 permutationsTexture, noiseTexture,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001319 this->getLocalMatrix(), paint.getAlpha()) :
1320 NULL;
1321
1322 // Unlock immediately, this is not great, but we don't have a way of
1323 // knowing when else to unlock it currently. TODO: Remove this when
1324 // unref becomes the unlock replacement for all types of textures.
1325 if (NULL != permutationsTexture) {
1326 GrUnlockAndUnrefCachedBitmapTexture(permutationsTexture);
1327 }
1328 if (NULL != noiseTexture) {
1329 GrUnlockAndUnrefCachedBitmapTexture(noiseTexture);
1330 }
sugoi@google.com4775cba2013-04-17 13:46:56 +00001331#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +00001332
1333 return effect;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001334}
1335
1336#else
1337
1338GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext*, const SkPaint&) const {
1339 SkDEBUGFAIL("Should not call in GPU-less build");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001340 return NULL;
1341}
1342
1343#endif
1344
1345#ifdef SK_DEVELOPER
1346void SkPerlinNoiseShader::toString(SkString* str) const {
1347 str->append("SkPerlinNoiseShader: (");
1348
1349 str->append("type: ");
1350 switch (fType) {
1351 case kFractalNoise_Type:
1352 str->append("\"fractal noise\"");
1353 break;
1354 case kTurbulence_Type:
1355 str->append("\"turbulence\"");
1356 break;
1357 default:
1358 str->append("\"unknown\"");
1359 break;
1360 }
1361 str->append(" base frequency: (");
1362 str->appendScalar(fBaseFrequencyX);
1363 str->append(", ");
1364 str->appendScalar(fBaseFrequencyY);
1365 str->append(") number of octaves: ");
1366 str->appendS32(fNumOctaves);
1367 str->append(" seed: ");
1368 str->appendScalar(fSeed);
1369 str->append(" stitch tiles: ");
1370 str->append(fStitchTiles ? "true " : "false ");
1371
1372 this->INHERITED::toString(str);
1373
1374 str->append(")");
1375}
1376#endif