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/GrUnrolledBinaryGradientColorizer.h"
22
23#include "include/gpu/GrRecordingContext.h"
24#include "src/gpu/GrCaps.h"
25#include "src/gpu/GrColor.h"
26#include "src/gpu/GrColorInfo.h"
27#include "src/gpu/GrRecordingContextPriv.h"
28#include "src/gpu/SkGr.h"
29#include "src/gpu/effects/GrTextureEffect.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
33static 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.
36static const int kMaxNumCachedGradientBitmaps = 32;
37static 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.
41static 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.fDstColorInfo->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 auto view = GrMakeCachedBitmapProxyView(args.fContext, bitmap);
63 if (!view.proxy()) {
64 SkDebugf("Gradient won't draw. Could not create texture.");
65 return nullptr;
66 }
67
68 auto m = SkMatrix::Scale(view.width(), 1.f);
69 return GrTextureEffect::Make(std::move(view), alphaType, m, GrSamplerState::Filter::kLinear);
70}
71
72// Analyze the shader's color stops and positions and chooses an appropriate colorizer to represent
73// the gradient.
74static 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 top-level effect based on the
155// gradient's tile mode
156static 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.fDstColorInfo->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 top-level effect has to export premul colors, but under certain conditions it doesn't
204 // need to do anything to achieve that: i.e. its interpolating already premul colors
205 // (inputPremul) or all the colors have a = 1, in which case premul is a no op. Note that this
206 // allOpaque check is more permissive than SkGradientShaderBase's isOpaque(), since we can
207 // optimize away the make-premul op for two point conical gradients (which report false for
208 // isOpaque).
209 bool makePremul = !inputPremul && !allOpaque;
210
211 // All tile modes are supported (unless something was added to SkShader)
212 std::unique_ptr<GrFragmentProcessor> gradient;
213 switch(shader.getTileMode()) {
214 case SkTileMode::kRepeat:
215 gradient = GrTiledGradientEffect::Make(std::move(colorizer), std::move(layout),
216 /* mirror */ false, makePremul, allOpaque);
217 break;
218 case SkTileMode::kMirror:
219 gradient = GrTiledGradientEffect::Make(std::move(colorizer), std::move(layout),
220 /* mirror */ true, makePremul, allOpaque);
221 break;
222 case SkTileMode::kClamp:
223 // For the clamped mode, the border colors are the first and last colors, corresponding
224 // to t=0 and t=1, because SkGradientShaderBase enforces that by adding color stops as
225 // appropriate. If there is a hard stop, this grabs the expected outer colors for the
226 // border.
227 gradient = GrClampedGradientEffect::Make(std::move(colorizer), std::move(layout),
228 colors[0], colors[shader.fColorCount - 1],
229 makePremul, allOpaque);
230 break;
231 case SkTileMode::kDecal:
232 // Even if the gradient colors are opaque, the decal borders are transparent so
233 // disable that optimization
234 gradient = GrClampedGradientEffect::Make(std::move(colorizer), std::move(layout),
235 SK_PMColor4fTRANSPARENT,
236 SK_PMColor4fTRANSPARENT,
237 makePremul, /* colorsAreOpaque */ false);
238 break;
239 }
240
241 if (gradient == nullptr) {
242 // Unexpected tile mode
243 return nullptr;
244 }
245 if (args.fInputColorIsOpaque) {
246 return GrFragmentProcessor::OverrideInput(std::move(gradient), SK_PMColor4fWHITE, false);
247 }
248 return GrFragmentProcessor::MulChildByInputAlpha(std::move(gradient));
249}
250
251namespace GrGradientShader {
252
253std::unique_ptr<GrFragmentProcessor> MakeLinear(const SkLinearGradient& shader,
254 const GrFPArgs& args) {
255 return make_gradient(shader, args, GrLinearGradientLayout::Make(shader, args));
256}
257
258std::unique_ptr<GrFragmentProcessor> MakeRadial(const SkRadialGradient& shader,
259 const GrFPArgs& args) {
260 return make_gradient(shader,args, GrRadialGradientLayout::Make(shader, args));
261}
262
263std::unique_ptr<GrFragmentProcessor> MakeSweep(const SkSweepGradient& shader,
264 const GrFPArgs& args) {
265 return make_gradient(shader,args, GrSweepGradientLayout::Make(shader, args));
266}
267
268std::unique_ptr<GrFragmentProcessor> MakeConical(const SkTwoPointConicalGradient& shader,
269 const GrFPArgs& args) {
270 return make_gradient(shader, args, GrTwoPointConicalGradientLayout::Make(shader, args));
271}
272
273#if GR_TEST_UTILS
274RandomParams::RandomParams(SkRandom* random) {
275 // Set color count to min of 2 so that we don't trigger the const color optimization and make
276 // a non-gradient processor.
277 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
278 fUseColors4f = random->nextBool();
279
280 // if one color, omit stops, otherwise randomly decide whether or not to
281 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
282 fStops = nullptr;
283 } else {
284 fStops = fStopStorage;
285 }
286
287 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
288 if (fUseColors4f) {
289 fColorSpace = GrTest::TestColorSpace(random);
290 }
291
292 SkScalar stop = 0.f;
293 for (int i = 0; i < fColorCount; ++i) {
294 if (fUseColors4f) {
295 fColors4f[i].fR = random->nextUScalar1();
296 fColors4f[i].fG = random->nextUScalar1();
297 fColors4f[i].fB = random->nextUScalar1();
298 fColors4f[i].fA = random->nextUScalar1();
299 } else {
300 fColors[i] = random->nextU();
301 }
302 if (fStops) {
303 fStops[i] = stop;
304 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
305 }
306 }
307 fTileMode = static_cast<SkTileMode>(random->nextULessThan(kSkTileModeCount));
308}
309#endif
310
311} // namespace GrGradientShader
312