1 /*
2 * Copyright 2018 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 "src/gpu/gradients/GrGradientShader.h"
9
10 #include "src/gpu/gradients/generated/GrClampedGradientEffect.h"
11 #include "src/gpu/gradients/generated/GrTiledGradientEffect.h"
12
13 #include "src/gpu/gradients/generated/GrLinearGradientLayout.h"
14 #include "src/gpu/gradients/generated/GrRadialGradientLayout.h"
15 #include "src/gpu/gradients/generated/GrSweepGradientLayout.h"
16 #include "src/gpu/gradients/generated/GrTwoPointConicalGradientLayout.h"
17
18 #include "src/gpu/gradients/GrGradientBitmapCache.h"
19 #include "src/gpu/gradients/generated/GrDualIntervalGradientColorizer.h"
20 #include "src/gpu/gradients/generated/GrSingleIntervalGradientColorizer.h"
21 #include "src/gpu/gradients/generated/GrTextureGradientColorizer.h"
22 #include "src/gpu/gradients/generated/GrUnrolledBinaryGradientColorizer.h"
23
24 #include "include/private/GrRecordingContext.h"
25 #include "src/gpu/GrCaps.h"
26 #include "src/gpu/GrColor.h"
27 #include "src/gpu/GrColorSpaceInfo.h"
28 #include "src/gpu/GrRecordingContextPriv.h"
29 #include "src/gpu/SkGr.h"
30
31 // Intervals smaller than this (that aren't hard stops) on low-precision-only devices force us to
32 // use the textured gradient
33 static const SkScalar kLowPrecisionIntervalLimit = 0.01f;
34
35 // Each cache entry costs 1K or 2K of RAM. Each bitmap will be 1x256 at either 32bpp or 64bpp.
36 static const int kMaxNumCachedGradientBitmaps = 32;
37 static const int kGradientTextureSize = 256;
38
39 // NOTE: signature takes raw pointers to the color/pos arrays and a count to make it easy for
40 // MakeColorizer to transparently take care of hard stops at the end points of the gradient.
make_textured_colorizer(const SkPMColor4f * colors,const SkScalar * positions,int count,bool premul,const GrFPArgs & args)41 static std::unique_ptr<GrFragmentProcessor> make_textured_colorizer(const SkPMColor4f* colors,
42 const SkScalar* positions, int count, bool premul, const GrFPArgs& args) {
43 static GrGradientBitmapCache gCache(kMaxNumCachedGradientBitmaps, kGradientTextureSize);
44
45 // Use 8888 or F16, depending on the destination config.
46 // TODO: Use 1010102 for opaque gradients, at least if destination is 1010102?
47 SkColorType colorType = kRGBA_8888_SkColorType;
48 if (GrColorTypeIsWiderThan(args.fDstColorSpaceInfo->colorType(), 8)) {
49 auto f16Format = args.fContext->priv().caps()->getDefaultBackendFormat(
50 GrColorType::kRGBA_F16, GrRenderable::kNo);
51 if (f16Format.isValid()) {
52 colorType = kRGBA_F16_SkColorType;
53 }
54 }
55 SkAlphaType alphaType = premul ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
56
57 SkBitmap bitmap;
58 gCache.getGradient(colors, positions, count, colorType, alphaType, &bitmap);
59 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
60 SkASSERT(bitmap.isImmutable());
61
62 sk_sp<GrTextureProxy> proxy = GrMakeCachedBitmapProxy(
63 args.fContext->priv().proxyProvider(), bitmap);
64 if (proxy == nullptr) {
65 SkDebugf("Gradient won't draw. Could not create texture.");
66 return nullptr;
67 }
68
69 return GrTextureGradientColorizer::Make(std::move(proxy));
70 }
71
72 // Analyze the shader's color stops and positions and chooses an appropriate colorizer to represent
73 // the gradient.
make_colorizer(const SkPMColor4f * colors,const SkScalar * positions,int count,bool premul,const GrFPArgs & args)74 static std::unique_ptr<GrFragmentProcessor> make_colorizer(const SkPMColor4f* colors,
75 const SkScalar* positions, int count, bool premul, const GrFPArgs& args) {
76 // If there are hard stops at the beginning or end, the first and/or last color should be
77 // ignored by the colorizer since it should only be used in a clamped border color. By detecting
78 // and removing these stops at the beginning, it makes optimizing the remaining color stops
79 // simpler.
80
81 // SkGradientShaderBase guarantees that pos[0] == 0 by adding a dummy
82 bool bottomHardStop = SkScalarNearlyEqual(positions[0], positions[1]);
83 // The same is true for pos[end] == 1
84 bool topHardStop = SkScalarNearlyEqual(positions[count - 2], positions[count - 1]);
85
86 int offset = 0;
87 if (bottomHardStop) {
88 offset += 1;
89 count--;
90 }
91 if (topHardStop) {
92 count--;
93 }
94
95 // Two remaining colors means a single interval from 0 to 1
96 // (but it may have originally been a 3 or 4 color gradient with 1-2 hard stops at the ends)
97 if (count == 2) {
98 return GrSingleIntervalGradientColorizer::Make(colors[offset], colors[offset + 1]);
99 }
100
101 // Do an early test for the texture fallback to skip all of the other tests for specific
102 // analytic support of the gradient (and compatibility with the hardware), when it's definitely
103 // impossible to use an analytic solution.
104 bool tryAnalyticColorizer = count <= GrUnrolledBinaryGradientColorizer::kMaxColorCount;
105
106 // The remaining analytic colorizers use scale*t+bias, and the scale/bias values can become
107 // quite large when thresholds are close (but still outside the hardstop limit). If float isn't
108 // 32-bit, output can be incorrect if the thresholds are too close together. However, the
109 // analytic shaders are higher quality, so they can be used with lower precision hardware when
110 // the thresholds are not ill-conditioned.
111 const GrShaderCaps* caps = args.fContext->priv().caps()->shaderCaps();
112 if (!caps->floatIs32Bits() && tryAnalyticColorizer) {
113 // Could run into problems, check if thresholds are close together (with a limit of .01, so
114 // that scales will be less than 100, which leaves 4 decimals of precision on 16-bit).
115 for (int i = offset; i < count - 1; i++) {
116 SkScalar dt = SkScalarAbs(positions[i] - positions[i + 1]);
117 if (dt <= kLowPrecisionIntervalLimit && dt > SK_ScalarNearlyZero) {
118 tryAnalyticColorizer = false;
119 break;
120 }
121 }
122 }
123
124 if (tryAnalyticColorizer) {
125 if (count == 3) {
126 // Must be a dual interval gradient, where the middle point is at offset+1 and the two
127 // intervals share the middle color stop.
128 return GrDualIntervalGradientColorizer::Make(colors[offset], colors[offset + 1],
129 colors[offset + 1], colors[offset + 2],
130 positions[offset + 1]);
131 } else if (count == 4 && SkScalarNearlyEqual(positions[offset + 1],
132 positions[offset + 2])) {
133 // Two separate intervals that join at the same threshold position
134 return GrDualIntervalGradientColorizer::Make(colors[offset], colors[offset + 1],
135 colors[offset + 2], colors[offset + 3],
136 positions[offset + 1]);
137 }
138
139 // The single and dual intervals are a specialized case of the unrolled binary search
140 // colorizer which can analytically render gradients of up to 8 intervals (up to 9 or 16
141 // colors depending on how many hard stops are inserted).
142 std::unique_ptr<GrFragmentProcessor> unrolled = GrUnrolledBinaryGradientColorizer::Make(
143 colors + offset, positions + offset, count);
144 if (unrolled) {
145 return unrolled;
146 }
147 }
148
149 // Otherwise fall back to a rasterized gradient sampled by a texture, which can handle
150 // arbitrary gradients (the only downside being sampling resolution).
151 return make_textured_colorizer(colors + offset, positions + offset, count, premul, args);
152 }
153
154 // Combines the colorizer and layout with an appropriately configured master effect based on the
155 // gradient's tile mode
make_gradient(const SkGradientShaderBase & shader,const GrFPArgs & args,std::unique_ptr<GrFragmentProcessor> layout)156 static std::unique_ptr<GrFragmentProcessor> make_gradient(const SkGradientShaderBase& shader,
157 const GrFPArgs& args, std::unique_ptr<GrFragmentProcessor> layout) {
158 // No shader is possible if a layout couldn't be created, e.g. a layout-specific Make() returned
159 // null.
160 if (layout == nullptr) {
161 return nullptr;
162 }
163
164 // Convert all colors into destination space and into SkPMColor4fs, and handle
165 // premul issues depending on the interpolation mode
166 bool inputPremul = shader.getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag;
167 bool allOpaque = true;
168 SkAutoSTMalloc<4, SkPMColor4f> colors(shader.fColorCount);
169 SkColor4fXformer xformedColors(shader.fOrigColors4f, shader.fColorCount,
170 shader.fColorSpace.get(), args.fDstColorSpaceInfo->colorSpace());
171 for (int i = 0; i < shader.fColorCount; i++) {
172 const SkColor4f& upmColor = xformedColors.fColors[i];
173 colors[i] = inputPremul ? upmColor.premul()
174 : SkPMColor4f{ upmColor.fR, upmColor.fG, upmColor.fB, upmColor.fA };
175 if (allOpaque && !SkScalarNearlyEqual(colors[i].fA, 1.0)) {
176 allOpaque = false;
177 }
178 }
179
180 // SkGradientShader stores positions implicitly when they are evenly spaced, but the getPos()
181 // implementation performs a branch for every position index. Since the shader conversion
182 // requires lots of position tests, calculate all of the positions up front if needed.
183 SkTArray<SkScalar, true> implicitPos;
184 SkScalar* positions;
185 if (shader.fOrigPos) {
186 positions = shader.fOrigPos;
187 } else {
188 implicitPos.reserve(shader.fColorCount);
189 SkScalar posScale = SK_Scalar1 / (shader.fColorCount - 1);
190 for (int i = 0 ; i < shader.fColorCount; i++) {
191 implicitPos.push_back(SkIntToScalar(i) * posScale);
192 }
193 positions = implicitPos.begin();
194 }
195
196 // All gradients are colorized the same way, regardless of layout
197 std::unique_ptr<GrFragmentProcessor> colorizer = make_colorizer(
198 colors.get(), positions, shader.fColorCount, inputPremul, args);
199 if (colorizer == nullptr) {
200 return nullptr;
201 }
202
203 // The master effect has to export premul colors, but under certain conditions it doesn't need
204 // to do anything to achieve that: i.e. its interpolating already premul colors (inputPremul)
205 // or all the colors have a = 1, in which case premul is a no op. Note that this allOpaque
206 // check is more permissive than SkGradientShaderBase's isOpaque(), since we can optimize away
207 // the make-premul op for two point conical gradients (which report false for isOpaque).
208 bool makePremul = !inputPremul && !allOpaque;
209
210 // All tile modes are supported (unless something was added to SkShader)
211 std::unique_ptr<GrFragmentProcessor> master;
212 switch(shader.getTileMode()) {
213 case SkTileMode::kRepeat:
214 master = GrTiledGradientEffect::Make(std::move(colorizer), std::move(layout),
215 /* mirror */ false, makePremul, allOpaque);
216 break;
217 case SkTileMode::kMirror:
218 master = GrTiledGradientEffect::Make(std::move(colorizer), std::move(layout),
219 /* mirror */ true, makePremul, allOpaque);
220 break;
221 case SkTileMode::kClamp:
222 // For the clamped mode, the border colors are the first and last colors, corresponding
223 // to t=0 and t=1, because SkGradientShaderBase enforces that by adding color stops as
224 // appropriate. If there is a hard stop, this grabs the expected outer colors for the
225 // border.
226 master = GrClampedGradientEffect::Make(std::move(colorizer), std::move(layout),
227 colors[0], colors[shader.fColorCount - 1], makePremul, allOpaque);
228 break;
229 case SkTileMode::kDecal:
230 // Even if the gradient colors are opaque, the decal borders are transparent so
231 // disable that optimization
232 master = GrClampedGradientEffect::Make(std::move(colorizer), std::move(layout),
233 SK_PMColor4fTRANSPARENT, SK_PMColor4fTRANSPARENT,
234 makePremul, /* colorsAreOpaque */ false);
235 break;
236 }
237
238 if (master == nullptr) {
239 // Unexpected tile mode
240 return nullptr;
241 }
242 if (args.fInputColorIsOpaque) {
243 return GrFragmentProcessor::OverrideInput(std::move(master), SK_PMColor4fWHITE, false);
244 }
245 return GrFragmentProcessor::MulChildByInputAlpha(std::move(master));
246 }
247
248 namespace GrGradientShader {
249
MakeLinear(const SkLinearGradient & shader,const GrFPArgs & args)250 std::unique_ptr<GrFragmentProcessor> MakeLinear(const SkLinearGradient& shader,
251 const GrFPArgs& args) {
252 return make_gradient(shader, args, GrLinearGradientLayout::Make(shader, args));
253 }
254
MakeRadial(const SkRadialGradient & shader,const GrFPArgs & args)255 std::unique_ptr<GrFragmentProcessor> MakeRadial(const SkRadialGradient& shader,
256 const GrFPArgs& args) {
257 return make_gradient(shader,args, GrRadialGradientLayout::Make(shader, args));
258 }
259
MakeSweep(const SkSweepGradient & shader,const GrFPArgs & args)260 std::unique_ptr<GrFragmentProcessor> MakeSweep(const SkSweepGradient& shader,
261 const GrFPArgs& args) {
262 return make_gradient(shader,args, GrSweepGradientLayout::Make(shader, args));
263 }
264
MakeConical(const SkTwoPointConicalGradient & shader,const GrFPArgs & args)265 std::unique_ptr<GrFragmentProcessor> MakeConical(const SkTwoPointConicalGradient& shader,
266 const GrFPArgs& args) {
267 return make_gradient(shader, args, GrTwoPointConicalGradientLayout::Make(shader, args));
268 }
269
270 #if GR_TEST_UTILS
RandomParams(SkRandom * random)271 RandomParams::RandomParams(SkRandom* random) {
272 // Set color count to min of 2 so that we don't trigger the const color optimization and make
273 // a non-gradient processor.
274 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
275 fUseColors4f = random->nextBool();
276
277 // if one color, omit stops, otherwise randomly decide whether or not to
278 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
279 fStops = nullptr;
280 } else {
281 fStops = fStopStorage;
282 }
283
284 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
285 if (fUseColors4f) {
286 fColorSpace = GrTest::TestColorSpace(random);
287 }
288
289 SkScalar stop = 0.f;
290 for (int i = 0; i < fColorCount; ++i) {
291 if (fUseColors4f) {
292 fColors4f[i].fR = random->nextUScalar1();
293 fColors4f[i].fG = random->nextUScalar1();
294 fColors4f[i].fB = random->nextUScalar1();
295 fColors4f[i].fA = random->nextUScalar1();
296 } else {
297 fColors[i] = random->nextU();
298 }
299 if (fStops) {
300 fStops[i] = stop;
301 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
302 }
303 }
304 fTileMode = static_cast<SkTileMode>(random->nextULessThan(kSkTileModeCount));
305 }
306 #endif
307
308 }
309