blob: c230c2d6482bad6a4e16a2d1750a7f226b790ef7 [file] [log] [blame]
sugoi@google.come3b4c502013-04-05 13:47:09 +00001/*
2 * Copyright 2013 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkDither.h"
9#include "SkPerlinNoiseShader.h"
commit-bot@chromium.orgc2a0ea62013-11-06 10:08:38 +000010#include "SkColorFilter.h"
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +000011#include "SkReadBuffer.h"
12#include "SkWriteBuffer.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000013#include "SkShader.h"
14#include "SkUnPreMultiply.h"
15#include "SkString.h"
16
17#if SK_SUPPORT_GPU
18#include "GrContext.h"
bsalomon@google.com77af6802013-10-02 13:04:56 +000019#include "GrCoordTransform.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000020#include "gl/GrGLEffect.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000021#include "GrTBackendEffectFactory.h"
22#include "SkGr.h"
23#endif
24
25static const int kBlockSize = 256;
26static const int kBlockMask = kBlockSize - 1;
27static const int kPerlinNoise = 4096;
28static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
29
30namespace {
31
32// noiseValue is the color component's value (or color)
33// limitValue is the maximum perlin noise array index value allowed
34// newValue is the current noise dimension (either width or height)
35inline int checkNoise(int noiseValue, int limitValue, int newValue) {
36 // If the noise value would bring us out of bounds of the current noise array while we are
37 // stiching noise tiles together, wrap the noise around the current dimension of the noise to
38 // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
39 if (noiseValue >= limitValue) {
40 noiseValue -= newValue;
41 }
sugoi@google.come3b4c502013-04-05 13:47:09 +000042 return noiseValue;
43}
44
45inline SkScalar smoothCurve(SkScalar t) {
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +000046 static const SkScalar SK_Scalar3 = 3.0f;
sugoi@google.come3b4c502013-04-05 13:47:09 +000047
48 // returns t * t * (3 - 2 * t)
49 return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
50}
51
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +000052bool perlin_noise_type_is_valid(SkPerlinNoiseShader::Type type) {
53 return (SkPerlinNoiseShader::kFractalNoise_Type == type) ||
54 (SkPerlinNoiseShader::kTurbulence_Type == type);
55}
56
sugoi@google.come3b4c502013-04-05 13:47:09 +000057} // end namespace
58
59struct SkPerlinNoiseShader::StitchData {
60 StitchData()
61 : fWidth(0)
62 , fWrapX(0)
63 , fHeight(0)
64 , fWrapY(0)
65 {}
66
67 bool operator==(const StitchData& other) const {
68 return fWidth == other.fWidth &&
69 fWrapX == other.fWrapX &&
70 fHeight == other.fHeight &&
71 fWrapY == other.fWrapY;
72 }
73
74 int fWidth; // How much to subtract to wrap for stitching.
75 int fWrapX; // Minimum value to wrap.
76 int fHeight;
77 int fWrapY;
78};
79
80struct SkPerlinNoiseShader::PaintingData {
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +000081 PaintingData(const SkISize& tileSize, SkScalar seed,
82 SkScalar baseFrequencyX, SkScalar baseFrequencyY)
83 : fTileSize(tileSize)
84 , fBaseFrequency(SkPoint::Make(baseFrequencyX, baseFrequencyY))
sugoi@google.come3b4c502013-04-05 13:47:09 +000085 {
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +000086 this->init(seed);
87 if (!fTileSize.isEmpty()) {
88 this->stitch();
89 }
90
91#if SK_SUPPORT_GPU && !defined(SK_USE_SIMPLEX_NOISE)
commit-bot@chromium.orga3264e52014-05-30 13:26:10 +000092 fPermutationsBitmap.setInfo(SkImageInfo::MakeA8(kBlockSize, 1));
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +000093 fPermutationsBitmap.setPixels(fLatticeSelector);
94
commit-bot@chromium.orga3264e52014-05-30 13:26:10 +000095 fNoiseBitmap.setInfo(SkImageInfo::MakeN32Premul(kBlockSize, 4));
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +000096 fNoiseBitmap.setPixels(fNoise[0][0]);
97#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +000098 }
99
100 int fSeed;
101 uint8_t fLatticeSelector[kBlockSize];
102 uint16_t fNoise[4][kBlockSize][2];
103 SkPoint fGradient[4][kBlockSize];
104 SkISize fTileSize;
105 SkVector fBaseFrequency;
106 StitchData fStitchDataInit;
107
108private:
109
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000110#if SK_SUPPORT_GPU && !defined(SK_USE_SIMPLEX_NOISE)
111 SkBitmap fPermutationsBitmap;
112 SkBitmap fNoiseBitmap;
113#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +0000114
115 inline int random() {
116 static const int gRandAmplitude = 16807; // 7**5; primitive root of m
117 static const int gRandQ = 127773; // m / a
118 static const int gRandR = 2836; // m % a
119
120 int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
121 if (result <= 0)
122 result += kRandMaximum;
123 fSeed = result;
124 return result;
125 }
126
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000127 // Only called once. Could be part of the constructor.
sugoi@google.come3b4c502013-04-05 13:47:09 +0000128 void init(SkScalar seed)
129 {
130 static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
131
senorblanco@chromium.org857e3202014-01-09 17:41:42 +0000132 // According to the SVG spec, we must truncate (not round) the seed value.
133 fSeed = SkScalarTruncToInt(seed);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000134 // The seed value clamp to the range [1, kRandMaximum - 1].
sugoi@google.come3b4c502013-04-05 13:47:09 +0000135 if (fSeed <= 0) {
136 fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
137 }
138 if (fSeed > kRandMaximum - 1) {
139 fSeed = kRandMaximum - 1;
140 }
141 for (int channel = 0; channel < 4; ++channel) {
142 for (int i = 0; i < kBlockSize; ++i) {
143 fLatticeSelector[i] = i;
144 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
145 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
146 }
147 }
148 for (int i = kBlockSize - 1; i > 0; --i) {
149 int k = fLatticeSelector[i];
150 int j = random() % kBlockSize;
151 SkASSERT(j >= 0);
152 SkASSERT(j < kBlockSize);
153 fLatticeSelector[i] = fLatticeSelector[j];
154 fLatticeSelector[j] = k;
155 }
156
157 // Perform the permutations now
158 {
159 // Copy noise data
160 uint16_t noise[4][kBlockSize][2];
161 for (int i = 0; i < kBlockSize; ++i) {
162 for (int channel = 0; channel < 4; ++channel) {
163 for (int j = 0; j < 2; ++j) {
164 noise[channel][i][j] = fNoise[channel][i][j];
165 }
166 }
167 }
168 // Do permutations on noise data
169 for (int i = 0; i < kBlockSize; ++i) {
170 for (int channel = 0; channel < 4; ++channel) {
171 for (int j = 0; j < 2; ++j) {
172 fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
173 }
174 }
175 }
176 }
177
178 // Half of the largest possible value for 16 bit unsigned int
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +0000179 static const SkScalar gHalfMax16bits = 32767.5f;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000180
181 // Compute gradients from permutated noise data
182 for (int channel = 0; channel < 4; ++channel) {
183 for (int i = 0; i < kBlockSize; ++i) {
184 fGradient[channel][i] = SkPoint::Make(
185 SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
186 gInvBlockSizef),
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000187 SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
sugoi@google.come3b4c502013-04-05 13:47:09 +0000188 gInvBlockSizef));
189 fGradient[channel][i].normalize();
190 // Put the normalized gradient back into the noise data
191 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000192 fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000193 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000194 fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000195 }
196 }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000197 }
198
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000199 // Only called once. Could be part of the constructor.
sugoi@google.come3b4c502013-04-05 13:47:09 +0000200 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
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000240public:
sugoi@google.come3b4c502013-04-05 13:47:09 +0000241
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000242#if SK_SUPPORT_GPU && !defined(SK_USE_SIMPLEX_NOISE)
243 const SkBitmap& getPermutationsBitmap() const { return fPermutationsBitmap; }
244
245 const SkBitmap& getNoiseBitmap() const { return fNoiseBitmap; }
246#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +0000247};
248
249SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
250 int numOctaves, SkScalar seed,
251 const SkISize* tileSize) {
252 return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY,
253 numOctaves, seed, tileSize));
254}
255
commit-bot@chromium.org9fbbcca2014-04-01 16:09:37 +0000256SkShader* SkPerlinNoiseShader::CreateTurbulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000257 int numOctaves, SkScalar seed,
258 const SkISize* tileSize) {
259 return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY,
260 numOctaves, seed, tileSize));
261}
262
263SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
264 SkScalar baseFrequencyX,
265 SkScalar baseFrequencyY,
266 int numOctaves,
267 SkScalar seed,
268 const SkISize* tileSize)
269 : fType(type)
270 , fBaseFrequencyX(baseFrequencyX)
271 , fBaseFrequencyY(baseFrequencyY)
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +0000272 , fNumOctaves(numOctaves > 255 ? 255 : numOctaves/*[0,255] octaves allowed*/)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000273 , fSeed(seed)
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000274 , fTileSize(NULL == tileSize ? SkISize::Make(0, 0) : *tileSize)
275 , fStitchTiles(!fTileSize.isEmpty())
sugoi@google.come3b4c502013-04-05 13:47:09 +0000276{
277 SkASSERT(numOctaves >= 0 && numOctaves < 256);
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000278 fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize, fSeed, fBaseFrequencyX, fBaseFrequencyY));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000279}
280
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000281SkPerlinNoiseShader::SkPerlinNoiseShader(SkReadBuffer& buffer)
282 : INHERITED(buffer)
283{
sugoi@google.come3b4c502013-04-05 13:47:09 +0000284 fType = (SkPerlinNoiseShader::Type) buffer.readInt();
285 fBaseFrequencyX = buffer.readScalar();
286 fBaseFrequencyY = buffer.readScalar();
287 fNumOctaves = buffer.readInt();
288 fSeed = buffer.readScalar();
289 fStitchTiles = buffer.readBool();
290 fTileSize.fWidth = buffer.readInt();
291 fTileSize.fHeight = buffer.readInt();
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000292 fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize, fSeed, fBaseFrequencyX, fBaseFrequencyY));
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +0000293 buffer.validate(perlin_noise_type_is_valid(fType) &&
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000294 (fNumOctaves >= 0) && (fNumOctaves <= 255) &&
295 (fStitchTiles != fTileSize.isEmpty()));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000296}
297
298SkPerlinNoiseShader::~SkPerlinNoiseShader() {
299 // Safety, should have been done in endContext()
300 SkDELETE(fPaintingData);
301}
302
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000303void SkPerlinNoiseShader::flatten(SkWriteBuffer& buffer) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000304 this->INHERITED::flatten(buffer);
305 buffer.writeInt((int) fType);
306 buffer.writeScalar(fBaseFrequencyX);
307 buffer.writeScalar(fBaseFrequencyY);
308 buffer.writeInt(fNumOctaves);
309 buffer.writeScalar(fSeed);
310 buffer.writeBool(fStitchTiles);
311 buffer.writeInt(fTileSize.fWidth);
312 buffer.writeInt(fTileSize.fHeight);
313}
314
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000315SkScalar SkPerlinNoiseShader::PerlinNoiseShaderContext::noise2D(
316 int channel, const PaintingData& paintingData,
317 const StitchData& stitchData, const SkPoint& noiseVector) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000318 struct Noise {
319 int noisePositionIntegerValue;
senorblancoce6a3542014-06-12 11:24:19 -0700320 int nextNoisePositionIntegerValue;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000321 SkScalar noisePositionFractionValue;
322 Noise(SkScalar component)
323 {
324 SkScalar position = component + kPerlinNoise;
325 noisePositionIntegerValue = SkScalarFloorToInt(position);
326 noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
senorblancoce6a3542014-06-12 11:24:19 -0700327 nextNoisePositionIntegerValue = noisePositionIntegerValue + 1;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000328 }
329 };
330 Noise noiseX(noiseVector.x());
331 Noise noiseY(noiseVector.y());
332 SkScalar u, v;
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000333 const SkPerlinNoiseShader& perlinNoiseShader = static_cast<const SkPerlinNoiseShader&>(fShader);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000334 // If stitching, adjust lattice points accordingly.
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000335 if (perlinNoiseShader.fStitchTiles) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000336 noiseX.noisePositionIntegerValue =
337 checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
338 noiseY.noisePositionIntegerValue =
339 checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
senorblancoce6a3542014-06-12 11:24:19 -0700340 noiseX.nextNoisePositionIntegerValue =
341 checkNoise(noiseX.nextNoisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
342 noiseY.nextNoisePositionIntegerValue =
343 checkNoise(noiseY.nextNoisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000344 }
345 noiseX.noisePositionIntegerValue &= kBlockMask;
346 noiseY.noisePositionIntegerValue &= kBlockMask;
senorblancoce6a3542014-06-12 11:24:19 -0700347 noiseX.nextNoisePositionIntegerValue &= kBlockMask;
348 noiseY.nextNoisePositionIntegerValue &= kBlockMask;
349 int i =
350 paintingData.fLatticeSelector[noiseX.noisePositionIntegerValue];
351 int j =
352 paintingData.fLatticeSelector[noiseX.nextNoisePositionIntegerValue];
353 int b00 = (i + noiseY.noisePositionIntegerValue) & kBlockMask;
354 int b10 = (j + noiseY.noisePositionIntegerValue) & kBlockMask;
355 int b01 = (i + noiseY.nextNoisePositionIntegerValue) & kBlockMask;
356 int b11 = (j + noiseY.nextNoisePositionIntegerValue) & kBlockMask;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000357 SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
358 SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
359 // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
360 SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
361 noiseY.noisePositionFractionValue); // Offset (0,0)
senorblancoce6a3542014-06-12 11:24:19 -0700362 u = paintingData.fGradient[channel][b00].dot(fractionValue);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000363 fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
senorblancoce6a3542014-06-12 11:24:19 -0700364 v = paintingData.fGradient[channel][b10].dot(fractionValue);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000365 SkScalar a = SkScalarInterp(u, v, sx);
366 fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
senorblancoce6a3542014-06-12 11:24:19 -0700367 v = paintingData.fGradient[channel][b11].dot(fractionValue);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000368 fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
senorblancoce6a3542014-06-12 11:24:19 -0700369 u = paintingData.fGradient[channel][b01].dot(fractionValue);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000370 SkScalar b = SkScalarInterp(u, v, sx);
371 return SkScalarInterp(a, b, sy);
372}
373
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000374SkScalar SkPerlinNoiseShader::PerlinNoiseShaderContext::calculateTurbulenceValueForPoint(
375 int channel, const PaintingData& paintingData,
376 StitchData& stitchData, const SkPoint& point) const {
377 const SkPerlinNoiseShader& perlinNoiseShader = static_cast<const SkPerlinNoiseShader&>(fShader);
378 if (perlinNoiseShader.fStitchTiles) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000379 // Set up TurbulenceInitial stitch values.
380 stitchData = paintingData.fStitchDataInit;
381 }
382 SkScalar turbulenceFunctionResult = 0;
383 SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), paintingData.fBaseFrequency.fX),
384 SkScalarMul(point.y(), paintingData.fBaseFrequency.fY)));
385 SkScalar ratio = SK_Scalar1;
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000386 for (int octave = 0; octave < perlinNoiseShader.fNumOctaves; ++octave) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000387 SkScalar noise = noise2D(channel, paintingData, stitchData, noiseVector);
388 turbulenceFunctionResult += SkScalarDiv(
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000389 (perlinNoiseShader.fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000390 noiseVector.fX *= 2;
391 noiseVector.fY *= 2;
392 ratio *= 2;
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000393 if (perlinNoiseShader.fStitchTiles) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000394 // Update stitch values
395 stitchData.fWidth *= 2;
396 stitchData.fWrapX = stitchData.fWidth + kPerlinNoise;
397 stitchData.fHeight *= 2;
398 stitchData.fWrapY = stitchData.fHeight + kPerlinNoise;
399 }
400 }
401
402 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
403 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000404 if (perlinNoiseShader.fType == kFractalNoise_Type) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000405 turbulenceFunctionResult =
406 SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
407 }
408
409 if (channel == 3) { // Scale alpha by paint value
410 turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult,
411 SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255)));
412 }
413
414 // Clamp result
415 return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
416}
417
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000418SkPMColor SkPerlinNoiseShader::PerlinNoiseShaderContext::shade(
419 const SkPoint& point, StitchData& stitchData) const {
420 const SkPerlinNoiseShader& perlinNoiseShader = static_cast<const SkPerlinNoiseShader&>(fShader);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000421 SkPoint newPoint;
senorblanco@chromium.orga8d95f82014-04-04 14:46:10 +0000422 fMatrix.mapPoints(&newPoint, &point, 1);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000423 newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
424 newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
425
426 U8CPU rgba[4];
427 for (int channel = 3; channel >= 0; --channel) {
428 rgba[channel] = SkScalarFloorToInt(255 *
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000429 calculateTurbulenceValueForPoint(channel, *perlinNoiseShader.fPaintingData,
430 stitchData, newPoint));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000431 }
432 return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
433}
434
commit-bot@chromium.orgce56d962014-05-05 18:39:18 +0000435SkShader::Context* SkPerlinNoiseShader::onCreateContext(const ContextRec& rec,
436 void* storage) const {
commit-bot@chromium.orge901b6d2014-05-01 19:31:31 +0000437 return SkNEW_PLACEMENT_ARGS(storage, PerlinNoiseShaderContext, (*this, rec));
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000438}
439
440size_t SkPerlinNoiseShader::contextSize() const {
441 return sizeof(PerlinNoiseShaderContext);
442}
443
444SkPerlinNoiseShader::PerlinNoiseShaderContext::PerlinNoiseShaderContext(
commit-bot@chromium.orge901b6d2014-05-01 19:31:31 +0000445 const SkPerlinNoiseShader& shader, const ContextRec& rec)
446 : INHERITED(shader, rec)
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000447{
commit-bot@chromium.orge901b6d2014-05-01 19:31:31 +0000448 SkMatrix newMatrix = *rec.fMatrix;
reed@google.comb67b8e62014-05-12 18:12:24 +0000449 newMatrix.preConcat(shader.getLocalMatrix());
450 if (rec.fLocalMatrix) {
451 newMatrix.preConcat(*rec.fLocalMatrix);
452 }
senorblanco@chromium.orga8d95f82014-04-04 14:46:10 +0000453 SkMatrix invMatrix;
454 if (!newMatrix.invert(&invMatrix)) {
455 invMatrix.reset();
456 }
457 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
458 // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
459 newMatrix.postTranslate(SK_Scalar1, SK_Scalar1);
460 newMatrix.postConcat(invMatrix);
461 newMatrix.postConcat(invMatrix);
462 fMatrix = newMatrix;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000463}
464
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000465void SkPerlinNoiseShader::PerlinNoiseShaderContext::shadeSpan(
466 int x, int y, SkPMColor result[], int count) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000467 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
468 StitchData stitchData;
469 for (int i = 0; i < count; ++i) {
470 result[i] = shade(point, stitchData);
471 point.fX += SK_Scalar1;
472 }
473}
474
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000475void SkPerlinNoiseShader::PerlinNoiseShaderContext::shadeSpan16(
476 int x, int y, uint16_t result[], int count) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000477 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
478 StitchData stitchData;
479 DITHER_565_SCAN(y);
480 for (int i = 0; i < count; ++i) {
481 unsigned dither = DITHER_VALUE(x);
482 result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
483 DITHER_INC_X(x);
484 point.fX += SK_Scalar1;
485 }
486}
487
488/////////////////////////////////////////////////////////////////////
489
commit-bot@chromium.org344cf452013-06-17 14:19:01 +0000490#if SK_SUPPORT_GPU
sugoi@google.come3b4c502013-04-05 13:47:09 +0000491
492#include "GrTBackendEffectFactory.h"
493
sugoi@google.com4775cba2013-04-17 13:46:56 +0000494class GrGLNoise : public GrGLEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000495public:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000496 GrGLNoise(const GrBackendEffectFactory& factory,
497 const GrDrawEffect& drawEffect);
498 virtual ~GrGLNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000499
sugoi@google.com4775cba2013-04-17 13:46:56 +0000500 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
501
502 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
503
504protected:
505 SkPerlinNoiseShader::Type fType;
506 bool fStitchTiles;
507 int fNumOctaves;
508 GrGLUniformManager::UniformHandle fBaseFrequencyUni;
509 GrGLUniformManager::UniformHandle fAlphaUni;
510 GrGLUniformManager::UniformHandle fInvMatrixUni;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000511
512private:
513 typedef GrGLEffect INHERITED;
514};
515
516class GrGLPerlinNoise : public GrGLNoise {
517public:
sugoi@google.come3b4c502013-04-05 13:47:09 +0000518 GrGLPerlinNoise(const GrBackendEffectFactory& factory,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000519 const GrDrawEffect& drawEffect)
520 : GrGLNoise(factory, drawEffect) {}
521 virtual ~GrGLPerlinNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000522
523 virtual void emitCode(GrGLShaderBuilder*,
524 const GrDrawEffect&,
525 EffectKey,
526 const char* outputColor,
527 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000528 const TransformedCoordsArray&,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000529 const TextureSamplerArray&) SK_OVERRIDE;
530
sugoi@google.com4775cba2013-04-17 13:46:56 +0000531 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000532
533private:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000534 GrGLUniformManager::UniformHandle fStitchDataUni;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000535
sugoi@google.com4775cba2013-04-17 13:46:56 +0000536 typedef GrGLNoise INHERITED;
537};
538
539class GrGLSimplexNoise : public GrGLNoise {
540 // Note : This is for reference only. GrGLPerlinNoise is used for processing.
541public:
542 GrGLSimplexNoise(const GrBackendEffectFactory& factory,
543 const GrDrawEffect& drawEffect)
544 : GrGLNoise(factory, drawEffect) {}
545
546 virtual ~GrGLSimplexNoise() {}
547
548 virtual void emitCode(GrGLShaderBuilder*,
549 const GrDrawEffect&,
550 EffectKey,
551 const char* outputColor,
552 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000553 const TransformedCoordsArray&,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000554 const TextureSamplerArray&) SK_OVERRIDE;
555
556 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
557
558private:
559 GrGLUniformManager::UniformHandle fSeedUni;
560
561 typedef GrGLNoise INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000562};
563
564/////////////////////////////////////////////////////////////////////
565
sugoi@google.com4775cba2013-04-17 13:46:56 +0000566class GrNoiseEffect : public GrEffect {
567public:
568 virtual ~GrNoiseEffect() { }
569
570 SkPerlinNoiseShader::Type type() const { return fType; }
571 bool stitchTiles() const { return fStitchTiles; }
572 const SkVector& baseFrequency() const { return fBaseFrequency; }
573 int numOctaves() const { return fNumOctaves; }
bsalomon@google.com77af6802013-10-02 13:04:56 +0000574 const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000575 uint8_t alpha() const { return fAlpha; }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000576
577 void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE {
578 *validFlags = 0; // This is noise. Nothing is constant.
579 }
580
581protected:
582 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
583 const GrNoiseEffect& s = CastEffect<GrNoiseEffect>(sBase);
584 return fType == s.fType &&
585 fBaseFrequency == s.fBaseFrequency &&
586 fNumOctaves == s.fNumOctaves &&
587 fStitchTiles == s.fStitchTiles &&
bsalomon@google.com77af6802013-10-02 13:04:56 +0000588 fCoordTransform.getMatrix() == s.fCoordTransform.getMatrix() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000589 fAlpha == s.fAlpha;
590 }
591
592 GrNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, int numOctaves,
593 bool stitchTiles, const SkMatrix& matrix, uint8_t alpha)
594 : fType(type)
595 , fBaseFrequency(baseFrequency)
596 , fNumOctaves(numOctaves)
597 , fStitchTiles(stitchTiles)
598 , fMatrix(matrix)
599 , fAlpha(alpha) {
bsalomon@google.com77af6802013-10-02 13:04:56 +0000600 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
601 // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions.
602 SkMatrix m = matrix;
603 m.postTranslate(SK_Scalar1, SK_Scalar1);
604 fCoordTransform.reset(kLocal_GrCoordSet, m);
605 this->addCoordTransform(&fCoordTransform);
commit-bot@chromium.orga34995e2013-10-23 05:42:03 +0000606 this->setWillNotUseInputColor();
sugoi@google.com4775cba2013-04-17 13:46:56 +0000607 }
608
609 SkPerlinNoiseShader::Type fType;
bsalomon@google.com77af6802013-10-02 13:04:56 +0000610 GrCoordTransform fCoordTransform;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000611 SkVector fBaseFrequency;
612 int fNumOctaves;
613 bool fStitchTiles;
614 SkMatrix fMatrix;
615 uint8_t fAlpha;
616
617private:
618 typedef GrEffect INHERITED;
619};
620
621class GrPerlinNoiseEffect : public GrNoiseEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000622public:
623 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
624 int numOctaves, bool stitchTiles,
625 const SkPerlinNoiseShader::StitchData& stitchData,
626 GrTexture* permutationsTexture, GrTexture* noiseTexture,
627 const SkMatrix& matrix, uint8_t alpha) {
628 AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves,
629 stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha)));
630 return CreateEffectRef(effect);
631 }
632
633 virtual ~GrPerlinNoiseEffect() { }
634
635 static const char* Name() { return "PerlinNoise"; }
636 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
637 return GrTBackendEffectFactory<GrPerlinNoiseEffect>::getInstance();
638 }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000639 const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000640
641 typedef GrGLPerlinNoise GLEffect;
642
sugoi@google.come3b4c502013-04-05 13:47:09 +0000643private:
644 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
645 const GrPerlinNoiseEffect& s = CastEffect<GrPerlinNoiseEffect>(sBase);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000646 return INHERITED::onIsEqual(sBase) &&
647 fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() &&
sugoi@google.come3b4c502013-04-05 13:47:09 +0000648 fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000649 fStitchData == s.fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000650 }
651
652 GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
653 int numOctaves, bool stitchTiles,
654 const SkPerlinNoiseShader::StitchData& stitchData,
655 GrTexture* permutationsTexture, GrTexture* noiseTexture,
656 const SkMatrix& matrix, uint8_t alpha)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000657 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
658 , fPermutationsAccess(permutationsTexture)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000659 , fNoiseAccess(noiseTexture)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000660 , fStitchData(stitchData) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000661 this->addTextureAccess(&fPermutationsAccess);
662 this->addTextureAccess(&fNoiseAccess);
663 }
664
sugoi@google.com4775cba2013-04-17 13:46:56 +0000665 GR_DECLARE_EFFECT_TEST;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000666
667 GrTextureAccess fPermutationsAccess;
668 GrTextureAccess fNoiseAccess;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000669 SkPerlinNoiseShader::StitchData fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000670
sugoi@google.com4775cba2013-04-17 13:46:56 +0000671 typedef GrNoiseEffect INHERITED;
672};
673
674class GrSimplexNoiseEffect : public GrNoiseEffect {
675 // Note : This is for reference only. GrPerlinNoiseEffect is used for processing.
676public:
677 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
678 int numOctaves, bool stitchTiles, const SkScalar seed,
679 const SkMatrix& matrix, uint8_t alpha) {
680 AutoEffectUnref effect(SkNEW_ARGS(GrSimplexNoiseEffect, (type, baseFrequency, numOctaves,
681 stitchTiles, seed, matrix, alpha)));
682 return CreateEffectRef(effect);
683 }
684
685 virtual ~GrSimplexNoiseEffect() { }
686
687 static const char* Name() { return "SimplexNoise"; }
688 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
689 return GrTBackendEffectFactory<GrSimplexNoiseEffect>::getInstance();
690 }
691 const SkScalar& seed() const { return fSeed; }
692
693 typedef GrGLSimplexNoise GLEffect;
694
695private:
696 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
697 const GrSimplexNoiseEffect& s = CastEffect<GrSimplexNoiseEffect>(sBase);
698 return INHERITED::onIsEqual(sBase) && fSeed == s.fSeed;
699 }
700
701 GrSimplexNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
702 int numOctaves, bool stitchTiles, const SkScalar seed,
703 const SkMatrix& matrix, uint8_t alpha)
704 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
705 , fSeed(seed) {
706 }
707
708 SkScalar fSeed;
709
710 typedef GrNoiseEffect INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000711};
712
713/////////////////////////////////////////////////////////////////////
sugoi@google.come3b4c502013-04-05 13:47:09 +0000714GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect);
715
commit-bot@chromium.orge0e7cfe2013-09-09 20:09:12 +0000716GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkRandom* random,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000717 GrContext* context,
718 const GrDrawTargetCaps&,
719 GrTexture**) {
sugoi@google.com423ac132013-04-18 14:04:57 +0000720 int numOctaves = random->nextRangeU(2, 10);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000721 bool stitchTiles = random->nextBool();
722 SkScalar seed = SkIntToScalar(random->nextU());
723 SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +0000724 SkScalar baseFrequencyX = random->nextRangeScalar(0.01f,
725 0.99f);
726 SkScalar baseFrequencyY = random->nextRangeScalar(0.01f,
727 0.99f);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000728
729 SkShader* shader = random->nextBool() ?
730 SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
731 stitchTiles ? &tileSize : NULL) :
commit-bot@chromium.org9fbbcca2014-04-01 16:09:37 +0000732 SkPerlinNoiseShader::CreateTurbulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000733 stitchTiles ? &tileSize : NULL);
734
735 SkPaint paint;
dandov9de5b512014-06-10 14:38:28 -0700736 GrColor grColor;
737 GrEffectRef* effect;
738 shader->asNewEffect(context, paint, NULL, &grColor, &effect);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000739
740 SkDELETE(shader);
741
742 return effect;
743}
sugoi@google.com4775cba2013-04-17 13:46:56 +0000744
sugoi@google.come3b4c502013-04-05 13:47:09 +0000745/////////////////////////////////////////////////////////////////////
746
sugoi@google.com4775cba2013-04-17 13:46:56 +0000747void GrGLSimplexNoise::emitCode(GrGLShaderBuilder* builder,
748 const GrDrawEffect&,
749 EffectKey key,
750 const char* outputColor,
751 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000752 const TransformedCoordsArray& coords,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000753 const TextureSamplerArray&) {
754 sk_ignore_unused_variable(inputColor);
755
bsalomon@google.com77af6802013-10-02 13:04:56 +0000756 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000757
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000758 fSeedUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000759 kFloat_GrSLType, "seed");
760 const char* seedUni = builder->getUniformCStr(fSeedUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000761 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000762 kMat33f_GrSLType, "invMatrix");
763 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000764 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000765 kVec2f_GrSLType, "baseFrequency");
766 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000767 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000768 kFloat_GrSLType, "alpha");
769 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
770
771 // Add vec3 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000772 static const GrGLShaderVar gVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000773 GrGLShaderVar("x", kVec3f_GrSLType)
774 };
775
776 SkString mod289_3_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000777 builder->fsEmitFunction(kVec3f_GrSLType,
778 "mod289", SK_ARRAY_COUNT(gVec3Args), gVec3Args,
779 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
780 "return x - floor(x * C.xxx) * C.yyy;", &mod289_3_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000781
782 // Add vec4 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000783 static const GrGLShaderVar gVec4Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000784 GrGLShaderVar("x", kVec4f_GrSLType)
785 };
786
787 SkString mod289_4_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000788 builder->fsEmitFunction(kVec4f_GrSLType,
789 "mod289", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
790 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
791 "return x - floor(x * C.xxxx) * C.yyyy;", &mod289_4_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000792
793 // Add vec4 permute function
sugoi@google.comd537af52013-06-10 13:59:25 +0000794 SkString permuteCode;
795 permuteCode.appendf("const vec2 C = vec2(34.0, 1.0);\n"
796 "return %s(((x * C.xxxx) + C.yyyy) * x);", mod289_4_funcName.c_str());
797 SkString permuteFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000798 builder->fsEmitFunction(kVec4f_GrSLType,
799 "permute", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
800 permuteCode.c_str(), &permuteFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000801
802 // Add vec4 taylorInvSqrt function
sugoi@google.comd537af52013-06-10 13:59:25 +0000803 SkString taylorInvSqrtFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000804 builder->fsEmitFunction(kVec4f_GrSLType,
805 "taylorInvSqrt", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
806 "const vec2 C = vec2(-0.85373472095314, 1.79284291400159);\n"
807 "return x * C.xxxx + C.yyyy;", &taylorInvSqrtFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000808
809 // Add vec3 noise function
sugoi@google.comd537af52013-06-10 13:59:25 +0000810 static const GrGLShaderVar gNoiseVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000811 GrGLShaderVar("v", kVec3f_GrSLType)
812 };
813
sugoi@google.comd537af52013-06-10 13:59:25 +0000814 SkString noiseCode;
815 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000816 "const vec2 C = vec2(1.0/6.0, 1.0/3.0);\n"
817 "const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n"
818
819 // First corner
820 "vec3 i = floor(v + dot(v, C.yyy));\n"
821 "vec3 x0 = v - i + dot(i, C.xxx);\n"
822
823 // Other corners
824 "vec3 g = step(x0.yzx, x0.xyz);\n"
825 "vec3 l = 1.0 - g;\n"
826 "vec3 i1 = min(g.xyz, l.zxy);\n"
827 "vec3 i2 = max(g.xyz, l.zxy);\n"
828
829 "vec3 x1 = x0 - i1 + C.xxx;\n"
830 "vec3 x2 = x0 - i2 + C.yyy;\n" // 2.0*C.x = 1/3 = C.y
831 "vec3 x3 = x0 - D.yyy;\n" // -1.0+3.0*C.x = -0.5 = -D.y
832 );
833
sugoi@google.comd537af52013-06-10 13:59:25 +0000834 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000835 // Permutations
836 "i = %s(i);\n"
837 "vec4 p = %s(%s(%s(\n"
838 " i.z + vec4(0.0, i1.z, i2.z, 1.0)) +\n"
839 " i.y + vec4(0.0, i1.y, i2.y, 1.0)) +\n"
840 " i.x + vec4(0.0, i1.x, i2.x, 1.0));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000841 mod289_3_funcName.c_str(), permuteFuncName.c_str(), permuteFuncName.c_str(),
842 permuteFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000843
sugoi@google.comd537af52013-06-10 13:59:25 +0000844 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000845 // Gradients: 7x7 points over a square, mapped onto an octahedron.
846 // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
847 "float n_ = 0.142857142857;\n" // 1.0/7.0
848 "vec3 ns = n_ * D.wyz - D.xzx;\n"
849
850 "vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\n" // mod(p,7*7)
851
852 "vec4 x_ = floor(j * ns.z);\n"
853 "vec4 y_ = floor(j - 7.0 * x_);" // mod(j,N)
854
855 "vec4 x = x_ *ns.x + ns.yyyy;\n"
856 "vec4 y = y_ *ns.x + ns.yyyy;\n"
857 "vec4 h = 1.0 - abs(x) - abs(y);\n"
858
859 "vec4 b0 = vec4(x.xy, y.xy);\n"
860 "vec4 b1 = vec4(x.zw, y.zw);\n"
861 );
862
sugoi@google.comd537af52013-06-10 13:59:25 +0000863 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000864 "vec4 s0 = floor(b0) * 2.0 + 1.0;\n"
865 "vec4 s1 = floor(b1) * 2.0 + 1.0;\n"
866 "vec4 sh = -step(h, vec4(0.0));\n"
867
868 "vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;\n"
869 "vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;\n"
870
871 "vec3 p0 = vec3(a0.xy, h.x);\n"
872 "vec3 p1 = vec3(a0.zw, h.y);\n"
873 "vec3 p2 = vec3(a1.xy, h.z);\n"
874 "vec3 p3 = vec3(a1.zw, h.w);\n"
875 );
876
sugoi@google.comd537af52013-06-10 13:59:25 +0000877 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000878 // Normalise gradients
879 "vec4 norm = %s(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n"
880 "p0 *= norm.x;\n"
881 "p1 *= norm.y;\n"
882 "p2 *= norm.z;\n"
883 "p3 *= norm.w;\n"
884
885 // Mix final noise value
886 "vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n"
887 "m = m * m;\n"
888 "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 +0000889 taylorInvSqrtFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000890
sugoi@google.comd537af52013-06-10 13:59:25 +0000891 SkString noiseFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000892 builder->fsEmitFunction(kFloat_GrSLType,
893 "snoise", SK_ARRAY_COUNT(gNoiseVec3Args), gNoiseVec3Args,
894 noiseCode.c_str(), &noiseFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000895
896 const char* noiseVecIni = "noiseVecIni";
897 const char* factors = "factors";
898 const char* sum = "sum";
899 const char* xOffsets = "xOffsets";
900 const char* yOffsets = "yOffsets";
901 const char* channel = "channel";
902
903 // Fill with some prime numbers
904 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(13.0, 53.0, 101.0, 151.0);\n", xOffsets);
905 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(109.0, 167.0, 23.0, 67.0);\n", yOffsets);
906
907 // There are rounding errors if the floor operation is not performed here
908 builder->fsCodeAppendf(
909 "\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 +0000910 noiseVecIni, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000911
912 // Perturb the texcoords with three components of noise
913 builder->fsCodeAppendf("\t\t%s += 0.1 * vec3(%s(%s + vec3( 0.0, 0.0, %s)),"
914 "%s(%s + vec3( 43.0, 17.0, %s)),"
915 "%s(%s + vec3(-17.0, -43.0, %s)));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000916 noiseVecIni, noiseFuncName.c_str(), noiseVecIni, seedUni,
917 noiseFuncName.c_str(), noiseVecIni, seedUni,
918 noiseFuncName.c_str(), noiseVecIni, seedUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000919
920 builder->fsCodeAppendf("\t\t%s = vec4(0.0);\n", outputColor);
921
922 builder->fsCodeAppendf("\t\tvec3 %s = vec3(1.0);\n", factors);
923 builder->fsCodeAppendf("\t\tfloat %s = 0.0;\n", sum);
924
925 // Loop over all octaves
926 builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {\n", fNumOctaves);
927
928 // Loop over the 4 channels
929 builder->fsCodeAppendf("\t\t\tfor (int %s = 3; %s >= 0; --%s) {\n", channel, channel, channel);
930
931 builder->fsCodeAppendf(
932 "\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 +0000933 outputColor, factors, noiseFuncName.c_str(), noiseVecIni, factors, xOffsets, channel,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000934 yOffsets, channel, seedUni, factors);
935
936 builder->fsCodeAppend("\t\t\t}\n"); // end of the for loop on channels
937
938 builder->fsCodeAppendf("\t\t\t%s += %s.x;\n", sum, factors);
939 builder->fsCodeAppendf("\t\t\t%s *= vec3(0.5, 2.0, 0.75);\n", factors);
940
941 builder->fsCodeAppend("\t\t}\n"); // end of the for loop on octaves
942
943 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
944 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
945 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
946 builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5 / %s) + vec4(0.5);\n",
947 outputColor, outputColor, sum);
948 } else {
949 builder->fsCodeAppendf("\t\t%s = abs(%s / vec4(%s));\n",
950 outputColor, outputColor, sum);
951 }
952
953 builder->fsCodeAppendf("\t\t%s.a *= %s;\n", outputColor, alphaUni);
954
955 // Clamp values
956 builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);\n", outputColor, outputColor);
957
958 // Pre-multiply the result
959 builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
960 outputColor, outputColor, outputColor, outputColor);
961}
962
sugoi@google.come3b4c502013-04-05 13:47:09 +0000963void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder,
964 const GrDrawEffect&,
965 EffectKey key,
966 const char* outputColor,
967 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000968 const TransformedCoordsArray& coords,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000969 const TextureSamplerArray& samplers) {
970 sk_ignore_unused_variable(inputColor);
971
bsalomon@google.com77af6802013-10-02 13:04:56 +0000972 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000973
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000974 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000975 kMat33f_GrSLType, "invMatrix");
976 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000977 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000978 kVec2f_GrSLType, "baseFrequency");
979 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000980 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000981 kFloat_GrSLType, "alpha");
982 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
983
984 const char* stitchDataUni = NULL;
985 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000986 fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
commit-bot@chromium.org98393202013-07-04 18:13:05 +0000987 kVec2f_GrSLType, "stitchData");
sugoi@google.come3b4c502013-04-05 13:47:09 +0000988 stitchDataUni = builder->getUniformCStr(fStitchDataUni);
989 }
990
sugoi@google.comd537af52013-06-10 13:59:25 +0000991 // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
992 const char* chanCoordR = "0.125";
993 const char* chanCoordG = "0.375";
994 const char* chanCoordB = "0.625";
995 const char* chanCoordA = "0.875";
996 const char* chanCoord = "chanCoord";
sugoi@google.come3b4c502013-04-05 13:47:09 +0000997 const char* stitchData = "stitchData";
998 const char* ratio = "ratio";
sugoi@google.come3b4c502013-04-05 13:47:09 +0000999 const char* noiseVec = "noiseVec";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001000 const char* noiseSmooth = "noiseSmooth";
senorblancoce6a3542014-06-12 11:24:19 -07001001 const char* floorVal = "floorVal";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001002 const char* fractVal = "fractVal";
1003 const char* uv = "uv";
1004 const char* ab = "ab";
1005 const char* latticeIdx = "latticeIdx";
senorblancoce6a3542014-06-12 11:24:19 -07001006 const char* bcoords = "bcoords";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001007 const char* lattice = "lattice";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001008 const char* inc8bit = "0.00390625"; // 1.0 / 256.0
1009 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
1010 // [-1,1] vector and perform a dot product between that vector and the provided vector.
1011 const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
1012
sugoi@google.comd537af52013-06-10 13:59:25 +00001013 // Add noise function
1014 static const GrGLShaderVar gPerlinNoiseArgs[] = {
1015 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001016 GrGLShaderVar(noiseVec, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001017 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001018
sugoi@google.comd537af52013-06-10 13:59:25 +00001019 static const GrGLShaderVar gPerlinNoiseStitchArgs[] = {
1020 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001021 GrGLShaderVar(noiseVec, kVec2f_GrSLType),
1022 GrGLShaderVar(stitchData, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001023 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001024
sugoi@google.comd537af52013-06-10 13:59:25 +00001025 SkString noiseCode;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001026
senorblancoce6a3542014-06-12 11:24:19 -07001027 noiseCode.appendf("\tvec4 %s;\n", floorVal);
1028 noiseCode.appendf("\t%s.xy = floor(%s);\n", floorVal, noiseVec);
1029 noiseCode.appendf("\t%s.zw = %s.xy + vec2(1.0);\n", floorVal, floorVal);
1030 noiseCode.appendf("\tvec2 %s = fract(%s);\n", fractVal, noiseVec);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001031
1032 // smooth curve : t * t * (3 - 2 * t)
senorblancoce6a3542014-06-12 11:24:19 -07001033 noiseCode.appendf("\n\tvec2 %s = %s * %s * (vec2(3.0) - vec2(2.0) * %s);",
1034 noiseSmooth, fractVal, fractVal, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001035
1036 // Adjust frequencies if we're stitching tiles
1037 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001038 noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
senorblancoce6a3542014-06-12 11:24:19 -07001039 floorVal, stitchData, floorVal, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001040 noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }",
senorblancoce6a3542014-06-12 11:24:19 -07001041 floorVal, stitchData, floorVal, stitchData);
1042 noiseCode.appendf("\n\tif(%s.z >= %s.x) { %s.z -= %s.x; }",
1043 floorVal, stitchData, floorVal, stitchData);
1044 noiseCode.appendf("\n\tif(%s.w >= %s.y) { %s.w -= %s.y; }",
1045 floorVal, stitchData, floorVal, stitchData);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001046 }
1047
1048 // Get texture coordinates and normalize
senorblancoce6a3542014-06-12 11:24:19 -07001049 noiseCode.appendf("\n\t%s = fract(floor(mod(%s, 256.0)) / vec4(256.0));\n",
1050 floorVal, floorVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001051
1052 // Get permutation for x
1053 {
1054 SkString xCoords("");
senorblancoce6a3542014-06-12 11:24:19 -07001055 xCoords.appendf("vec2(%s.x, 0.5)", floorVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001056
sugoi@google.comd537af52013-06-10 13:59:25 +00001057 noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
1058 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1059 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001060 }
1061
1062 // Get permutation for x + 1
1063 {
1064 SkString xCoords("");
senorblancoce6a3542014-06-12 11:24:19 -07001065 xCoords.appendf("vec2(%s.z, 0.5)", floorVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001066
sugoi@google.comd537af52013-06-10 13:59:25 +00001067 noiseCode.appendf("\n\t%s.y = ", latticeIdx);
1068 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1069 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001070 }
1071
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001072#if defined(SK_BUILD_FOR_ANDROID)
1073 // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
1074 // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
1075 // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
1076 // (or 0.484368 here). The following rounding operation prevents these precision issues from
1077 // affecting the result of the noise by making sure that we only have multiples of 1/255.
1078 // (Note that 1/255 is about 0.003921569, which is the value used here).
1079 noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);",
1080 latticeIdx, latticeIdx);
1081#endif
1082
sugoi@google.come3b4c502013-04-05 13:47:09 +00001083 // Get (x,y) coordinates with the permutated x
senorblancoce6a3542014-06-12 11:24:19 -07001084 noiseCode.appendf("\n\tvec4 %s = fract(%s.xyxy + %s.yyww);", bcoords, latticeIdx, floorVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001085
sugoi@google.comd537af52013-06-10 13:59:25 +00001086 noiseCode.appendf("\n\n\tvec2 %s;", uv);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001087 // Compute u, at offset (0,0)
1088 {
1089 SkString latticeCoords("");
senorblancoce6a3542014-06-12 11:24:19 -07001090 latticeCoords.appendf("vec2(%s.x, %s)", bcoords, chanCoord);
sugoi@google.comd537af52013-06-10 13:59:25 +00001091 noiseCode.appendf("\n\tvec4 %s = ", lattice);
1092 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1093 kVec2f_GrSLType);
1094 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1095 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001096 }
1097
sugoi@google.comd537af52013-06-10 13:59:25 +00001098 noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001099 // Compute v, at offset (-1,0)
1100 {
1101 SkString latticeCoords("");
senorblancoce6a3542014-06-12 11:24:19 -07001102 latticeCoords.appendf("vec2(%s.y, %s)", bcoords, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001103 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001104 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1105 kVec2f_GrSLType);
1106 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1107 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001108 }
1109
1110 // Compute 'a' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001111 noiseCode.appendf("\n\tvec2 %s;", ab);
1112 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 +00001113
sugoi@google.comd537af52013-06-10 13:59:25 +00001114 noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001115 // Compute v, at offset (-1,-1)
1116 {
1117 SkString latticeCoords("");
senorblancoce6a3542014-06-12 11:24:19 -07001118 latticeCoords.appendf("vec2(%s.w, %s)", bcoords, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001119 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001120 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1121 kVec2f_GrSLType);
1122 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1123 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001124 }
1125
sugoi@google.comd537af52013-06-10 13:59:25 +00001126 noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001127 // Compute u, at offset (0,-1)
1128 {
1129 SkString latticeCoords("");
senorblancoce6a3542014-06-12 11:24:19 -07001130 latticeCoords.appendf("vec2(%s.z, %s)", bcoords, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001131 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001132 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1133 kVec2f_GrSLType);
1134 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1135 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001136 }
1137
1138 // Compute 'b' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001139 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 +00001140 // Compute the noise as a linear interpolation of 'a' and 'b'
sugoi@google.comd537af52013-06-10 13:59:25 +00001141 noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001142
sugoi@google.comd537af52013-06-10 13:59:25 +00001143 SkString noiseFuncName;
1144 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001145 builder->fsEmitFunction(kFloat_GrSLType,
1146 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
1147 gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001148 } else {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001149 builder->fsEmitFunction(kFloat_GrSLType,
1150 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
1151 gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001152 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001153
sugoi@google.comd537af52013-06-10 13:59:25 +00001154 // There are rounding errors if the floor operation is not performed here
1155 builder->fsCodeAppendf("\n\t\tvec2 %s = floor((%s * vec3(%s, 1.0)).xy) * %s;",
commit-bot@chromium.org7ab7ca42013-08-28 15:59:13 +00001156 noiseVec, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.comd537af52013-06-10 13:59:25 +00001157
1158 // Clear the color accumulator
1159 builder->fsCodeAppendf("\n\t\t%s = vec4(0.0);", outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001160
1161 if (fStitchTiles) {
sugoi@google.comd537af52013-06-10 13:59:25 +00001162 // Set up TurbulenceInitial stitch values.
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001163 builder->fsCodeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001164 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001165
sugoi@google.comd537af52013-06-10 13:59:25 +00001166 builder->fsCodeAppendf("\n\t\tfloat %s = 1.0;", ratio);
1167
1168 // Loop over all octaves
1169 builder->fsCodeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
1170
1171 builder->fsCodeAppendf("\n\t\t\t%s += ", outputColor);
1172 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1173 builder->fsCodeAppend("abs(");
1174 }
1175 if (fStitchTiles) {
1176 builder->fsCodeAppendf(
1177 "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
1178 "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
1179 noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
1180 noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
1181 noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
1182 noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
1183 } else {
1184 builder->fsCodeAppendf(
1185 "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
1186 "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
1187 noiseFuncName.c_str(), chanCoordR, noiseVec,
1188 noiseFuncName.c_str(), chanCoordG, noiseVec,
1189 noiseFuncName.c_str(), chanCoordB, noiseVec,
1190 noiseFuncName.c_str(), chanCoordA, noiseVec);
1191 }
1192 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1193 builder->fsCodeAppendf(")"); // end of "abs("
1194 }
1195 builder->fsCodeAppendf(" * %s;", ratio);
1196
1197 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
1198 builder->fsCodeAppendf("\n\t\t\t%s *= 0.5;", ratio);
1199
1200 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001201 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData);
sugoi@google.comd537af52013-06-10 13:59:25 +00001202 }
1203 builder->fsCodeAppend("\n\t\t}"); // end of the for loop on octaves
sugoi@google.come3b4c502013-04-05 13:47:09 +00001204
1205 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
1206 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
1207 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
sugoi@google.comd537af52013-06-10 13:59:25 +00001208 builder->fsCodeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001209 }
1210
sugoi@google.comd537af52013-06-10 13:59:25 +00001211 builder->fsCodeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001212
1213 // Clamp values
sugoi@google.comd537af52013-06-10 13:59:25 +00001214 builder->fsCodeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001215
1216 // Pre-multiply the result
sugoi@google.comd537af52013-06-10 13:59:25 +00001217 builder->fsCodeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
sugoi@google.come3b4c502013-04-05 13:47:09 +00001218 outputColor, outputColor, outputColor, outputColor);
1219}
1220
sugoi@google.com4775cba2013-04-17 13:46:56 +00001221GrGLNoise::GrGLNoise(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect)
sugoi@google.come3b4c502013-04-05 13:47:09 +00001222 : INHERITED (factory)
1223 , fType(drawEffect.castEffect<GrPerlinNoiseEffect>().type())
1224 , fStitchTiles(drawEffect.castEffect<GrPerlinNoiseEffect>().stitchTiles())
bsalomon@google.com77af6802013-10-02 13:04:56 +00001225 , fNumOctaves(drawEffect.castEffect<GrPerlinNoiseEffect>().numOctaves()) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001226}
1227
sugoi@google.com4775cba2013-04-17 13:46:56 +00001228GrGLEffect::EffectKey GrGLNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001229 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1230
1231 EffectKey key = turbulence.numOctaves();
1232
1233 key = key << 3; // Make room for next 3 bits
1234
1235 switch (turbulence.type()) {
1236 case SkPerlinNoiseShader::kFractalNoise_Type:
1237 key |= 0x1;
1238 break;
1239 case SkPerlinNoiseShader::kTurbulence_Type:
1240 key |= 0x2;
1241 break;
1242 default:
1243 // leave key at 0
1244 break;
1245 }
1246
1247 if (turbulence.stitchTiles()) {
1248 key |= 0x4; // Flip the 3rd bit if tile stitching is on
1249 }
1250
bsalomon@google.com77af6802013-10-02 13:04:56 +00001251 return key;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001252}
1253
sugoi@google.com4775cba2013-04-17 13:46:56 +00001254void GrGLNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001255 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1256
1257 const SkVector& baseFrequency = turbulence.baseFrequency();
1258 uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001259 uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
1260
1261 SkMatrix m = turbulence.matrix();
bsalomon@google.com77af6802013-10-02 13:04:56 +00001262 m.postTranslate(-SK_Scalar1, -SK_Scalar1);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001263 SkMatrix invM;
1264 if (!m.invert(&invM)) {
1265 invM.reset();
1266 } else {
1267 invM.postConcat(invM); // Square the matrix
1268 }
1269 uman.setSkMatrix(fInvMatrixUni, invM);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001270}
1271
sugoi@google.com4775cba2013-04-17 13:46:56 +00001272void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1273 INHERITED::setData(uman, drawEffect);
1274
1275 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1276 if (turbulence.stitchTiles()) {
1277 const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001278 uman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
1279 SkIntToScalar(stitchData.fHeight));
sugoi@google.com4775cba2013-04-17 13:46:56 +00001280 }
1281}
1282
1283void GrGLSimplexNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1284 INHERITED::setData(uman, drawEffect);
1285
1286 const GrSimplexNoiseEffect& turbulence = drawEffect.castEffect<GrSimplexNoiseEffect>();
1287 uman.set1f(fSeedUni, turbulence.seed());
1288}
1289
sugoi@google.come3b4c502013-04-05 13:47:09 +00001290/////////////////////////////////////////////////////////////////////
1291
dandov9de5b512014-06-10 14:38:28 -07001292bool SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint,
1293 const SkMatrix* externalLocalMatrix, GrColor* grColor,
1294 GrEffectRef** grEffect) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001295 SkASSERT(NULL != context);
dandov9de5b512014-06-10 14:38:28 -07001296
1297 *grColor = SkColor2GrColorJustAlpha(paint.getColor());
1298
commit-bot@chromium.org96fb7482014-05-09 20:28:11 +00001299 SkMatrix localMatrix = this->getLocalMatrix();
1300 if (externalLocalMatrix) {
1301 localMatrix.preConcat(*externalLocalMatrix);
1302 }
1303
commit-bot@chromium.orgc2a0ea62013-11-06 10:08:38 +00001304 if (0 == fNumOctaves) {
1305 SkColor clearColor = 0;
1306 if (kFractalNoise_Type == fType) {
1307 clearColor = SkColorSetARGB(paint.getAlpha() / 2, 127, 127, 127);
1308 }
1309 SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(
1310 clearColor, SkXfermode::kSrc_Mode));
dandov9de5b512014-06-10 14:38:28 -07001311 *grEffect = cf->asNewEffect(context);
1312 return true;
commit-bot@chromium.orgc2a0ea62013-11-06 10:08:38 +00001313 }
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);
dandov9de5b512014-06-10 14:38:28 -07001321 *grEffect =
sugoi@google.com4775cba2013-04-17 13:46:56 +00001322 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(
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +00001327 context, fPaintingData->getPermutationsBitmap(), NULL);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001328 GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture(
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +00001329 context, fPaintingData->getNoiseBitmap(), NULL);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001330
dandov9de5b512014-06-10 14:38:28 -07001331 *grEffect = (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,
commit-bot@chromium.org96fb7482014-05-09 20:28:11 +00001336 localMatrix, paint.getAlpha()) :
sugoi@google.come3b4c502013-04-05 13:47:09 +00001337 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
dandov9de5b512014-06-10 14:38:28 -07001350 return true;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001351}
1352
1353#else
1354
dandov9de5b512014-06-10 14:38:28 -07001355bool SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint,
1356 const SkMatrix* externalLocalMatrix, GrColor* grColor,
1357 GrEffectRef** grEffect) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001358 SkDEBUGFAIL("Should not call in GPU-less build");
dandov9de5b512014-06-10 14:38:28 -07001359 return false;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001360}
1361
1362#endif
1363
commit-bot@chromium.org0f10f7b2014-03-13 18:02:17 +00001364#ifndef SK_IGNORE_TO_STRING
sugoi@google.come3b4c502013-04-05 13:47:09 +00001365void SkPerlinNoiseShader::toString(SkString* str) const {
1366 str->append("SkPerlinNoiseShader: (");
1367
1368 str->append("type: ");
1369 switch (fType) {
1370 case kFractalNoise_Type:
1371 str->append("\"fractal noise\"");
1372 break;
1373 case kTurbulence_Type:
1374 str->append("\"turbulence\"");
1375 break;
1376 default:
1377 str->append("\"unknown\"");
1378 break;
1379 }
1380 str->append(" base frequency: (");
1381 str->appendScalar(fBaseFrequencyX);
1382 str->append(", ");
1383 str->appendScalar(fBaseFrequencyY);
1384 str->append(") number of octaves: ");
1385 str->appendS32(fNumOctaves);
1386 str->append(" seed: ");
1387 str->appendScalar(fSeed);
1388 str->append(" stitch tiles: ");
1389 str->append(fStitchTiles ? "true " : "false ");
1390
1391 this->INHERITED::toString(str);
1392
1393 str->append(")");
1394}
1395#endif