1 /*
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 "include/effects/SkPerlinNoiseShader.h"
9
10 #include "include/core/SkBitmap.h"
11 #include "include/core/SkColorFilter.h"
12 #include "include/core/SkShader.h"
13 #include "include/core/SkString.h"
14 #include "include/core/SkUnPreMultiply.h"
15 #include "include/private/SkTPin.h"
16 #include "src/core/SkArenaAlloc.h"
17 #include "src/core/SkMatrixProvider.h"
18 #include "src/core/SkReadBuffer.h"
19 #include "src/core/SkVM.h"
20 #include "src/core/SkWriteBuffer.h"
21
22 #if SK_SUPPORT_GPU
23 #include "include/gpu/GrRecordingContext.h"
24 #include "src/gpu/GrRecordingContextPriv.h"
25 #include "src/gpu/SkGr.h"
26 #include "src/gpu/effects/GrMatrixEffect.h"
27 #include "src/gpu/effects/GrTextureEffect.h"
28 #include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
29 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
30 #include "src/gpu/glsl/GrGLSLProgramDataManager.h"
31 #include "src/gpu/glsl/GrGLSLUniformHandler.h"
32 #endif
33
34 static const int kBlockSize = 256;
35 static const int kBlockMask = kBlockSize - 1;
36 static const int kPerlinNoise = 4096;
37 static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
38
39 class SkPerlinNoiseShaderImpl : public SkShaderBase {
40 public:
41 struct StitchData {
StitchDataSkPerlinNoiseShaderImpl::StitchData42 StitchData()
43 : fWidth(0)
44 , fWrapX(0)
45 , fHeight(0)
46 , fWrapY(0)
47 {}
48
StitchDataSkPerlinNoiseShaderImpl::StitchData49 StitchData(SkScalar w, SkScalar h)
50 : fWidth(std::min(SkScalarRoundToInt(w), SK_MaxS32 - kPerlinNoise))
51 , fWrapX(kPerlinNoise + fWidth)
52 , fHeight(std::min(SkScalarRoundToInt(h), SK_MaxS32 - kPerlinNoise))
53 , fWrapY(kPerlinNoise + fHeight) {}
54
operator ==SkPerlinNoiseShaderImpl::StitchData55 bool operator==(const StitchData& other) const {
56 return fWidth == other.fWidth &&
57 fWrapX == other.fWrapX &&
58 fHeight == other.fHeight &&
59 fWrapY == other.fWrapY;
60 }
61
62 int fWidth; // How much to subtract to wrap for stitching.
63 int fWrapX; // Minimum value to wrap.
64 int fHeight;
65 int fWrapY;
66 };
67
68 struct PaintingData {
PaintingDataSkPerlinNoiseShaderImpl::PaintingData69 PaintingData(const SkISize& tileSize, SkScalar seed,
70 SkScalar baseFrequencyX, SkScalar baseFrequencyY,
71 const SkMatrix& matrix)
72 {
73 SkVector tileVec;
74 matrix.mapVector(SkIntToScalar(tileSize.fWidth), SkIntToScalar(tileSize.fHeight),
75 &tileVec);
76
77 SkSize scale;
78 if (!matrix.decomposeScale(&scale, nullptr)) {
79 scale.set(SK_ScalarNearlyZero, SK_ScalarNearlyZero);
80 }
81 fBaseFrequency.set(baseFrequencyX * SkScalarInvert(scale.width()),
82 baseFrequencyY * SkScalarInvert(scale.height()));
83 fTileSize.set(SkScalarRoundToInt(tileVec.fX), SkScalarRoundToInt(tileVec.fY));
84 this->init(seed);
85 if (!fTileSize.isEmpty()) {
86 this->stitch();
87 }
88
89 #if SK_SUPPORT_GPU
90 SkImageInfo info = SkImageInfo::MakeA8(kBlockSize, 1);
91 fPermutationsBitmap.installPixels(info, fLatticeSelector, info.minRowBytes());
92 fPermutationsBitmap.setImmutable();
93
94 info = SkImageInfo::Make(kBlockSize, 4, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
95 fNoiseBitmap.installPixels(info, fNoise[0][0], info.minRowBytes());
96 fNoiseBitmap.setImmutable();
97 #endif
98 }
99
100 #if SK_SUPPORT_GPU
PaintingDataSkPerlinNoiseShaderImpl::PaintingData101 PaintingData(const PaintingData& that)
102 : fSeed(that.fSeed)
103 , fTileSize(that.fTileSize)
104 , fBaseFrequency(that.fBaseFrequency)
105 , fStitchDataInit(that.fStitchDataInit)
106 , fPermutationsBitmap(that.fPermutationsBitmap)
107 , fNoiseBitmap(that.fNoiseBitmap) {
108 memcpy(fLatticeSelector, that.fLatticeSelector, sizeof(fLatticeSelector));
109 memcpy(fNoise, that.fNoise, sizeof(fNoise));
110 memcpy(fGradient, that.fGradient, sizeof(fGradient));
111 }
112 #endif
113
114 int fSeed;
115 uint8_t fLatticeSelector[kBlockSize];
116 uint16_t fNoise[4][kBlockSize][2];
117 SkPoint fGradient[4][kBlockSize];
118 SkISize fTileSize;
119 SkVector fBaseFrequency;
120 StitchData fStitchDataInit;
121
122 private:
123
124 #if SK_SUPPORT_GPU
125 SkBitmap fPermutationsBitmap;
126 SkBitmap fNoiseBitmap;
127 #endif
128
randomSkPerlinNoiseShaderImpl::PaintingData129 inline int random() {
130 // See https://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
131 // m = kRandMaximum, 2**31 - 1 (2147483647)
132 static constexpr int kRandAmplitude = 16807; // 7**5; primitive root of m
133 static constexpr int kRandQ = 127773; // m / a
134 static constexpr int kRandR = 2836; // m % a
135
136 int result = kRandAmplitude * (fSeed % kRandQ) - kRandR * (fSeed / kRandQ);
137 if (result <= 0) {
138 result += kRandMaximum;
139 }
140 fSeed = result;
141 return result;
142 }
143
144 // Only called once. Could be part of the constructor.
initSkPerlinNoiseShaderImpl::PaintingData145 void init(SkScalar seed)
146 {
147 // According to the SVG spec, we must truncate (not round) the seed value.
148 fSeed = SkScalarTruncToInt(seed);
149 // The seed value clamp to the range [1, kRandMaximum - 1].
150 if (fSeed <= 0) {
151 fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
152 }
153 if (fSeed > kRandMaximum - 1) {
154 fSeed = kRandMaximum - 1;
155 }
156 for (int channel = 0; channel < 4; ++channel) {
157 for (int i = 0; i < kBlockSize; ++i) {
158 fLatticeSelector[i] = i;
159 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
160 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
161 }
162 }
163 for (int i = kBlockSize - 1; i > 0; --i) {
164 int k = fLatticeSelector[i];
165 int j = random() % kBlockSize;
166 SkASSERT(j >= 0);
167 SkASSERT(j < kBlockSize);
168 fLatticeSelector[i] = fLatticeSelector[j];
169 fLatticeSelector[j] = k;
170 }
171
172 // Perform the permutations now
173 {
174 // Copy noise data
175 uint16_t noise[4][kBlockSize][2];
176 for (int i = 0; i < kBlockSize; ++i) {
177 for (int channel = 0; channel < 4; ++channel) {
178 for (int j = 0; j < 2; ++j) {
179 noise[channel][i][j] = fNoise[channel][i][j];
180 }
181 }
182 }
183 // Do permutations on noise data
184 for (int i = 0; i < kBlockSize; ++i) {
185 for (int channel = 0; channel < 4; ++channel) {
186 for (int j = 0; j < 2; ++j) {
187 fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
188 }
189 }
190 }
191 }
192
193 // Half of the largest possible value for 16 bit unsigned int
194 static constexpr SkScalar kHalfMax16bits = 32767.5f;
195
196 // Compute gradients from permutated noise data
197 static constexpr SkScalar kInvBlockSizef = 1.0 / SkIntToScalar(kBlockSize);
198 for (int channel = 0; channel < 4; ++channel) {
199 for (int i = 0; i < kBlockSize; ++i) {
200 fGradient[channel][i] = SkPoint::Make(
201 (fNoise[channel][i][0] - kBlockSize) * kInvBlockSizef,
202 (fNoise[channel][i][1] - kBlockSize) * kInvBlockSizef);
203 fGradient[channel][i].normalize();
204 // Put the normalized gradient back into the noise data
205 fNoise[channel][i][0] =
206 SkScalarRoundToInt((fGradient[channel][i].fX + 1) * kHalfMax16bits);
207 fNoise[channel][i][1] =
208 SkScalarRoundToInt((fGradient[channel][i].fY + 1) * kHalfMax16bits);
209 }
210 }
211 }
212
213 // Only called once. Could be part of the constructor.
stitchSkPerlinNoiseShaderImpl::PaintingData214 void stitch() {
215 SkScalar tileWidth = SkIntToScalar(fTileSize.width());
216 SkScalar tileHeight = SkIntToScalar(fTileSize.height());
217 SkASSERT(tileWidth > 0 && tileHeight > 0);
218 // When stitching tiled turbulence, the frequencies must be adjusted
219 // so that the tile borders will be continuous.
220 if (fBaseFrequency.fX) {
221 SkScalar lowFrequencx =
222 SkScalarFloorToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
223 SkScalar highFrequencx =
224 SkScalarCeilToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
225 // BaseFrequency should be non-negative according to the standard.
226 // lowFrequencx can be 0 if fBaseFrequency.fX is very small.
227 if (sk_ieee_float_divide(fBaseFrequency.fX, lowFrequencx) < highFrequencx / fBaseFrequency.fX) {
228 fBaseFrequency.fX = lowFrequencx;
229 } else {
230 fBaseFrequency.fX = highFrequencx;
231 }
232 }
233 if (fBaseFrequency.fY) {
234 SkScalar lowFrequency =
235 SkScalarFloorToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
236 SkScalar highFrequency =
237 SkScalarCeilToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
238 // lowFrequency can be 0 if fBaseFrequency.fY is very small.
239 if (sk_ieee_float_divide(fBaseFrequency.fY, lowFrequency) < highFrequency / fBaseFrequency.fY) {
240 fBaseFrequency.fY = lowFrequency;
241 } else {
242 fBaseFrequency.fY = highFrequency;
243 }
244 }
245 // Set up TurbulenceInitial stitch values.
246 fStitchDataInit = StitchData(tileWidth * fBaseFrequency.fX,
247 tileHeight * fBaseFrequency.fY);
248 }
249
250 public:
251
252 #if SK_SUPPORT_GPU
getPermutationsBitmapSkPerlinNoiseShaderImpl::PaintingData253 const SkBitmap& getPermutationsBitmap() const { return fPermutationsBitmap; }
254
getNoiseBitmapSkPerlinNoiseShaderImpl::PaintingData255 const SkBitmap& getNoiseBitmap() const { return fNoiseBitmap; }
256 #endif
257 };
258
259 /**
260 * About the noise types : the difference between the first 2 is just minor tweaks to the
261 * algorithm, they're not 2 entirely different noises. The output looks different, but once the
262 * noise is generated in the [1, -1] range, the output is brought back in the [0, 1] range by
263 * doing :
264 * kFractalNoise_Type : noise * 0.5 + 0.5
265 * kTurbulence_Type : abs(noise)
266 * Very little differences between the 2 types, although you can tell the difference visually.
267 */
268 enum Type {
269 kFractalNoise_Type,
270 kTurbulence_Type,
271 kLast_Type = kTurbulence_Type
272 };
273
274 static const int kMaxOctaves = 255; // numOctaves must be <= 0 and <= kMaxOctaves
275
276 SkPerlinNoiseShaderImpl(SkPerlinNoiseShaderImpl::Type type, SkScalar baseFrequencyX,
277 SkScalar baseFrequencyY, int numOctaves, SkScalar seed,
278 const SkISize* tileSize);
279
280 class PerlinNoiseShaderContext : public Context {
281 public:
282 PerlinNoiseShaderContext(const SkPerlinNoiseShaderImpl& shader, const ContextRec&);
283
284 void shadeSpan(int x, int y, SkPMColor[], int count) override;
285
286 private:
287 SkPMColor shade(const SkPoint& point, StitchData& stitchData) const;
288 SkScalar calculateTurbulenceValueForPoint(
289 int channel,
290 StitchData& stitchData, const SkPoint& point) const;
291 SkScalar noise2D(int channel,
292 const StitchData& stitchData, const SkPoint& noiseVector) const;
293
294 SkMatrix fMatrix;
295 PaintingData fPaintingData;
296
297 using INHERITED = Context;
298 };
299
300 #if SK_SUPPORT_GPU
301 std::unique_ptr<GrFragmentProcessor> asFragmentProcessor(const GrFPArgs&) const override;
302 #endif
303
onProgram(skvm::Builder *,skvm::Coord,skvm::Coord,skvm::Color,const SkMatrixProvider &,const SkMatrix *,const SkColorInfo &,skvm::Uniforms *,SkArenaAlloc *) const304 skvm::Color onProgram(skvm::Builder*,
305 skvm::Coord, skvm::Coord, skvm::Color,
306 const SkMatrixProvider&, const SkMatrix*, const SkColorInfo&,
307 skvm::Uniforms*, SkArenaAlloc*) const override {
308 // TODO?
309 return {};
310 }
311
312 protected:
313 void flatten(SkWriteBuffer&) const override;
314 #ifdef SK_ENABLE_LEGACY_SHADERCONTEXT
315 Context* onMakeContext(const ContextRec&, SkArenaAlloc*) const override;
316 #endif
317
318 private:
319 SK_FLATTENABLE_HOOKS(SkPerlinNoiseShaderImpl)
320
321 const SkPerlinNoiseShaderImpl::Type fType;
322 const SkScalar fBaseFrequencyX;
323 const SkScalar fBaseFrequencyY;
324 const int fNumOctaves;
325 const SkScalar fSeed;
326 const SkISize fTileSize;
327 const bool fStitchTiles;
328
329 friend class ::SkPerlinNoiseShader;
330
331 using INHERITED = SkShaderBase;
332 };
333
334 namespace {
335
336 // noiseValue is the color component's value (or color)
337 // limitValue is the maximum perlin noise array index value allowed
338 // newValue is the current noise dimension (either width or height)
checkNoise(int noiseValue,int limitValue,int newValue)339 inline int checkNoise(int noiseValue, int limitValue, int newValue) {
340 // If the noise value would bring us out of bounds of the current noise array while we are
341 // stiching noise tiles together, wrap the noise around the current dimension of the noise to
342 // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
343 if (noiseValue >= limitValue) {
344 noiseValue -= newValue;
345 }
346 return noiseValue;
347 }
348
smoothCurve(SkScalar t)349 inline SkScalar smoothCurve(SkScalar t) {
350 return t * t * (3 - 2 * t);
351 }
352
353 } // end namespace
354
SkPerlinNoiseShaderImpl(SkPerlinNoiseShaderImpl::Type type,SkScalar baseFrequencyX,SkScalar baseFrequencyY,int numOctaves,SkScalar seed,const SkISize * tileSize)355 SkPerlinNoiseShaderImpl::SkPerlinNoiseShaderImpl(SkPerlinNoiseShaderImpl::Type type,
356 SkScalar baseFrequencyX,
357 SkScalar baseFrequencyY,
358 int numOctaves,
359 SkScalar seed,
360 const SkISize* tileSize)
361 : fType(type)
362 , fBaseFrequencyX(baseFrequencyX)
363 , fBaseFrequencyY(baseFrequencyY)
364 , fNumOctaves(numOctaves > kMaxOctaves ? kMaxOctaves : numOctaves/*[0,255] octaves allowed*/)
365 , fSeed(seed)
366 , fTileSize(nullptr == tileSize ? SkISize::Make(0, 0) : *tileSize)
367 , fStitchTiles(!fTileSize.isEmpty())
368 {
369 SkASSERT(numOctaves >= 0 && numOctaves <= kMaxOctaves);
370 SkASSERT(fBaseFrequencyX >= 0);
371 SkASSERT(fBaseFrequencyY >= 0);
372 }
373
CreateProc(SkReadBuffer & buffer)374 sk_sp<SkFlattenable> SkPerlinNoiseShaderImpl::CreateProc(SkReadBuffer& buffer) {
375 Type type = buffer.read32LE(kLast_Type);
376
377 SkScalar freqX = buffer.readScalar();
378 SkScalar freqY = buffer.readScalar();
379 int octaves = buffer.read32LE<int>(kMaxOctaves);
380
381 SkScalar seed = buffer.readScalar();
382 SkISize tileSize;
383 tileSize.fWidth = buffer.readInt();
384 tileSize.fHeight = buffer.readInt();
385
386 switch (type) {
387 case kFractalNoise_Type:
388 return SkPerlinNoiseShader::MakeFractalNoise(freqX, freqY, octaves, seed, &tileSize);
389 case kTurbulence_Type:
390 return SkPerlinNoiseShader::MakeTurbulence(freqX, freqY, octaves, seed, &tileSize);
391 default:
392 // Really shouldn't get here b.c. of earlier check on type
393 buffer.validate(false);
394 return nullptr;
395 }
396 }
397
flatten(SkWriteBuffer & buffer) const398 void SkPerlinNoiseShaderImpl::flatten(SkWriteBuffer& buffer) const {
399 buffer.writeInt((int) fType);
400 buffer.writeScalar(fBaseFrequencyX);
401 buffer.writeScalar(fBaseFrequencyY);
402 buffer.writeInt(fNumOctaves);
403 buffer.writeScalar(fSeed);
404 buffer.writeInt(fTileSize.fWidth);
405 buffer.writeInt(fTileSize.fHeight);
406 }
407
noise2D(int channel,const StitchData & stitchData,const SkPoint & noiseVector) const408 SkScalar SkPerlinNoiseShaderImpl::PerlinNoiseShaderContext::noise2D(
409 int channel, const StitchData& stitchData, const SkPoint& noiseVector) const {
410 struct Noise {
411 int noisePositionIntegerValue;
412 int nextNoisePositionIntegerValue;
413 SkScalar noisePositionFractionValue;
414 Noise(SkScalar component)
415 {
416 SkScalar position = component + kPerlinNoise;
417 noisePositionIntegerValue = SkScalarFloorToInt(position);
418 noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
419 nextNoisePositionIntegerValue = noisePositionIntegerValue + 1;
420 }
421 };
422 Noise noiseX(noiseVector.x());
423 Noise noiseY(noiseVector.y());
424 SkScalar u, v;
425 const SkPerlinNoiseShaderImpl& perlinNoiseShader = static_cast<const SkPerlinNoiseShaderImpl&>(fShader);
426 // If stitching, adjust lattice points accordingly.
427 if (perlinNoiseShader.fStitchTiles) {
428 noiseX.noisePositionIntegerValue =
429 checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
430 noiseY.noisePositionIntegerValue =
431 checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
432 noiseX.nextNoisePositionIntegerValue =
433 checkNoise(noiseX.nextNoisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
434 noiseY.nextNoisePositionIntegerValue =
435 checkNoise(noiseY.nextNoisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
436 }
437 noiseX.noisePositionIntegerValue &= kBlockMask;
438 noiseY.noisePositionIntegerValue &= kBlockMask;
439 noiseX.nextNoisePositionIntegerValue &= kBlockMask;
440 noiseY.nextNoisePositionIntegerValue &= kBlockMask;
441 int i = fPaintingData.fLatticeSelector[noiseX.noisePositionIntegerValue];
442 int j = fPaintingData.fLatticeSelector[noiseX.nextNoisePositionIntegerValue];
443 int b00 = (i + noiseY.noisePositionIntegerValue) & kBlockMask;
444 int b10 = (j + noiseY.noisePositionIntegerValue) & kBlockMask;
445 int b01 = (i + noiseY.nextNoisePositionIntegerValue) & kBlockMask;
446 int b11 = (j + noiseY.nextNoisePositionIntegerValue) & kBlockMask;
447 SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
448 SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
449
450 if (sx < 0 || sy < 0 || sx > 1 || sy > 1) {
451 return 0; // Check for pathological inputs.
452 }
453
454 // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
455 SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
456 noiseY.noisePositionFractionValue); // Offset (0,0)
457 u = fPaintingData.fGradient[channel][b00].dot(fractionValue);
458 fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
459 v = fPaintingData.fGradient[channel][b10].dot(fractionValue);
460 SkScalar a = SkScalarInterp(u, v, sx);
461 fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
462 v = fPaintingData.fGradient[channel][b11].dot(fractionValue);
463 fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
464 u = fPaintingData.fGradient[channel][b01].dot(fractionValue);
465 SkScalar b = SkScalarInterp(u, v, sx);
466 return SkScalarInterp(a, b, sy);
467 }
468
calculateTurbulenceValueForPoint(int channel,StitchData & stitchData,const SkPoint & point) const469 SkScalar SkPerlinNoiseShaderImpl::PerlinNoiseShaderContext::calculateTurbulenceValueForPoint(
470 int channel, StitchData& stitchData, const SkPoint& point) const {
471 const SkPerlinNoiseShaderImpl& perlinNoiseShader = static_cast<const SkPerlinNoiseShaderImpl&>(fShader);
472 if (perlinNoiseShader.fStitchTiles) {
473 // Set up TurbulenceInitial stitch values.
474 stitchData = fPaintingData.fStitchDataInit;
475 }
476 SkScalar turbulenceFunctionResult = 0;
477 SkPoint noiseVector(SkPoint::Make(point.x() * fPaintingData.fBaseFrequency.fX,
478 point.y() * fPaintingData.fBaseFrequency.fY));
479 SkScalar ratio = SK_Scalar1;
480 for (int octave = 0; octave < perlinNoiseShader.fNumOctaves; ++octave) {
481 SkScalar noise = noise2D(channel, stitchData, noiseVector);
482 SkScalar numer = (perlinNoiseShader.fType == kFractalNoise_Type) ?
483 noise : SkScalarAbs(noise);
484 turbulenceFunctionResult += numer / ratio;
485 noiseVector.fX *= 2;
486 noiseVector.fY *= 2;
487 ratio *= 2;
488 if (perlinNoiseShader.fStitchTiles) {
489 // Update stitch values
490 stitchData = StitchData(SkIntToScalar(stitchData.fWidth) * 2,
491 SkIntToScalar(stitchData.fHeight) * 2);
492 }
493 }
494
495 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
496 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
497 if (perlinNoiseShader.fType == kFractalNoise_Type) {
498 turbulenceFunctionResult = SkScalarHalf(turbulenceFunctionResult + 1);
499 }
500
501 if (channel == 3) { // Scale alpha by paint value
502 turbulenceFunctionResult *= SkIntToScalar(getPaintAlpha()) / 255;
503 }
504
505 // Clamp result
506 return SkTPin(turbulenceFunctionResult, 0.0f, SK_Scalar1);
507 }
508
509 ////////////////////////////////////////////////////////////////////////////////////////////////////
510
shade(const SkPoint & point,StitchData & stitchData) const511 SkPMColor SkPerlinNoiseShaderImpl::PerlinNoiseShaderContext::shade(
512 const SkPoint& point, StitchData& stitchData) const {
513 SkPoint newPoint;
514 fMatrix.mapPoints(&newPoint, &point, 1);
515 newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
516 newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
517
518 U8CPU rgba[4];
519 for (int channel = 3; channel >= 0; --channel) {
520 SkScalar value;
521 value = calculateTurbulenceValueForPoint(channel, stitchData, newPoint);
522 rgba[channel] = SkScalarFloorToInt(255 * value);
523 }
524 return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
525 }
526
527 #ifdef SK_ENABLE_LEGACY_SHADERCONTEXT
onMakeContext(const ContextRec & rec,SkArenaAlloc * alloc) const528 SkShaderBase::Context* SkPerlinNoiseShaderImpl::onMakeContext(const ContextRec& rec,
529 SkArenaAlloc* alloc) const {
530 // should we pay attention to rec's device-colorspace?
531 return alloc->make<PerlinNoiseShaderContext>(*this, rec);
532 }
533 #endif
534
total_matrix(const SkShaderBase::ContextRec & rec,const SkShaderBase & shader)535 static inline SkMatrix total_matrix(const SkShaderBase::ContextRec& rec,
536 const SkShaderBase& shader) {
537 SkMatrix matrix = SkMatrix::Concat(*rec.fMatrix, shader.getLocalMatrix());
538 if (rec.fLocalMatrix) {
539 matrix.preConcat(*rec.fLocalMatrix);
540 }
541
542 return matrix;
543 }
544
PerlinNoiseShaderContext(const SkPerlinNoiseShaderImpl & shader,const ContextRec & rec)545 SkPerlinNoiseShaderImpl::PerlinNoiseShaderContext::PerlinNoiseShaderContext(
546 const SkPerlinNoiseShaderImpl& shader, const ContextRec& rec)
547 : INHERITED(shader, rec)
548 , fMatrix(total_matrix(rec, shader)) // used for temp storage, adjusted below
549 , fPaintingData(shader.fTileSize, shader.fSeed, shader.fBaseFrequencyX,
550 shader.fBaseFrequencyY, fMatrix)
551 {
552 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
553 // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
554 fMatrix.setTranslate(-fMatrix.getTranslateX() + SK_Scalar1,
555 -fMatrix.getTranslateY() + SK_Scalar1);
556 }
557
shadeSpan(int x,int y,SkPMColor result[],int count)558 void SkPerlinNoiseShaderImpl::PerlinNoiseShaderContext::shadeSpan(
559 int x, int y, SkPMColor result[], int count) {
560 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
561 StitchData stitchData;
562 for (int i = 0; i < count; ++i) {
563 result[i] = shade(point, stitchData);
564 point.fX += SK_Scalar1;
565 }
566 }
567
568 /////////////////////////////////////////////////////////////////////
569
570 #if SK_SUPPORT_GPU
571
572 class GrGLPerlinNoise : public GrGLSLFragmentProcessor {
573 public:
574 void emitCode(EmitArgs&) override;
575
576 static inline void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder* b);
577
578 protected:
579 void onSetData(const GrGLSLProgramDataManager&, const GrFragmentProcessor&) override;
580
581 private:
582 GrGLSLProgramDataManager::UniformHandle fStitchDataUni;
583 GrGLSLProgramDataManager::UniformHandle fBaseFrequencyUni;
584
585 using INHERITED = GrGLSLFragmentProcessor;
586 };
587
588 /////////////////////////////////////////////////////////////////////
589
590 class GrPerlinNoise2Effect : public GrFragmentProcessor {
591 public:
Make(SkPerlinNoiseShaderImpl::Type type,int numOctaves,bool stitchTiles,std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> paintingData,GrSurfaceProxyView permutationsView,GrSurfaceProxyView noiseView,const SkMatrix & matrix,const GrCaps & caps)592 static std::unique_ptr<GrFragmentProcessor> Make(
593 SkPerlinNoiseShaderImpl::Type type,
594 int numOctaves,
595 bool stitchTiles,
596 std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> paintingData,
597 GrSurfaceProxyView permutationsView,
598 GrSurfaceProxyView noiseView,
599 const SkMatrix& matrix,
600 const GrCaps& caps) {
601 static constexpr GrSamplerState kRepeatXSampler = {GrSamplerState::WrapMode::kRepeat,
602 GrSamplerState::WrapMode::kClamp,
603 GrSamplerState::Filter::kNearest};
604 auto permutationsFP =
605 GrTextureEffect::Make(std::move(permutationsView), kPremul_SkAlphaType,
606 SkMatrix::I(), kRepeatXSampler, caps);
607 auto noiseFP = GrTextureEffect::Make(std::move(noiseView), kPremul_SkAlphaType,
608 SkMatrix::I(), kRepeatXSampler, caps);
609
610 return GrMatrixEffect::Make(matrix, std::unique_ptr<GrFragmentProcessor>(
611 new GrPerlinNoise2Effect(type, numOctaves, stitchTiles, std::move(paintingData),
612 std::move(permutationsFP), std::move(noiseFP))));
613 }
614
name() const615 const char* name() const override { return "PerlinNoise"; }
616
clone() const617 std::unique_ptr<GrFragmentProcessor> clone() const override {
618 return std::unique_ptr<GrFragmentProcessor>(new GrPerlinNoise2Effect(*this));
619 }
620
stitchData() const621 const SkPerlinNoiseShaderImpl::StitchData& stitchData() const { return fPaintingData->fStitchDataInit; }
622
type() const623 SkPerlinNoiseShaderImpl::Type type() const { return fType; }
stitchTiles() const624 bool stitchTiles() const { return fStitchTiles; }
baseFrequency() const625 const SkVector& baseFrequency() const { return fPaintingData->fBaseFrequency; }
numOctaves() const626 int numOctaves() const { return fNumOctaves; }
627
628 private:
onMakeProgramImpl() const629 std::unique_ptr<GrGLSLFragmentProcessor> onMakeProgramImpl() const override {
630 return std::make_unique<GrGLPerlinNoise>();
631 }
632
onGetGLSLProcessorKey(const GrShaderCaps & caps,GrProcessorKeyBuilder * b) const633 void onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const override {
634 GrGLPerlinNoise::GenKey(*this, caps, b);
635 }
636
onIsEqual(const GrFragmentProcessor & sBase) const637 bool onIsEqual(const GrFragmentProcessor& sBase) const override {
638 const GrPerlinNoise2Effect& s = sBase.cast<GrPerlinNoise2Effect>();
639 return fType == s.fType &&
640 fPaintingData->fBaseFrequency == s.fPaintingData->fBaseFrequency &&
641 fNumOctaves == s.fNumOctaves &&
642 fStitchTiles == s.fStitchTiles &&
643 fPaintingData->fStitchDataInit == s.fPaintingData->fStitchDataInit;
644 }
645
GrPerlinNoise2Effect(SkPerlinNoiseShaderImpl::Type type,int numOctaves,bool stitchTiles,std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> paintingData,std::unique_ptr<GrFragmentProcessor> permutationsFP,std::unique_ptr<GrFragmentProcessor> noiseFP)646 GrPerlinNoise2Effect(SkPerlinNoiseShaderImpl::Type type,
647 int numOctaves,
648 bool stitchTiles,
649 std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> paintingData,
650 std::unique_ptr<GrFragmentProcessor> permutationsFP,
651 std::unique_ptr<GrFragmentProcessor> noiseFP)
652 : INHERITED(kGrPerlinNoise2Effect_ClassID, kNone_OptimizationFlags)
653 , fType(type)
654 , fNumOctaves(numOctaves)
655 , fStitchTiles(stitchTiles)
656 , fPaintingData(std::move(paintingData)) {
657 this->registerChild(std::move(permutationsFP), SkSL::SampleUsage::Explicit());
658 this->registerChild(std::move(noiseFP), SkSL::SampleUsage::Explicit());
659 this->setUsesSampleCoordsDirectly();
660 }
661
GrPerlinNoise2Effect(const GrPerlinNoise2Effect & that)662 GrPerlinNoise2Effect(const GrPerlinNoise2Effect& that)
663 : INHERITED(kGrPerlinNoise2Effect_ClassID, kNone_OptimizationFlags)
664 , fType(that.fType)
665 , fNumOctaves(that.fNumOctaves)
666 , fStitchTiles(that.fStitchTiles)
667 , fPaintingData(new SkPerlinNoiseShaderImpl::PaintingData(*that.fPaintingData)) {
668 this->cloneAndRegisterAllChildProcessors(that);
669 this->setUsesSampleCoordsDirectly();
670 }
671
672
673 GR_DECLARE_FRAGMENT_PROCESSOR_TEST
674
675 SkPerlinNoiseShaderImpl::Type fType;
676 int fNumOctaves;
677 bool fStitchTiles;
678
679 std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> fPaintingData;
680
681 using INHERITED = GrFragmentProcessor;
682 };
683
684 /////////////////////////////////////////////////////////////////////
685 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrPerlinNoise2Effect);
686
687 #if GR_TEST_UTILS
TestCreate(GrProcessorTestData * d)688 std::unique_ptr<GrFragmentProcessor> GrPerlinNoise2Effect::TestCreate(GrProcessorTestData* d) {
689 int numOctaves = d->fRandom->nextRangeU(2, 10);
690 bool stitchTiles = d->fRandom->nextBool();
691 SkScalar seed = SkIntToScalar(d->fRandom->nextU());
692 SkISize tileSize;
693 tileSize.fWidth = d->fRandom->nextRangeU(4, 4096);
694 tileSize.fHeight = d->fRandom->nextRangeU(4, 4096);
695 SkScalar baseFrequencyX = d->fRandom->nextRangeScalar(0.01f, 0.99f);
696 SkScalar baseFrequencyY = d->fRandom->nextRangeScalar(0.01f, 0.99f);
697
698 sk_sp<SkShader> shader(d->fRandom->nextBool() ?
699 SkPerlinNoiseShader::MakeFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
700 stitchTiles ? &tileSize : nullptr) :
701 SkPerlinNoiseShader::MakeTurbulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
702 stitchTiles ? &tileSize : nullptr));
703
704 GrTest::TestAsFPArgs asFPArgs(d);
705 return as_SB(shader)->asFragmentProcessor(asFPArgs.args());
706 }
707 #endif
708
emitCode(EmitArgs & args)709 void GrGLPerlinNoise::emitCode(EmitArgs& args) {
710 const GrPerlinNoise2Effect& pne = args.fFp.cast<GrPerlinNoise2Effect>();
711
712 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
713 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
714
715 fBaseFrequencyUni = uniformHandler->addUniform(&pne, kFragment_GrShaderFlag, kHalf2_GrSLType,
716 "baseFrequency");
717 const char* baseFrequencyUni = uniformHandler->getUniformCStr(fBaseFrequencyUni);
718
719 const char* stitchDataUni = nullptr;
720 if (pne.stitchTiles()) {
721 fStitchDataUni = uniformHandler->addUniform(&pne, kFragment_GrShaderFlag, kHalf2_GrSLType,
722 "stitchData");
723 stitchDataUni = uniformHandler->getUniformCStr(fStitchDataUni);
724 }
725
726 // Add noise function
727 const GrShaderVar gPerlinNoiseArgs[] = {{"chanCoord", kHalf_GrSLType },
728 {"noiseVec ", kHalf2_GrSLType}};
729
730 const GrShaderVar gPerlinNoiseStitchArgs[] = {{"chanCoord" , kHalf_GrSLType },
731 {"noiseVec" , kHalf2_GrSLType},
732 {"stitchData", kHalf2_GrSLType}};
733
734 SkString noiseCode;
735
736 noiseCode.append(
737 R"(half4 floorVal;
738 floorVal.xy = floor(noiseVec);
739 floorVal.zw = floorVal.xy + half2(1);
740 half2 fractVal = fract(noiseVec);
741 // smooth curve : t^2*(3 - 2*t)
742 half2 noiseSmooth = fractVal*fractVal*(half2(3) - 2*fractVal);)");
743
744 // Adjust frequencies if we're stitching tiles
745 if (pne.stitchTiles()) {
746 noiseCode.append(
747 R"(if (floorVal.x >= stitchData.x) { floorVal.x -= stitchData.x; };
748 if (floorVal.y >= stitchData.y) { floorVal.y -= stitchData.y; };
749 if (floorVal.z >= stitchData.x) { floorVal.z -= stitchData.x; };
750 if (floorVal.w >= stitchData.y) { floorVal.w -= stitchData.y; };)");
751 }
752
753 // NOTE: We need to explicitly pass half4(1) as input color here, because the helper function
754 // can't see fInputColor (which is "_input" in the FP's outer function). skbug.com/10506
755 SkString sampleX = this->invokeChild(0, "half4(1)", args, "half2(floorVal.x, 0.5)");
756 SkString sampleY = this->invokeChild(0, "half4(1)", args, "half2(floorVal.z, 0.5)");
757 noiseCode.appendf("half2 latticeIdx = half2(%s.a, %s.a);", sampleX.c_str(), sampleY.c_str());
758
759 #if defined(SK_BUILD_FOR_ANDROID)
760 // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
761 // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
762 // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
763 // (or 0.484368 here). The following rounding operation prevents these precision issues from
764 // affecting the result of the noise by making sure that we only have multiples of 1/255.
765 // (Note that 1/255 is about 0.003921569, which is the value used here).
766 noiseCode.append(
767 "latticeIdx = floor(latticeIdx * half2(255.0) + half2(0.5)) * half2(0.003921569);");
768 #endif
769
770 // Get (x,y) coordinates with the permutated x
771 noiseCode.append("half4 bcoords = 256*latticeIdx.xyxy + floorVal.yyww;");
772
773 noiseCode.append("half2 uv;");
774
775 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
776 // [-1,1] vector and perform a dot product between that vector and the provided vector.
777 // Save it as a string because we will repeat it 4x.
778 static constexpr const char* inc8bit = "0.00390625"; // 1.0 / 256.0
779 SkString dotLattice =
780 SkStringPrintf("dot((lattice.ga + lattice.rb*%s)*2 - half2(1), fractVal)", inc8bit);
781
782 SkString sampleA = this->invokeChild(1, "half4(1)", args, "half2(bcoords.x, chanCoord)");
783 SkString sampleB = this->invokeChild(1, "half4(1)", args, "half2(bcoords.y, chanCoord)");
784 SkString sampleC = this->invokeChild(1, "half4(1)", args, "half2(bcoords.w, chanCoord)");
785 SkString sampleD = this->invokeChild(1, "half4(1)", args, "half2(bcoords.z, chanCoord)");
786
787 // Compute u, at offset (0,0)
788 noiseCode.appendf("half4 lattice = %s;", sampleA.c_str());
789 noiseCode.appendf("uv.x = %s;", dotLattice.c_str());
790
791 // Compute v, at offset (-1,0)
792 noiseCode.append("fractVal.x -= 1.0;");
793 noiseCode.appendf("lattice = %s;", sampleB.c_str());
794 noiseCode.appendf("uv.y = %s;", dotLattice.c_str());
795
796 // Compute 'a' as a linear interpolation of 'u' and 'v'
797 noiseCode.append("half2 ab;");
798 noiseCode.append("ab.x = mix(uv.x, uv.y, noiseSmooth.x);");
799
800 // Compute v, at offset (-1,-1)
801 noiseCode.append("fractVal.y -= 1.0;");
802 noiseCode.appendf("lattice = %s;", sampleC.c_str());
803 noiseCode.appendf("uv.y = %s;", dotLattice.c_str());
804
805 // Compute u, at offset (0,-1)
806 noiseCode.append("fractVal.x += 1.0;");
807 noiseCode.appendf("lattice = %s;", sampleD.c_str());
808 noiseCode.appendf("uv.x = %s;", dotLattice.c_str());
809
810 // Compute 'b' as a linear interpolation of 'u' and 'v'
811 noiseCode.append("ab.y = mix(uv.x, uv.y, noiseSmooth.x);");
812 // Compute the noise as a linear interpolation of 'a' and 'b'
813 noiseCode.append("return mix(ab.x, ab.y, noiseSmooth.y);");
814
815 SkString noiseFuncName = fragBuilder->getMangledFunctionName("noiseFuncName");
816 if (pne.stitchTiles()) {
817 fragBuilder->emitFunction(kHalf_GrSLType, noiseFuncName.c_str(),
818 {gPerlinNoiseStitchArgs, SK_ARRAY_COUNT(gPerlinNoiseStitchArgs)},
819 noiseCode.c_str());
820 } else {
821 fragBuilder->emitFunction(kHalf_GrSLType, noiseFuncName.c_str(),
822 {gPerlinNoiseArgs, SK_ARRAY_COUNT(gPerlinNoiseArgs)},
823 noiseCode.c_str());
824 }
825
826 // There are rounding errors if the floor operation is not performed here
827 fragBuilder->codeAppendf("half2 noiseVec = half2(floor(%s.xy) * %s);",
828 args.fSampleCoord, baseFrequencyUni);
829
830 // Clear the color accumulator
831 fragBuilder->codeAppendf("half4 color = half4(0);");
832
833 if (pne.stitchTiles()) {
834 // Set up TurbulenceInitial stitch values.
835 fragBuilder->codeAppendf("half2 stitchData = %s;", stitchDataUni);
836 }
837
838 fragBuilder->codeAppendf("half ratio = 1.0;");
839
840 // Loop over all octaves
841 fragBuilder->codeAppendf("for (int octave = 0; octave < %d; ++octave) {", pne.numOctaves());
842 fragBuilder->codeAppendf(" color += ");
843 if (pne.type() != SkPerlinNoiseShaderImpl::kFractalNoise_Type) {
844 fragBuilder->codeAppend("abs(");
845 }
846
847 // There are 4 lines, put y coords at center of each.
848 static constexpr const char* chanCoordR = "0.5";
849 static constexpr const char* chanCoordG = "1.5";
850 static constexpr const char* chanCoordB = "2.5";
851 static constexpr const char* chanCoordA = "3.5";
852 if (pne.stitchTiles()) {
853 fragBuilder->codeAppendf(R"(
854 half4(%s(%s, noiseVec, stitchData), %s(%s, noiseVec, stitchData),
855 %s(%s, noiseVec, stitchData), %s(%s, noiseVec, stitchData)))",
856 noiseFuncName.c_str(), chanCoordR,
857 noiseFuncName.c_str(), chanCoordG,
858 noiseFuncName.c_str(), chanCoordB,
859 noiseFuncName.c_str(), chanCoordA);
860 } else {
861 fragBuilder->codeAppendf(R"(
862 half4(%s(%s, noiseVec), %s(%s, noiseVec),
863 %s(%s, noiseVec), %s(%s, noiseVec)))",
864 noiseFuncName.c_str(), chanCoordR,
865 noiseFuncName.c_str(), chanCoordG,
866 noiseFuncName.c_str(), chanCoordB,
867 noiseFuncName.c_str(), chanCoordA);
868 }
869 if (pne.type() != SkPerlinNoiseShaderImpl::kFractalNoise_Type) {
870 fragBuilder->codeAppend(")"); // end of "abs("
871 }
872 fragBuilder->codeAppend(" * ratio;");
873
874 fragBuilder->codeAppend(R"(noiseVec *= half2(2.0);
875 ratio *= 0.5;)");
876
877 if (pne.stitchTiles()) {
878 fragBuilder->codeAppend("stitchData *= half2(2.0);");
879 }
880 fragBuilder->codeAppend("}"); // end of the for loop on octaves
881
882 if (pne.type() == SkPerlinNoiseShaderImpl::kFractalNoise_Type) {
883 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
884 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
885 fragBuilder->codeAppendf("color = color * half4(0.5) + half4(0.5);");
886 }
887
888 // Clamp values
889 fragBuilder->codeAppendf("color = saturate(color);");
890
891 // Pre-multiply the result
892 fragBuilder->codeAppendf("return half4(color.rgb * color.aaa, color.a);");
893 }
894
GenKey(const GrProcessor & processor,const GrShaderCaps &,GrProcessorKeyBuilder * b)895 void GrGLPerlinNoise::GenKey(const GrProcessor& processor, const GrShaderCaps&,
896 GrProcessorKeyBuilder* b) {
897 const GrPerlinNoise2Effect& turbulence = processor.cast<GrPerlinNoise2Effect>();
898
899 uint32_t key = turbulence.numOctaves();
900
901 key = key << 3; // Make room for next 3 bits
902
903 switch (turbulence.type()) {
904 case SkPerlinNoiseShaderImpl::kFractalNoise_Type:
905 key |= 0x1;
906 break;
907 case SkPerlinNoiseShaderImpl::kTurbulence_Type:
908 key |= 0x2;
909 break;
910 default:
911 // leave key at 0
912 break;
913 }
914
915 if (turbulence.stitchTiles()) {
916 key |= 0x4; // Flip the 3rd bit if tile stitching is on
917 }
918
919 b->add32(key);
920 }
921
onSetData(const GrGLSLProgramDataManager & pdman,const GrFragmentProcessor & processor)922 void GrGLPerlinNoise::onSetData(const GrGLSLProgramDataManager& pdman,
923 const GrFragmentProcessor& processor) {
924 INHERITED::onSetData(pdman, processor);
925
926 const GrPerlinNoise2Effect& turbulence = processor.cast<GrPerlinNoise2Effect>();
927
928 const SkVector& baseFrequency = turbulence.baseFrequency();
929 pdman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
930
931 if (turbulence.stitchTiles()) {
932 const SkPerlinNoiseShaderImpl::StitchData& stitchData = turbulence.stitchData();
933 pdman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
934 SkIntToScalar(stitchData.fHeight));
935 }
936 }
937
938 /////////////////////////////////////////////////////////////////////
939
asFragmentProcessor(const GrFPArgs & args) const940 std::unique_ptr<GrFragmentProcessor> SkPerlinNoiseShaderImpl::asFragmentProcessor(
941 const GrFPArgs& args) const {
942 SkASSERT(args.fContext);
943
944 const auto localMatrix = this->totalLocalMatrix(args.fPreLocalMatrix);
945 const auto paintMatrix = SkMatrix::Concat(args.fMatrixProvider.localToDevice(), *localMatrix);
946
947 // Either we don't stitch tiles, either we have a valid tile size
948 SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
949
950 std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> paintingData =
951 std::make_unique<SkPerlinNoiseShaderImpl::PaintingData>(fTileSize,
952 fSeed,
953 fBaseFrequencyX,
954 fBaseFrequencyY,
955 paintMatrix);
956
957 SkMatrix m = args.fMatrixProvider.localToDevice();
958 m.setTranslateX(-localMatrix->getTranslateX() + SK_Scalar1);
959 m.setTranslateY(-localMatrix->getTranslateY() + SK_Scalar1);
960
961 auto context = args.fContext;
962
963 if (0 == fNumOctaves) {
964 if (kFractalNoise_Type == fType) {
965 // Extract the incoming alpha and emit rgba = (a/4, a/4, a/4, a/2)
966 // TODO: Either treat the output of this shader as sRGB or allow client to specify a
967 // color space of the noise. Either way, this case (and the GLSL) need to convert to
968 // the destination.
969 auto inner = GrFragmentProcessor::ModulateRGBA(
970 /*child=*/nullptr, SkPMColor4f::FromBytes_RGBA(0x80404040));
971 return GrFragmentProcessor::MulChildByInputAlpha(std::move(inner));
972 }
973 // Emit zero.
974 return GrFragmentProcessor::MakeColor(SK_PMColor4fTRANSPARENT);
975 }
976
977 const SkBitmap& permutationsBitmap = paintingData->getPermutationsBitmap();
978 const SkBitmap& noiseBitmap = paintingData->getNoiseBitmap();
979
980 auto permutationsView = std::get<0>(GrMakeCachedBitmapProxyView(context, permutationsBitmap));
981 auto noiseView = std::get<0>(GrMakeCachedBitmapProxyView(context, noiseBitmap));
982
983 if (permutationsView && noiseView) {
984 auto inner = GrPerlinNoise2Effect::Make(fType,
985 fNumOctaves,
986 fStitchTiles,
987 std::move(paintingData),
988 std::move(permutationsView),
989 std::move(noiseView),
990 m,
991 *context->priv().caps());
992 return GrFragmentProcessor::MulChildByInputAlpha(std::move(inner));
993 }
994 return nullptr;
995 }
996
997 #endif
998
999 ///////////////////////////////////////////////////////////////////////////////////////////////////
1000
valid_input(SkScalar baseX,SkScalar baseY,int numOctaves,const SkISize * tileSize,SkScalar seed)1001 static bool valid_input(SkScalar baseX, SkScalar baseY, int numOctaves, const SkISize* tileSize,
1002 SkScalar seed) {
1003 if (!(baseX >= 0 && baseY >= 0)) {
1004 return false;
1005 }
1006 if (!(numOctaves >= 0 && numOctaves <= SkPerlinNoiseShaderImpl::kMaxOctaves)) {
1007 return false;
1008 }
1009 if (tileSize && !(tileSize->width() >= 0 && tileSize->height() >= 0)) {
1010 return false;
1011 }
1012 if (!SkScalarIsFinite(seed)) {
1013 return false;
1014 }
1015 return true;
1016 }
1017
MakeFractalNoise(SkScalar baseFrequencyX,SkScalar baseFrequencyY,int numOctaves,SkScalar seed,const SkISize * tileSize)1018 sk_sp<SkShader> SkPerlinNoiseShader::MakeFractalNoise(SkScalar baseFrequencyX,
1019 SkScalar baseFrequencyY,
1020 int numOctaves, SkScalar seed,
1021 const SkISize* tileSize) {
1022 if (!valid_input(baseFrequencyX, baseFrequencyY, numOctaves, tileSize, seed)) {
1023 return nullptr;
1024 }
1025 return sk_sp<SkShader>(new SkPerlinNoiseShaderImpl(SkPerlinNoiseShaderImpl::kFractalNoise_Type,
1026 baseFrequencyX, baseFrequencyY, numOctaves, seed,
1027 tileSize));
1028 }
1029
MakeTurbulence(SkScalar baseFrequencyX,SkScalar baseFrequencyY,int numOctaves,SkScalar seed,const SkISize * tileSize)1030 sk_sp<SkShader> SkPerlinNoiseShader::MakeTurbulence(SkScalar baseFrequencyX,
1031 SkScalar baseFrequencyY,
1032 int numOctaves, SkScalar seed,
1033 const SkISize* tileSize) {
1034 if (!valid_input(baseFrequencyX, baseFrequencyY, numOctaves, tileSize, seed)) {
1035 return nullptr;
1036 }
1037 return sk_sp<SkShader>(new SkPerlinNoiseShaderImpl(SkPerlinNoiseShaderImpl::kTurbulence_Type,
1038 baseFrequencyX, baseFrequencyY, numOctaves, seed,
1039 tileSize));
1040 }
1041
RegisterFlattenables()1042 void SkPerlinNoiseShader::RegisterFlattenables() {
1043 SK_REGISTER_FLATTENABLE(SkPerlinNoiseShaderImpl);
1044 }
1045