blob: 80163e582b0743df2bc90e45432e1fbfd6fae0f3 [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/gpu/gradients/GrGradientShader.h"
Michael Ludwig4f94ef62018-09-12 15:22:16 -04009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/gpu/gradients/generated/GrClampedGradientEffect.h"
11#include "src/gpu/gradients/generated/GrTiledGradientEffect.h"
Michael Ludwig4f94ef62018-09-12 15:22:16 -040012
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#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"
Michael Ludwig4089df82018-09-12 15:22:37 -040017
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#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"
Michael Ludwig4f94ef62018-09-12 15:22:16 -040023
Robert Phillipsb7bfbc22020-07-01 12:55:01 -040024#include "include/gpu/GrRecordingContext.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/gpu/GrCaps.h"
Greg Danielf91aeb22019-06-18 09:58:02 -040026#include "src/gpu/GrColor.h"
Brian Salomon4bc0c1f2019-09-30 15:12:27 -040027#include "src/gpu/GrColorInfo.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050028#include "src/gpu/GrRecordingContextPriv.h"
29#include "src/gpu/SkGr.h"
Brian Salomon17473752020-06-19 09:53:50 -040030#include "src/gpu/effects/GrTextureEffect.h"
Michael Ludwiga7914d32018-09-14 09:47:21 -040031
Michael Ludwig72535fb2018-09-28 11:53:32 -040032// Intervals smaller than this (that aren't hard stops) on low-precision-only devices force us to
33// use the textured gradient
34static const SkScalar kLowPrecisionIntervalLimit = 0.01f;
35
Michael Ludwiga7914d32018-09-14 09:47:21 -040036// Each cache entry costs 1K or 2K of RAM. Each bitmap will be 1x256 at either 32bpp or 64bpp.
37static const int kMaxNumCachedGradientBitmaps = 32;
38static const int kGradientTextureSize = 256;
39
40// NOTE: signature takes raw pointers to the color/pos arrays and a count to make it easy for
41// MakeColorizer to transparently take care of hard stops at the end points of the gradient.
Brian Osman021ed512018-10-16 15:19:44 -040042static std::unique_ptr<GrFragmentProcessor> make_textured_colorizer(const SkPMColor4f* colors,
Michael Ludwiga7914d32018-09-14 09:47:21 -040043 const SkScalar* positions, int count, bool premul, const GrFPArgs& args) {
44 static GrGradientBitmapCache gCache(kMaxNumCachedGradientBitmaps, kGradientTextureSize);
45
46 // Use 8888 or F16, depending on the destination config.
47 // TODO: Use 1010102 for opaque gradients, at least if destination is 1010102?
48 SkColorType colorType = kRGBA_8888_SkColorType;
Brian Salomon4bc0c1f2019-09-30 15:12:27 -040049 if (GrColorTypeIsWiderThan(args.fDstColorInfo->colorType(), 8)) {
Greg Daniel7bfc9132019-08-14 14:23:53 -040050 auto f16Format = args.fContext->priv().caps()->getDefaultBackendFormat(
51 GrColorType::kRGBA_F16, GrRenderable::kNo);
52 if (f16Format.isValid()) {
53 colorType = kRGBA_F16_SkColorType;
54 }
Michael Ludwiga7914d32018-09-14 09:47:21 -040055 }
56 SkAlphaType alphaType = premul ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
57
58 SkBitmap bitmap;
59 gCache.getGradient(colors, positions, count, colorType, alphaType, &bitmap);
60 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
61 SkASSERT(bitmap.isImmutable());
62
Greg Danielc52db712020-01-28 17:03:46 -050063 auto view = GrMakeCachedBitmapProxyView(args.fContext, bitmap);
64 if (!view.proxy()) {
Michael Ludwiga7914d32018-09-14 09:47:21 -040065 SkDebugf("Gradient won't draw. Could not create texture.");
66 return nullptr;
67 }
Brian Salomon17473752020-06-19 09:53:50 -040068 // TODO: When we start sampling colorizers with explicit coords rather than using sk_InColor
69 // the GrTextureEffect can simply be the colorizer.
70 auto m = SkMatrix::Scale(view.width(), 1.f);
71 auto te = GrTextureEffect::Make(std::move(view), alphaType, m, GrSamplerState::Filter::kBilerp);
72 return GrTextureGradientColorizer::Make(std::move(te));
Michael Ludwiga7914d32018-09-14 09:47:21 -040073}
Michael Ludwig4f94ef62018-09-12 15:22:16 -040074
75// Analyze the shader's color stops and positions and chooses an appropriate colorizer to represent
76// the gradient.
Brian Osman021ed512018-10-16 15:19:44 -040077static std::unique_ptr<GrFragmentProcessor> make_colorizer(const SkPMColor4f* colors,
Michael Ludwiga7914d32018-09-14 09:47:21 -040078 const SkScalar* positions, int count, bool premul, const GrFPArgs& args) {
Michael Ludwig4f94ef62018-09-12 15:22:16 -040079 // If there are hard stops at the beginning or end, the first and/or last color should be
80 // ignored by the colorizer since it should only be used in a clamped border color. By detecting
81 // and removing these stops at the beginning, it makes optimizing the remaining color stops
82 // simpler.
83
Michael Ludwig0495f7a2018-09-12 15:23:33 -040084 // SkGradientShaderBase guarantees that pos[0] == 0 by adding a dummy
85 bool bottomHardStop = SkScalarNearlyEqual(positions[0], positions[1]);
86 // The same is true for pos[end] == 1
Michael Ludwiga7914d32018-09-14 09:47:21 -040087 bool topHardStop = SkScalarNearlyEqual(positions[count - 2], positions[count - 1]);
Michael Ludwig4f94ef62018-09-12 15:22:16 -040088
89 int offset = 0;
Michael Ludwig4f94ef62018-09-12 15:22:16 -040090 if (bottomHardStop) {
91 offset += 1;
92 count--;
93 }
94 if (topHardStop) {
95 count--;
96 }
97
Michael Ludwig0495f7a2018-09-12 15:23:33 -040098 // Two remaining colors means a single interval from 0 to 1
99 // (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 -0400100 if (count == 2) {
101 return GrSingleIntervalGradientColorizer::Make(colors[offset], colors[offset + 1]);
102 }
103
Michael Ludwig72535fb2018-09-28 11:53:32 -0400104 // Do an early test for the texture fallback to skip all of the other tests for specific
105 // analytic support of the gradient (and compatibility with the hardware), when it's definitely
106 // impossible to use an analytic solution.
107 bool tryAnalyticColorizer = count <= GrUnrolledBinaryGradientColorizer::kMaxColorCount;
108
109 // The remaining analytic colorizers use scale*t+bias, and the scale/bias values can become
110 // quite large when thresholds are close (but still outside the hardstop limit). If float isn't
111 // 32-bit, output can be incorrect if the thresholds are too close together. However, the
112 // analytic shaders are higher quality, so they can be used with lower precision hardware when
113 // the thresholds are not ill-conditioned.
Robert Phillips9da87e02019-02-04 13:26:26 -0500114 const GrShaderCaps* caps = args.fContext->priv().caps()->shaderCaps();
Michael Ludwig72535fb2018-09-28 11:53:32 -0400115 if (!caps->floatIs32Bits() && tryAnalyticColorizer) {
116 // Could run into problems, check if thresholds are close together (with a limit of .01, so
117 // that scales will be less than 100, which leaves 4 decimals of precision on 16-bit).
118 for (int i = offset; i < count - 1; i++) {
119 SkScalar dt = SkScalarAbs(positions[i] - positions[i + 1]);
120 if (dt <= kLowPrecisionIntervalLimit && dt > SK_ScalarNearlyZero) {
121 tryAnalyticColorizer = false;
122 break;
123 }
124 }
125 }
126
127 if (tryAnalyticColorizer) {
128 if (count == 3) {
129 // Must be a dual interval gradient, where the middle point is at offset+1 and the two
130 // intervals share the middle color stop.
131 return GrDualIntervalGradientColorizer::Make(colors[offset], colors[offset + 1],
132 colors[offset + 1], colors[offset + 2],
133 positions[offset + 1]);
134 } else if (count == 4 && SkScalarNearlyEqual(positions[offset + 1],
135 positions[offset + 2])) {
136 // Two separate intervals that join at the same threshold position
137 return GrDualIntervalGradientColorizer::Make(colors[offset], colors[offset + 1],
138 colors[offset + 2], colors[offset + 3],
139 positions[offset + 1]);
140 }
141
142 // The single and dual intervals are a specialized case of the unrolled binary search
143 // colorizer which can analytically render gradients of up to 8 intervals (up to 9 or 16
144 // colors depending on how many hard stops are inserted).
145 std::unique_ptr<GrFragmentProcessor> unrolled = GrUnrolledBinaryGradientColorizer::Make(
146 colors + offset, positions + offset, count);
147 if (unrolled) {
148 return unrolled;
149 }
150 }
151
152 // Otherwise fall back to a rasterized gradient sampled by a texture, which can handle
153 // arbitrary gradients (the only downside being sampling resolution).
Michael Ludwiga7914d32018-09-14 09:47:21 -0400154 return make_textured_colorizer(colors + offset, positions + offset, count, premul, args);
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400155}
156
157// Combines the colorizer and layout with an appropriately configured master effect based on the
158// gradient's tile mode
159static std::unique_ptr<GrFragmentProcessor> make_gradient(const SkGradientShaderBase& shader,
160 const GrFPArgs& args, std::unique_ptr<GrFragmentProcessor> layout) {
161 // No shader is possible if a layout couldn't be created, e.g. a layout-specific Make() returned
162 // null.
163 if (layout == nullptr) {
164 return nullptr;
165 }
166
Brian Osman021ed512018-10-16 15:19:44 -0400167 // Convert all colors into destination space and into SkPMColor4fs, and handle
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400168 // premul issues depending on the interpolation mode
169 bool inputPremul = shader.getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag;
Michael Ludwigb96cba32018-09-14 13:59:24 -0400170 bool allOpaque = true;
Brian Osman021ed512018-10-16 15:19:44 -0400171 SkAutoSTMalloc<4, SkPMColor4f> colors(shader.fColorCount);
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400172 SkColor4fXformer xformedColors(shader.fOrigColors4f, shader.fColorCount,
Brian Salomon4bc0c1f2019-09-30 15:12:27 -0400173 shader.fColorSpace.get(), args.fDstColorInfo->colorSpace());
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400174 for (int i = 0; i < shader.fColorCount; i++) {
Brian Osman021ed512018-10-16 15:19:44 -0400175 const SkColor4f& upmColor = xformedColors.fColors[i];
176 colors[i] = inputPremul ? upmColor.premul()
177 : SkPMColor4f{ upmColor.fR, upmColor.fG, upmColor.fB, upmColor.fA };
178 if (allOpaque && !SkScalarNearlyEqual(colors[i].fA, 1.0)) {
Michael Ludwigb96cba32018-09-14 13:59:24 -0400179 allOpaque = false;
180 }
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400181 }
182
Michael Ludwig0495f7a2018-09-12 15:23:33 -0400183 // SkGradientShader stores positions implicitly when they are evenly spaced, but the getPos()
184 // implementation performs a branch for every position index. Since the shader conversion
185 // requires lots of position tests, calculate all of the positions up front if needed.
186 SkTArray<SkScalar, true> implicitPos;
187 SkScalar* positions;
188 if (shader.fOrigPos) {
189 positions = shader.fOrigPos;
190 } else {
191 implicitPos.reserve(shader.fColorCount);
Mike Kleind3ed3012018-11-06 19:23:08 -0500192 SkScalar posScale = SK_Scalar1 / (shader.fColorCount - 1);
Michael Ludwig0495f7a2018-09-12 15:23:33 -0400193 for (int i = 0 ; i < shader.fColorCount; i++) {
194 implicitPos.push_back(SkIntToScalar(i) * posScale);
195 }
196 positions = implicitPos.begin();
197 }
198
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400199 // All gradients are colorized the same way, regardless of layout
Michael Ludwiga7914d32018-09-14 09:47:21 -0400200 std::unique_ptr<GrFragmentProcessor> colorizer = make_colorizer(
201 colors.get(), positions, shader.fColorCount, inputPremul, args);
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400202 if (colorizer == nullptr) {
203 return nullptr;
204 }
205
Michael Ludwigb96cba32018-09-14 13:59:24 -0400206 // The master effect has to export premul colors, but under certain conditions it doesn't need
207 // to do anything to achieve that: i.e. its interpolating already premul colors (inputPremul)
208 // or all the colors have a = 1, in which case premul is a no op. Note that this allOpaque
209 // check is more permissive than SkGradientShaderBase's isOpaque(), since we can optimize away
210 // the make-premul op for two point conical gradients (which report false for isOpaque).
211 bool makePremul = !inputPremul && !allOpaque;
212
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400213 // All tile modes are supported (unless something was added to SkShader)
214 std::unique_ptr<GrFragmentProcessor> master;
215 switch(shader.getTileMode()) {
Mike Reedfae8fce2019-04-03 10:27:45 -0400216 case SkTileMode::kRepeat:
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400217 master = GrTiledGradientEffect::Make(std::move(colorizer), std::move(layout),
Michael Ludwigb96cba32018-09-14 13:59:24 -0400218 /* mirror */ false, makePremul, allOpaque);
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400219 break;
Mike Reedfae8fce2019-04-03 10:27:45 -0400220 case SkTileMode::kMirror:
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400221 master = GrTiledGradientEffect::Make(std::move(colorizer), std::move(layout),
Michael Ludwigb96cba32018-09-14 13:59:24 -0400222 /* mirror */ true, makePremul, allOpaque);
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400223 break;
Mike Reedfae8fce2019-04-03 10:27:45 -0400224 case SkTileMode::kClamp:
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400225 // For the clamped mode, the border colors are the first and last colors, corresponding
226 // to t=0 and t=1, because SkGradientShaderBase enforces that by adding color stops as
227 // appropriate. If there is a hard stop, this grabs the expected outer colors for the
228 // border.
229 master = GrClampedGradientEffect::Make(std::move(colorizer), std::move(layout),
Michael Ludwigb96cba32018-09-14 13:59:24 -0400230 colors[0], colors[shader.fColorCount - 1], makePremul, allOpaque);
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400231 break;
Mike Reedfae8fce2019-04-03 10:27:45 -0400232 case SkTileMode::kDecal:
Michael Ludwigb96cba32018-09-14 13:59:24 -0400233 // Even if the gradient colors are opaque, the decal borders are transparent so
234 // disable that optimization
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400235 master = GrClampedGradientEffect::Make(std::move(colorizer), std::move(layout),
Brian Osman021ed512018-10-16 15:19:44 -0400236 SK_PMColor4fTRANSPARENT, SK_PMColor4fTRANSPARENT,
Michael Ludwigb96cba32018-09-14 13:59:24 -0400237 makePremul, /* colorsAreOpaque */ false);
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400238 break;
239 }
240
241 if (master == nullptr) {
242 // Unexpected tile mode
243 return nullptr;
244 }
Brian Salomonc0d79e52019-04-10 15:02:11 -0400245 if (args.fInputColorIsOpaque) {
246 return GrFragmentProcessor::OverrideInput(std::move(master), SK_PMColor4fWHITE, false);
247 }
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400248 return GrFragmentProcessor::MulChildByInputAlpha(std::move(master));
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
Michael Ludwig4089df82018-09-12 15:22:37 -0400258std::unique_ptr<GrFragmentProcessor> MakeRadial(const SkRadialGradient& shader,
259 const GrFPArgs& args) {
260 return make_gradient(shader,args, GrRadialGradientLayout::Make(shader, args));
261}
262
Michael Ludwig24d438b2018-09-12 15:22:50 -0400263std::unique_ptr<GrFragmentProcessor> MakeSweep(const SkSweepGradient& shader,
264 const GrFPArgs& args) {
265 return make_gradient(shader,args, GrSweepGradientLayout::Make(shader, args));
266}
267
Michael Ludwig8f685082018-09-12 15:23:01 -0400268std::unique_ptr<GrFragmentProcessor> MakeConical(const SkTwoPointConicalGradient& shader,
269 const GrFPArgs& args) {
270 return make_gradient(shader, args, GrTwoPointConicalGradientLayout::Make(shader, args));
271}
272
Michael Ludwig7f8c5242018-09-14 15:07:55 -0400273#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 }
Mike Reedfae8fce2019-04-03 10:27:45 -0400307 fTileMode = static_cast<SkTileMode>(random->nextULessThan(kSkTileModeCount));
Michael Ludwig7f8c5242018-09-14 15:07:55 -0400308}
309#endif
310
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400311}