blob: a8f76c47d46b551aa2870b12d5b5eb92950a8a65 [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>
Mike Kleinc0bd9f92019-04-23 12:05:21 -05009#include "include/core/SkMallocPixelRef.h"
10#include "include/private/SkFloatBits.h"
11#include "include/private/SkHalf.h"
Mike Klein85754d52020-01-22 10:04:11 -060012#include "include/private/SkVx.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/core/SkColorSpacePriv.h"
14#include "src/core/SkConvertPixels.h"
15#include "src/core/SkReadBuffer.h"
Mike Klein85754d52020-01-22 10:04:11 -060016#include "src/core/SkVM.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050017#include "src/core/SkWriteBuffer.h"
18#include "src/shaders/gradients/Sk4fLinearGradient.h"
19#include "src/shaders/gradients/SkGradientShaderPriv.h"
20#include "src/shaders/gradients/SkLinearGradient.h"
21#include "src/shaders/gradients/SkRadialGradient.h"
22#include "src/shaders/gradients/SkSweepGradient.h"
23#include "src/shaders/gradients/SkTwoPointConicalGradient.h"
rileya@google.com589708b2012-07-26 20:04:23 +000024
brianosmane25d71c2016-09-28 11:27:28 -070025enum GradientSerializationFlags {
26 // Bits 29:31 used for various boolean flags
27 kHasPosition_GSF = 0x80000000,
28 kHasLocalMatrix_GSF = 0x40000000,
29 kHasColorSpace_GSF = 0x20000000,
30
31 // Bits 12:28 unused
32
33 // Bits 8:11 for fTileMode
34 kTileModeShift_GSF = 8,
35 kTileModeMask_GSF = 0xF,
36
37 // Bits 0:7 for fGradFlags (note that kForce4fContext_PrivateFlag is 0x80)
38 kGradFlagsShift_GSF = 0,
39 kGradFlagsMask_GSF = 0xFF,
40};
41
reed9fa60da2014-08-21 07:59:51 -070042void SkGradientShaderBase::Descriptor::flatten(SkWriteBuffer& buffer) const {
brianosmane25d71c2016-09-28 11:27:28 -070043 uint32_t flags = 0;
reed9fa60da2014-08-21 07:59:51 -070044 if (fPos) {
brianosmane25d71c2016-09-28 11:27:28 -070045 flags |= kHasPosition_GSF;
reed9fa60da2014-08-21 07:59:51 -070046 }
reed9fa60da2014-08-21 07:59:51 -070047 if (fLocalMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -070048 flags |= kHasLocalMatrix_GSF;
49 }
50 sk_sp<SkData> colorSpaceData = fColorSpace ? fColorSpace->serialize() : nullptr;
51 if (colorSpaceData) {
52 flags |= kHasColorSpace_GSF;
53 }
54 SkASSERT(static_cast<uint32_t>(fTileMode) <= kTileModeMask_GSF);
Mike Reedfae8fce2019-04-03 10:27:45 -040055 flags |= ((unsigned)fTileMode << kTileModeShift_GSF);
brianosmane25d71c2016-09-28 11:27:28 -070056 SkASSERT(fGradFlags <= kGradFlagsMask_GSF);
57 flags |= (fGradFlags << kGradFlagsShift_GSF);
58
59 buffer.writeUInt(flags);
60
61 buffer.writeColor4fArray(fColors, fCount);
62 if (colorSpaceData) {
63 buffer.writeDataAsByteArray(colorSpaceData.get());
64 }
65 if (fPos) {
66 buffer.writeScalarArray(fPos, fCount);
67 }
68 if (fLocalMatrix) {
reed9fa60da2014-08-21 07:59:51 -070069 buffer.writeMatrix(*fLocalMatrix);
reed9fa60da2014-08-21 07:59:51 -070070 }
71}
72
Florin Malitaf77db112018-05-10 09:52:27 -040073template <int N, typename T, bool MEM_MOVE>
74static bool validate_array(SkReadBuffer& buffer, size_t count, SkSTArray<N, T, MEM_MOVE>* array) {
Kevin Lubickdaebae92018-05-17 11:29:10 -040075 if (!buffer.validateCanReadN<T>(count)) {
Florin Malitaf77db112018-05-10 09:52:27 -040076 return false;
77 }
78
79 array->resize_back(count);
80 return true;
81}
82
reed9fa60da2014-08-21 07:59:51 -070083bool SkGradientShaderBase::DescriptorScope::unflatten(SkReadBuffer& buffer) {
Mike Reed70bc94f2017-06-08 12:45:52 -040084 // New gradient format. Includes floating point color, color space, densely packed flags
85 uint32_t flags = buffer.readUInt();
reed9fa60da2014-08-21 07:59:51 -070086
Mike Reedfae8fce2019-04-03 10:27:45 -040087 fTileMode = (SkTileMode)((flags >> kTileModeShift_GSF) & kTileModeMask_GSF);
Mike Reed70bc94f2017-06-08 12:45:52 -040088 fGradFlags = (flags >> kGradFlagsShift_GSF) & kGradFlagsMask_GSF;
reed9fa60da2014-08-21 07:59:51 -070089
Mike Reed70bc94f2017-06-08 12:45:52 -040090 fCount = buffer.getArrayCount();
Florin Malitaf77db112018-05-10 09:52:27 -040091
92 if (!(validate_array(buffer, fCount, &fColorStorage) &&
93 buffer.readColor4fArray(fColorStorage.begin(), fCount))) {
Mike Reed70bc94f2017-06-08 12:45:52 -040094 return false;
95 }
Florin Malitaf77db112018-05-10 09:52:27 -040096 fColors = fColorStorage.begin();
97
Mike Reed70bc94f2017-06-08 12:45:52 -040098 if (SkToBool(flags & kHasColorSpace_GSF)) {
99 sk_sp<SkData> data = buffer.readByteArrayAsData();
Florin Malitac2ea3272018-05-10 09:41:38 -0400100 fColorSpace = data ? SkColorSpace::Deserialize(data->data(), data->size()) : nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -0400101 } else {
brianosmane25d71c2016-09-28 11:27:28 -0700102 fColorSpace = nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -0400103 }
104 if (SkToBool(flags & kHasPosition_GSF)) {
Florin Malitaf77db112018-05-10 09:52:27 -0400105 if (!(validate_array(buffer, fCount, &fPosStorage) &&
106 buffer.readScalarArray(fPosStorage.begin(), fCount))) {
Mike Reed70bc94f2017-06-08 12:45:52 -0400107 return false;
brianosmane25d71c2016-09-28 11:27:28 -0700108 }
Florin Malitaf77db112018-05-10 09:52:27 -0400109 fPos = fPosStorage.begin();
reed9fa60da2014-08-21 07:59:51 -0700110 } else {
Mike Reed70bc94f2017-06-08 12:45:52 -0400111 fPos = nullptr;
112 }
113 if (SkToBool(flags & kHasLocalMatrix_GSF)) {
114 fLocalMatrix = &fLocalMatrixStorage;
115 buffer.readMatrix(&fLocalMatrixStorage);
116 } else {
117 fLocalMatrix = nullptr;
reed9fa60da2014-08-21 07:59:51 -0700118 }
119 return buffer.isValid();
120}
121
122////////////////////////////////////////////////////////////////////////////////////////////
123
mtkleincc695fe2014-12-10 10:29:19 -0800124SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc, const SkMatrix& ptsToUnit)
reedaddf2ed2014-08-11 08:28:24 -0700125 : INHERITED(desc.fLocalMatrix)
mtkleincc695fe2014-12-10 10:29:19 -0800126 , fPtsToUnit(ptsToUnit)
Brian Osman6667fb12018-07-03 16:44:02 -0400127 , fColorSpace(desc.fColorSpace ? desc.fColorSpace : SkColorSpace::MakeSRGB())
Florin Malita39d71de2017-10-31 11:33:49 -0400128 , fColorsAreOpaque(true)
commit-bot@chromium.org9c9005a2014-04-28 14:55:39 +0000129{
mtkleincc695fe2014-12-10 10:29:19 -0800130 fPtsToUnit.getType(); // Precache so reads are threadsafe.
reed@google.com437d6eb2013-05-23 19:03:05 +0000131 SkASSERT(desc.fCount > 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000132
fmalita6d7e4e82016-09-20 06:55:16 -0700133 fGradFlags = static_cast<uint8_t>(desc.fGradFlags);
rileya@google.com589708b2012-07-26 20:04:23 +0000134
Mike Reedfae8fce2019-04-03 10:27:45 -0400135 SkASSERT((unsigned)desc.fTileMode < kSkTileModeCount);
reed@google.com437d6eb2013-05-23 19:03:05 +0000136 fTileMode = desc.fTileMode;
rileya@google.com589708b2012-07-26 20:04:23 +0000137
rileya@google.com589708b2012-07-26 20:04:23 +0000138 /* Note: we let the caller skip the first and/or last position.
139 i.e. pos[0] = 0.3, pos[1] = 0.7
140 In these cases, we insert dummy entries to ensure that the final data
141 will be bracketed by [0, 1].
142 i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
143
144 Thus colorCount (the caller's value, and fColorCount (our value) may
145 differ by up to 2. In the above example:
146 colorCount = 2
147 fColorCount = 4
148 */
reed@google.com437d6eb2013-05-23 19:03:05 +0000149 fColorCount = desc.fCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000150 // check if we need to add in dummy start and/or end position/colors
151 bool dummyFirst = false;
152 bool dummyLast = false;
reed@google.com437d6eb2013-05-23 19:03:05 +0000153 if (desc.fPos) {
154 dummyFirst = desc.fPos[0] != 0;
155 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
rileya@google.com589708b2012-07-26 20:04:23 +0000156 fColorCount += dummyFirst + dummyLast;
157 }
158
Mike Reed62ce2ca2018-02-19 14:20:15 -0500159 size_t storageSize = fColorCount * (sizeof(SkColor4f) + (desc.fPos ? sizeof(SkScalar) : 0));
Florin Malita89ab2402017-11-01 10:14:57 -0400160 fOrigColors4f = reinterpret_cast<SkColor4f*>(fStorage.reset(storageSize));
Mike Reed62ce2ca2018-02-19 14:20:15 -0500161 fOrigPos = desc.fPos ? reinterpret_cast<SkScalar*>(fOrigColors4f + fColorCount)
162 : nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000163
brianosmane25d71c2016-09-28 11:27:28 -0700164 // Now copy over the colors, adding the dummies as needed
165 SkColor4f* origColors = fOrigColors4f;
166 if (dummyFirst) {
167 *origColors++ = desc.fColors[0];
168 }
Florin Malita39d71de2017-10-31 11:33:49 -0400169 for (int i = 0; i < desc.fCount; ++i) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500170 origColors[i] = desc.fColors[i];
Florin Malita39d71de2017-10-31 11:33:49 -0400171 fColorsAreOpaque = fColorsAreOpaque && (desc.fColors[i].fA == 1);
172 }
brianosmane25d71c2016-09-28 11:27:28 -0700173 if (dummyLast) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500174 origColors += desc.fCount;
175 *origColors = desc.fColors[desc.fCount - 1];
brianosmane25d71c2016-09-28 11:27:28 -0700176 }
brianosmanb9c51372016-09-15 11:09:45 -0700177
Florin Malita89ab2402017-11-01 10:14:57 -0400178 if (desc.fPos) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400179 SkScalar prev = 0;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500180 SkScalar* origPosPtr = fOrigPos;
Florin Malita64bb78e2017-11-03 12:54:07 -0400181 *origPosPtr++ = prev; // force the first pos to 0
reed9fa60da2014-08-21 07:59:51 -0700182
Florin Malita89ab2402017-11-01 10:14:57 -0400183 int startIndex = dummyFirst ? 0 : 1;
184 int count = desc.fCount + dummyLast;
Florin Malita64bb78e2017-11-03 12:54:07 -0400185
186 bool uniformStops = true;
187 const SkScalar uniformStep = desc.fPos[startIndex] - prev;
Florin Malita89ab2402017-11-01 10:14:57 -0400188 for (int i = startIndex; i < count; i++) {
Florin Malita3e20d022017-11-03 12:11:38 -0400189 // Pin the last value to 1.0, and make sure pos is monotonic.
Florin Malita64bb78e2017-11-03 12:54:07 -0400190 auto curr = (i == desc.fCount) ? 1 : SkScalarPin(desc.fPos[i], prev, 1);
191 uniformStops &= SkScalarNearlyEqual(uniformStep, curr - prev);
192
193 *origPosPtr++ = prev = curr;
reed9fa60da2014-08-21 07:59:51 -0700194 }
Florin Malita64bb78e2017-11-03 12:54:07 -0400195
Florin Malita64bb78e2017-11-03 12:54:07 -0400196 // If the stops are uniform, treat them as implicit.
Mike Reed62ce2ca2018-02-19 14:20:15 -0500197 if (uniformStops) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400198 fOrigPos = nullptr;
199 }
rileya@google.com589708b2012-07-26 20:04:23 +0000200 }
rileya@google.com589708b2012-07-26 20:04:23 +0000201}
202
Florin Malita89ab2402017-11-01 10:14:57 -0400203SkGradientShaderBase::~SkGradientShaderBase() {}
rileya@google.com589708b2012-07-26 20:04:23 +0000204
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000205void SkGradientShaderBase::flatten(SkWriteBuffer& buffer) const {
reed9fa60da2014-08-21 07:59:51 -0700206 Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700207 desc.fColors = fOrigColors4f;
brianosmanb9c51372016-09-15 11:09:45 -0700208 desc.fColorSpace = fColorSpace;
reed9fa60da2014-08-21 07:59:51 -0700209 desc.fPos = fOrigPos;
210 desc.fCount = fColorCount;
211 desc.fTileMode = fTileMode;
212 desc.fGradFlags = fGradFlags;
213
214 const SkMatrix& m = this->getLocalMatrix();
halcanary96fcdcc2015-08-27 07:41:13 -0700215 desc.fLocalMatrix = m.isIdentity() ? nullptr : &m;
reed9fa60da2014-08-21 07:59:51 -0700216 desc.flatten(buffer);
rileya@google.com589708b2012-07-26 20:04:23 +0000217}
218
Mike Kleinb11ab572018-10-24 06:42:14 -0400219static void add_stop_color(SkRasterPipeline_GradientCtx* ctx, size_t stop, SkPMColor4f Fs, SkPMColor4f Bs) {
Brian Osman781e3502018-10-03 15:42:47 -0400220 (ctx->fs[0])[stop] = Fs.fR;
221 (ctx->fs[1])[stop] = Fs.fG;
222 (ctx->fs[2])[stop] = Fs.fB;
223 (ctx->fs[3])[stop] = Fs.fA;
Mike Klein85754d52020-01-22 10:04:11 -0600224
Brian Osman781e3502018-10-03 15:42:47 -0400225 (ctx->bs[0])[stop] = Bs.fR;
226 (ctx->bs[1])[stop] = Bs.fG;
227 (ctx->bs[2])[stop] = Bs.fB;
228 (ctx->bs[3])[stop] = Bs.fA;
Mike Kleinf945cbb2017-05-17 09:30:58 -0400229}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400230
Mike Kleinb11ab572018-10-24 06:42:14 -0400231static void add_const_color(SkRasterPipeline_GradientCtx* ctx, size_t stop, SkPMColor4f color) {
Brian Osman781e3502018-10-03 15:42:47 -0400232 add_stop_color(ctx, stop, { 0, 0, 0, 0 }, color);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400233}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400234
235// Calculate a factor F and a bias B so that color = F*t + B when t is in range of
236// the stop. Assume that the distance between stops is 1/gapCount.
237static void init_stop_evenly(
Mike Kleinb11ab572018-10-24 06:42:14 -0400238 SkRasterPipeline_GradientCtx* ctx, float gapCount, size_t stop, SkPMColor4f c_l, SkPMColor4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400239 // Clankium's GCC 4.9 targeting ARMv7 is barfing when we use Sk4f math here, so go scalar...
Brian Osman781e3502018-10-03 15:42:47 -0400240 SkPMColor4f Fs = {
241 (c_r.fR - c_l.fR) * gapCount,
242 (c_r.fG - c_l.fG) * gapCount,
243 (c_r.fB - c_l.fB) * gapCount,
244 (c_r.fA - c_l.fA) * gapCount,
245 };
246 SkPMColor4f Bs = {
247 c_l.fR - Fs.fR*(stop/gapCount),
248 c_l.fG - Fs.fG*(stop/gapCount),
249 c_l.fB - Fs.fB*(stop/gapCount),
250 c_l.fA - Fs.fA*(stop/gapCount),
251 };
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400252 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400253}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400254
255// For each stop we calculate a bias B and a scale factor F, such that
256// for any t between stops n and n+1, the color we want is B[n] + F[n]*t.
257static void init_stop_pos(
Mike Kleinb11ab572018-10-24 06:42:14 -0400258 SkRasterPipeline_GradientCtx* ctx, size_t stop, float t_l, float t_r, SkPMColor4f c_l, SkPMColor4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400259 // See note about Clankium's old compiler in init_stop_evenly().
Brian Osman781e3502018-10-03 15:42:47 -0400260 SkPMColor4f Fs = {
261 (c_r.fR - c_l.fR) / (t_r - t_l),
262 (c_r.fG - c_l.fG) / (t_r - t_l),
263 (c_r.fB - c_l.fB) / (t_r - t_l),
264 (c_r.fA - c_l.fA) / (t_r - t_l),
265 };
266 SkPMColor4f Bs = {
267 c_l.fR - Fs.fR*t_l,
268 c_l.fG - Fs.fG*t_l,
269 c_l.fB - Fs.fB*t_l,
270 c_l.fA - Fs.fA*t_l,
271 };
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400272 ctx->ts[stop] = t_l;
273 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400274}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400275
Mike Reed1386b2d2019-03-13 21:15:05 -0400276bool SkGradientShaderBase::onAppendStages(const SkStageRec& rec) const {
Mike Reed1d8c42e2017-08-29 14:58:19 -0400277 SkRasterPipeline* p = rec.fPipeline;
278 SkArenaAlloc* alloc = rec.fAlloc;
Mike Kleinb11ab572018-10-24 06:42:14 -0400279 SkRasterPipeline_DecalTileCtx* decal_ctx = nullptr;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400280
Mike Kleina3771842017-05-04 19:38:48 -0400281 SkMatrix matrix;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400282 if (!this->computeTotalInverse(rec.fCTM, rec.fLocalM, &matrix)) {
Mike Kleina3771842017-05-04 19:38:48 -0400283 return false;
284 }
Florin Malita50b20842017-07-29 19:08:28 -0400285 matrix.postConcat(fPtsToUnit);
Mike Kleina3771842017-05-04 19:38:48 -0400286
Florin Malita2e409002017-06-28 14:46:54 -0400287 SkRasterPipeline_<256> postPipeline;
Mike Kleina3771842017-05-04 19:38:48 -0400288
Mike Kleine8de0242018-03-10 12:37:11 -0500289 p->append(SkRasterPipeline::seed_shader);
Mike Reed6b59bf42017-07-03 21:26:44 -0400290 p->append_matrix(alloc, matrix);
Florin Malita50b20842017-07-29 19:08:28 -0400291 this->appendGradientStages(alloc, p, &postPipeline);
Mike Kleine7598532017-05-11 11:29:29 -0400292
Mike Reed62ce2ca2018-02-19 14:20:15 -0500293 switch(fTileMode) {
Mike Reedfae8fce2019-04-03 10:27:45 -0400294 case SkTileMode::kMirror: p->append(SkRasterPipeline::mirror_x_1); break;
295 case SkTileMode::kRepeat: p->append(SkRasterPipeline::repeat_x_1); break;
296 case SkTileMode::kDecal:
Mike Kleinb11ab572018-10-24 06:42:14 -0400297 decal_ctx = alloc->make<SkRasterPipeline_DecalTileCtx>();
Mike Reed62ce2ca2018-02-19 14:20:15 -0500298 decal_ctx->limit_x = SkBits2Float(SkFloat2Bits(1.0f) + 1);
299 // reuse mask + limit_x stage, or create a custom decal_1 that just stores the mask
300 p->append(SkRasterPipeline::decal_x, decal_ctx);
301 // fall-through to clamp
Mike Reedfae8fce2019-04-03 10:27:45 -0400302 case SkTileMode::kClamp:
Mike Kleine7598532017-05-11 11:29:29 -0400303 if (!fOrigPos) {
304 // We clamp only when the stops are evenly spaced.
305 // If not, there may be hard stops, and clamping ruins hard stops at 0 and/or 1.
Mike Klein5c7960b2017-05-11 10:59:22 -0400306 // In that case, we must make sure we're using the general "gradient" stage,
Mike Kleine7598532017-05-11 11:29:29 -0400307 // which is the only stage that will correctly handle unclamped t.
Mike Klein9f85d682017-05-23 07:52:01 -0400308 p->append(SkRasterPipeline::clamp_x_1);
Mike Kleine7598532017-05-11 11:29:29 -0400309 }
Mike Reed62ce2ca2018-02-19 14:20:15 -0500310 break;
Mike Kleine7598532017-05-11 11:29:29 -0400311 }
Mike Kleina3771842017-05-04 19:38:48 -0400312
313 const bool premulGrad = fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag;
Brian Osman6667fb12018-07-03 16:44:02 -0400314
315 // Transform all of the colors to destination color space
316 SkColor4fXformer xformedColors(fOrigColors4f, fColorCount, fColorSpace.get(), rec.fDstCS);
317
318 auto prepareColor = [premulGrad, &xformedColors](int i) {
319 SkColor4f c = xformedColors.fColors[i];
Brian Osman781e3502018-10-03 15:42:47 -0400320 return premulGrad ? c.premul()
321 : SkPMColor4f{ c.fR, c.fG, c.fB, c.fA };
Mike Kleina3771842017-05-04 19:38:48 -0400322 };
323
324 // The two-stop case with stops at 0 and 1.
325 if (fColorCount == 2 && fOrigPos == nullptr) {
Brian Osman781e3502018-10-03 15:42:47 -0400326 const SkPMColor4f c_l = prepareColor(0),
327 c_r = prepareColor(1);
Mike Kleina3771842017-05-04 19:38:48 -0400328
329 // See F and B below.
Mike Kleinb11ab572018-10-24 06:42:14 -0400330 auto ctx = alloc->make<SkRasterPipeline_EvenlySpaced2StopGradientCtx>();
Brian Osman781e3502018-10-03 15:42:47 -0400331 (Sk4f::Load(c_r.vec()) - Sk4f::Load(c_l.vec())).store(ctx->f);
332 ( Sk4f::Load(c_l.vec())).store(ctx->b);
Mike Klein24de6482018-09-07 12:05:29 -0400333 ctx->interpolatedInPremul = premulGrad;
Mike Kleina3771842017-05-04 19:38:48 -0400334
Mike Klein24de6482018-09-07 12:05:29 -0400335 p->append(SkRasterPipeline::evenly_spaced_2_stop_gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400336 } else {
Mike Kleinb11ab572018-10-24 06:42:14 -0400337 auto* ctx = alloc->make<SkRasterPipeline_GradientCtx>();
Mike Klein24de6482018-09-07 12:05:29 -0400338 ctx->interpolatedInPremul = premulGrad;
Herb Derby4de13042017-05-15 10:49:39 -0400339
340 // Note: In order to handle clamps in search, the search assumes a stop conceptully placed
341 // at -inf. Therefore, the max number of stops is fColorCount+1.
342 for (int i = 0; i < 4; i++) {
343 // Allocate at least at for the AVX2 gather from a YMM register.
344 ctx->fs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
345 ctx->bs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
346 }
347
Mike Kleina3771842017-05-04 19:38:48 -0400348 if (fOrigPos == nullptr) {
349 // Handle evenly distributed stops.
350
Herb Derby4de13042017-05-15 10:49:39 -0400351 size_t stopCount = fColorCount;
352 float gapCount = stopCount - 1;
Mike Kleina3771842017-05-04 19:38:48 -0400353
Brian Osman781e3502018-10-03 15:42:47 -0400354 SkPMColor4f c_l = prepareColor(0);
Herb Derby4de13042017-05-15 10:49:39 -0400355 for (size_t i = 0; i < stopCount - 1; i++) {
Brian Osman781e3502018-10-03 15:42:47 -0400356 SkPMColor4f c_r = prepareColor(i + 1);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400357 init_stop_evenly(ctx, gapCount, i, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400358 c_l = c_r;
359 }
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400360 add_const_color(ctx, stopCount - 1, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400361
Herb Derby4de13042017-05-15 10:49:39 -0400362 ctx->stopCount = stopCount;
363 p->append(SkRasterPipeline::evenly_spaced_gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400364 } else {
365 // Handle arbitrary stops.
366
Herb Derby4de13042017-05-15 10:49:39 -0400367 ctx->ts = alloc->makeArray<float>(fColorCount+1);
368
Mike Kleina3771842017-05-04 19:38:48 -0400369 // Remove the dummy stops inserted by SkGradientShaderBase::SkGradientShaderBase
370 // because they are naturally handled by the search method.
371 int firstStop;
372 int lastStop;
373 if (fColorCount > 2) {
374 firstStop = fOrigColors4f[0] != fOrigColors4f[1] ? 0 : 1;
375 lastStop = fOrigColors4f[fColorCount - 2] != fOrigColors4f[fColorCount - 1]
376 ? fColorCount - 1 : fColorCount - 2;
377 } else {
378 firstStop = 0;
379 lastStop = 1;
380 }
Mike Kleina3771842017-05-04 19:38:48 -0400381
Mike Kleina3771842017-05-04 19:38:48 -0400382 size_t stopCount = 0;
383 float t_l = fOrigPos[firstStop];
Brian Osman781e3502018-10-03 15:42:47 -0400384 SkPMColor4f c_l = prepareColor(firstStop);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400385 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400386 // N.B. lastStop is the index of the last stop, not one after.
387 for (int i = firstStop; i < lastStop; i++) {
388 float t_r = fOrigPos[i + 1];
Brian Osman781e3502018-10-03 15:42:47 -0400389 SkPMColor4f c_r = prepareColor(i + 1);
Florin Malita3e20d022017-11-03 12:11:38 -0400390 SkASSERT(t_l <= t_r);
Mike Kleina3771842017-05-04 19:38:48 -0400391 if (t_l < t_r) {
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400392 init_stop_pos(ctx, stopCount, t_l, t_r, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400393 stopCount += 1;
394 }
395 t_l = t_r;
396 c_l = c_r;
397 }
398
Herb Derby4de13042017-05-15 10:49:39 -0400399 ctx->ts[stopCount] = t_l;
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400400 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400401
Herb Derby4de13042017-05-15 10:49:39 -0400402 ctx->stopCount = stopCount;
403 p->append(SkRasterPipeline::gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400404 }
Mike Kleina3771842017-05-04 19:38:48 -0400405 }
406
Mike Reed62ce2ca2018-02-19 14:20:15 -0500407 if (decal_ctx) {
408 p->append(SkRasterPipeline::check_decal_mask, decal_ctx);
409 }
410
Mike Kleina3771842017-05-04 19:38:48 -0400411 if (!premulGrad && !this->colorsAreOpaque()) {
Mike Kleine7598532017-05-11 11:29:29 -0400412 p->append(SkRasterPipeline::premul);
Mike Kleina3771842017-05-04 19:38:48 -0400413 }
414
Florin Malita2e409002017-06-28 14:46:54 -0400415 p->extend(postPipeline);
416
Mike Kleina3771842017-05-04 19:38:48 -0400417 return true;
418}
419
Mike Klein85754d52020-01-22 10:04:11 -0600420bool SkGradientShaderBase::onProgram(skvm::Builder* p,
421 const SkMatrix& ctm, const SkMatrix* localM,
422 SkFilterQuality quality, SkColorSpace* dstCS,
423 skvm::Uniforms* uniforms, SkArenaAlloc* alloc,
424 skvm::F32 x, skvm::F32 y,
425 skvm::F32* r, skvm::F32* g, skvm::F32* b, skvm::F32* a) const {
426 SkMatrix inv;
427 if (!this->computeTotalInverse(ctm, localM, &inv)) {
428 return false;
429 }
430 inv.postConcat(fPtsToUnit);
431 inv.normalizePerspective();
432
433 // Having tacked on fPtsToUnit at the end means we'll be left with t in x.
434 SkShaderBase::ApplyMatrix(p, inv, &x,&y,uniforms);
435 skvm::F32 t = x;
436 if (!this->transformT(p, &t)) { // Hook into subclasses for linear, radial, etc.
437 return false;
438 }
439
440 // Most tiling happens here, with kDecal doing its work at the end.
441 // Perhaps unexpectedly, all clamping is handled by our search, so
442 // we don't explicitly clamp t to [0,1]. That clamp would break
443 // hard stops right at 0 or 1 boundaries in kClamp mode.
444 // (kRepeat and kMirror always produce values in [0,1].)
445 switch(fTileMode) {
446 case SkTileMode::kDecal: break;
447 case SkTileMode::kClamp: break;
448 case SkTileMode::kRepeat: t = p->sub(t, p->floor(t)); break;
449 case SkTileMode::kMirror: {
450 // t = | (t-1) - 2*(floor( (t-1)*0.5 )) - 1 |
451 // {-A-} {--------B-------}
452 skvm::F32 A = p->sub(t, p->splat(1.0f)),
453 B = p->floor( p->mul(A, p->splat(0.5f)));
454 t = p->abs(p->sub(p->sub(A, p->add(B,B)),
455 p->splat(1.0f)));
456 } break;
457 }
458
459 // Transform our colors as we want them interpolated, in dst color space, possibly premul.
460 SkImageInfo common = SkImageInfo::Make(fColorCount,1, kRGBA_F32_SkColorType
461 , kUnpremul_SkAlphaType),
462 src = common.makeColorSpace(fColorSpace),
463 dst = common.makeColorSpace(sk_ref_sp(dstCS));
464 if (fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag) {
465 dst = dst.makeAlphaType(kPremul_SkAlphaType);
466 }
467
468 std::vector<float> rgba(4*fColorCount); // TODO: SkSTArray?
469 SkConvertPixels(dst, rgba.data(), dst.minRowBytes(),
470 src, fOrigColors4f, src.minRowBytes());
471
472 // Transform our colors into a scale factor f and bias b such that for
473 // any t between stops i and i+1, the color we want is mad(t, f[i], b[i]).
474 using F4 = skvx::Vec<4,float>;
475 struct FB { F4 f,b; };
476
477 if (fColorCount == 2) {
478 // 2-stop gradients have colors at 0 and 1, and so must be evenly spaced.
479 SkASSERT(fOrigPos == nullptr);
480
481 // With 2 stops, we upload the single FB as uniforms and interpolate directly with t.
482 F4 lo = F4::Load(rgba.data() + 0),
483 hi = F4::Load(rgba.data() + 4);
484 F4 F = hi - lo,
485 B = lo;
486
487 auto T = p->clamp(t, p->splat(0.0f), p->splat(1.0f));
488 *r = p->mad(T, p->uniformF(uniforms->pushF(F[0])), p->uniformF(uniforms->pushF(B[0])));
489 *g = p->mad(T, p->uniformF(uniforms->pushF(F[1])), p->uniformF(uniforms->pushF(B[1])));
490 *b = p->mad(T, p->uniformF(uniforms->pushF(F[2])), p->uniformF(uniforms->pushF(B[2])));
491 *a = p->mad(T, p->uniformF(uniforms->pushF(F[3])), p->uniformF(uniforms->pushF(B[3])));
492 } else {
493 // To handle clamps in search we add a conceptual stop at t=-inf, so we
494 // may need up to fColorCount+1 FBs and fColorCount t stops between them:
495 //
496 // FBs: [color 0] [color 0->1] [color 1->2] [color 2->3] ...
497 // stops: (-inf) t0 t1 t2 ...
498 //
499 // Both these arrays could end up shorter if any hard stops share the same t.
500 FB* fb = alloc->makeArrayDefault<FB>(fColorCount+1);
501 std::vector<float> stops; // TODO: SkSTArray?
502 stops.reserve(fColorCount);
503
504 // Here's our conceptual stop at t=-inf covering all t<=0, clamping to our first color.
505 float t_lo = this->getPos(0);
506 F4 color_lo = F4::Load(rgba.data());
507 fb[0] = { 0.0f, color_lo };
508 // N.B. No stops[] entry for this implicit -inf.
509
510 // Now the non-edge cases, calculating scale and bias between adjacent normal stops.
511 for (int i = 1; i < fColorCount; i++) {
512 float t_hi = this->getPos(i);
513 F4 color_hi = F4::Load(rgba.data() + 4*i);
514
515 // If t_lo == t_hi, we're on a hard stop, and transition immediately to the next color.
516 SkASSERT(t_lo <= t_hi);
517 if (t_lo < t_hi) {
518 F4 f = (color_hi - color_lo) / (t_hi - t_lo),
519 b = color_lo - f*t_lo;
520 stops.push_back(t_lo);
521 fb[stops.size()] = {f,b};
522 }
523
524 t_lo = t_hi;
525 color_lo = color_hi;
526 }
527 // Anything >= our final t clamps to our final color.
528 stops.push_back(t_lo);
529 fb[stops.size()] = { 0.0f, color_lo };
530
531 // We'll gather FBs from that array we just created.
532 skvm::Builder::Uniform fbs = uniforms->pushPtr(fb);
533
534 // Find the two stops we need to interpolate.
535 skvm::I32 ix;
536 if (fOrigPos == nullptr) {
537 // Evenly spaced stops... we can calculate ix directly.
538 // Of note: we need to clamp t and skip over that conceptual -inf stop we made up.
539 ix = p->trunc(p->mad(p->clamp(t, p->splat(0.0f), p->splat(1.0f)),
540 p->uniformF(uniforms->pushF(stops.size() - 1.0f)),
541 p->splat(1.0f)));
542 } else {
543 // Starting ix at 0 bakes in our conceptual first stop at -inf.
544 // TODO: good place to experiment with a loop in skvm.... stops.size() can be huge.
545 ix = p->splat(0);
546 for (float stop : stops) {
547 // ix += (t >= stop) ? +1 : 0 ~~>
548 // ix -= (t >= stop) ? -1 : 0
549 ix = p->sub(ix, p->gte(t, p->uniformF(uniforms->pushF(stop))));
550 }
551 // TODO: we could skip any of the dummy stops GradientShaderBase's ctor added
552 // to ensure the full [0,1] span is covered. This linear search doesn't need
553 // them for correctness, and it'd be up to two fewer stops to check.
554 // N.B. we do still need those stops for the fOrigPos == nullptr direct math path.
555 }
556
557 // A scale factor and bias for each lane, 8 total.
558 // TODO: simpler, faster, tidier to push 8 uniform pointers, one for each struct lane?
559 ix = p->shl(ix, 3); skvm::F32 Fr = p->bit_cast(p->gather32(fbs, ix));
560 ix = p->add(ix, p->splat(1)); skvm::F32 Fg = p->bit_cast(p->gather32(fbs, ix));
561 ix = p->add(ix, p->splat(1)); skvm::F32 Fb = p->bit_cast(p->gather32(fbs, ix));
562 ix = p->add(ix, p->splat(1)); skvm::F32 Fa = p->bit_cast(p->gather32(fbs, ix));
563
564 ix = p->add(ix, p->splat(1)); skvm::F32 Br = p->bit_cast(p->gather32(fbs, ix));
565 ix = p->add(ix, p->splat(1)); skvm::F32 Bg = p->bit_cast(p->gather32(fbs, ix));
566 ix = p->add(ix, p->splat(1)); skvm::F32 Bb = p->bit_cast(p->gather32(fbs, ix));
567 ix = p->add(ix, p->splat(1)); skvm::F32 Ba = p->bit_cast(p->gather32(fbs, ix));
568
569 // This is what we've been building towards!
570 *r = p->mad(t, Fr, Br);
571 *g = p->mad(t, Fg, Bg);
572 *b = p->mad(t, Fb, Bb);
573 *a = p->mad(t, Fa, Ba);
574 }
575
576 // If we interpolated unpremul, premul now to match our output convention.
577 if (0 == (fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag)
578 && !fColorsAreOpaque) {
579 p->premul(r,g,b,*a);
580 }
581
582 // Mask away any pixels that we tried to sample outside the bounds in kDecal.
583 if (fTileMode == SkTileMode::kDecal) {
584 skvm::I32 in_bounds = p->eq(t, p->clamp(t, p->splat(0.0f), p->splat(1.0f)));
585 *r = p->bit_cast(p->bit_and(in_bounds, p->bit_cast(*r)));
586 *g = p->bit_cast(p->bit_and(in_bounds, p->bit_cast(*g)));
587 *b = p->bit_cast(p->bit_and(in_bounds, p->bit_cast(*b)));
588 *a = p->bit_cast(p->bit_and(in_bounds, p->bit_cast(*a)));
589 }
590
591 return true;
592}
593
Mike Kleina3771842017-05-04 19:38:48 -0400594
rileya@google.com589708b2012-07-26 20:04:23 +0000595bool SkGradientShaderBase::isOpaque() const {
Mike Reedfae8fce2019-04-03 10:27:45 -0400596 return fColorsAreOpaque && (this->getTileMode() != SkTileMode::kDecal);
Mike Reed62ce2ca2018-02-19 14:20:15 -0500597}
598
reed8367b8c2014-08-22 08:30:20 -0700599static unsigned rounded_divide(unsigned numer, unsigned denom) {
600 return (numer + (denom >> 1)) / denom;
601}
602
603bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
604 // we just compute an average color.
605 // possibly we could weight this based on the proportional width for each color
606 // assuming they are not evenly distributed in the fPos array.
607 int r = 0;
608 int g = 0;
609 int b = 0;
610 const int n = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400611 // TODO: use linear colors?
reed8367b8c2014-08-22 08:30:20 -0700612 for (int i = 0; i < n; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400613 SkColor c = this->getLegacyColor(i);
reed8367b8c2014-08-22 08:30:20 -0700614 r += SkColorGetR(c);
615 g += SkColorGetG(c);
616 b += SkColorGetB(c);
617 }
618 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
619 return true;
620}
621
Brian Osman6667fb12018-07-03 16:44:02 -0400622SkColor4fXformer::SkColor4fXformer(const SkColor4f* colors, int colorCount,
623 SkColorSpace* src, SkColorSpace* dst) {
Brian Osman6667fb12018-07-03 16:44:02 -0400624 fColors = colors;
Brian Osmanccd39952018-07-06 16:16:43 -0400625
Mike Kleinf9f68ff2018-10-12 14:23:06 -0400626 if (dst && !SkColorSpace::Equals(src, dst)) {
Brian Osman6667fb12018-07-03 16:44:02 -0400627 fStorage.reset(colorCount);
Brian Salomon5dfcf132018-10-12 14:39:32 +0000628
629 auto info = SkImageInfo::Make(colorCount,1, kRGBA_F32_SkColorType, kUnpremul_SkAlphaType);
630
631 SkConvertPixels(info.makeColorSpace(sk_ref_sp(dst)), fStorage.begin(), info.minRowBytes(),
632 info.makeColorSpace(sk_ref_sp(src)), fColors , info.minRowBytes());
633
Brian Osman6667fb12018-07-03 16:44:02 -0400634 fColors = fStorage.begin();
635 }
636}
637
Florin Malita5f379a82017-10-18 16:22:35 -0400638void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000639 if (info) {
640 if (info->fColorCount >= fColorCount) {
641 if (info->fColors) {
Florin Malita39d71de2017-10-31 11:33:49 -0400642 for (int i = 0; i < fColorCount; ++i) {
643 info->fColors[i] = this->getLegacyColor(i);
644 }
rileya@google.com589708b2012-07-26 20:04:23 +0000645 }
646 if (info->fColorOffsets) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400647 for (int i = 0; i < fColorCount; ++i) {
648 info->fColorOffsets[i] = this->getPos(i);
rileya@google.com589708b2012-07-26 20:04:23 +0000649 }
650 }
651 }
652 info->fColorCount = fColorCount;
653 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000654 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000655 }
656}
657
658///////////////////////////////////////////////////////////////////////////////
659///////////////////////////////////////////////////////////////////////////////
660
reed1b747302015-01-06 07:13:19 -0800661// Return true if these parameters are valid/legal/safe to construct a gradient
662//
brianosmane25d71c2016-09-28 11:27:28 -0700663static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
Mike Reedfae8fce2019-04-03 10:27:45 -0400664 SkTileMode tileMode) {
665 return nullptr != colors && count >= 1 && (unsigned)tileMode < kSkTileModeCount;
reed1b747302015-01-06 07:13:19 -0800666}
667
reed@google.com437d6eb2013-05-23 19:03:05 +0000668static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700669 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
670 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400671 SkTileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700672 SkASSERT(colorCount > 1);
673
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000674 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700675 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000676 desc->fPos = pos;
677 desc->fCount = colorCount;
678 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000679 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700680 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000681}
682
Mike Klein024072a2018-11-11 00:26:30 +0000683static SkColor4f average_gradient_color(const SkColor4f colors[], const SkScalar pos[],
684 int colorCount) {
685 // The gradient is a piecewise linear interpolation between colors. For a given interval,
686 // the integral between the two endpoints is 0.5 * (ci + cj) * (pj - pi), which provides that
687 // intervals average color. The overall average color is thus the sum of each piece. The thing
688 // to keep in mind is that the provided gradient definition may implicitly use p=0 and p=1.
689 Sk4f blend(0.0);
690 // Bake 1/(colorCount - 1) uniform stop difference into this scale factor
691 SkScalar wScale = pos ? 0.5 : 0.5 / (colorCount - 1);
692 for (int i = 0; i < colorCount - 1; ++i) {
693 // Calculate the average color for the interval between pos(i) and pos(i+1)
694 Sk4f c0 = Sk4f::Load(&colors[i]);
695 Sk4f c1 = Sk4f::Load(&colors[i + 1]);
696 // when pos == null, there are colorCount uniformly distributed stops, going from 0 to 1,
697 // so pos[i + 1] - pos[i] = 1/(colorCount-1)
698 SkScalar w = pos ? (pos[i + 1] - pos[i]) : SK_Scalar1;
699 blend += wScale * w * (c1 + c0);
700 }
701
702 // Now account for any implicit intervals at the start or end of the stop definitions
703 if (pos) {
704 if (pos[0] > 0.0) {
705 // The first color is fixed between p = 0 to pos[0], so 0.5 * (ci + cj) * (pj - pi)
706 // becomes 0.5 * (c + c) * (pj - 0) = c * pj
707 Sk4f c = Sk4f::Load(&colors[0]);
708 blend += pos[0] * c;
709 }
710 if (pos[colorCount - 1] < SK_Scalar1) {
711 // The last color is fixed between pos[n-1] to p = 1, so 0.5 * (ci + cj) * (pj - pi)
712 // becomes 0.5 * (c + c) * (1 - pi) = c * (1 - pi)
713 Sk4f c = Sk4f::Load(&colors[colorCount - 1]);
714 blend += (1 - pos[colorCount - 1]) * c;
715 }
716 }
717
718 SkColor4f avg;
719 blend.store(&avg);
720 return avg;
721}
722
Michael Ludwigd431c722018-11-16 10:00:24 -0500723// The default SkScalarNearlyZero threshold of .0024 is too big and causes regressions for svg
724// gradients defined in the wild.
725static constexpr SkScalar kDegenerateThreshold = SK_Scalar1 / (1 << 15);
726
Mike Klein024072a2018-11-11 00:26:30 +0000727// Except for special circumstances of clamped gradients, every gradient shape--when degenerate--
728// can be mapped to the same fallbacks. The specific shape factories must account for special
729// clamped conditions separately, this will always return the last color for clamped gradients.
730static sk_sp<SkShader> make_degenerate_gradient(const SkColor4f colors[], const SkScalar pos[],
731 int colorCount, sk_sp<SkColorSpace> colorSpace,
Mike Reedfae8fce2019-04-03 10:27:45 -0400732 SkTileMode mode) {
Mike Klein024072a2018-11-11 00:26:30 +0000733 switch(mode) {
Mike Reedfae8fce2019-04-03 10:27:45 -0400734 case SkTileMode::kDecal:
Mike Klein024072a2018-11-11 00:26:30 +0000735 // normally this would reject the area outside of the interpolation region, so since
736 // inside region is empty when the radii are equal, the entire draw region is empty
Mike Reedc8bea7d2019-04-09 13:55:36 -0400737 return SkShaders::Empty();
Mike Reedfae8fce2019-04-03 10:27:45 -0400738 case SkTileMode::kRepeat:
739 case SkTileMode::kMirror:
Mike Klein024072a2018-11-11 00:26:30 +0000740 // repeat and mirror are treated the same: the border colors are never visible,
741 // but approximate the final color as infinite repetitions of the colors, so
742 // it can be represented as the average color of the gradient.
Mike Reedc8bea7d2019-04-09 13:55:36 -0400743 return SkShaders::Color(
Mike Klein024072a2018-11-11 00:26:30 +0000744 average_gradient_color(colors, pos, colorCount), std::move(colorSpace));
Mike Reedfae8fce2019-04-03 10:27:45 -0400745 case SkTileMode::kClamp:
Mike Klein024072a2018-11-11 00:26:30 +0000746 // Depending on how the gradient shape degenerates, there may be a more specialized
747 // fallback representation for the factories to use, but this is a reasonable default.
Mike Reedc8bea7d2019-04-09 13:55:36 -0400748 return SkShaders::Color(colors[colorCount - 1], std::move(colorSpace));
Mike Klein024072a2018-11-11 00:26:30 +0000749 }
Mike Reedfae8fce2019-04-03 10:27:45 -0400750 SkDEBUGFAIL("Should not be reached");
751 return nullptr;
Mike Klein024072a2018-11-11 00:26:30 +0000752}
753
brianosmane25d71c2016-09-28 11:27:28 -0700754// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700755#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700756 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700757 do { \
758 if (1 == count) { \
759 tmp[0] = tmp[1] = colors[0]; \
760 colors = tmp; \
761 pos = nullptr; \
762 count = 2; \
763 } \
764 } while (0)
765
fmenozzi68d952c2016-08-19 08:56:56 -0700766struct ColorStopOptimizer {
Mike Reedfae8fce2019-04-03 10:27:45 -0400767 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos, int count, SkTileMode mode)
fmenozzi68d952c2016-08-19 08:56:56 -0700768 : fColors(colors)
769 , fPos(pos)
770 , fCount(count) {
771
772 if (!pos || count != 3) {
773 return;
774 }
775
776 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
777 SkScalarNearlyEqual(pos[1], 0.0f) &&
778 SkScalarNearlyEqual(pos[2], 1.0f)) {
779
Mike Reedfae8fce2019-04-03 10:27:45 -0400780 if (SkTileMode::kRepeat == mode || SkTileMode::kMirror == mode ||
fmenozzi68d952c2016-08-19 08:56:56 -0700781 colors[0] == colors[1]) {
782
fmalita582a6562016-08-22 06:28:57 -0700783 // Ignore the leftmost color/pos.
784 fColors += 1;
785 fPos += 1;
786 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700787 }
788 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
789 SkScalarNearlyEqual(pos[1], 1.0f) &&
790 SkScalarNearlyEqual(pos[2], 1.0f)) {
791
Mike Reedfae8fce2019-04-03 10:27:45 -0400792 if (SkTileMode::kRepeat == mode || SkTileMode::kMirror == mode ||
fmenozzi68d952c2016-08-19 08:56:56 -0700793 colors[1] == colors[2]) {
794
fmalita582a6562016-08-22 06:28:57 -0700795 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700796 fCount = 2;
797 }
798 }
799 }
800
brianosmane25d71c2016-09-28 11:27:28 -0700801 const SkColor4f* fColors;
802 const SkScalar* fPos;
803 int fCount;
804};
805
806struct ColorConverter {
807 ColorConverter(const SkColor* colors, int count) {
Brian Osman6667fb12018-07-03 16:44:02 -0400808 const float ONE_OVER_255 = 1.f / 255;
brianosmane25d71c2016-09-28 11:27:28 -0700809 for (int i = 0; i < count; ++i) {
Brian Osman6667fb12018-07-03 16:44:02 -0400810 fColors4f.push_back({
811 SkColorGetR(colors[i]) * ONE_OVER_255,
812 SkColorGetG(colors[i]) * ONE_OVER_255,
813 SkColorGetB(colors[i]) * ONE_OVER_255,
814 SkColorGetA(colors[i]) * ONE_OVER_255 });
brianosmane25d71c2016-09-28 11:27:28 -0700815 }
816 }
817
818 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700819};
820
reed8a21c9f2016-03-08 18:50:00 -0800821sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700822 const SkColor colors[],
823 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400824 SkTileMode mode,
fmenozzi68d952c2016-08-19 08:56:56 -0700825 uint32_t flags,
826 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700827 ColorConverter converter(colors, colorCount);
828 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
829 localMatrix);
830}
831
832sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
833 const SkColor4f colors[],
834 sk_sp<SkColorSpace> colorSpace,
835 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400836 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700837 uint32_t flags,
838 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700839 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700840 return nullptr;
reed1b747302015-01-06 07:13:19 -0800841 }
842 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700843 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000844 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700845 if (1 == colorCount) {
Mike Reedc8bea7d2019-04-09 13:55:36 -0400846 return SkShaders::Color(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700847 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000848 if (localMatrix && !localMatrix->invert(nullptr)) {
849 return nullptr;
850 }
rileya@google.com589708b2012-07-26 20:04:23 +0000851
Michael Ludwigd431c722018-11-16 10:00:24 -0500852 if (SkScalarNearlyZero((pts[1] - pts[0]).length(), kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000853 // Degenerate gradient, the only tricky complication is when in clamp mode, the limit of
854 // the gradient approaches two half planes of solid color (first and last). However, they
855 // are divided by the line perpendicular to the start and end point, which becomes undefined
856 // once start and end are exactly the same, so just use the end color for a stable solution.
857 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
858 }
859
fmenozzi68d952c2016-08-19 08:56:56 -0700860 ColorStopOptimizer opt(colors, pos, colorCount, mode);
861
reed@google.com437d6eb2013-05-23 19:03:05 +0000862 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700863 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
864 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800865 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000866}
867
reed8a21c9f2016-03-08 18:50:00 -0800868sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700869 const SkColor colors[],
870 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400871 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700872 uint32_t flags,
873 const SkMatrix* localMatrix) {
874 ColorConverter converter(colors, colorCount);
875 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
876 flags, localMatrix);
877}
878
879sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
880 const SkColor4f colors[],
881 sk_sp<SkColorSpace> colorSpace,
882 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400883 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700884 uint32_t flags,
885 const SkMatrix* localMatrix) {
Mike Klein024072a2018-11-11 00:26:30 +0000886 if (radius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700887 return nullptr;
reed1b747302015-01-06 07:13:19 -0800888 }
889 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700890 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000891 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700892 if (1 == colorCount) {
Mike Reedc8bea7d2019-04-09 13:55:36 -0400893 return SkShaders::Color(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700894 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000895 if (localMatrix && !localMatrix->invert(nullptr)) {
896 return nullptr;
897 }
rileya@google.com589708b2012-07-26 20:04:23 +0000898
Michael Ludwigd431c722018-11-16 10:00:24 -0500899 if (SkScalarNearlyZero(radius, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000900 // Degenerate gradient optimization, and no special logic needed for clamped radial gradient
901 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
902 }
903
fmenozzi68d952c2016-08-19 08:56:56 -0700904 ColorStopOptimizer opt(colors, pos, colorCount, mode);
905
reed@google.com437d6eb2013-05-23 19:03:05 +0000906 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700907 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
908 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800909 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000910}
911
reed8a21c9f2016-03-08 18:50:00 -0800912sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -0700913 SkScalar startRadius,
914 const SkPoint& end,
915 SkScalar endRadius,
916 const SkColor colors[],
917 const SkScalar pos[],
918 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400919 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700920 uint32_t flags,
921 const SkMatrix* localMatrix) {
922 ColorConverter converter(colors, colorCount);
923 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
924 nullptr, pos, colorCount, mode, flags, localMatrix);
925}
926
927sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
928 SkScalar startRadius,
929 const SkPoint& end,
930 SkScalar endRadius,
931 const SkColor4f colors[],
932 sk_sp<SkColorSpace> colorSpace,
933 const SkScalar pos[],
934 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400935 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700936 uint32_t flags,
937 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800938 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700939 return nullptr;
reed1b747302015-01-06 07:13:19 -0800940 }
941 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700942 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000943 }
Michael Ludwigd431c722018-11-16 10:00:24 -0500944 if (SkScalarNearlyZero((start - end).length(), kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000945 // If the center positions are the same, then the gradient is the radial variant of a 2 pt
946 // conical gradient, an actual radial gradient (startRadius == 0), or it is fully degenerate
947 // (startRadius == endRadius).
Michael Ludwigd431c722018-11-16 10:00:24 -0500948 if (SkScalarNearlyEqual(startRadius, endRadius, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000949 // Degenerate case, where the interpolation region area approaches zero. The proper
950 // behavior depends on the tile mode, which is consistent with the default degenerate
951 // gradient behavior, except when mode = clamp and the radii > 0.
Mike Reedfae8fce2019-04-03 10:27:45 -0400952 if (mode == SkTileMode::kClamp && endRadius > kDegenerateThreshold) {
Mike Klein024072a2018-11-11 00:26:30 +0000953 // The interpolation region becomes an infinitely thin ring at the radius, so the
954 // final gradient will be the first color repeated from p=0 to 1, and then a hard
955 // stop switching to the last color at p=1.
956 static constexpr SkScalar circlePos[3] = {0, 1, 1};
957 SkColor4f reColors[3] = {colors[0], colors[0], colors[colorCount - 1]};
958 return MakeRadial(start, endRadius, reColors, std::move(colorSpace),
959 circlePos, 3, mode, flags, localMatrix);
960 } else {
961 // Otherwise use the default degenerate case
962 return make_degenerate_gradient(
963 colors, pos, colorCount, std::move(colorSpace), mode);
964 }
Michael Ludwigd431c722018-11-16 10:00:24 -0500965 } else if (SkScalarNearlyZero(startRadius, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000966 // We can treat this gradient as radial, which is faster. If we got here, we know
967 // that endRadius is not equal to 0, so this produces a meaningful gradient
968 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
969 mode, flags, localMatrix);
Brian Osman2dfab272018-11-06 00:41:40 +0000970 }
Mike Klein024072a2018-11-11 00:26:30 +0000971 // Else it's the 2pt conical radial variant with no degenerate radii, so fall through to the
972 // regular 2pt constructor.
Brian Osman2dfab272018-11-06 00:41:40 +0000973 }
Mike Klein024072a2018-11-11 00:26:30 +0000974
Florin Malita8d3ffad2017-02-03 18:21:17 +0000975 if (localMatrix && !localMatrix->invert(nullptr)) {
976 return nullptr;
977 }
reed6b7a6c72016-08-18 16:13:50 -0700978 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000979
fmenozzi68d952c2016-08-19 08:56:56 -0700980 ColorStopOptimizer opt(colors, pos, colorCount, mode);
981
reed@google.com437d6eb2013-05-23 19:03:05 +0000982 SkGradientShaderBase::Descriptor desc;
Florin Malita5f379a82017-10-18 16:22:35 -0400983 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
984 localMatrix);
985 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000986}
987
reed8a21c9f2016-03-08 18:50:00 -0800988sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -0700989 const SkColor colors[],
990 const SkScalar pos[],
991 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400992 SkTileMode mode,
Florin Malita5a9a9812017-08-01 16:38:08 -0400993 SkScalar startAngle,
994 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700995 uint32_t flags,
996 const SkMatrix* localMatrix) {
997 ColorConverter converter(colors, colorCount);
Florin Malita5a9a9812017-08-01 16:38:08 -0400998 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
999 mode, startAngle, endAngle, flags, localMatrix);
brianosmane25d71c2016-09-28 11:27:28 -07001000}
1001
1002sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
1003 const SkColor4f colors[],
1004 sk_sp<SkColorSpace> colorSpace,
1005 const SkScalar pos[],
1006 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -04001007 SkTileMode mode,
Florin Malita5a9a9812017-08-01 16:38:08 -04001008 SkScalar startAngle,
1009 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -07001010 uint32_t flags,
1011 const SkMatrix* localMatrix) {
Florin Malita5a9a9812017-08-01 16:38:08 -04001012 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001013 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +00001014 }
fmenozzie9fd0f82016-08-19 07:50:57 -07001015 if (1 == colorCount) {
Mike Reedc8bea7d2019-04-09 13:55:36 -04001016 return SkShaders::Color(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -07001017 }
Mike Klein024072a2018-11-11 00:26:30 +00001018 if (!SkScalarIsFinite(startAngle) || !SkScalarIsFinite(endAngle) || startAngle > endAngle) {
Florin Malita5a9a9812017-08-01 16:38:08 -04001019 return nullptr;
1020 }
Florin Malita8d3ffad2017-02-03 18:21:17 +00001021 if (localMatrix && !localMatrix->invert(nullptr)) {
1022 return nullptr;
1023 }
rileya@google.com589708b2012-07-26 20:04:23 +00001024
Michael Ludwigd431c722018-11-16 10:00:24 -05001025 if (SkScalarNearlyEqual(startAngle, endAngle, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +00001026 // Degenerate gradient, which should follow default degenerate behavior unless it is
1027 // clamped and the angle is greater than 0.
Mike Reedfae8fce2019-04-03 10:27:45 -04001028 if (mode == SkTileMode::kClamp && endAngle > kDegenerateThreshold) {
Mike Klein024072a2018-11-11 00:26:30 +00001029 // In this case, the first color is repeated from 0 to the angle, then a hardstop
1030 // switches to the last color (all other colors are compressed to the infinitely thin
1031 // interpolation region).
1032 static constexpr SkScalar clampPos[3] = {0, 1, 1};
1033 SkColor4f reColors[3] = {colors[0], colors[0], colors[colorCount - 1]};
1034 return MakeSweep(cx, cy, reColors, std::move(colorSpace), clampPos, 3, mode, 0,
1035 endAngle, flags, localMatrix);
1036 } else {
1037 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
1038 }
1039 }
1040
Florin Malita5a9a9812017-08-01 16:38:08 -04001041 if (startAngle <= 0 && endAngle >= 360) {
1042 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
Mike Reedfae8fce2019-04-03 10:27:45 -04001043 mode = SkTileMode::kClamp;
Florin Malita5a9a9812017-08-01 16:38:08 -04001044 }
fmenozzi68d952c2016-08-19 08:56:56 -07001045
1046 ColorStopOptimizer opt(colors, pos, colorCount, mode);
1047
reed@google.com437d6eb2013-05-23 19:03:05 +00001048 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -07001049 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
1050 localMatrix);
Florin Malita5a9a9812017-08-01 16:38:08 -04001051
1052 const SkScalar t0 = startAngle / 360,
1053 t1 = endAngle / 360;
1054
1055 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
rileya@google.com589708b2012-07-26 20:04:23 +00001056}
1057
Mike Kleinfa5f6ce2018-10-20 08:21:31 -04001058void SkGradientShader::RegisterFlattenables() {
Brian Salomon23356442018-11-30 15:33:19 -05001059 SK_REGISTER_FLATTENABLE(SkLinearGradient);
1060 SK_REGISTER_FLATTENABLE(SkRadialGradient);
1061 SK_REGISTER_FLATTENABLE(SkSweepGradient);
1062 SK_REGISTER_FLATTENABLE(SkTwoPointConicalGradient);
Mike Klein12956722018-10-19 10:00:21 -04001063}