blob: 05ba798fe96f34490a0f6c1532a8ccb63cc1a0b0 [file] [log] [blame]
rileya@google.com589708b2012-07-26 20:04:23 +00001/*
2 * Copyright 2006 The Android Open Source Project
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
Herb Derby4de13042017-05-15 10:49:39 -04008#include <algorithm>
fmalitabc590c02016-02-22 09:12:33 -08009#include "Sk4fLinearGradient.h"
raftias94888332016-10-18 10:02:51 -070010#include "SkColorSpace_XYZ.h"
Florin Malita39d71de2017-10-31 11:33:49 -040011#include "SkColorSpaceXformer.h"
Florin Malitacad3b8c2017-10-28 21:42:50 -040012#include "SkFloatBits.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040013#include "SkGradientBitmapCache.h"
rileya@google.com589708b2012-07-26 20:04:23 +000014#include "SkGradientShaderPriv.h"
brianosmand4546092016-09-22 12:31:58 -070015#include "SkHalf.h"
rileya@google.com589708b2012-07-26 20:04:23 +000016#include "SkLinearGradient.h"
Mike Reed6b3155c2017-04-03 14:41:44 -040017#include "SkMallocPixelRef.h"
rileya@google.com589708b2012-07-26 20:04:23 +000018#include "SkRadialGradient.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040019#include "SkReadBuffer.h"
Mike Klein02ab8cc2017-05-04 22:41:05 +000020#include "SkSweepGradient.h"
Mike Kleina3771842017-05-04 19:38:48 -040021#include "SkTwoPointConicalGradient.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040022#include "SkWriteBuffer.h"
Herb Derby4de13042017-05-15 10:49:39 -040023#include "../../jumper/SkJumper.h"
24
rileya@google.com589708b2012-07-26 20:04:23 +000025
brianosmane25d71c2016-09-28 11:27:28 -070026enum GradientSerializationFlags {
27 // Bits 29:31 used for various boolean flags
28 kHasPosition_GSF = 0x80000000,
29 kHasLocalMatrix_GSF = 0x40000000,
30 kHasColorSpace_GSF = 0x20000000,
31
32 // Bits 12:28 unused
33
34 // Bits 8:11 for fTileMode
35 kTileModeShift_GSF = 8,
36 kTileModeMask_GSF = 0xF,
37
38 // Bits 0:7 for fGradFlags (note that kForce4fContext_PrivateFlag is 0x80)
39 kGradFlagsShift_GSF = 0,
40 kGradFlagsMask_GSF = 0xFF,
41};
42
reed9fa60da2014-08-21 07:59:51 -070043void SkGradientShaderBase::Descriptor::flatten(SkWriteBuffer& buffer) const {
brianosmane25d71c2016-09-28 11:27:28 -070044 uint32_t flags = 0;
reed9fa60da2014-08-21 07:59:51 -070045 if (fPos) {
brianosmane25d71c2016-09-28 11:27:28 -070046 flags |= kHasPosition_GSF;
reed9fa60da2014-08-21 07:59:51 -070047 }
reed9fa60da2014-08-21 07:59:51 -070048 if (fLocalMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -070049 flags |= kHasLocalMatrix_GSF;
50 }
51 sk_sp<SkData> colorSpaceData = fColorSpace ? fColorSpace->serialize() : nullptr;
52 if (colorSpaceData) {
53 flags |= kHasColorSpace_GSF;
54 }
55 SkASSERT(static_cast<uint32_t>(fTileMode) <= kTileModeMask_GSF);
56 flags |= (fTileMode << kTileModeShift_GSF);
57 SkASSERT(fGradFlags <= kGradFlagsMask_GSF);
58 flags |= (fGradFlags << kGradFlagsShift_GSF);
59
60 buffer.writeUInt(flags);
61
62 buffer.writeColor4fArray(fColors, fCount);
63 if (colorSpaceData) {
64 buffer.writeDataAsByteArray(colorSpaceData.get());
65 }
66 if (fPos) {
67 buffer.writeScalarArray(fPos, fCount);
68 }
69 if (fLocalMatrix) {
reed9fa60da2014-08-21 07:59:51 -070070 buffer.writeMatrix(*fLocalMatrix);
reed9fa60da2014-08-21 07:59:51 -070071 }
72}
73
74bool SkGradientShaderBase::DescriptorScope::unflatten(SkReadBuffer& buffer) {
Mike Reed70bc94f2017-06-08 12:45:52 -040075 // New gradient format. Includes floating point color, color space, densely packed flags
76 uint32_t flags = buffer.readUInt();
reed9fa60da2014-08-21 07:59:51 -070077
Mike Reed70bc94f2017-06-08 12:45:52 -040078 fTileMode = (SkShader::TileMode)((flags >> kTileModeShift_GSF) & kTileModeMask_GSF);
79 fGradFlags = (flags >> kGradFlagsShift_GSF) & kGradFlagsMask_GSF;
reed9fa60da2014-08-21 07:59:51 -070080
Mike Reed70bc94f2017-06-08 12:45:52 -040081 fCount = buffer.getArrayCount();
82 if (fCount > kStorageCount) {
83 size_t allocSize = (sizeof(SkColor4f) + sizeof(SkScalar)) * fCount;
84 fDynamicStorage.reset(allocSize);
85 fColors = (SkColor4f*)fDynamicStorage.get();
86 fPos = (SkScalar*)(fColors + fCount);
87 } else {
88 fColors = fColorStorage;
89 fPos = fPosStorage;
90 }
91 if (!buffer.readColor4fArray(mutableColors(), fCount)) {
92 return false;
93 }
94 if (SkToBool(flags & kHasColorSpace_GSF)) {
95 sk_sp<SkData> data = buffer.readByteArrayAsData();
96 fColorSpace = SkColorSpace::Deserialize(data->data(), data->size());
97 } else {
brianosmane25d71c2016-09-28 11:27:28 -070098 fColorSpace = nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -040099 }
100 if (SkToBool(flags & kHasPosition_GSF)) {
101 if (!buffer.readScalarArray(mutablePos(), fCount)) {
102 return false;
brianosmane25d71c2016-09-28 11:27:28 -0700103 }
reed9fa60da2014-08-21 07:59:51 -0700104 } else {
Mike Reed70bc94f2017-06-08 12:45:52 -0400105 fPos = nullptr;
106 }
107 if (SkToBool(flags & kHasLocalMatrix_GSF)) {
108 fLocalMatrix = &fLocalMatrixStorage;
109 buffer.readMatrix(&fLocalMatrixStorage);
110 } else {
111 fLocalMatrix = nullptr;
reed9fa60da2014-08-21 07:59:51 -0700112 }
113 return buffer.isValid();
114}
115
116////////////////////////////////////////////////////////////////////////////////////////////
117
mtkleincc695fe2014-12-10 10:29:19 -0800118SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc, const SkMatrix& ptsToUnit)
reedaddf2ed2014-08-11 08:28:24 -0700119 : INHERITED(desc.fLocalMatrix)
mtkleincc695fe2014-12-10 10:29:19 -0800120 , fPtsToUnit(ptsToUnit)
Florin Malita39d71de2017-10-31 11:33:49 -0400121 , fColorsAreOpaque(true)
commit-bot@chromium.org9c9005a2014-04-28 14:55:39 +0000122{
mtkleincc695fe2014-12-10 10:29:19 -0800123 fPtsToUnit.getType(); // Precache so reads are threadsafe.
reed@google.com437d6eb2013-05-23 19:03:05 +0000124 SkASSERT(desc.fCount > 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000125
fmalita6d7e4e82016-09-20 06:55:16 -0700126 fGradFlags = static_cast<uint8_t>(desc.fGradFlags);
rileya@google.com589708b2012-07-26 20:04:23 +0000127
reed@google.com437d6eb2013-05-23 19:03:05 +0000128 SkASSERT((unsigned)desc.fTileMode < SkShader::kTileModeCount);
reed@google.com437d6eb2013-05-23 19:03:05 +0000129 fTileMode = desc.fTileMode;
rileya@google.com589708b2012-07-26 20:04:23 +0000130
rileya@google.com589708b2012-07-26 20:04:23 +0000131 /* Note: we let the caller skip the first and/or last position.
132 i.e. pos[0] = 0.3, pos[1] = 0.7
133 In these cases, we insert dummy entries to ensure that the final data
134 will be bracketed by [0, 1].
135 i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
136
137 Thus colorCount (the caller's value, and fColorCount (our value) may
138 differ by up to 2. In the above example:
139 colorCount = 2
140 fColorCount = 4
141 */
reed@google.com437d6eb2013-05-23 19:03:05 +0000142 fColorCount = desc.fCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000143 // check if we need to add in dummy start and/or end position/colors
144 bool dummyFirst = false;
145 bool dummyLast = false;
reed@google.com437d6eb2013-05-23 19:03:05 +0000146 if (desc.fPos) {
147 dummyFirst = desc.fPos[0] != 0;
148 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
rileya@google.com589708b2012-07-26 20:04:23 +0000149 fColorCount += dummyFirst + dummyLast;
150 }
151
Mike Reeddfc0e912018-02-16 12:40:18 -0500152 bool decal_mode = (desc.fTileMode == SkShader::kDecal_TileMode);
153 bool need_pos = (desc.fPos != nullptr);
154 if (decal_mode) {
155 fColorCount += 2; // extra first and last stops
156 need_pos = true;
157 }
158
159 size_t storageSize = fColorCount * (sizeof(SkColor4f) + (need_pos ? sizeof(SkScalar) : 0));
Florin Malita89ab2402017-11-01 10:14:57 -0400160 fOrigColors4f = reinterpret_cast<SkColor4f*>(fStorage.reset(storageSize));
Mike Reeddfc0e912018-02-16 12:40:18 -0500161 fOrigPos = need_pos ? reinterpret_cast<SkScalar*>(fOrigColors4f + fColorCount)
162 : nullptr;
163
164 SkASSERT(need_pos == (fOrigPos != nullptr));
rileya@google.com589708b2012-07-26 20:04:23 +0000165
brianosmane25d71c2016-09-28 11:27:28 -0700166 // Now copy over the colors, adding the dummies as needed
167 SkColor4f* origColors = fOrigColors4f;
Mike Reeddfc0e912018-02-16 12:40:18 -0500168 if (decal_mode) {
169 *origColors++ = { 0, 0, 0, 0 };
170 }
brianosmane25d71c2016-09-28 11:27:28 -0700171 if (dummyFirst) {
172 *origColors++ = desc.fColors[0];
173 }
Florin Malita39d71de2017-10-31 11:33:49 -0400174 for (int i = 0; i < desc.fCount; ++i) {
Mike Reeddfc0e912018-02-16 12:40:18 -0500175 *origColors++ = desc.fColors[i];
Florin Malita39d71de2017-10-31 11:33:49 -0400176 fColorsAreOpaque = fColorsAreOpaque && (desc.fColors[i].fA == 1);
177 }
brianosmane25d71c2016-09-28 11:27:28 -0700178 if (dummyLast) {
Mike Reeddfc0e912018-02-16 12:40:18 -0500179 *origColors++ = desc.fColors[desc.fCount - 1];
brianosmane25d71c2016-09-28 11:27:28 -0700180 }
Mike Reeddfc0e912018-02-16 12:40:18 -0500181 if (decal_mode) {
182 *origColors++ = { 0, 0, 0, 0 };
183 fColorsAreOpaque = false;
184 }
185 SkASSERT(fColorCount == (origColors - fOrigColors4f));
brianosmanb9c51372016-09-15 11:09:45 -0700186
brianosmane25d71c2016-09-28 11:27:28 -0700187 if (!desc.fColorSpace) {
188 // This happens if we were constructed from SkColors, so our colors are really sRGB
Matt Sarett77a7a1b2017-02-07 13:56:11 -0500189 fColorSpace = SkColorSpace::MakeSRGBLinear();
brianosmanb9c51372016-09-15 11:09:45 -0700190 } else {
brianosmane25d71c2016-09-28 11:27:28 -0700191 // The color space refers to the float colors, so it must be linear gamma
Brian Osmanf06ead92017-10-30 13:47:41 -0400192 // TODO: GPU code no longer requires this (see GrGradientEffect). Remove this restriction?
brianosmane25d71c2016-09-28 11:27:28 -0700193 SkASSERT(desc.fColorSpace->gammaIsLinear());
brianosmanb9c51372016-09-15 11:09:45 -0700194 fColorSpace = desc.fColorSpace;
rileya@google.com589708b2012-07-26 20:04:23 +0000195 }
196
Mike Reeddfc0e912018-02-16 12:40:18 -0500197 SkScalar* origPosPtr = fOrigPos;
198 if (decal_mode) {
199 *origPosPtr++ = 0;
200 }
201
Florin Malita89ab2402017-11-01 10:14:57 -0400202 if (desc.fPos) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400203 SkScalar prev = 0;
Florin Malita64bb78e2017-11-03 12:54:07 -0400204 *origPosPtr++ = prev; // force the first pos to 0
reed9fa60da2014-08-21 07:59:51 -0700205
Florin Malita89ab2402017-11-01 10:14:57 -0400206 int startIndex = dummyFirst ? 0 : 1;
207 int count = desc.fCount + dummyLast;
Florin Malita64bb78e2017-11-03 12:54:07 -0400208
209 bool uniformStops = true;
210 const SkScalar uniformStep = desc.fPos[startIndex] - prev;
Florin Malita89ab2402017-11-01 10:14:57 -0400211 for (int i = startIndex; i < count; i++) {
Florin Malita3e20d022017-11-03 12:11:38 -0400212 // Pin the last value to 1.0, and make sure pos is monotonic.
Florin Malita64bb78e2017-11-03 12:54:07 -0400213 auto curr = (i == desc.fCount) ? 1 : SkScalarPin(desc.fPos[i], prev, 1);
214 uniformStops &= SkScalarNearlyEqual(uniformStep, curr - prev);
215
216 *origPosPtr++ = prev = curr;
reed9fa60da2014-08-21 07:59:51 -0700217 }
Florin Malita64bb78e2017-11-03 12:54:07 -0400218
Florin Malita64bb78e2017-11-03 12:54:07 -0400219 // If the stops are uniform, treat them as implicit.
Mike Reeddfc0e912018-02-16 12:40:18 -0500220 if (uniformStops && !decal_mode) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400221 fOrigPos = nullptr;
222 }
Mike Reeddfc0e912018-02-16 12:40:18 -0500223 } else if (decal_mode) {
224 // we need to create evenly spaced positions, since decal has forced extra start/ends
225 int n = fColorCount - 2; // subtract off the extra 2 decal added
226 float dt = 1.0f / (n - 1);
227 float t = 0;
228 for (int i = 0; i < n - 1; ++i) {
229 *origPosPtr++ = t;
230 t += dt;
231 }
232 *origPosPtr++ = 1.0f; // store the last explicitly, so we always hit 1.0 exactly
233 }
234
235 if (decal_mode) {
236 SkASSERT(origPosPtr[-1] == 1.0f);
237 *origPosPtr++ = SkBits2Float(SkFloat2Bits(1.0f) + 1);
238 }
239 if (fOrigPos) {
240 SkASSERT(fColorCount == (origPosPtr - fOrigPos));
241 }
242
243 // Now that we've munged the stops, pretend we're clamp
244 // (so we don't do this again via serialization)
245 if (decal_mode) {
246 fTileMode = SkShader::kClamp_TileMode;
rileya@google.com589708b2012-07-26 20:04:23 +0000247 }
rileya@google.com589708b2012-07-26 20:04:23 +0000248}
249
Florin Malita89ab2402017-11-01 10:14:57 -0400250SkGradientShaderBase::~SkGradientShaderBase() {}
rileya@google.com589708b2012-07-26 20:04:23 +0000251
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000252void SkGradientShaderBase::flatten(SkWriteBuffer& buffer) const {
reed9fa60da2014-08-21 07:59:51 -0700253 Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700254 desc.fColors = fOrigColors4f;
brianosmanb9c51372016-09-15 11:09:45 -0700255 desc.fColorSpace = fColorSpace;
reed9fa60da2014-08-21 07:59:51 -0700256 desc.fPos = fOrigPos;
257 desc.fCount = fColorCount;
258 desc.fTileMode = fTileMode;
259 desc.fGradFlags = fGradFlags;
260
261 const SkMatrix& m = this->getLocalMatrix();
halcanary96fcdcc2015-08-27 07:41:13 -0700262 desc.fLocalMatrix = m.isIdentity() ? nullptr : &m;
reed9fa60da2014-08-21 07:59:51 -0700263 desc.flatten(buffer);
rileya@google.com589708b2012-07-26 20:04:23 +0000264}
265
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400266static void add_stop_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f Fs, SkPM4f Bs) {
267 (ctx->fs[0])[stop] = Fs.r();
268 (ctx->fs[1])[stop] = Fs.g();
269 (ctx->fs[2])[stop] = Fs.b();
270 (ctx->fs[3])[stop] = Fs.a();
271 (ctx->bs[0])[stop] = Bs.r();
272 (ctx->bs[1])[stop] = Bs.g();
273 (ctx->bs[2])[stop] = Bs.b();
274 (ctx->bs[3])[stop] = Bs.a();
Mike Kleinf945cbb2017-05-17 09:30:58 -0400275}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400276
277static void add_const_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f color) {
278 add_stop_color(ctx, stop, SkPM4f::FromPremulRGBA(0,0,0,0), color);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400279}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400280
281// Calculate a factor F and a bias B so that color = F*t + B when t is in range of
282// the stop. Assume that the distance between stops is 1/gapCount.
283static void init_stop_evenly(
284 SkJumper_GradientCtx* ctx, float gapCount, size_t stop, SkPM4f c_l, SkPM4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400285 // Clankium's GCC 4.9 targeting ARMv7 is barfing when we use Sk4f math here, so go scalar...
286 SkPM4f Fs = {{
287 (c_r.r() - c_l.r()) * gapCount,
288 (c_r.g() - c_l.g()) * gapCount,
289 (c_r.b() - c_l.b()) * gapCount,
290 (c_r.a() - c_l.a()) * gapCount,
291 }};
292 SkPM4f Bs = {{
293 c_l.r() - Fs.r()*(stop/gapCount),
294 c_l.g() - Fs.g()*(stop/gapCount),
295 c_l.b() - Fs.b()*(stop/gapCount),
296 c_l.a() - Fs.a()*(stop/gapCount),
297 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400298 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400299}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400300
301// For each stop we calculate a bias B and a scale factor F, such that
302// for any t between stops n and n+1, the color we want is B[n] + F[n]*t.
303static void init_stop_pos(
304 SkJumper_GradientCtx* ctx, size_t stop, float t_l, float t_r, SkPM4f c_l, SkPM4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400305 // See note about Clankium's old compiler in init_stop_evenly().
306 SkPM4f Fs = {{
307 (c_r.r() - c_l.r()) / (t_r - t_l),
308 (c_r.g() - c_l.g()) / (t_r - t_l),
309 (c_r.b() - c_l.b()) / (t_r - t_l),
310 (c_r.a() - c_l.a()) / (t_r - t_l),
311 }};
312 SkPM4f Bs = {{
313 c_l.r() - Fs.r()*t_l,
314 c_l.g() - Fs.g()*t_l,
315 c_l.b() - Fs.b()*t_l,
316 c_l.a() - Fs.a()*t_l,
317 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400318 ctx->ts[stop] = t_l;
319 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400320}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400321
Mike Reed1d8c42e2017-08-29 14:58:19 -0400322bool SkGradientShaderBase::onAppendStages(const StageRec& rec) const {
323 SkRasterPipeline* p = rec.fPipeline;
324 SkArenaAlloc* alloc = rec.fAlloc;
325 SkColorSpace* dstCS = rec.fDstCS;
326
Mike Kleina3771842017-05-04 19:38:48 -0400327 SkMatrix matrix;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400328 if (!this->computeTotalInverse(rec.fCTM, rec.fLocalM, &matrix)) {
Mike Kleina3771842017-05-04 19:38:48 -0400329 return false;
330 }
Florin Malita50b20842017-07-29 19:08:28 -0400331 matrix.postConcat(fPtsToUnit);
Mike Kleina3771842017-05-04 19:38:48 -0400332
Florin Malita2e409002017-06-28 14:46:54 -0400333 SkRasterPipeline_<256> postPipeline;
Mike Kleina3771842017-05-04 19:38:48 -0400334
Mike Klein85f85362017-10-17 14:22:58 -0400335 p->append_seed_shader();
Mike Reed6b59bf42017-07-03 21:26:44 -0400336 p->append_matrix(alloc, matrix);
Florin Malita50b20842017-07-29 19:08:28 -0400337 this->appendGradientStages(alloc, p, &postPipeline);
Mike Kleine7598532017-05-11 11:29:29 -0400338
Mike Reeddfc0e912018-02-16 12:40:18 -0500339 switch (fTileMode) {
Mike Klein9f85d682017-05-23 07:52:01 -0400340 case kMirror_TileMode: p->append(SkRasterPipeline::mirror_x_1); break;
341 case kRepeat_TileMode: p->append(SkRasterPipeline::repeat_x_1); break;
Mike Reeddfc0e912018-02-16 12:40:18 -0500342 case kDecal_TileMode:
343 // TODO: need decal stages
344 // fall-through for now
Mike Kleine7598532017-05-11 11:29:29 -0400345 case kClamp_TileMode:
346 if (!fOrigPos) {
347 // We clamp only when the stops are evenly spaced.
348 // If not, there may be hard stops, and clamping ruins hard stops at 0 and/or 1.
Mike Klein5c7960b2017-05-11 10:59:22 -0400349 // In that case, we must make sure we're using the general "gradient" stage,
Mike Kleine7598532017-05-11 11:29:29 -0400350 // which is the only stage that will correctly handle unclamped t.
Mike Klein9f85d682017-05-23 07:52:01 -0400351 p->append(SkRasterPipeline::clamp_x_1);
Mike Kleine7598532017-05-11 11:29:29 -0400352 }
353 }
Mike Kleina3771842017-05-04 19:38:48 -0400354
355 const bool premulGrad = fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag;
356 auto prepareColor = [premulGrad, dstCS, this](int i) {
Florin Malita0e36b3f2017-06-05 23:33:45 -0400357 SkColor4f c = this->getXformedColor(i, dstCS);
Mike Kleina3771842017-05-04 19:38:48 -0400358 return premulGrad ? c.premul()
359 : SkPM4f::From4f(Sk4f::Load(&c));
360 };
361
362 // The two-stop case with stops at 0 and 1.
363 if (fColorCount == 2 && fOrigPos == nullptr) {
364 const SkPM4f c_l = prepareColor(0),
Mike Reed1d8c42e2017-08-29 14:58:19 -0400365 c_r = prepareColor(1);
Mike Kleina3771842017-05-04 19:38:48 -0400366
367 // See F and B below.
368 auto* f_and_b = alloc->makeArrayDefault<SkPM4f>(2);
369 f_and_b[0] = SkPM4f::From4f(c_r.to4f() - c_l.to4f());
370 f_and_b[1] = c_l;
371
Mike Klein5c7960b2017-05-11 10:59:22 -0400372 p->append(SkRasterPipeline::evenly_spaced_2_stop_gradient, f_and_b);
Mike Kleina3771842017-05-04 19:38:48 -0400373 } else {
Herb Derby4de13042017-05-15 10:49:39 -0400374 auto* ctx = alloc->make<SkJumper_GradientCtx>();
Herb Derby4de13042017-05-15 10:49:39 -0400375
376 // Note: In order to handle clamps in search, the search assumes a stop conceptully placed
377 // at -inf. Therefore, the max number of stops is fColorCount+1.
378 for (int i = 0; i < 4; i++) {
379 // Allocate at least at for the AVX2 gather from a YMM register.
380 ctx->fs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
381 ctx->bs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
382 }
383
Mike Kleina3771842017-05-04 19:38:48 -0400384 if (fOrigPos == nullptr) {
385 // Handle evenly distributed stops.
386
Herb Derby4de13042017-05-15 10:49:39 -0400387 size_t stopCount = fColorCount;
388 float gapCount = stopCount - 1;
Mike Kleina3771842017-05-04 19:38:48 -0400389
Herb Derby4de13042017-05-15 10:49:39 -0400390 SkPM4f c_l = prepareColor(0);
391 for (size_t i = 0; i < stopCount - 1; i++) {
Mike Kleina3771842017-05-04 19:38:48 -0400392 SkPM4f c_r = prepareColor(i + 1);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400393 init_stop_evenly(ctx, gapCount, i, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400394 c_l = c_r;
395 }
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400396 add_const_color(ctx, stopCount - 1, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400397
Herb Derby4de13042017-05-15 10:49:39 -0400398 ctx->stopCount = stopCount;
399 p->append(SkRasterPipeline::evenly_spaced_gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400400 } else {
401 // Handle arbitrary stops.
402
Herb Derby4de13042017-05-15 10:49:39 -0400403 ctx->ts = alloc->makeArray<float>(fColorCount+1);
404
Mike Kleina3771842017-05-04 19:38:48 -0400405 // Remove the dummy stops inserted by SkGradientShaderBase::SkGradientShaderBase
406 // because they are naturally handled by the search method.
407 int firstStop;
408 int lastStop;
409 if (fColorCount > 2) {
410 firstStop = fOrigColors4f[0] != fOrigColors4f[1] ? 0 : 1;
411 lastStop = fOrigColors4f[fColorCount - 2] != fOrigColors4f[fColorCount - 1]
412 ? fColorCount - 1 : fColorCount - 2;
413 } else {
414 firstStop = 0;
415 lastStop = 1;
416 }
Mike Kleina3771842017-05-04 19:38:48 -0400417
Mike Kleina3771842017-05-04 19:38:48 -0400418 size_t stopCount = 0;
419 float t_l = fOrigPos[firstStop];
420 SkPM4f c_l = prepareColor(firstStop);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400421 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400422 // N.B. lastStop is the index of the last stop, not one after.
423 for (int i = firstStop; i < lastStop; i++) {
424 float t_r = fOrigPos[i + 1];
425 SkPM4f c_r = prepareColor(i + 1);
Florin Malita3e20d022017-11-03 12:11:38 -0400426 SkASSERT(t_l <= t_r);
Mike Kleina3771842017-05-04 19:38:48 -0400427 if (t_l < t_r) {
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400428 init_stop_pos(ctx, stopCount, t_l, t_r, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400429 stopCount += 1;
430 }
431 t_l = t_r;
432 c_l = c_r;
433 }
434
Herb Derby4de13042017-05-15 10:49:39 -0400435 ctx->ts[stopCount] = t_l;
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400436 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400437
Herb Derby4de13042017-05-15 10:49:39 -0400438 ctx->stopCount = stopCount;
439 p->append(SkRasterPipeline::gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400440 }
Mike Kleina3771842017-05-04 19:38:48 -0400441 }
442
443 if (!premulGrad && !this->colorsAreOpaque()) {
Mike Kleine7598532017-05-11 11:29:29 -0400444 p->append(SkRasterPipeline::premul);
Mike Kleina3771842017-05-04 19:38:48 -0400445 }
446
Florin Malita2e409002017-06-28 14:46:54 -0400447 p->extend(postPipeline);
448
Mike Kleina3771842017-05-04 19:38:48 -0400449 return true;
450}
451
452
rileya@google.com589708b2012-07-26 20:04:23 +0000453bool SkGradientShaderBase::isOpaque() const {
454 return fColorsAreOpaque;
455}
456
reed8367b8c2014-08-22 08:30:20 -0700457static unsigned rounded_divide(unsigned numer, unsigned denom) {
458 return (numer + (denom >> 1)) / denom;
459}
460
461bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
462 // we just compute an average color.
463 // possibly we could weight this based on the proportional width for each color
464 // assuming they are not evenly distributed in the fPos array.
465 int r = 0;
466 int g = 0;
467 int b = 0;
468 const int n = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400469 // TODO: use linear colors?
reed8367b8c2014-08-22 08:30:20 -0700470 for (int i = 0; i < n; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400471 SkColor c = this->getLegacyColor(i);
reed8367b8c2014-08-22 08:30:20 -0700472 r += SkColorGetR(c);
473 g += SkColorGetG(c);
474 b += SkColorGetB(c);
475 }
476 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
477 return true;
478}
479
Florin Malita39d71de2017-10-31 11:33:49 -0400480SkGradientShaderBase::AutoXformColors::AutoXformColors(const SkGradientShaderBase& grad,
481 SkColorSpaceXformer* xformer)
482 : fColors(grad.fColorCount) {
483 // TODO: stay in 4f to preserve precision?
484
485 SkAutoSTMalloc<8, SkColor> origColors(grad.fColorCount);
486 for (int i = 0; i < grad.fColorCount; ++i) {
487 origColors[i] = grad.getLegacyColor(i);
488 }
489
490 xformer->apply(fColors.get(), origColors.get(), grad.fColorCount);
491}
492
Florin Malitad4e9ec82017-10-25 18:00:26 -0400493static constexpr int kGradientTextureSize = 256;
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000494
Florin Malita84d7cf92017-10-25 15:31:54 -0400495void SkGradientShaderBase::initLinearBitmap(SkBitmap* bitmap, GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700496 const bool interpInPremul = SkToBool(fGradFlags &
497 SkGradientShader::kInterpolateColorsInPremul_Flag);
brianosmand4546092016-09-22 12:31:58 -0700498 SkHalf* pixelsF16 = reinterpret_cast<SkHalf*>(bitmap->getPixels());
Florin Malita84d7cf92017-10-25 15:31:54 -0400499 uint32_t* pixels32 = reinterpret_cast<uint32_t*>(bitmap->getPixels());
brianosmand4546092016-09-22 12:31:58 -0700500
501 typedef std::function<void(const Sk4f&, int)> pixelWriteFn_t;
502
503 pixelWriteFn_t writeF16Pixel = [&](const Sk4f& x, int index) {
504 Sk4h c = SkFloatToHalf_finite_ftz(x);
505 pixelsF16[4*index+0] = c[0];
506 pixelsF16[4*index+1] = c[1];
507 pixelsF16[4*index+2] = c[2];
508 pixelsF16[4*index+3] = c[3];
509 };
510 pixelWriteFn_t writeS32Pixel = [&](const Sk4f& c, int index) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400511 pixels32[index] = Sk4f_toS32(c);
512 };
513 pixelWriteFn_t writeL32Pixel = [&](const Sk4f& c, int index) {
514 pixels32[index] = Sk4f_toL32(c);
brianosmand4546092016-09-22 12:31:58 -0700515 };
516
517 pixelWriteFn_t writeSizedPixel =
Florin Malita84d7cf92017-10-25 15:31:54 -0400518 (bitmapType == GradientBitmapType::kHalfFloat) ? writeF16Pixel :
519 (bitmapType == GradientBitmapType::kSRGB ) ? writeS32Pixel : writeL32Pixel;
brianosmand4546092016-09-22 12:31:58 -0700520 pixelWriteFn_t writeUnpremulPixel = [&](const Sk4f& c, int index) {
521 writeSizedPixel(c * Sk4f(c[3], c[3], c[3], 1.0f), index);
522 };
523
524 pixelWriteFn_t writePixel = interpInPremul ? writeSizedPixel : writeUnpremulPixel;
525
Florin Malita84d7cf92017-10-25 15:31:54 -0400526 // When not in legacy mode, we just want the original 4f colors - so we pass in
527 // our own CS for identity/no transform.
528 auto* cs = bitmapType != GradientBitmapType::kLegacy ? fColorSpace.get() : nullptr;
529
brianosmand4546092016-09-22 12:31:58 -0700530 int prevIndex = 0;
531 for (int i = 1; i < fColorCount; i++) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400532 // Historically, stops have been mapped to [0, 256], with 256 then nudged to the
533 // next smaller value, then truncate for the texture index. This seems to produce
534 // the best results for some common distributions, so we preserve the behavior.
535 int nextIndex = SkTMin(this->getPos(i) * kGradientTextureSize,
536 SkIntToScalar(kGradientTextureSize - 1));
brianosmand4546092016-09-22 12:31:58 -0700537
538 if (nextIndex > prevIndex) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400539 SkColor4f color0 = this->getXformedColor(i - 1, cs),
540 color1 = this->getXformedColor(i , cs);
541 Sk4f c0 = Sk4f::Load(color0.vec()),
542 c1 = Sk4f::Load(color1.vec());
543
brianosmand4546092016-09-22 12:31:58 -0700544 if (interpInPremul) {
545 c0 = c0 * Sk4f(c0[3], c0[3], c0[3], 1.0f);
546 c1 = c1 * Sk4f(c1[3], c1[3], c1[3], 1.0f);
547 }
548
549 Sk4f step = Sk4f(1.0f / static_cast<float>(nextIndex - prevIndex));
550 Sk4f delta = (c1 - c0) * step;
551
552 for (int curIndex = prevIndex; curIndex <= nextIndex; ++curIndex) {
553 writePixel(c0, curIndex);
554 c0 += delta;
555 }
556 }
557 prevIndex = nextIndex;
558 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400559 SkASSERT(prevIndex == kGradientTextureSize - 1);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000560}
561
Mike Reeddfc0e912018-02-16 12:40:18 -0500562bool SkGradientShaderBase::onIsRasterPipelineOnly(const SkMatrix& ctm) const {
563 if (this->getTileMode() == SkShader::kDecal_TileMode) {
564 return true;
565 }
566 return this->INHERITED::onIsRasterPipelineOnly(ctm);
567}
568
Florin Malita0e36b3f2017-06-05 23:33:45 -0400569SkColor4f SkGradientShaderBase::getXformedColor(size_t i, SkColorSpace* dstCS) const {
Florin Malita79363b62017-11-01 15:43:52 -0400570 if (dstCS) {
571 return to_colorspace(fOrigColors4f[i], fColorSpace.get(), dstCS);
572 }
573
574 // Legacy/srgb color.
Florin Malita79363b62017-11-01 15:43:52 -0400575 // We quantize upfront to ensure stable SkColor round-trips.
576 auto rgb255 = sk_linear_to_srgb(Sk4f::Load(fOrigColors4f[i].vec()));
577 auto rgb = SkNx_cast<float>(rgb255) * (1/255.0f);
578 return { rgb[0], rgb[1], rgb[2], fOrigColors4f[i].fA };
Florin Malita0e36b3f2017-06-05 23:33:45 -0400579}
580
reed086eea92016-05-04 17:12:46 -0700581SK_DECLARE_STATIC_MUTEX(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000582/*
583 * Because our caller might rebuild the same (logically the same) gradient
584 * over and over, we'd like to return exactly the same "bitmap" if possible,
585 * allowing the client to utilize a cache of our bitmap (e.g. with a GPU).
586 * To do that, we maintain a private cache of built-bitmaps, based on our
Brian Osmanfe3e8582017-10-20 11:27:49 -0400587 * colors and positions.
rileya@google.com589708b2012-07-26 20:04:23 +0000588 */
brianosmand4546092016-09-22 12:31:58 -0700589void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap,
590 GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700591 // build our key: [numColors + colors[] + {positions[]} + flags + colorType ]
Florin Malita39d71de2017-10-31 11:33:49 -0400592 static_assert(sizeof(SkColor4f) % sizeof(int32_t) == 0, "");
593 const int colorsAsIntCount = fColorCount * sizeof(SkColor4f) / sizeof(int32_t);
594 int count = 1 + colorsAsIntCount + 1 + 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000595 if (fColorCount > 2) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400596 count += fColorCount - 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000597 }
598
Florin Malita39d71de2017-10-31 11:33:49 -0400599 SkAutoSTMalloc<64, int32_t> storage(count);
rileya@google.com589708b2012-07-26 20:04:23 +0000600 int32_t* buffer = storage.get();
601
602 *buffer++ = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400603 memcpy(buffer, fOrigColors4f, fColorCount * sizeof(SkColor4f));
604 buffer += colorsAsIntCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000605 if (fColorCount > 2) {
606 for (int i = 1; i < fColorCount; i++) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400607 *buffer++ = SkFloat2Bits(this->getPos(i));
rileya@google.com589708b2012-07-26 20:04:23 +0000608 }
609 }
reed@google.com3d3a8602013-05-24 14:58:44 +0000610 *buffer++ = fGradFlags;
brianosmand4546092016-09-22 12:31:58 -0700611 *buffer++ = static_cast<int32_t>(bitmapType);
rileya@google.com589708b2012-07-26 20:04:23 +0000612 SkASSERT(buffer - storage.get() == count);
613
614 ///////////////////////////////////
615
reeda6cac4c2014-08-21 10:50:25 -0700616 static SkGradientBitmapCache* gCache;
brianosmand4546092016-09-22 12:31:58 -0700617 // each cache cost 1K or 2K of RAM, since each bitmap will be 1x256 at either 32bpp or 64bpp
rileya@google.com589708b2012-07-26 20:04:23 +0000618 static const int MAX_NUM_CACHED_GRADIENT_BITMAPS = 32;
bungemand6aeb6d2014-07-25 11:52:47 -0700619 SkAutoMutexAcquire ama(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000620
halcanary96fcdcc2015-08-27 07:41:13 -0700621 if (nullptr == gCache) {
halcanary385fe4d2015-08-26 13:07:48 -0700622 gCache = new SkGradientBitmapCache(MAX_NUM_CACHED_GRADIENT_BITMAPS);
rileya@google.com589708b2012-07-26 20:04:23 +0000623 }
624 size_t size = count * sizeof(int32_t);
625
626 if (!gCache->find(storage.get(), size, bitmap)) {
Florin Malitad4e9ec82017-10-25 18:00:26 -0400627 // For these cases we use the bitmap cache, but not the GradientShaderCache. So just
628 // allocate and populate the bitmap's data directly.
Florin Malita63376532017-10-24 10:56:52 -0400629
Florin Malitad4e9ec82017-10-25 18:00:26 -0400630 SkImageInfo info;
631 switch (bitmapType) {
632 case GradientBitmapType::kLegacy:
633 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
634 kPremul_SkAlphaType);
635 break;
636 case GradientBitmapType::kSRGB:
637 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
638 kPremul_SkAlphaType, SkColorSpace::MakeSRGB());
639 break;
640 case GradientBitmapType::kHalfFloat:
641 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_F16_SkColorType,
642 kPremul_SkAlphaType, SkColorSpace::MakeSRGBLinear());
643 break;
brianosmand4546092016-09-22 12:31:58 -0700644 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400645
646 bitmap->allocPixels(info);
647 this->initLinearBitmap(bitmap, bitmapType);
Robert Phillips7a926392018-02-01 15:49:54 -0500648 bitmap->setImmutable();
rileya@google.com589708b2012-07-26 20:04:23 +0000649 gCache->add(storage.get(), size, *bitmap);
650 }
651}
652
Florin Malita5f379a82017-10-18 16:22:35 -0400653void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000654 if (info) {
655 if (info->fColorCount >= fColorCount) {
656 if (info->fColors) {
Florin Malita39d71de2017-10-31 11:33:49 -0400657 for (int i = 0; i < fColorCount; ++i) {
658 info->fColors[i] = this->getLegacyColor(i);
659 }
rileya@google.com589708b2012-07-26 20:04:23 +0000660 }
661 if (info->fColorOffsets) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400662 for (int i = 0; i < fColorCount; ++i) {
663 info->fColorOffsets[i] = this->getPos(i);
rileya@google.com589708b2012-07-26 20:04:23 +0000664 }
665 }
666 }
667 info->fColorCount = fColorCount;
668 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000669 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000670 }
671}
672
commit-bot@chromium.org0f10f7b2014-03-13 18:02:17 +0000673#ifndef SK_IGNORE_TO_STRING
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000674void SkGradientShaderBase::toString(SkString* str) const {
675
676 str->appendf("%d colors: ", fColorCount);
677
678 for (int i = 0; i < fColorCount; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400679 str->appendHex(this->getLegacyColor(i), 8);
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000680 if (i < fColorCount-1) {
681 str->append(", ");
682 }
683 }
684
685 if (fColorCount > 2) {
686 str->append(" points: (");
687 for (int i = 0; i < fColorCount; ++i) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400688 str->appendScalar(this->getPos(i));
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000689 if (i < fColorCount-1) {
690 str->append(", ");
691 }
692 }
693 str->append(")");
694 }
695
696 static const char* gTileModeName[SkShader::kTileModeCount] = {
Mike Reeddfc0e912018-02-16 12:40:18 -0500697 "clamp", "repeat", "mirror", "decal",
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000698 };
699
700 str->append(" ");
701 str->append(gTileModeName[fTileMode]);
702
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000703 this->INHERITED::toString(str);
704}
705#endif
706
rileya@google.com589708b2012-07-26 20:04:23 +0000707///////////////////////////////////////////////////////////////////////////////
708///////////////////////////////////////////////////////////////////////////////
709
reed1b747302015-01-06 07:13:19 -0800710// Return true if these parameters are valid/legal/safe to construct a gradient
711//
brianosmane25d71c2016-09-28 11:27:28 -0700712static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
713 unsigned tileMode) {
halcanary96fcdcc2015-08-27 07:41:13 -0700714 return nullptr != colors && count >= 1 && tileMode < (unsigned)SkShader::kTileModeCount;
reed1b747302015-01-06 07:13:19 -0800715}
716
reed@google.com437d6eb2013-05-23 19:03:05 +0000717static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700718 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
719 const SkScalar pos[], int colorCount,
reedaddf2ed2014-08-11 08:28:24 -0700720 SkShader::TileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700721 SkASSERT(colorCount > 1);
722
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000723 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700724 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000725 desc->fPos = pos;
726 desc->fCount = colorCount;
727 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000728 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700729 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000730}
731
brianosmane25d71c2016-09-28 11:27:28 -0700732// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700733#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700734 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700735 do { \
736 if (1 == count) { \
737 tmp[0] = tmp[1] = colors[0]; \
738 colors = tmp; \
739 pos = nullptr; \
740 count = 2; \
741 } \
742 } while (0)
743
fmenozzi68d952c2016-08-19 08:56:56 -0700744struct ColorStopOptimizer {
brianosmane25d71c2016-09-28 11:27:28 -0700745 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos,
fmenozzi68d952c2016-08-19 08:56:56 -0700746 int count, SkShader::TileMode mode)
747 : fColors(colors)
748 , fPos(pos)
749 , fCount(count) {
750
751 if (!pos || count != 3) {
752 return;
753 }
754
755 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
756 SkScalarNearlyEqual(pos[1], 0.0f) &&
757 SkScalarNearlyEqual(pos[2], 1.0f)) {
758
759 if (SkShader::kRepeat_TileMode == mode ||
760 SkShader::kMirror_TileMode == mode ||
761 colors[0] == colors[1]) {
762
fmalita582a6562016-08-22 06:28:57 -0700763 // Ignore the leftmost color/pos.
764 fColors += 1;
765 fPos += 1;
766 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700767 }
768 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
769 SkScalarNearlyEqual(pos[1], 1.0f) &&
770 SkScalarNearlyEqual(pos[2], 1.0f)) {
771
772 if (SkShader::kRepeat_TileMode == mode ||
773 SkShader::kMirror_TileMode == mode ||
774 colors[1] == colors[2]) {
775
fmalita582a6562016-08-22 06:28:57 -0700776 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700777 fCount = 2;
778 }
779 }
780 }
781
brianosmane25d71c2016-09-28 11:27:28 -0700782 const SkColor4f* fColors;
783 const SkScalar* fPos;
784 int fCount;
785};
786
787struct ColorConverter {
788 ColorConverter(const SkColor* colors, int count) {
789 for (int i = 0; i < count; ++i) {
790 fColors4f.push_back(SkColor4f::FromColor(colors[i]));
791 }
792 }
793
794 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700795};
796
reed8a21c9f2016-03-08 18:50:00 -0800797sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700798 const SkColor colors[],
799 const SkScalar pos[], int colorCount,
800 SkShader::TileMode mode,
801 uint32_t flags,
802 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700803 ColorConverter converter(colors, colorCount);
804 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
805 localMatrix);
806}
807
808sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
809 const SkColor4f colors[],
810 sk_sp<SkColorSpace> colorSpace,
811 const SkScalar pos[], int colorCount,
812 SkShader::TileMode mode,
813 uint32_t flags,
814 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700815 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700816 return nullptr;
reed1b747302015-01-06 07:13:19 -0800817 }
818 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700819 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000820 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700821 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700822 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700823 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000824 if (localMatrix && !localMatrix->invert(nullptr)) {
825 return nullptr;
826 }
rileya@google.com589708b2012-07-26 20:04:23 +0000827
fmenozzi68d952c2016-08-19 08:56:56 -0700828 ColorStopOptimizer opt(colors, pos, colorCount, mode);
829
reed@google.com437d6eb2013-05-23 19:03:05 +0000830 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700831 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
832 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800833 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000834}
835
reed8a21c9f2016-03-08 18:50:00 -0800836sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700837 const SkColor colors[],
838 const SkScalar pos[], int colorCount,
839 SkShader::TileMode mode,
840 uint32_t flags,
841 const SkMatrix* localMatrix) {
842 ColorConverter converter(colors, colorCount);
843 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
844 flags, localMatrix);
845}
846
847sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
848 const SkColor4f colors[],
849 sk_sp<SkColorSpace> colorSpace,
850 const SkScalar pos[], int colorCount,
851 SkShader::TileMode mode,
852 uint32_t flags,
853 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800854 if (radius <= 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700855 return nullptr;
reed1b747302015-01-06 07:13:19 -0800856 }
857 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700858 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000859 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700860 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700861 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700862 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000863 if (localMatrix && !localMatrix->invert(nullptr)) {
864 return nullptr;
865 }
rileya@google.com589708b2012-07-26 20:04:23 +0000866
fmenozzi68d952c2016-08-19 08:56:56 -0700867 ColorStopOptimizer opt(colors, pos, colorCount, mode);
868
reed@google.com437d6eb2013-05-23 19:03:05 +0000869 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700870 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
871 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800872 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000873}
874
reed8a21c9f2016-03-08 18:50:00 -0800875sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -0700876 SkScalar startRadius,
877 const SkPoint& end,
878 SkScalar endRadius,
879 const SkColor colors[],
880 const SkScalar pos[],
881 int colorCount,
882 SkShader::TileMode mode,
883 uint32_t flags,
884 const SkMatrix* localMatrix) {
885 ColorConverter converter(colors, colorCount);
886 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
887 nullptr, pos, colorCount, mode, flags, localMatrix);
888}
889
890sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
891 SkScalar startRadius,
892 const SkPoint& end,
893 SkScalar endRadius,
894 const SkColor4f colors[],
895 sk_sp<SkColorSpace> colorSpace,
896 const SkScalar pos[],
897 int colorCount,
898 SkShader::TileMode mode,
899 uint32_t flags,
900 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800901 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700902 return nullptr;
reed1b747302015-01-06 07:13:19 -0800903 }
Florin Malita327290f2017-07-07 09:23:16 -0400904 if (SkScalarNearlyZero((start - end).length()) && SkScalarNearlyZero(startRadius)) {
905 // We can treat this gradient as radial, which is faster.
906 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
907 mode, flags, localMatrix);
908 }
reed1b747302015-01-06 07:13:19 -0800909 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700910 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000911 }
fmalita5edf82e2016-03-03 06:41:54 -0800912 if (startRadius == endRadius) {
913 if (start == end || startRadius == 0) {
reed8a21c9f2016-03-08 18:50:00 -0800914 return SkShader::MakeEmptyShader();
fmalita5edf82e2016-03-03 06:41:54 -0800915 }
rileya@google.com589708b2012-07-26 20:04:23 +0000916 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000917 if (localMatrix && !localMatrix->invert(nullptr)) {
918 return nullptr;
919 }
reed6b7a6c72016-08-18 16:13:50 -0700920 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000921
fmenozzi68d952c2016-08-19 08:56:56 -0700922 ColorStopOptimizer opt(colors, pos, colorCount, mode);
923
reed@google.com437d6eb2013-05-23 19:03:05 +0000924 SkGradientShaderBase::Descriptor desc;
Florin Malita5f379a82017-10-18 16:22:35 -0400925 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
926 localMatrix);
927 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000928}
929
reed8a21c9f2016-03-08 18:50:00 -0800930sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -0700931 const SkColor colors[],
932 const SkScalar pos[],
933 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400934 SkShader::TileMode mode,
935 SkScalar startAngle,
936 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700937 uint32_t flags,
938 const SkMatrix* localMatrix) {
939 ColorConverter converter(colors, colorCount);
Florin Malita5a9a9812017-08-01 16:38:08 -0400940 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
941 mode, startAngle, endAngle, flags, localMatrix);
brianosmane25d71c2016-09-28 11:27:28 -0700942}
943
944sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
945 const SkColor4f colors[],
946 sk_sp<SkColorSpace> colorSpace,
947 const SkScalar pos[],
948 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400949 SkShader::TileMode mode,
950 SkScalar startAngle,
951 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700952 uint32_t flags,
953 const SkMatrix* localMatrix) {
Florin Malita5a9a9812017-08-01 16:38:08 -0400954 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700955 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000956 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700957 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700958 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700959 }
Florin Malita5a9a9812017-08-01 16:38:08 -0400960 if (startAngle >= endAngle) {
961 return nullptr;
962 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000963 if (localMatrix && !localMatrix->invert(nullptr)) {
964 return nullptr;
965 }
rileya@google.com589708b2012-07-26 20:04:23 +0000966
Florin Malita5a9a9812017-08-01 16:38:08 -0400967 if (startAngle <= 0 && endAngle >= 360) {
968 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
969 mode = SkShader::kClamp_TileMode;
970 }
fmenozzi68d952c2016-08-19 08:56:56 -0700971
972 ColorStopOptimizer opt(colors, pos, colorCount, mode);
973
reed@google.com437d6eb2013-05-23 19:03:05 +0000974 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700975 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
976 localMatrix);
Florin Malita5a9a9812017-08-01 16:38:08 -0400977
978 const SkScalar t0 = startAngle / 360,
979 t1 = endAngle / 360;
980
981 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000982}
983
984SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
985 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
986 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
987 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
rileya@google.com589708b2012-07-26 20:04:23 +0000988 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
989SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
rileya@google.comd7cc6512012-07-27 14:00:39 +0000990
991///////////////////////////////////////////////////////////////////////////////
992
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000993#if SK_SUPPORT_GPU
994
Brian Osman5911a7c2017-10-25 12:52:31 -0400995#include "GrColorSpaceXform.h"
brianosmana6359362016-03-21 06:55:37 -0700996#include "GrContext.h"
Robert Phillips1afd4cd2018-01-08 13:40:32 -0500997#include "GrContextPriv.h"
Brian Salomon94efbf52016-11-29 13:43:05 -0500998#include "GrShaderCaps.h"
ajuma95243eb2016-08-24 08:19:02 -0700999#include "GrTextureStripAtlas.h"
egdanielf5294392015-10-21 07:14:17 -07001000#include "gl/GrGLContext.h"
egdaniel2d721d32015-11-11 13:06:05 -08001001#include "glsl/GrGLSLFragmentShaderBuilder.h"
egdaniel018fb622015-10-28 07:26:40 -07001002#include "glsl/GrGLSLProgramDataManager.h"
egdaniel7ea439b2015-12-03 09:20:44 -08001003#include "glsl/GrGLSLUniformHandler.h"
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001004#include "SkGr.h"
1005
fmenozzi55d318d2016-08-09 08:05:57 -07001006void GrGradientEffect::GLSLProcessor::emitUniforms(GrGLSLUniformHandler* uniformHandler,
1007 const GrGradientEffect& ge) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001008 switch (ge.fStrategy) {
1009 case GrGradientEffect::InterpolationStrategy::kThreshold:
1010 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1011 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1012 fThresholdUni = uniformHandler->addUniform(kFragment_GrShaderFlag,
1013 kFloat_GrSLType,
1014 kHigh_GrSLPrecision,
1015 "Threshold");
1016 // fall through
1017 case GrGradientEffect::InterpolationStrategy::kSingle:
1018 fIntervalsUni = uniformHandler->addUniformArray(kFragment_GrShaderFlag,
1019 kHalf4_GrSLType,
1020 "Intervals",
1021 ge.fIntervals.count());
1022 break;
1023 case GrGradientEffect::InterpolationStrategy::kTexture:
1024 fFSYUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType,
1025 "GradientYCoordFS");
1026 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001027 }
1028}
1029
fmenozzi55d318d2016-08-09 08:05:57 -07001030void GrGradientEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman,
Brian Salomonab015ef2017-04-04 10:15:51 -04001031 const GrFragmentProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -07001032 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +00001033
Florin Malita14a8dd72017-11-08 15:46:42 -05001034 switch (e.fStrategy) {
1035 case GrGradientEffect::InterpolationStrategy::kThreshold:
1036 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1037 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1038 pdman.set1f(fThresholdUni, e.fThreshold);
Brian Salomon466ad992016-10-13 16:08:36 -04001039 // fall through
Florin Malita14a8dd72017-11-08 15:46:42 -05001040 case GrGradientEffect::InterpolationStrategy::kSingle:
1041 pdman.set4fv(fIntervalsUni, e.fIntervals.count(),
1042 reinterpret_cast<const float*>(e.fIntervals.begin()));
fmenozzicd9a1d02016-08-15 07:03:47 -07001043 break;
Florin Malita14a8dd72017-11-08 15:46:42 -05001044 case GrGradientEffect::InterpolationStrategy::kTexture:
1045 if (e.fYCoord != fCachedYCoord) {
1046 pdman.set1f(fFSYUni, e.fYCoord);
1047 fCachedYCoord = e.fYCoord;
fmenozzicd9a1d02016-08-15 07:03:47 -07001048 }
1049 break;
rileya@google.comb3e50f22012-08-20 17:43:08 +00001050 }
1051}
1052
Florin Malitae657dc82017-11-03 08:46:18 -04001053void GrGradientEffect::onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const {
1054 b->add32(GLSLProcessor::GenBaseGradientKey(*this));
1055}
1056
fmenozzi55d318d2016-08-09 08:05:57 -07001057uint32_t GrGradientEffect::GLSLProcessor::GenBaseGradientKey(const GrProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -07001058 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001059
Florin Malita14a8dd72017-11-08 15:46:42 -05001060 // Build a key using the following bit allocation:
1061 static constexpr uint32_t kStrategyBits = 3;
1062 static constexpr uint32_t kPremulBits = 1;
1063 SkDEBUGCODE(static constexpr uint32_t kWrapModeBits = 2;)
bsalomon@google.com82d12232013-09-09 15:36:26 +00001064
Florin Malita14a8dd72017-11-08 15:46:42 -05001065 uint32_t key = static_cast<uint32_t>(e.fStrategy);
1066 SkASSERT(key < (1 << kStrategyBits));
1067
1068 // This is already baked into the table for texture gradients,
1069 // and only changes behavior for analytical gradients.
1070 if (e.fStrategy != InterpolationStrategy::kTexture &&
1071 e.fPremulType == GrGradientEffect::kBeforeInterp_PremulType) {
1072 key |= 1 << kStrategyBits;
1073 SkASSERT(key < (1 << (kStrategyBits + kPremulBits)));
bsalomon@google.com82d12232013-09-09 15:36:26 +00001074 }
1075
Florin Malita14a8dd72017-11-08 15:46:42 -05001076 key |= static_cast<uint32_t>(e.fWrapMode) << (kStrategyBits + kPremulBits);
1077 SkASSERT(key < (1 << (kStrategyBits + kPremulBits + kWrapModeBits)));
fmenozzicd9a1d02016-08-15 07:03:47 -07001078
bsalomon@google.com82d12232013-09-09 15:36:26 +00001079 return key;
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +00001080}
1081
Florin Malitab81a8b92017-08-08 12:14:17 -04001082void GrGradientEffect::GLSLProcessor::emitAnalyticalColor(GrGLSLFPFragmentBuilder* fragBuilder,
1083 GrGLSLUniformHandler* uniformHandler,
1084 const GrShaderCaps* shaderCaps,
1085 const GrGradientEffect& ge,
1086 const char* t,
1087 const char* outputColor,
1088 const char* inputColor) {
1089 // First, apply tiling rules.
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001090 switch (ge.fWrapMode) {
1091 case GrSamplerState::WrapMode::kClamp:
Florin Malita14a8dd72017-11-08 15:46:42 -05001092 switch (ge.fStrategy) {
1093 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1094 // allow t > 1, in order to hit the clamp interval (1, inf)
1095 fragBuilder->codeAppendf("half tiled_t = max(%s, 0.0);", t);
1096 break;
1097 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1098 // allow t < 0, in order to hit the clamp interval (-inf, 0)
1099 fragBuilder->codeAppendf("half tiled_t = min(%s, 1.0);", t);
1100 break;
1101 default:
1102 // regular [0, 1] clamping
1103 fragBuilder->codeAppendf("half tiled_t = clamp(%s, 0.0, 1.0);", t);
1104 }
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001105 break;
1106 case GrSamplerState::WrapMode::kRepeat:
Florin Malita14a8dd72017-11-08 15:46:42 -05001107 fragBuilder->codeAppendf("half tiled_t = fract(%s);", t);
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001108 break;
1109 case GrSamplerState::WrapMode::kMirrorRepeat:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001110 fragBuilder->codeAppendf("half t_1 = %s - 1.0;", t);
Greg Daniel10ed2432017-12-01 16:19:43 -05001111 fragBuilder->codeAppendf("half tiled_t = t_1 - 2.0 * floor(t_1 * 0.5) - 1.0;");
1112 if (shaderCaps->mustDoOpBetweenFloorAndAbs()) {
1113 // At this point the expected value of tiled_t should between -1 and 1, so this
1114 // clamp has no effect other than to break up the floor and abs calls and make sure
1115 // the compiler doesn't merge them back together.
1116 fragBuilder->codeAppendf("tiled_t = clamp(tiled_t, -1.0, 1.0);");
1117 }
1118 fragBuilder->codeAppendf("tiled_t = abs(tiled_t);");
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001119 break;
Florin Malita8a0044f2017-08-07 14:38:22 -04001120 }
Florin Malita8a0044f2017-08-07 14:38:22 -04001121
Florin Malitab81a8b92017-08-08 12:14:17 -04001122 // Calculate the color.
Florin Malita14a8dd72017-11-08 15:46:42 -05001123 const char* intervals = uniformHandler->getUniformCStr(fIntervalsUni);
fmenozzicd9a1d02016-08-15 07:03:47 -07001124
Florin Malita14a8dd72017-11-08 15:46:42 -05001125 switch (ge.fStrategy) {
1126 case GrGradientEffect::InterpolationStrategy::kSingle:
1127 SkASSERT(ge.fIntervals.count() == 2);
1128 fragBuilder->codeAppendf(
1129 "half4 color_scale = %s[0],"
1130 " color_bias = %s[1];"
1131 , intervals, intervals
1132 );
fmenozzicd9a1d02016-08-15 07:03:47 -07001133 break;
Florin Malita14a8dd72017-11-08 15:46:42 -05001134 case GrGradientEffect::InterpolationStrategy::kThreshold:
1135 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1136 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1137 {
1138 SkASSERT(ge.fIntervals.count() == 4);
1139 const char* threshold = uniformHandler->getUniformCStr(fThresholdUni);
1140 fragBuilder->codeAppendf(
1141 "half4 color_scale, color_bias;"
1142 "if (tiled_t < %s) {"
1143 " color_scale = %s[0];"
1144 " color_bias = %s[1];"
1145 "} else {"
1146 " color_scale = %s[2];"
1147 " color_bias = %s[3];"
1148 "}"
1149 , threshold, intervals, intervals, intervals, intervals
1150 );
1151 } break;
Florin Malitab81a8b92017-08-08 12:14:17 -04001152 default:
1153 SkASSERT(false);
fmenozzicd9a1d02016-08-15 07:03:47 -07001154 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001155 }
Florin Malitab81a8b92017-08-08 12:14:17 -04001156
Florin Malita14a8dd72017-11-08 15:46:42 -05001157 fragBuilder->codeAppend("half4 colorTemp = tiled_t * color_scale + color_bias;");
1158
Brian Osmanfe3e8582017-10-20 11:27:49 -04001159 // We could skip this step if all colors are known to be opaque. Two considerations:
Florin Malitab81a8b92017-08-08 12:14:17 -04001160 // The gradient SkShader reporting opaque is more restrictive than necessary in the two
1161 // pt case. Make sure the key reflects this optimization (and note that it can use the
Brian Osmanfe3e8582017-10-20 11:27:49 -04001162 // same shader as the kBeforeInterp case).
Florin Malita14a8dd72017-11-08 15:46:42 -05001163 if (ge.fPremulType == GrGradientEffect::kAfterInterp_PremulType) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001164 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1165 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001166
1167 // If the input colors were floats, or there was a color space xform, we may end up out of
Brian Osman8f912d52017-10-26 12:10:11 -04001168 // range. The simplest solution is to always clamp our (premul) value here. We only need to
1169 // clamp RGB, but that causes hangs on the Tegra3 Nexus7. Clamping RGBA avoids the problem.
1170 fragBuilder->codeAppend("colorTemp = clamp(colorTemp, 0, colorTemp.a);");
Florin Malitab81a8b92017-08-08 12:14:17 -04001171
1172 fragBuilder->codeAppendf("%s = %s * colorTemp;", outputColor, inputColor);
1173}
1174
1175void GrGradientEffect::GLSLProcessor::emitColor(GrGLSLFPFragmentBuilder* fragBuilder,
1176 GrGLSLUniformHandler* uniformHandler,
1177 const GrShaderCaps* shaderCaps,
1178 const GrGradientEffect& ge,
1179 const char* gradientTValue,
1180 const char* outputColor,
1181 const char* inputColor,
1182 const TextureSamplers& texSamplers) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001183 if (ge.fStrategy != InterpolationStrategy::kTexture) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001184 this->emitAnalyticalColor(fragBuilder, uniformHandler, shaderCaps, ge, gradientTValue,
1185 outputColor, inputColor);
1186 return;
1187 }
1188
Florin Malitab81a8b92017-08-08 12:14:17 -04001189 const char* fsyuni = uniformHandler->getUniformCStr(fFSYUni);
1190
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001191 fragBuilder->codeAppendf("half2 coord = half2(%s, %s);", gradientTValue, fsyuni);
Florin Malitab81a8b92017-08-08 12:14:17 -04001192 fragBuilder->codeAppendf("%s = ", outputColor);
1193 fragBuilder->appendTextureLookupAndModulate(inputColor, texSamplers[0], "coord",
Brian Osman5911a7c2017-10-25 12:52:31 -04001194 kFloat2_GrSLType);
Florin Malitab81a8b92017-08-08 12:14:17 -04001195 fragBuilder->codeAppend(";");
rileya@google.comd7cc6512012-07-27 14:00:39 +00001196}
1197
1198/////////////////////////////////////////////////////////////////////
1199
Brian Salomon587e08f2017-01-27 10:59:27 -05001200inline GrFragmentProcessor::OptimizationFlags GrGradientEffect::OptFlags(bool isOpaque) {
Brian Salomonf3b995b2017-02-15 10:22:23 -05001201 return isOpaque
1202 ? kPreservesOpaqueInput_OptimizationFlag |
1203 kCompatibleWithCoverageAsAlpha_OptimizationFlag
1204 : kCompatibleWithCoverageAsAlpha_OptimizationFlag;
Brian Salomon587e08f2017-01-27 10:59:27 -05001205}
1206
Florin Malita14a8dd72017-11-08 15:46:42 -05001207void GrGradientEffect::addInterval(const SkGradientShaderBase& shader, size_t idx0, size_t idx1,
1208 SkColorSpace* dstCS) {
1209 SkASSERT(idx0 <= idx1);
1210 const auto c4f0 = shader.getXformedColor(idx0, dstCS),
1211 c4f1 = shader.getXformedColor(idx1, dstCS);
1212 const auto c0 = (fPremulType == kBeforeInterp_PremulType)
1213 ? c4f0.premul().to4f() : Sk4f::Load(c4f0.vec()),
1214 c1 = (fPremulType == kBeforeInterp_PremulType)
1215 ? c4f1.premul().to4f() : Sk4f::Load(c4f1.vec());
1216 const auto t0 = shader.getPos(idx0),
1217 t1 = shader.getPos(idx1),
1218 dt = t1 - t0;
1219 SkASSERT(dt >= 0);
1220 // dt can be 0 for clamp intervals => in this case we want a scale == 0
1221 const auto scale = SkScalarNearlyZero(dt) ? 0 : (c1 - c0) / dt,
1222 bias = c0 - t0 * scale;
1223
1224 // Intervals are stored as (scale, bias) tuples.
1225 SkASSERT(!(fIntervals.count() & 1));
1226 fIntervals.emplace_back(scale[0], scale[1], scale[2], scale[3]);
1227 fIntervals.emplace_back( bias[0], bias[1], bias[2], bias[3]);
1228}
1229
Ethan Nicholasabff9562017-10-09 10:54:08 -04001230GrGradientEffect::GrGradientEffect(ClassID classID, const CreateArgs& args, bool isOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001231 : INHERITED(classID, OptFlags(isOpaque))
1232 , fWrapMode(args.fWrapMode)
1233 , fRow(-1)
1234 , fIsOpaque(args.fShader->isOpaque())
1235 , fStrategy(InterpolationStrategy::kTexture)
1236 , fThreshold(0) {
1237
brianosman9557c272016-09-15 06:59:15 -07001238 const SkGradientShaderBase& shader(*args.fShader);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001239
Florin Malita14a8dd72017-11-08 15:46:42 -05001240 fPremulType = (args.fShader->getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag)
1241 ? kBeforeInterp_PremulType : kAfterInterp_PremulType;
bsalomon@google.com371e1052013-01-11 21:08:55 +00001242
Florin Malita14a8dd72017-11-08 15:46:42 -05001243 // First, determine the interpolation strategy and params.
1244 switch (shader.fColorCount) {
1245 case 2:
1246 SkASSERT(!shader.fOrigPos);
1247 fStrategy = InterpolationStrategy::kSingle;
1248 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1249 break;
1250 case 3:
1251 fThreshold = shader.getPos(1);
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +00001252
Florin Malita14a8dd72017-11-08 15:46:42 -05001253 if (shader.fOrigPos) {
1254 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1255 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[2], 1));
1256 if (SkScalarNearlyEqual(shader.fOrigPos[1], 0)) {
1257 // hard stop on the left edge.
1258 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1259 fStrategy = InterpolationStrategy::kThresholdClamp1;
1260 // Clamp interval (scale == 0, bias == colors[0]).
1261 this->addInterval(shader, 0, 0, args.fDstColorSpace);
1262 } else {
1263 // We can ignore the hard stop when not clamping.
1264 fStrategy = InterpolationStrategy::kSingle;
1265 }
1266 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1267 break;
1268 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001269
Florin Malita14a8dd72017-11-08 15:46:42 -05001270 if (SkScalarNearlyEqual(shader.fOrigPos[1], 1)) {
1271 // hard stop on the right edge.
1272 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1273 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1274 fStrategy = InterpolationStrategy::kThresholdClamp0;
1275 // Clamp interval (scale == 0, bias == colors[2]).
1276 this->addInterval(shader, 2, 2, args.fDstColorSpace);
1277 } else {
1278 // We can ignore the hard stop when not clamping.
1279 fStrategy = InterpolationStrategy::kSingle;
1280 }
1281 break;
1282 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001283 }
1284
Florin Malita14a8dd72017-11-08 15:46:42 -05001285 // Two arbitrary interpolation intervals.
1286 fStrategy = InterpolationStrategy::kThreshold;
1287 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1288 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1289 break;
1290 case 4:
1291 if (shader.fOrigPos && SkScalarNearlyEqual(shader.fOrigPos[1], shader.fOrigPos[2])) {
1292 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1293 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[3], 1));
fmenozzi2a495912016-08-12 06:33:52 -07001294
Florin Malita14a8dd72017-11-08 15:46:42 -05001295 // Single hard stop => two arbitrary interpolation intervals.
1296 fStrategy = InterpolationStrategy::kThreshold;
1297 fThreshold = shader.getPos(1);
1298 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1299 this->addInterval(shader, 2, 3, args.fDstColorSpace);
1300 }
1301 break;
1302 default:
1303 break;
fmenozzi2a495912016-08-12 06:33:52 -07001304 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001305
Florin Malita14a8dd72017-11-08 15:46:42 -05001306 // Now that we've locked down a strategy, adjust any dependent params.
1307 if (fStrategy != InterpolationStrategy::kTexture) {
1308 // Analytical cases.
1309 fCoordTransform.reset(*args.fMatrix);
1310 } else {
1311 SkGradientShaderBase::GradientBitmapType bitmapType =
1312 SkGradientShaderBase::GradientBitmapType::kLegacy;
1313 if (args.fDstColorSpace) {
1314 // Try to use F16 if we can
1315 if (args.fContext->caps()->isConfigTexturable(kRGBA_half_GrPixelConfig)) {
1316 bitmapType = SkGradientShaderBase::GradientBitmapType::kHalfFloat;
1317 } else if (args.fContext->caps()->isConfigTexturable(kSRGBA_8888_GrPixelConfig)) {
1318 bitmapType = SkGradientShaderBase::GradientBitmapType::kSRGB;
fmenozzicd9a1d02016-08-15 07:03:47 -07001319 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001320 // This can happen, but only if someone explicitly creates an unsupported
1321 // (eg sRGB) surface. Just fall back to legacy behavior.
fmenozzicd9a1d02016-08-15 07:03:47 -07001322 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001323 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001324
Florin Malita14a8dd72017-11-08 15:46:42 -05001325 SkBitmap bitmap;
1326 shader.getGradientTableBitmap(&bitmap, bitmapType);
1327 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
fmenozzicd9a1d02016-08-15 07:03:47 -07001328
Florin Malita14a8dd72017-11-08 15:46:42 -05001329
1330 GrTextureStripAtlas::Desc desc;
1331 desc.fWidth = bitmap.width();
1332 desc.fHeight = 32;
Robert Phillips7a926392018-02-01 15:49:54 -05001333 desc.fRowHeight = bitmap.height(); // always 1 here
Florin Malita14a8dd72017-11-08 15:46:42 -05001334 desc.fContext = args.fContext;
1335 desc.fConfig = SkImageInfo2GrPixelConfig(bitmap.info(), *args.fContext->caps());
1336 fAtlas = GrTextureStripAtlas::GetAtlas(desc);
1337 SkASSERT(fAtlas);
1338
1339 // We always filter the gradient table. Each table is one row of a texture, always
1340 // y-clamp.
1341 GrSamplerState samplerState(args.fWrapMode, GrSamplerState::Filter::kBilerp);
1342
1343 fRow = fAtlas->lockRow(bitmap);
1344 if (-1 != fRow) {
1345 fYCoord = fAtlas->getYOffset(fRow)+SK_ScalarHalf*fAtlas->getNormalizedTexelHeight();
1346 // This is 1/2 places where auto-normalization is disabled
1347 fCoordTransform.reset(*args.fMatrix, fAtlas->asTextureProxyRef().get(), false);
1348 fTextureSampler.reset(fAtlas->asTextureProxyRef(), samplerState);
1349 } else {
1350 // In this instance we know the samplerState state is:
1351 // clampY, bilerp
1352 // and the proxy is:
1353 // exact fit, power of two in both dimensions
1354 // Only the x-tileMode is unknown. However, given all the other knowns we know
Robert Phillips7a926392018-02-01 15:49:54 -05001355 // that GrMakeCachedImageProxy is sufficient (i.e., it won't need to be
Florin Malita14a8dd72017-11-08 15:46:42 -05001356 // extracted to a subset or mipmapped).
Robert Phillips7a926392018-02-01 15:49:54 -05001357
1358 SkASSERT(bitmap.isImmutable());
1359 sk_sp<SkImage> srcImage = SkImage::MakeFromBitmap(bitmap);
1360 if (!srcImage) {
1361 return;
1362 }
1363
1364 sk_sp<GrTextureProxy> proxy = GrMakeCachedImageProxy(
Robert Phillips1afd4cd2018-01-08 13:40:32 -05001365 args.fContext->contextPriv().proxyProvider(),
Robert Phillips7a926392018-02-01 15:49:54 -05001366 std::move(srcImage));
Florin Malita14a8dd72017-11-08 15:46:42 -05001367 if (!proxy) {
1368 SkDebugf("Gradient won't draw. Could not create texture.");
1369 return;
1370 }
1371 // This is 2/2 places where auto-normalization is disabled
1372 fCoordTransform.reset(*args.fMatrix, proxy.get(), false);
1373 fTextureSampler.reset(std::move(proxy), samplerState);
1374 fYCoord = SK_ScalarHalf;
1375 }
1376
1377 this->addTextureSampler(&fTextureSampler);
fmenozzicd9a1d02016-08-15 07:03:47 -07001378 }
1379
bsalomon@google.com77af6802013-10-02 13:04:56 +00001380 this->addCoordTransform(&fCoordTransform);
rileya@google.comd7cc6512012-07-27 14:00:39 +00001381}
1382
Brian Salomonf8480b92017-07-27 15:45:59 -04001383GrGradientEffect::GrGradientEffect(const GrGradientEffect& that)
Ethan Nicholasabff9562017-10-09 10:54:08 -04001384 : INHERITED(that.classID(), OptFlags(that.fIsOpaque))
Florin Malita14a8dd72017-11-08 15:46:42 -05001385 , fIntervals(that.fIntervals)
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001386 , fWrapMode(that.fWrapMode)
Brian Salomonf8480b92017-07-27 15:45:59 -04001387 , fCoordTransform(that.fCoordTransform)
1388 , fTextureSampler(that.fTextureSampler)
1389 , fYCoord(that.fYCoord)
1390 , fAtlas(that.fAtlas)
1391 , fRow(that.fRow)
1392 , fIsOpaque(that.fIsOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001393 , fStrategy(that.fStrategy)
1394 , fThreshold(that.fThreshold)
Brian Salomonf8480b92017-07-27 15:45:59 -04001395 , fPremulType(that.fPremulType) {
1396 this->addCoordTransform(&fCoordTransform);
Florin Malita14a8dd72017-11-08 15:46:42 -05001397 if (fStrategy == InterpolationStrategy::kTexture) {
Brian Salomonf8480b92017-07-27 15:45:59 -04001398 this->addTextureSampler(&fTextureSampler);
1399 }
1400 if (this->useAtlas()) {
1401 fAtlas->lockRow(fRow);
1402 }
1403}
1404
rileya@google.comd7cc6512012-07-27 14:00:39 +00001405GrGradientEffect::~GrGradientEffect() {
rileya@google.comb3e50f22012-08-20 17:43:08 +00001406 if (this->useAtlas()) {
1407 fAtlas->unlockRow(fRow);
rileya@google.comb3e50f22012-08-20 17:43:08 +00001408 }
rileya@google.comd7cc6512012-07-27 14:00:39 +00001409}
1410
bsalomon0e08fc12014-10-15 08:19:04 -07001411bool GrGradientEffect::onIsEqual(const GrFragmentProcessor& processor) const {
fmenozzicd9a1d02016-08-15 07:03:47 -07001412 const GrGradientEffect& ge = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +00001413
Florin Malita14a8dd72017-11-08 15:46:42 -05001414 if (fWrapMode != ge.fWrapMode || fStrategy != ge.fStrategy) {
Brian Salomon466ad992016-10-13 16:08:36 -04001415 return false;
1416 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001417
Brian Salomon466ad992016-10-13 16:08:36 -04001418 SkASSERT(this->useAtlas() == ge.useAtlas());
Florin Malita14a8dd72017-11-08 15:46:42 -05001419 if (fStrategy == InterpolationStrategy::kTexture) {
1420 if (fYCoord != ge.fYCoord) {
Brian Salomon466ad992016-10-13 16:08:36 -04001421 return false;
1422 }
1423 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001424 if (fThreshold != ge.fThreshold ||
1425 fIntervals != ge.fIntervals ||
1426 fPremulType != ge.fPremulType) {
Brian Salomon466ad992016-10-13 16:08:36 -04001427 return false;
1428 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001429 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001430 return true;
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001431}
1432
Hal Canary6f6961e2017-01-31 13:50:44 -05001433#if GR_TEST_UTILS
Brian Osman3f748602016-10-03 18:29:03 -04001434GrGradientEffect::RandomGradientParams::RandomGradientParams(SkRandom* random) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -05001435 // Set color count to min of 2 so that we don't trigger the const color optimization and make
1436 // a non-gradient processor.
1437 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
Brian Osmana2196532016-10-17 12:48:13 -04001438 fUseColors4f = random->nextBool();
bsalomon@google.comd4726202012-08-03 14:34:46 +00001439
1440 // if one color, omit stops, otherwise randomly decide whether or not to
Brian Osman3f748602016-10-03 18:29:03 -04001441 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
1442 fStops = nullptr;
1443 } else {
1444 fStops = fStopStorage;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001445 }
1446
Brian Osmana2196532016-10-17 12:48:13 -04001447 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
1448 if (fUseColors4f) {
1449 fColorSpace = GrTest::TestColorSpace(random);
1450 if (fColorSpace) {
Brian Osman36703d92017-12-12 14:09:31 -05001451 fColorSpace = fColorSpace->makeLinearGamma();
Brian Osmana2196532016-10-17 12:48:13 -04001452 }
1453 }
1454
bsalomon@google.com81712882012-11-01 17:12:34 +00001455 SkScalar stop = 0.f;
Brian Osman3f748602016-10-03 18:29:03 -04001456 for (int i = 0; i < fColorCount; ++i) {
Brian Osmana2196532016-10-17 12:48:13 -04001457 if (fUseColors4f) {
1458 fColors4f[i].fR = random->nextUScalar1();
1459 fColors4f[i].fG = random->nextUScalar1();
1460 fColors4f[i].fB = random->nextUScalar1();
1461 fColors4f[i].fA = random->nextUScalar1();
1462 } else {
1463 fColors[i] = random->nextU();
1464 }
Brian Osman3f748602016-10-03 18:29:03 -04001465 if (fStops) {
1466 fStops[i] = stop;
1467 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001468 }
1469 }
Brian Osman3f748602016-10-03 18:29:03 -04001470 fTileMode = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
bsalomon@google.comd4726202012-08-03 14:34:46 +00001471}
Hal Canary6f6961e2017-01-31 13:50:44 -05001472#endif
bsalomon@google.comd4726202012-08-03 14:34:46 +00001473
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001474#endif