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