blob: 4c6a42571aee2ebe3aee2a76bd45cd15464c03dd [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"
Cary Clark4dc5a452018-05-21 11:56:57 -040012#include "SkFlattenablePriv.h"
Florin Malitacad3b8c2017-10-28 21:42:50 -040013#include "SkFloatBits.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040014#include "SkGradientBitmapCache.h"
rileya@google.com589708b2012-07-26 20:04:23 +000015#include "SkGradientShaderPriv.h"
brianosmand4546092016-09-22 12:31:58 -070016#include "SkHalf.h"
rileya@google.com589708b2012-07-26 20:04:23 +000017#include "SkLinearGradient.h"
Mike Reed6b3155c2017-04-03 14:41:44 -040018#include "SkMallocPixelRef.h"
rileya@google.com589708b2012-07-26 20:04:23 +000019#include "SkRadialGradient.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040020#include "SkReadBuffer.h"
Mike Klein02ab8cc2017-05-04 22:41:05 +000021#include "SkSweepGradient.h"
Mike Kleina3771842017-05-04 19:38:48 -040022#include "SkTwoPointConicalGradient.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040023#include "SkWriteBuffer.h"
Herb Derby4de13042017-05-15 10:49:39 -040024#include "../../jumper/SkJumper.h"
25
rileya@google.com589708b2012-07-26 20:04:23 +000026
brianosmane25d71c2016-09-28 11:27:28 -070027enum GradientSerializationFlags {
28 // Bits 29:31 used for various boolean flags
29 kHasPosition_GSF = 0x80000000,
30 kHasLocalMatrix_GSF = 0x40000000,
31 kHasColorSpace_GSF = 0x20000000,
32
33 // Bits 12:28 unused
34
35 // Bits 8:11 for fTileMode
36 kTileModeShift_GSF = 8,
37 kTileModeMask_GSF = 0xF,
38
39 // Bits 0:7 for fGradFlags (note that kForce4fContext_PrivateFlag is 0x80)
40 kGradFlagsShift_GSF = 0,
41 kGradFlagsMask_GSF = 0xFF,
42};
43
reed9fa60da2014-08-21 07:59:51 -070044void SkGradientShaderBase::Descriptor::flatten(SkWriteBuffer& buffer) const {
brianosmane25d71c2016-09-28 11:27:28 -070045 uint32_t flags = 0;
reed9fa60da2014-08-21 07:59:51 -070046 if (fPos) {
brianosmane25d71c2016-09-28 11:27:28 -070047 flags |= kHasPosition_GSF;
reed9fa60da2014-08-21 07:59:51 -070048 }
reed9fa60da2014-08-21 07:59:51 -070049 if (fLocalMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -070050 flags |= kHasLocalMatrix_GSF;
51 }
52 sk_sp<SkData> colorSpaceData = fColorSpace ? fColorSpace->serialize() : nullptr;
53 if (colorSpaceData) {
54 flags |= kHasColorSpace_GSF;
55 }
56 SkASSERT(static_cast<uint32_t>(fTileMode) <= kTileModeMask_GSF);
57 flags |= (fTileMode << kTileModeShift_GSF);
58 SkASSERT(fGradFlags <= kGradFlagsMask_GSF);
59 flags |= (fGradFlags << kGradFlagsShift_GSF);
60
61 buffer.writeUInt(flags);
62
63 buffer.writeColor4fArray(fColors, fCount);
64 if (colorSpaceData) {
65 buffer.writeDataAsByteArray(colorSpaceData.get());
66 }
67 if (fPos) {
68 buffer.writeScalarArray(fPos, fCount);
69 }
70 if (fLocalMatrix) {
reed9fa60da2014-08-21 07:59:51 -070071 buffer.writeMatrix(*fLocalMatrix);
reed9fa60da2014-08-21 07:59:51 -070072 }
73}
74
Florin Malitaf77db112018-05-10 09:52:27 -040075template <int N, typename T, bool MEM_MOVE>
76static bool validate_array(SkReadBuffer& buffer, size_t count, SkSTArray<N, T, MEM_MOVE>* array) {
Kevin Lubickdaebae92018-05-17 11:29:10 -040077 if (!buffer.validateCanReadN<T>(count)) {
Florin Malitaf77db112018-05-10 09:52:27 -040078 return false;
79 }
80
81 array->resize_back(count);
82 return true;
83}
84
reed9fa60da2014-08-21 07:59:51 -070085bool SkGradientShaderBase::DescriptorScope::unflatten(SkReadBuffer& buffer) {
Mike Reed70bc94f2017-06-08 12:45:52 -040086 // New gradient format. Includes floating point color, color space, densely packed flags
87 uint32_t flags = buffer.readUInt();
reed9fa60da2014-08-21 07:59:51 -070088
Mike Reed70bc94f2017-06-08 12:45:52 -040089 fTileMode = (SkShader::TileMode)((flags >> kTileModeShift_GSF) & kTileModeMask_GSF);
90 fGradFlags = (flags >> kGradFlagsShift_GSF) & kGradFlagsMask_GSF;
reed9fa60da2014-08-21 07:59:51 -070091
Mike Reed70bc94f2017-06-08 12:45:52 -040092 fCount = buffer.getArrayCount();
Florin Malitaf77db112018-05-10 09:52:27 -040093
94 if (!(validate_array(buffer, fCount, &fColorStorage) &&
95 buffer.readColor4fArray(fColorStorage.begin(), fCount))) {
Mike Reed70bc94f2017-06-08 12:45:52 -040096 return false;
97 }
Florin Malitaf77db112018-05-10 09:52:27 -040098 fColors = fColorStorage.begin();
99
Mike Reed70bc94f2017-06-08 12:45:52 -0400100 if (SkToBool(flags & kHasColorSpace_GSF)) {
101 sk_sp<SkData> data = buffer.readByteArrayAsData();
Florin Malitac2ea3272018-05-10 09:41:38 -0400102 fColorSpace = data ? SkColorSpace::Deserialize(data->data(), data->size()) : nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -0400103 } else {
brianosmane25d71c2016-09-28 11:27:28 -0700104 fColorSpace = nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -0400105 }
106 if (SkToBool(flags & kHasPosition_GSF)) {
Florin Malitaf77db112018-05-10 09:52:27 -0400107 if (!(validate_array(buffer, fCount, &fPosStorage) &&
108 buffer.readScalarArray(fPosStorage.begin(), fCount))) {
Mike Reed70bc94f2017-06-08 12:45:52 -0400109 return false;
brianosmane25d71c2016-09-28 11:27:28 -0700110 }
Florin Malitaf77db112018-05-10 09:52:27 -0400111 fPos = fPosStorage.begin();
reed9fa60da2014-08-21 07:59:51 -0700112 } else {
Mike Reed70bc94f2017-06-08 12:45:52 -0400113 fPos = nullptr;
114 }
115 if (SkToBool(flags & kHasLocalMatrix_GSF)) {
116 fLocalMatrix = &fLocalMatrixStorage;
117 buffer.readMatrix(&fLocalMatrixStorage);
118 } else {
119 fLocalMatrix = nullptr;
reed9fa60da2014-08-21 07:59:51 -0700120 }
121 return buffer.isValid();
122}
123
124////////////////////////////////////////////////////////////////////////////////////////////
125
mtkleincc695fe2014-12-10 10:29:19 -0800126SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc, const SkMatrix& ptsToUnit)
reedaddf2ed2014-08-11 08:28:24 -0700127 : INHERITED(desc.fLocalMatrix)
mtkleincc695fe2014-12-10 10:29:19 -0800128 , fPtsToUnit(ptsToUnit)
Florin Malitaabc85752018-04-25 22:18:37 -0400129 , fColorSpace(desc.fColorSpace ? desc.fColorSpace : SkColorSpace::MakeSRGBLinear())
Florin Malita39d71de2017-10-31 11:33:49 -0400130 , fColorsAreOpaque(true)
commit-bot@chromium.org9c9005a2014-04-28 14:55:39 +0000131{
mtkleincc695fe2014-12-10 10:29:19 -0800132 fPtsToUnit.getType(); // Precache so reads are threadsafe.
reed@google.com437d6eb2013-05-23 19:03:05 +0000133 SkASSERT(desc.fCount > 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000134
fmalita6d7e4e82016-09-20 06:55:16 -0700135 fGradFlags = static_cast<uint8_t>(desc.fGradFlags);
rileya@google.com589708b2012-07-26 20:04:23 +0000136
reed@google.com437d6eb2013-05-23 19:03:05 +0000137 SkASSERT((unsigned)desc.fTileMode < SkShader::kTileModeCount);
reed@google.com437d6eb2013-05-23 19:03:05 +0000138 fTileMode = desc.fTileMode;
rileya@google.com589708b2012-07-26 20:04:23 +0000139
rileya@google.com589708b2012-07-26 20:04:23 +0000140 /* Note: we let the caller skip the first and/or last position.
141 i.e. pos[0] = 0.3, pos[1] = 0.7
142 In these cases, we insert dummy entries to ensure that the final data
143 will be bracketed by [0, 1].
144 i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
145
146 Thus colorCount (the caller's value, and fColorCount (our value) may
147 differ by up to 2. In the above example:
148 colorCount = 2
149 fColorCount = 4
150 */
reed@google.com437d6eb2013-05-23 19:03:05 +0000151 fColorCount = desc.fCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000152 // check if we need to add in dummy start and/or end position/colors
153 bool dummyFirst = false;
154 bool dummyLast = false;
reed@google.com437d6eb2013-05-23 19:03:05 +0000155 if (desc.fPos) {
156 dummyFirst = desc.fPos[0] != 0;
157 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
rileya@google.com589708b2012-07-26 20:04:23 +0000158 fColorCount += dummyFirst + dummyLast;
159 }
160
Mike Reed62ce2ca2018-02-19 14:20:15 -0500161 size_t storageSize = fColorCount * (sizeof(SkColor4f) + (desc.fPos ? sizeof(SkScalar) : 0));
Florin Malita89ab2402017-11-01 10:14:57 -0400162 fOrigColors4f = reinterpret_cast<SkColor4f*>(fStorage.reset(storageSize));
Mike Reed62ce2ca2018-02-19 14:20:15 -0500163 fOrigPos = desc.fPos ? reinterpret_cast<SkScalar*>(fOrigColors4f + fColorCount)
164 : 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;
168 if (dummyFirst) {
169 *origColors++ = desc.fColors[0];
170 }
Florin Malita39d71de2017-10-31 11:33:49 -0400171 for (int i = 0; i < desc.fCount; ++i) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500172 origColors[i] = desc.fColors[i];
Florin Malita39d71de2017-10-31 11:33:49 -0400173 fColorsAreOpaque = fColorsAreOpaque && (desc.fColors[i].fA == 1);
174 }
brianosmane25d71c2016-09-28 11:27:28 -0700175 if (dummyLast) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500176 origColors += desc.fCount;
177 *origColors = desc.fColors[desc.fCount - 1];
brianosmane25d71c2016-09-28 11:27:28 -0700178 }
brianosmanb9c51372016-09-15 11:09:45 -0700179
Florin Malita89ab2402017-11-01 10:14:57 -0400180 if (desc.fPos) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400181 SkScalar prev = 0;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500182 SkScalar* origPosPtr = fOrigPos;
Florin Malita64bb78e2017-11-03 12:54:07 -0400183 *origPosPtr++ = prev; // force the first pos to 0
reed9fa60da2014-08-21 07:59:51 -0700184
Florin Malita89ab2402017-11-01 10:14:57 -0400185 int startIndex = dummyFirst ? 0 : 1;
186 int count = desc.fCount + dummyLast;
Florin Malita64bb78e2017-11-03 12:54:07 -0400187
188 bool uniformStops = true;
189 const SkScalar uniformStep = desc.fPos[startIndex] - prev;
Florin Malita89ab2402017-11-01 10:14:57 -0400190 for (int i = startIndex; i < count; i++) {
Florin Malita3e20d022017-11-03 12:11:38 -0400191 // Pin the last value to 1.0, and make sure pos is monotonic.
Florin Malita64bb78e2017-11-03 12:54:07 -0400192 auto curr = (i == desc.fCount) ? 1 : SkScalarPin(desc.fPos[i], prev, 1);
193 uniformStops &= SkScalarNearlyEqual(uniformStep, curr - prev);
194
195 *origPosPtr++ = prev = curr;
reed9fa60da2014-08-21 07:59:51 -0700196 }
Florin Malita64bb78e2017-11-03 12:54:07 -0400197
Florin Malita64bb78e2017-11-03 12:54:07 -0400198 // If the stops are uniform, treat them as implicit.
Mike Reed62ce2ca2018-02-19 14:20:15 -0500199 if (uniformStops) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400200 fOrigPos = nullptr;
201 }
rileya@google.com589708b2012-07-26 20:04:23 +0000202 }
rileya@google.com589708b2012-07-26 20:04:23 +0000203}
204
Florin Malita89ab2402017-11-01 10:14:57 -0400205SkGradientShaderBase::~SkGradientShaderBase() {}
rileya@google.com589708b2012-07-26 20:04:23 +0000206
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000207void SkGradientShaderBase::flatten(SkWriteBuffer& buffer) const {
reed9fa60da2014-08-21 07:59:51 -0700208 Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700209 desc.fColors = fOrigColors4f;
brianosmanb9c51372016-09-15 11:09:45 -0700210 desc.fColorSpace = fColorSpace;
reed9fa60da2014-08-21 07:59:51 -0700211 desc.fPos = fOrigPos;
212 desc.fCount = fColorCount;
213 desc.fTileMode = fTileMode;
214 desc.fGradFlags = fGradFlags;
215
216 const SkMatrix& m = this->getLocalMatrix();
halcanary96fcdcc2015-08-27 07:41:13 -0700217 desc.fLocalMatrix = m.isIdentity() ? nullptr : &m;
reed9fa60da2014-08-21 07:59:51 -0700218 desc.flatten(buffer);
rileya@google.com589708b2012-07-26 20:04:23 +0000219}
220
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400221static void add_stop_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f Fs, SkPM4f Bs) {
222 (ctx->fs[0])[stop] = Fs.r();
223 (ctx->fs[1])[stop] = Fs.g();
224 (ctx->fs[2])[stop] = Fs.b();
225 (ctx->fs[3])[stop] = Fs.a();
226 (ctx->bs[0])[stop] = Bs.r();
227 (ctx->bs[1])[stop] = Bs.g();
228 (ctx->bs[2])[stop] = Bs.b();
229 (ctx->bs[3])[stop] = Bs.a();
Mike Kleinf945cbb2017-05-17 09:30:58 -0400230}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400231
232static void add_const_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f color) {
233 add_stop_color(ctx, stop, SkPM4f::FromPremulRGBA(0,0,0,0), color);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400234}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400235
236// Calculate a factor F and a bias B so that color = F*t + B when t is in range of
237// the stop. Assume that the distance between stops is 1/gapCount.
238static void init_stop_evenly(
239 SkJumper_GradientCtx* ctx, float gapCount, size_t stop, SkPM4f c_l, SkPM4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400240 // Clankium's GCC 4.9 targeting ARMv7 is barfing when we use Sk4f math here, so go scalar...
241 SkPM4f Fs = {{
242 (c_r.r() - c_l.r()) * gapCount,
243 (c_r.g() - c_l.g()) * gapCount,
244 (c_r.b() - c_l.b()) * gapCount,
245 (c_r.a() - c_l.a()) * gapCount,
246 }};
247 SkPM4f Bs = {{
248 c_l.r() - Fs.r()*(stop/gapCount),
249 c_l.g() - Fs.g()*(stop/gapCount),
250 c_l.b() - Fs.b()*(stop/gapCount),
251 c_l.a() - Fs.a()*(stop/gapCount),
252 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400253 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400254}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400255
256// For each stop we calculate a bias B and a scale factor F, such that
257// for any t between stops n and n+1, the color we want is B[n] + F[n]*t.
258static void init_stop_pos(
259 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 -0400260 // See note about Clankium's old compiler in init_stop_evenly().
261 SkPM4f Fs = {{
262 (c_r.r() - c_l.r()) / (t_r - t_l),
263 (c_r.g() - c_l.g()) / (t_r - t_l),
264 (c_r.b() - c_l.b()) / (t_r - t_l),
265 (c_r.a() - c_l.a()) / (t_r - t_l),
266 }};
267 SkPM4f Bs = {{
268 c_l.r() - Fs.r()*t_l,
269 c_l.g() - Fs.g()*t_l,
270 c_l.b() - Fs.b()*t_l,
271 c_l.a() - Fs.a()*t_l,
272 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400273 ctx->ts[stop] = t_l;
274 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400275}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400276
Mike Reed1d8c42e2017-08-29 14:58:19 -0400277bool SkGradientShaderBase::onAppendStages(const StageRec& rec) const {
278 SkRasterPipeline* p = rec.fPipeline;
279 SkArenaAlloc* alloc = rec.fAlloc;
280 SkColorSpace* dstCS = rec.fDstCS;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500281 SkJumper_DecalTileCtx* decal_ctx = nullptr;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400282
Mike Kleina3771842017-05-04 19:38:48 -0400283 SkMatrix matrix;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400284 if (!this->computeTotalInverse(rec.fCTM, rec.fLocalM, &matrix)) {
Mike Kleina3771842017-05-04 19:38:48 -0400285 return false;
286 }
Florin Malita50b20842017-07-29 19:08:28 -0400287 matrix.postConcat(fPtsToUnit);
Mike Kleina3771842017-05-04 19:38:48 -0400288
Florin Malita2e409002017-06-28 14:46:54 -0400289 SkRasterPipeline_<256> postPipeline;
Mike Kleina3771842017-05-04 19:38:48 -0400290
Mike Kleine8de0242018-03-10 12:37:11 -0500291 p->append(SkRasterPipeline::seed_shader);
Mike Reed6b59bf42017-07-03 21:26:44 -0400292 p->append_matrix(alloc, matrix);
Florin Malita50b20842017-07-29 19:08:28 -0400293 this->appendGradientStages(alloc, p, &postPipeline);
Mike Kleine7598532017-05-11 11:29:29 -0400294
Mike Reed62ce2ca2018-02-19 14:20:15 -0500295 switch(fTileMode) {
Mike Klein9f85d682017-05-23 07:52:01 -0400296 case kMirror_TileMode: p->append(SkRasterPipeline::mirror_x_1); break;
297 case kRepeat_TileMode: p->append(SkRasterPipeline::repeat_x_1); break;
Mike Reeddfc0e912018-02-16 12:40:18 -0500298 case kDecal_TileMode:
Mike Reed62ce2ca2018-02-19 14:20:15 -0500299 decal_ctx = alloc->make<SkJumper_DecalTileCtx>();
300 decal_ctx->limit_x = SkBits2Float(SkFloat2Bits(1.0f) + 1);
301 // reuse mask + limit_x stage, or create a custom decal_1 that just stores the mask
302 p->append(SkRasterPipeline::decal_x, decal_ctx);
303 // fall-through to clamp
Mike Kleine7598532017-05-11 11:29:29 -0400304 case kClamp_TileMode:
305 if (!fOrigPos) {
306 // We clamp only when the stops are evenly spaced.
307 // If not, there may be hard stops, and clamping ruins hard stops at 0 and/or 1.
Mike Klein5c7960b2017-05-11 10:59:22 -0400308 // In that case, we must make sure we're using the general "gradient" stage,
Mike Kleine7598532017-05-11 11:29:29 -0400309 // which is the only stage that will correctly handle unclamped t.
Mike Klein9f85d682017-05-23 07:52:01 -0400310 p->append(SkRasterPipeline::clamp_x_1);
Mike Kleine7598532017-05-11 11:29:29 -0400311 }
Mike Reed62ce2ca2018-02-19 14:20:15 -0500312 break;
Mike Kleine7598532017-05-11 11:29:29 -0400313 }
Mike Kleina3771842017-05-04 19:38:48 -0400314
315 const bool premulGrad = fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag;
316 auto prepareColor = [premulGrad, dstCS, this](int i) {
Florin Malita0e36b3f2017-06-05 23:33:45 -0400317 SkColor4f c = this->getXformedColor(i, dstCS);
Mike Kleina3771842017-05-04 19:38:48 -0400318 return premulGrad ? c.premul()
319 : SkPM4f::From4f(Sk4f::Load(&c));
320 };
321
322 // The two-stop case with stops at 0 and 1.
323 if (fColorCount == 2 && fOrigPos == nullptr) {
324 const SkPM4f c_l = prepareColor(0),
Mike Reed1d8c42e2017-08-29 14:58:19 -0400325 c_r = prepareColor(1);
Mike Kleina3771842017-05-04 19:38:48 -0400326
327 // See F and B below.
328 auto* f_and_b = alloc->makeArrayDefault<SkPM4f>(2);
329 f_and_b[0] = SkPM4f::From4f(c_r.to4f() - c_l.to4f());
330 f_and_b[1] = c_l;
331
Mike Klein5c7960b2017-05-11 10:59:22 -0400332 p->append(SkRasterPipeline::evenly_spaced_2_stop_gradient, f_and_b);
Mike Kleina3771842017-05-04 19:38:48 -0400333 } else {
Herb Derby4de13042017-05-15 10:49:39 -0400334 auto* ctx = alloc->make<SkJumper_GradientCtx>();
Herb Derby4de13042017-05-15 10:49:39 -0400335
336 // Note: In order to handle clamps in search, the search assumes a stop conceptully placed
337 // at -inf. Therefore, the max number of stops is fColorCount+1.
338 for (int i = 0; i < 4; i++) {
339 // Allocate at least at for the AVX2 gather from a YMM register.
340 ctx->fs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
341 ctx->bs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
342 }
343
Mike Kleina3771842017-05-04 19:38:48 -0400344 if (fOrigPos == nullptr) {
345 // Handle evenly distributed stops.
346
Herb Derby4de13042017-05-15 10:49:39 -0400347 size_t stopCount = fColorCount;
348 float gapCount = stopCount - 1;
Mike Kleina3771842017-05-04 19:38:48 -0400349
Herb Derby4de13042017-05-15 10:49:39 -0400350 SkPM4f c_l = prepareColor(0);
351 for (size_t i = 0; i < stopCount - 1; i++) {
Mike Kleina3771842017-05-04 19:38:48 -0400352 SkPM4f c_r = prepareColor(i + 1);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400353 init_stop_evenly(ctx, gapCount, i, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400354 c_l = c_r;
355 }
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400356 add_const_color(ctx, stopCount - 1, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400357
Herb Derby4de13042017-05-15 10:49:39 -0400358 ctx->stopCount = stopCount;
359 p->append(SkRasterPipeline::evenly_spaced_gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400360 } else {
361 // Handle arbitrary stops.
362
Herb Derby4de13042017-05-15 10:49:39 -0400363 ctx->ts = alloc->makeArray<float>(fColorCount+1);
364
Mike Kleina3771842017-05-04 19:38:48 -0400365 // Remove the dummy stops inserted by SkGradientShaderBase::SkGradientShaderBase
366 // because they are naturally handled by the search method.
367 int firstStop;
368 int lastStop;
369 if (fColorCount > 2) {
370 firstStop = fOrigColors4f[0] != fOrigColors4f[1] ? 0 : 1;
371 lastStop = fOrigColors4f[fColorCount - 2] != fOrigColors4f[fColorCount - 1]
372 ? fColorCount - 1 : fColorCount - 2;
373 } else {
374 firstStop = 0;
375 lastStop = 1;
376 }
Mike Kleina3771842017-05-04 19:38:48 -0400377
Mike Kleina3771842017-05-04 19:38:48 -0400378 size_t stopCount = 0;
379 float t_l = fOrigPos[firstStop];
380 SkPM4f c_l = prepareColor(firstStop);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400381 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400382 // N.B. lastStop is the index of the last stop, not one after.
383 for (int i = firstStop; i < lastStop; i++) {
384 float t_r = fOrigPos[i + 1];
385 SkPM4f c_r = prepareColor(i + 1);
Florin Malita3e20d022017-11-03 12:11:38 -0400386 SkASSERT(t_l <= t_r);
Mike Kleina3771842017-05-04 19:38:48 -0400387 if (t_l < t_r) {
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400388 init_stop_pos(ctx, stopCount, t_l, t_r, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400389 stopCount += 1;
390 }
391 t_l = t_r;
392 c_l = c_r;
393 }
394
Herb Derby4de13042017-05-15 10:49:39 -0400395 ctx->ts[stopCount] = t_l;
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400396 add_const_color(ctx, stopCount++, 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::gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400400 }
Mike Kleina3771842017-05-04 19:38:48 -0400401 }
402
Mike Reed62ce2ca2018-02-19 14:20:15 -0500403 if (decal_ctx) {
404 p->append(SkRasterPipeline::check_decal_mask, decal_ctx);
405 }
406
Mike Kleina3771842017-05-04 19:38:48 -0400407 if (!premulGrad && !this->colorsAreOpaque()) {
Mike Kleine7598532017-05-11 11:29:29 -0400408 p->append(SkRasterPipeline::premul);
Mike Kleina3771842017-05-04 19:38:48 -0400409 }
410
Florin Malita2e409002017-06-28 14:46:54 -0400411 p->extend(postPipeline);
412
Mike Kleina3771842017-05-04 19:38:48 -0400413 return true;
414}
415
416
rileya@google.com589708b2012-07-26 20:04:23 +0000417bool SkGradientShaderBase::isOpaque() const {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500418 return fColorsAreOpaque && (this->getTileMode() != SkShader::kDecal_TileMode);
419}
420
reed8367b8c2014-08-22 08:30:20 -0700421static unsigned rounded_divide(unsigned numer, unsigned denom) {
422 return (numer + (denom >> 1)) / denom;
423}
424
425bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
426 // we just compute an average color.
427 // possibly we could weight this based on the proportional width for each color
428 // assuming they are not evenly distributed in the fPos array.
429 int r = 0;
430 int g = 0;
431 int b = 0;
432 const int n = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400433 // TODO: use linear colors?
reed8367b8c2014-08-22 08:30:20 -0700434 for (int i = 0; i < n; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400435 SkColor c = this->getLegacyColor(i);
reed8367b8c2014-08-22 08:30:20 -0700436 r += SkColorGetR(c);
437 g += SkColorGetG(c);
438 b += SkColorGetB(c);
439 }
440 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
441 return true;
442}
443
Florin Malita39d71de2017-10-31 11:33:49 -0400444SkGradientShaderBase::AutoXformColors::AutoXformColors(const SkGradientShaderBase& grad,
445 SkColorSpaceXformer* xformer)
446 : fColors(grad.fColorCount) {
447 // TODO: stay in 4f to preserve precision?
448
449 SkAutoSTMalloc<8, SkColor> origColors(grad.fColorCount);
450 for (int i = 0; i < grad.fColorCount; ++i) {
451 origColors[i] = grad.getLegacyColor(i);
452 }
453
454 xformer->apply(fColors.get(), origColors.get(), grad.fColorCount);
455}
456
Florin Malitad4e9ec82017-10-25 18:00:26 -0400457static constexpr int kGradientTextureSize = 256;
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000458
Florin Malita84d7cf92017-10-25 15:31:54 -0400459void SkGradientShaderBase::initLinearBitmap(SkBitmap* bitmap, GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700460 const bool interpInPremul = SkToBool(fGradFlags &
461 SkGradientShader::kInterpolateColorsInPremul_Flag);
brianosmand4546092016-09-22 12:31:58 -0700462 SkHalf* pixelsF16 = reinterpret_cast<SkHalf*>(bitmap->getPixels());
Florin Malita84d7cf92017-10-25 15:31:54 -0400463 uint32_t* pixels32 = reinterpret_cast<uint32_t*>(bitmap->getPixels());
brianosmand4546092016-09-22 12:31:58 -0700464
465 typedef std::function<void(const Sk4f&, int)> pixelWriteFn_t;
466
467 pixelWriteFn_t writeF16Pixel = [&](const Sk4f& x, int index) {
468 Sk4h c = SkFloatToHalf_finite_ftz(x);
469 pixelsF16[4*index+0] = c[0];
470 pixelsF16[4*index+1] = c[1];
471 pixelsF16[4*index+2] = c[2];
472 pixelsF16[4*index+3] = c[3];
473 };
474 pixelWriteFn_t writeS32Pixel = [&](const Sk4f& c, int index) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400475 pixels32[index] = Sk4f_toS32(c);
476 };
477 pixelWriteFn_t writeL32Pixel = [&](const Sk4f& c, int index) {
478 pixels32[index] = Sk4f_toL32(c);
brianosmand4546092016-09-22 12:31:58 -0700479 };
480
481 pixelWriteFn_t writeSizedPixel =
Florin Malita84d7cf92017-10-25 15:31:54 -0400482 (bitmapType == GradientBitmapType::kHalfFloat) ? writeF16Pixel :
483 (bitmapType == GradientBitmapType::kSRGB ) ? writeS32Pixel : writeL32Pixel;
brianosmand4546092016-09-22 12:31:58 -0700484 pixelWriteFn_t writeUnpremulPixel = [&](const Sk4f& c, int index) {
485 writeSizedPixel(c * Sk4f(c[3], c[3], c[3], 1.0f), index);
486 };
487
488 pixelWriteFn_t writePixel = interpInPremul ? writeSizedPixel : writeUnpremulPixel;
489
Florin Malita84d7cf92017-10-25 15:31:54 -0400490 // When not in legacy mode, we just want the original 4f colors - so we pass in
491 // our own CS for identity/no transform.
492 auto* cs = bitmapType != GradientBitmapType::kLegacy ? fColorSpace.get() : nullptr;
493
brianosmand4546092016-09-22 12:31:58 -0700494 int prevIndex = 0;
495 for (int i = 1; i < fColorCount; i++) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400496 // Historically, stops have been mapped to [0, 256], with 256 then nudged to the
497 // next smaller value, then truncate for the texture index. This seems to produce
498 // the best results for some common distributions, so we preserve the behavior.
499 int nextIndex = SkTMin(this->getPos(i) * kGradientTextureSize,
500 SkIntToScalar(kGradientTextureSize - 1));
brianosmand4546092016-09-22 12:31:58 -0700501
502 if (nextIndex > prevIndex) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400503 SkColor4f color0 = this->getXformedColor(i - 1, cs),
504 color1 = this->getXformedColor(i , cs);
505 Sk4f c0 = Sk4f::Load(color0.vec()),
506 c1 = Sk4f::Load(color1.vec());
507
brianosmand4546092016-09-22 12:31:58 -0700508 if (interpInPremul) {
509 c0 = c0 * Sk4f(c0[3], c0[3], c0[3], 1.0f);
510 c1 = c1 * Sk4f(c1[3], c1[3], c1[3], 1.0f);
511 }
512
513 Sk4f step = Sk4f(1.0f / static_cast<float>(nextIndex - prevIndex));
514 Sk4f delta = (c1 - c0) * step;
515
516 for (int curIndex = prevIndex; curIndex <= nextIndex; ++curIndex) {
517 writePixel(c0, curIndex);
518 c0 += delta;
519 }
520 }
521 prevIndex = nextIndex;
522 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400523 SkASSERT(prevIndex == kGradientTextureSize - 1);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000524}
525
Florin Malita0e36b3f2017-06-05 23:33:45 -0400526SkColor4f SkGradientShaderBase::getXformedColor(size_t i, SkColorSpace* dstCS) const {
Florin Malita79363b62017-11-01 15:43:52 -0400527 if (dstCS) {
528 return to_colorspace(fOrigColors4f[i], fColorSpace.get(), dstCS);
529 }
530
531 // Legacy/srgb color.
Florin Malita79363b62017-11-01 15:43:52 -0400532 // We quantize upfront to ensure stable SkColor round-trips.
533 auto rgb255 = sk_linear_to_srgb(Sk4f::Load(fOrigColors4f[i].vec()));
534 auto rgb = SkNx_cast<float>(rgb255) * (1/255.0f);
535 return { rgb[0], rgb[1], rgb[2], fOrigColors4f[i].fA };
Florin Malita0e36b3f2017-06-05 23:33:45 -0400536}
537
reed086eea92016-05-04 17:12:46 -0700538SK_DECLARE_STATIC_MUTEX(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000539/*
540 * Because our caller might rebuild the same (logically the same) gradient
541 * over and over, we'd like to return exactly the same "bitmap" if possible,
542 * allowing the client to utilize a cache of our bitmap (e.g. with a GPU).
543 * To do that, we maintain a private cache of built-bitmaps, based on our
Brian Osmanfe3e8582017-10-20 11:27:49 -0400544 * colors and positions.
rileya@google.com589708b2012-07-26 20:04:23 +0000545 */
brianosmand4546092016-09-22 12:31:58 -0700546void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap,
547 GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700548 // build our key: [numColors + colors[] + {positions[]} + flags + colorType ]
Florin Malita39d71de2017-10-31 11:33:49 -0400549 static_assert(sizeof(SkColor4f) % sizeof(int32_t) == 0, "");
550 const int colorsAsIntCount = fColorCount * sizeof(SkColor4f) / sizeof(int32_t);
551 int count = 1 + colorsAsIntCount + 1 + 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000552 if (fColorCount > 2) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400553 count += fColorCount - 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000554 }
555
Florin Malita39d71de2017-10-31 11:33:49 -0400556 SkAutoSTMalloc<64, int32_t> storage(count);
rileya@google.com589708b2012-07-26 20:04:23 +0000557 int32_t* buffer = storage.get();
558
559 *buffer++ = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400560 memcpy(buffer, fOrigColors4f, fColorCount * sizeof(SkColor4f));
561 buffer += colorsAsIntCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000562 if (fColorCount > 2) {
563 for (int i = 1; i < fColorCount; i++) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400564 *buffer++ = SkFloat2Bits(this->getPos(i));
rileya@google.com589708b2012-07-26 20:04:23 +0000565 }
566 }
reed@google.com3d3a8602013-05-24 14:58:44 +0000567 *buffer++ = fGradFlags;
brianosmand4546092016-09-22 12:31:58 -0700568 *buffer++ = static_cast<int32_t>(bitmapType);
rileya@google.com589708b2012-07-26 20:04:23 +0000569 SkASSERT(buffer - storage.get() == count);
570
571 ///////////////////////////////////
572
reeda6cac4c2014-08-21 10:50:25 -0700573 static SkGradientBitmapCache* gCache;
brianosmand4546092016-09-22 12:31:58 -0700574 // 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 +0000575 static const int MAX_NUM_CACHED_GRADIENT_BITMAPS = 32;
bungemand6aeb6d2014-07-25 11:52:47 -0700576 SkAutoMutexAcquire ama(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000577
halcanary96fcdcc2015-08-27 07:41:13 -0700578 if (nullptr == gCache) {
halcanary385fe4d2015-08-26 13:07:48 -0700579 gCache = new SkGradientBitmapCache(MAX_NUM_CACHED_GRADIENT_BITMAPS);
rileya@google.com589708b2012-07-26 20:04:23 +0000580 }
581 size_t size = count * sizeof(int32_t);
582
583 if (!gCache->find(storage.get(), size, bitmap)) {
Florin Malitad4e9ec82017-10-25 18:00:26 -0400584 // For these cases we use the bitmap cache, but not the GradientShaderCache. So just
585 // allocate and populate the bitmap's data directly.
Florin Malita63376532017-10-24 10:56:52 -0400586
Florin Malitad4e9ec82017-10-25 18:00:26 -0400587 SkImageInfo info;
588 switch (bitmapType) {
589 case GradientBitmapType::kLegacy:
590 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
591 kPremul_SkAlphaType);
592 break;
593 case GradientBitmapType::kSRGB:
594 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
595 kPremul_SkAlphaType, SkColorSpace::MakeSRGB());
596 break;
597 case GradientBitmapType::kHalfFloat:
598 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_F16_SkColorType,
599 kPremul_SkAlphaType, SkColorSpace::MakeSRGBLinear());
600 break;
brianosmand4546092016-09-22 12:31:58 -0700601 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400602
603 bitmap->allocPixels(info);
604 this->initLinearBitmap(bitmap, bitmapType);
Robert Phillips7a926392018-02-01 15:49:54 -0500605 bitmap->setImmutable();
rileya@google.com589708b2012-07-26 20:04:23 +0000606 gCache->add(storage.get(), size, *bitmap);
607 }
608}
609
Florin Malita5f379a82017-10-18 16:22:35 -0400610void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000611 if (info) {
612 if (info->fColorCount >= fColorCount) {
613 if (info->fColors) {
Florin Malita39d71de2017-10-31 11:33:49 -0400614 for (int i = 0; i < fColorCount; ++i) {
615 info->fColors[i] = this->getLegacyColor(i);
616 }
rileya@google.com589708b2012-07-26 20:04:23 +0000617 }
618 if (info->fColorOffsets) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400619 for (int i = 0; i < fColorCount; ++i) {
620 info->fColorOffsets[i] = this->getPos(i);
rileya@google.com589708b2012-07-26 20:04:23 +0000621 }
622 }
623 }
624 info->fColorCount = fColorCount;
625 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000626 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000627 }
628}
629
Cary Clark89ad31e2018-05-31 12:27:33 +0000630void SkGradientShaderBase::toString(SkString* str) const {
631
632 str->appendf("%d colors: ", fColorCount);
633
634 for (int i = 0; i < fColorCount; ++i) {
635 str->appendHex(this->getLegacyColor(i), 8);
636 if (i < fColorCount-1) {
637 str->append(", ");
638 }
639 }
640
641 if (fColorCount > 2) {
642 str->append(" points: (");
643 for (int i = 0; i < fColorCount; ++i) {
644 str->appendScalar(this->getPos(i));
645 if (i < fColorCount-1) {
646 str->append(", ");
647 }
648 }
649 str->append(")");
650 }
651
652 static const char* gTileModeName[SkShader::kTileModeCount] = {
653 "clamp", "repeat", "mirror", "decal",
654 };
655
656 str->append(" ");
657 str->append(gTileModeName[fTileMode]);
658
659 this->INHERITED::toString(str);
660}
661
rileya@google.com589708b2012-07-26 20:04:23 +0000662///////////////////////////////////////////////////////////////////////////////
663///////////////////////////////////////////////////////////////////////////////
664
reed1b747302015-01-06 07:13:19 -0800665// Return true if these parameters are valid/legal/safe to construct a gradient
666//
brianosmane25d71c2016-09-28 11:27:28 -0700667static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
668 unsigned tileMode) {
halcanary96fcdcc2015-08-27 07:41:13 -0700669 return nullptr != colors && count >= 1 && tileMode < (unsigned)SkShader::kTileModeCount;
reed1b747302015-01-06 07:13:19 -0800670}
671
reed@google.com437d6eb2013-05-23 19:03:05 +0000672static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700673 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
674 const SkScalar pos[], int colorCount,
reedaddf2ed2014-08-11 08:28:24 -0700675 SkShader::TileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700676 SkASSERT(colorCount > 1);
677
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000678 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700679 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000680 desc->fPos = pos;
681 desc->fCount = colorCount;
682 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000683 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700684 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000685}
686
brianosmane25d71c2016-09-28 11:27:28 -0700687// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700688#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700689 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700690 do { \
691 if (1 == count) { \
692 tmp[0] = tmp[1] = colors[0]; \
693 colors = tmp; \
694 pos = nullptr; \
695 count = 2; \
696 } \
697 } while (0)
698
fmenozzi68d952c2016-08-19 08:56:56 -0700699struct ColorStopOptimizer {
brianosmane25d71c2016-09-28 11:27:28 -0700700 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos,
fmenozzi68d952c2016-08-19 08:56:56 -0700701 int count, SkShader::TileMode mode)
702 : fColors(colors)
703 , fPos(pos)
704 , fCount(count) {
705
706 if (!pos || count != 3) {
707 return;
708 }
709
710 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
711 SkScalarNearlyEqual(pos[1], 0.0f) &&
712 SkScalarNearlyEqual(pos[2], 1.0f)) {
713
714 if (SkShader::kRepeat_TileMode == mode ||
715 SkShader::kMirror_TileMode == mode ||
716 colors[0] == colors[1]) {
717
fmalita582a6562016-08-22 06:28:57 -0700718 // Ignore the leftmost color/pos.
719 fColors += 1;
720 fPos += 1;
721 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700722 }
723 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
724 SkScalarNearlyEqual(pos[1], 1.0f) &&
725 SkScalarNearlyEqual(pos[2], 1.0f)) {
726
727 if (SkShader::kRepeat_TileMode == mode ||
728 SkShader::kMirror_TileMode == mode ||
729 colors[1] == colors[2]) {
730
fmalita582a6562016-08-22 06:28:57 -0700731 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700732 fCount = 2;
733 }
734 }
735 }
736
brianosmane25d71c2016-09-28 11:27:28 -0700737 const SkColor4f* fColors;
738 const SkScalar* fPos;
739 int fCount;
740};
741
742struct ColorConverter {
743 ColorConverter(const SkColor* colors, int count) {
744 for (int i = 0; i < count; ++i) {
745 fColors4f.push_back(SkColor4f::FromColor(colors[i]));
746 }
747 }
748
749 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700750};
751
reed8a21c9f2016-03-08 18:50:00 -0800752sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700753 const SkColor colors[],
754 const SkScalar pos[], int colorCount,
755 SkShader::TileMode mode,
756 uint32_t flags,
757 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700758 ColorConverter converter(colors, colorCount);
759 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
760 localMatrix);
761}
762
763sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
764 const SkColor4f colors[],
765 sk_sp<SkColorSpace> colorSpace,
766 const SkScalar pos[], int colorCount,
767 SkShader::TileMode mode,
768 uint32_t flags,
769 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700770 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700771 return nullptr;
reed1b747302015-01-06 07:13:19 -0800772 }
773 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700774 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000775 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700776 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700777 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700778 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000779 if (localMatrix && !localMatrix->invert(nullptr)) {
780 return nullptr;
781 }
rileya@google.com589708b2012-07-26 20:04:23 +0000782
fmenozzi68d952c2016-08-19 08:56:56 -0700783 ColorStopOptimizer opt(colors, pos, colorCount, mode);
784
reed@google.com437d6eb2013-05-23 19:03:05 +0000785 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700786 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
787 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800788 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000789}
790
reed8a21c9f2016-03-08 18:50:00 -0800791sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700792 const SkColor colors[],
793 const SkScalar pos[], int colorCount,
794 SkShader::TileMode mode,
795 uint32_t flags,
796 const SkMatrix* localMatrix) {
797 ColorConverter converter(colors, colorCount);
798 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
799 flags, localMatrix);
800}
801
802sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
803 const SkColor4f colors[],
804 sk_sp<SkColorSpace> colorSpace,
805 const SkScalar pos[], int colorCount,
806 SkShader::TileMode mode,
807 uint32_t flags,
808 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800809 if (radius <= 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700810 return nullptr;
reed1b747302015-01-06 07:13:19 -0800811 }
812 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700813 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000814 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700815 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700816 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700817 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000818 if (localMatrix && !localMatrix->invert(nullptr)) {
819 return nullptr;
820 }
rileya@google.com589708b2012-07-26 20:04:23 +0000821
fmenozzi68d952c2016-08-19 08:56:56 -0700822 ColorStopOptimizer opt(colors, pos, colorCount, mode);
823
reed@google.com437d6eb2013-05-23 19:03:05 +0000824 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700825 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
826 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800827 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000828}
829
reed8a21c9f2016-03-08 18:50:00 -0800830sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -0700831 SkScalar startRadius,
832 const SkPoint& end,
833 SkScalar endRadius,
834 const SkColor colors[],
835 const SkScalar pos[],
836 int colorCount,
837 SkShader::TileMode mode,
838 uint32_t flags,
839 const SkMatrix* localMatrix) {
840 ColorConverter converter(colors, colorCount);
841 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
842 nullptr, pos, colorCount, mode, flags, localMatrix);
843}
844
845sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
846 SkScalar startRadius,
847 const SkPoint& end,
848 SkScalar endRadius,
849 const SkColor4f colors[],
850 sk_sp<SkColorSpace> colorSpace,
851 const SkScalar pos[],
852 int colorCount,
853 SkShader::TileMode mode,
854 uint32_t flags,
855 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800856 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700857 return nullptr;
reed1b747302015-01-06 07:13:19 -0800858 }
Florin Malita327290f2017-07-07 09:23:16 -0400859 if (SkScalarNearlyZero((start - end).length()) && SkScalarNearlyZero(startRadius)) {
860 // We can treat this gradient as radial, which is faster.
861 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
862 mode, flags, localMatrix);
863 }
reed1b747302015-01-06 07:13:19 -0800864 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700865 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000866 }
fmalita5edf82e2016-03-03 06:41:54 -0800867 if (startRadius == endRadius) {
868 if (start == end || startRadius == 0) {
reed8a21c9f2016-03-08 18:50:00 -0800869 return SkShader::MakeEmptyShader();
fmalita5edf82e2016-03-03 06:41:54 -0800870 }
rileya@google.com589708b2012-07-26 20:04:23 +0000871 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000872 if (localMatrix && !localMatrix->invert(nullptr)) {
873 return nullptr;
874 }
reed6b7a6c72016-08-18 16:13:50 -0700875 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000876
fmenozzi68d952c2016-08-19 08:56:56 -0700877 ColorStopOptimizer opt(colors, pos, colorCount, mode);
878
reed@google.com437d6eb2013-05-23 19:03:05 +0000879 SkGradientShaderBase::Descriptor desc;
Florin Malita5f379a82017-10-18 16:22:35 -0400880 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
881 localMatrix);
882 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000883}
884
reed8a21c9f2016-03-08 18:50:00 -0800885sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -0700886 const SkColor colors[],
887 const SkScalar pos[],
888 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400889 SkShader::TileMode mode,
890 SkScalar startAngle,
891 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700892 uint32_t flags,
893 const SkMatrix* localMatrix) {
894 ColorConverter converter(colors, colorCount);
Florin Malita5a9a9812017-08-01 16:38:08 -0400895 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
896 mode, startAngle, endAngle, flags, localMatrix);
brianosmane25d71c2016-09-28 11:27:28 -0700897}
898
899sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
900 const SkColor4f colors[],
901 sk_sp<SkColorSpace> colorSpace,
902 const SkScalar pos[],
903 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400904 SkShader::TileMode mode,
905 SkScalar startAngle,
906 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700907 uint32_t flags,
908 const SkMatrix* localMatrix) {
Florin Malita5a9a9812017-08-01 16:38:08 -0400909 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 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700912 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700913 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700914 }
Florin Malita5a9a9812017-08-01 16:38:08 -0400915 if (startAngle >= endAngle) {
916 return nullptr;
917 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000918 if (localMatrix && !localMatrix->invert(nullptr)) {
919 return nullptr;
920 }
rileya@google.com589708b2012-07-26 20:04:23 +0000921
Florin Malita5a9a9812017-08-01 16:38:08 -0400922 if (startAngle <= 0 && endAngle >= 360) {
923 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
924 mode = SkShader::kClamp_TileMode;
925 }
fmenozzi68d952c2016-08-19 08:56:56 -0700926
927 ColorStopOptimizer opt(colors, pos, colorCount, mode);
928
reed@google.com437d6eb2013-05-23 19:03:05 +0000929 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700930 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
931 localMatrix);
Florin Malita5a9a9812017-08-01 16:38:08 -0400932
933 const SkScalar t0 = startAngle / 360,
934 t1 = endAngle / 360;
935
936 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000937}
938
939SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
940 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
941 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
942 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
rileya@google.com589708b2012-07-26 20:04:23 +0000943 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
944SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
rileya@google.comd7cc6512012-07-27 14:00:39 +0000945
946///////////////////////////////////////////////////////////////////////////////
947
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000948#if SK_SUPPORT_GPU
949
Brian Osman5911a7c2017-10-25 12:52:31 -0400950#include "GrColorSpaceXform.h"
brianosmana6359362016-03-21 06:55:37 -0700951#include "GrContext.h"
Robert Phillips1afd4cd2018-01-08 13:40:32 -0500952#include "GrContextPriv.h"
Brian Salomon94efbf52016-11-29 13:43:05 -0500953#include "GrShaderCaps.h"
ajuma95243eb2016-08-24 08:19:02 -0700954#include "GrTextureStripAtlas.h"
egdanielf5294392015-10-21 07:14:17 -0700955#include "gl/GrGLContext.h"
egdaniel2d721d32015-11-11 13:06:05 -0800956#include "glsl/GrGLSLFragmentShaderBuilder.h"
egdaniel018fb622015-10-28 07:26:40 -0700957#include "glsl/GrGLSLProgramDataManager.h"
egdaniel7ea439b2015-12-03 09:20:44 -0800958#include "glsl/GrGLSLUniformHandler.h"
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000959#include "SkGr.h"
960
fmenozzi55d318d2016-08-09 08:05:57 -0700961void GrGradientEffect::GLSLProcessor::emitUniforms(GrGLSLUniformHandler* uniformHandler,
962 const GrGradientEffect& ge) {
Florin Malita14a8dd72017-11-08 15:46:42 -0500963 switch (ge.fStrategy) {
964 case GrGradientEffect::InterpolationStrategy::kThreshold:
965 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
966 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
967 fThresholdUni = uniformHandler->addUniform(kFragment_GrShaderFlag,
968 kFloat_GrSLType,
969 kHigh_GrSLPrecision,
970 "Threshold");
971 // fall through
972 case GrGradientEffect::InterpolationStrategy::kSingle:
973 fIntervalsUni = uniformHandler->addUniformArray(kFragment_GrShaderFlag,
974 kHalf4_GrSLType,
975 "Intervals",
976 ge.fIntervals.count());
977 break;
978 case GrGradientEffect::InterpolationStrategy::kTexture:
979 fFSYUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType,
980 "GradientYCoordFS");
981 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +0000982 }
983}
984
fmenozzi55d318d2016-08-09 08:05:57 -0700985void GrGradientEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman,
Brian Salomonab015ef2017-04-04 10:15:51 -0400986 const GrFragmentProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -0700987 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +0000988
Florin Malita14a8dd72017-11-08 15:46:42 -0500989 switch (e.fStrategy) {
990 case GrGradientEffect::InterpolationStrategy::kThreshold:
991 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
992 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
993 pdman.set1f(fThresholdUni, e.fThreshold);
Brian Salomon466ad992016-10-13 16:08:36 -0400994 // fall through
Florin Malita14a8dd72017-11-08 15:46:42 -0500995 case GrGradientEffect::InterpolationStrategy::kSingle:
996 pdman.set4fv(fIntervalsUni, e.fIntervals.count(),
997 reinterpret_cast<const float*>(e.fIntervals.begin()));
fmenozzicd9a1d02016-08-15 07:03:47 -0700998 break;
Florin Malita14a8dd72017-11-08 15:46:42 -0500999 case GrGradientEffect::InterpolationStrategy::kTexture:
1000 if (e.fYCoord != fCachedYCoord) {
1001 pdman.set1f(fFSYUni, e.fYCoord);
1002 fCachedYCoord = e.fYCoord;
fmenozzicd9a1d02016-08-15 07:03:47 -07001003 }
1004 break;
rileya@google.comb3e50f22012-08-20 17:43:08 +00001005 }
1006}
1007
Florin Malitae657dc82017-11-03 08:46:18 -04001008void GrGradientEffect::onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const {
1009 b->add32(GLSLProcessor::GenBaseGradientKey(*this));
1010}
1011
fmenozzi55d318d2016-08-09 08:05:57 -07001012uint32_t GrGradientEffect::GLSLProcessor::GenBaseGradientKey(const GrProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -07001013 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001014
Florin Malita14a8dd72017-11-08 15:46:42 -05001015 // Build a key using the following bit allocation:
1016 static constexpr uint32_t kStrategyBits = 3;
1017 static constexpr uint32_t kPremulBits = 1;
1018 SkDEBUGCODE(static constexpr uint32_t kWrapModeBits = 2;)
bsalomon@google.com82d12232013-09-09 15:36:26 +00001019
Florin Malita14a8dd72017-11-08 15:46:42 -05001020 uint32_t key = static_cast<uint32_t>(e.fStrategy);
1021 SkASSERT(key < (1 << kStrategyBits));
1022
1023 // This is already baked into the table for texture gradients,
1024 // and only changes behavior for analytical gradients.
1025 if (e.fStrategy != InterpolationStrategy::kTexture &&
1026 e.fPremulType == GrGradientEffect::kBeforeInterp_PremulType) {
1027 key |= 1 << kStrategyBits;
1028 SkASSERT(key < (1 << (kStrategyBits + kPremulBits)));
bsalomon@google.com82d12232013-09-09 15:36:26 +00001029 }
1030
Florin Malita14a8dd72017-11-08 15:46:42 -05001031 key |= static_cast<uint32_t>(e.fWrapMode) << (kStrategyBits + kPremulBits);
1032 SkASSERT(key < (1 << (kStrategyBits + kPremulBits + kWrapModeBits)));
fmenozzicd9a1d02016-08-15 07:03:47 -07001033
bsalomon@google.com82d12232013-09-09 15:36:26 +00001034 return key;
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +00001035}
1036
Florin Malitab81a8b92017-08-08 12:14:17 -04001037void GrGradientEffect::GLSLProcessor::emitAnalyticalColor(GrGLSLFPFragmentBuilder* fragBuilder,
1038 GrGLSLUniformHandler* uniformHandler,
1039 const GrShaderCaps* shaderCaps,
1040 const GrGradientEffect& ge,
1041 const char* t,
1042 const char* outputColor,
1043 const char* inputColor) {
1044 // First, apply tiling rules.
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001045 switch (ge.fWrapMode) {
1046 case GrSamplerState::WrapMode::kClamp:
Florin Malita14a8dd72017-11-08 15:46:42 -05001047 switch (ge.fStrategy) {
1048 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1049 // allow t > 1, in order to hit the clamp interval (1, inf)
1050 fragBuilder->codeAppendf("half tiled_t = max(%s, 0.0);", t);
1051 break;
1052 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1053 // allow t < 0, in order to hit the clamp interval (-inf, 0)
1054 fragBuilder->codeAppendf("half tiled_t = min(%s, 1.0);", t);
1055 break;
1056 default:
1057 // regular [0, 1] clamping
1058 fragBuilder->codeAppendf("half tiled_t = clamp(%s, 0.0, 1.0);", t);
1059 }
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001060 break;
1061 case GrSamplerState::WrapMode::kRepeat:
Florin Malita14a8dd72017-11-08 15:46:42 -05001062 fragBuilder->codeAppendf("half tiled_t = fract(%s);", t);
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001063 break;
1064 case GrSamplerState::WrapMode::kMirrorRepeat:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001065 fragBuilder->codeAppendf("half t_1 = %s - 1.0;", t);
Greg Daniel10ed2432017-12-01 16:19:43 -05001066 fragBuilder->codeAppendf("half tiled_t = t_1 - 2.0 * floor(t_1 * 0.5) - 1.0;");
1067 if (shaderCaps->mustDoOpBetweenFloorAndAbs()) {
1068 // At this point the expected value of tiled_t should between -1 and 1, so this
1069 // clamp has no effect other than to break up the floor and abs calls and make sure
1070 // the compiler doesn't merge them back together.
1071 fragBuilder->codeAppendf("tiled_t = clamp(tiled_t, -1.0, 1.0);");
1072 }
1073 fragBuilder->codeAppendf("tiled_t = abs(tiled_t);");
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001074 break;
Florin Malita8a0044f2017-08-07 14:38:22 -04001075 }
Florin Malita8a0044f2017-08-07 14:38:22 -04001076
Florin Malitab81a8b92017-08-08 12:14:17 -04001077 // Calculate the color.
Florin Malita14a8dd72017-11-08 15:46:42 -05001078 const char* intervals = uniformHandler->getUniformCStr(fIntervalsUni);
fmenozzicd9a1d02016-08-15 07:03:47 -07001079
Florin Malita14a8dd72017-11-08 15:46:42 -05001080 switch (ge.fStrategy) {
1081 case GrGradientEffect::InterpolationStrategy::kSingle:
1082 SkASSERT(ge.fIntervals.count() == 2);
1083 fragBuilder->codeAppendf(
1084 "half4 color_scale = %s[0],"
1085 " color_bias = %s[1];"
1086 , intervals, intervals
1087 );
fmenozzicd9a1d02016-08-15 07:03:47 -07001088 break;
Florin Malita14a8dd72017-11-08 15:46:42 -05001089 case GrGradientEffect::InterpolationStrategy::kThreshold:
1090 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1091 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1092 {
1093 SkASSERT(ge.fIntervals.count() == 4);
1094 const char* threshold = uniformHandler->getUniformCStr(fThresholdUni);
1095 fragBuilder->codeAppendf(
1096 "half4 color_scale, color_bias;"
1097 "if (tiled_t < %s) {"
1098 " color_scale = %s[0];"
1099 " color_bias = %s[1];"
1100 "} else {"
1101 " color_scale = %s[2];"
1102 " color_bias = %s[3];"
1103 "}"
1104 , threshold, intervals, intervals, intervals, intervals
1105 );
1106 } break;
Florin Malitab81a8b92017-08-08 12:14:17 -04001107 default:
1108 SkASSERT(false);
fmenozzicd9a1d02016-08-15 07:03:47 -07001109 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001110 }
Florin Malitab81a8b92017-08-08 12:14:17 -04001111
Florin Malita14a8dd72017-11-08 15:46:42 -05001112 fragBuilder->codeAppend("half4 colorTemp = tiled_t * color_scale + color_bias;");
1113
Brian Osmanfe3e8582017-10-20 11:27:49 -04001114 // We could skip this step if all colors are known to be opaque. Two considerations:
Florin Malitab81a8b92017-08-08 12:14:17 -04001115 // The gradient SkShader reporting opaque is more restrictive than necessary in the two
1116 // pt case. Make sure the key reflects this optimization (and note that it can use the
Brian Osmanfe3e8582017-10-20 11:27:49 -04001117 // same shader as the kBeforeInterp case).
Florin Malita14a8dd72017-11-08 15:46:42 -05001118 if (ge.fPremulType == GrGradientEffect::kAfterInterp_PremulType) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001119 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1120 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001121
1122 // 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 -04001123 // range. The simplest solution is to always clamp our (premul) value here. We only need to
1124 // clamp RGB, but that causes hangs on the Tegra3 Nexus7. Clamping RGBA avoids the problem.
1125 fragBuilder->codeAppend("colorTemp = clamp(colorTemp, 0, colorTemp.a);");
Florin Malitab81a8b92017-08-08 12:14:17 -04001126
1127 fragBuilder->codeAppendf("%s = %s * colorTemp;", outputColor, inputColor);
1128}
1129
1130void GrGradientEffect::GLSLProcessor::emitColor(GrGLSLFPFragmentBuilder* fragBuilder,
1131 GrGLSLUniformHandler* uniformHandler,
1132 const GrShaderCaps* shaderCaps,
1133 const GrGradientEffect& ge,
1134 const char* gradientTValue,
1135 const char* outputColor,
1136 const char* inputColor,
1137 const TextureSamplers& texSamplers) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001138 if (ge.fStrategy != InterpolationStrategy::kTexture) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001139 this->emitAnalyticalColor(fragBuilder, uniformHandler, shaderCaps, ge, gradientTValue,
1140 outputColor, inputColor);
1141 return;
1142 }
1143
Florin Malitab81a8b92017-08-08 12:14:17 -04001144 const char* fsyuni = uniformHandler->getUniformCStr(fFSYUni);
1145
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001146 fragBuilder->codeAppendf("half2 coord = half2(%s, %s);", gradientTValue, fsyuni);
Florin Malitab81a8b92017-08-08 12:14:17 -04001147 fragBuilder->codeAppendf("%s = ", outputColor);
1148 fragBuilder->appendTextureLookupAndModulate(inputColor, texSamplers[0], "coord",
Brian Osman5911a7c2017-10-25 12:52:31 -04001149 kFloat2_GrSLType);
Florin Malitab81a8b92017-08-08 12:14:17 -04001150 fragBuilder->codeAppend(";");
rileya@google.comd7cc6512012-07-27 14:00:39 +00001151}
1152
1153/////////////////////////////////////////////////////////////////////
1154
Brian Salomon587e08f2017-01-27 10:59:27 -05001155inline GrFragmentProcessor::OptimizationFlags GrGradientEffect::OptFlags(bool isOpaque) {
Brian Salomonf3b995b2017-02-15 10:22:23 -05001156 return isOpaque
1157 ? kPreservesOpaqueInput_OptimizationFlag |
1158 kCompatibleWithCoverageAsAlpha_OptimizationFlag
1159 : kCompatibleWithCoverageAsAlpha_OptimizationFlag;
Brian Salomon587e08f2017-01-27 10:59:27 -05001160}
1161
Florin Malita14a8dd72017-11-08 15:46:42 -05001162void GrGradientEffect::addInterval(const SkGradientShaderBase& shader, size_t idx0, size_t idx1,
1163 SkColorSpace* dstCS) {
1164 SkASSERT(idx0 <= idx1);
1165 const auto c4f0 = shader.getXformedColor(idx0, dstCS),
1166 c4f1 = shader.getXformedColor(idx1, dstCS);
1167 const auto c0 = (fPremulType == kBeforeInterp_PremulType)
1168 ? c4f0.premul().to4f() : Sk4f::Load(c4f0.vec()),
1169 c1 = (fPremulType == kBeforeInterp_PremulType)
1170 ? c4f1.premul().to4f() : Sk4f::Load(c4f1.vec());
1171 const auto t0 = shader.getPos(idx0),
1172 t1 = shader.getPos(idx1),
1173 dt = t1 - t0;
1174 SkASSERT(dt >= 0);
1175 // dt can be 0 for clamp intervals => in this case we want a scale == 0
1176 const auto scale = SkScalarNearlyZero(dt) ? 0 : (c1 - c0) / dt,
1177 bias = c0 - t0 * scale;
1178
1179 // Intervals are stored as (scale, bias) tuples.
1180 SkASSERT(!(fIntervals.count() & 1));
1181 fIntervals.emplace_back(scale[0], scale[1], scale[2], scale[3]);
1182 fIntervals.emplace_back( bias[0], bias[1], bias[2], bias[3]);
1183}
1184
Ethan Nicholasabff9562017-10-09 10:54:08 -04001185GrGradientEffect::GrGradientEffect(ClassID classID, const CreateArgs& args, bool isOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001186 : INHERITED(classID, OptFlags(isOpaque))
1187 , fWrapMode(args.fWrapMode)
1188 , fRow(-1)
1189 , fIsOpaque(args.fShader->isOpaque())
1190 , fStrategy(InterpolationStrategy::kTexture)
1191 , fThreshold(0) {
1192
brianosman9557c272016-09-15 06:59:15 -07001193 const SkGradientShaderBase& shader(*args.fShader);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001194
Florin Malita14a8dd72017-11-08 15:46:42 -05001195 fPremulType = (args.fShader->getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag)
1196 ? kBeforeInterp_PremulType : kAfterInterp_PremulType;
bsalomon@google.com371e1052013-01-11 21:08:55 +00001197
Florin Malita14a8dd72017-11-08 15:46:42 -05001198 // First, determine the interpolation strategy and params.
1199 switch (shader.fColorCount) {
1200 case 2:
1201 SkASSERT(!shader.fOrigPos);
1202 fStrategy = InterpolationStrategy::kSingle;
1203 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1204 break;
1205 case 3:
1206 fThreshold = shader.getPos(1);
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +00001207
Florin Malita14a8dd72017-11-08 15:46:42 -05001208 if (shader.fOrigPos) {
1209 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1210 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[2], 1));
1211 if (SkScalarNearlyEqual(shader.fOrigPos[1], 0)) {
1212 // hard stop on the left edge.
1213 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1214 fStrategy = InterpolationStrategy::kThresholdClamp1;
1215 // Clamp interval (scale == 0, bias == colors[0]).
1216 this->addInterval(shader, 0, 0, args.fDstColorSpace);
1217 } else {
1218 // We can ignore the hard stop when not clamping.
1219 fStrategy = InterpolationStrategy::kSingle;
1220 }
1221 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1222 break;
1223 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001224
Florin Malita14a8dd72017-11-08 15:46:42 -05001225 if (SkScalarNearlyEqual(shader.fOrigPos[1], 1)) {
1226 // hard stop on the right edge.
1227 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1228 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1229 fStrategy = InterpolationStrategy::kThresholdClamp0;
1230 // Clamp interval (scale == 0, bias == colors[2]).
1231 this->addInterval(shader, 2, 2, args.fDstColorSpace);
1232 } else {
1233 // We can ignore the hard stop when not clamping.
1234 fStrategy = InterpolationStrategy::kSingle;
1235 }
1236 break;
1237 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001238 }
1239
Florin Malita14a8dd72017-11-08 15:46:42 -05001240 // Two arbitrary interpolation intervals.
1241 fStrategy = InterpolationStrategy::kThreshold;
1242 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1243 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1244 break;
1245 case 4:
1246 if (shader.fOrigPos && SkScalarNearlyEqual(shader.fOrigPos[1], shader.fOrigPos[2])) {
1247 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1248 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[3], 1));
fmenozzi2a495912016-08-12 06:33:52 -07001249
Florin Malita14a8dd72017-11-08 15:46:42 -05001250 // Single hard stop => two arbitrary interpolation intervals.
1251 fStrategy = InterpolationStrategy::kThreshold;
1252 fThreshold = shader.getPos(1);
1253 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1254 this->addInterval(shader, 2, 3, args.fDstColorSpace);
1255 }
1256 break;
1257 default:
1258 break;
fmenozzi2a495912016-08-12 06:33:52 -07001259 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001260
Florin Malita14a8dd72017-11-08 15:46:42 -05001261 // Now that we've locked down a strategy, adjust any dependent params.
1262 if (fStrategy != InterpolationStrategy::kTexture) {
1263 // Analytical cases.
1264 fCoordTransform.reset(*args.fMatrix);
1265 } else {
1266 SkGradientShaderBase::GradientBitmapType bitmapType =
1267 SkGradientShaderBase::GradientBitmapType::kLegacy;
Brian Salomonc7fe0f72018-05-11 10:14:21 -04001268 auto caps = args.fContext->contextPriv().caps();
Florin Malita14a8dd72017-11-08 15:46:42 -05001269 if (args.fDstColorSpace) {
1270 // Try to use F16 if we can
Brian Salomonc7fe0f72018-05-11 10:14:21 -04001271 if (caps->isConfigTexturable(kRGBA_half_GrPixelConfig)) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001272 bitmapType = SkGradientShaderBase::GradientBitmapType::kHalfFloat;
Brian Salomonc7fe0f72018-05-11 10:14:21 -04001273 } else if (caps->isConfigTexturable(kSRGBA_8888_GrPixelConfig)) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001274 bitmapType = SkGradientShaderBase::GradientBitmapType::kSRGB;
fmenozzicd9a1d02016-08-15 07:03:47 -07001275 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001276 // This can happen, but only if someone explicitly creates an unsupported
1277 // (eg sRGB) surface. Just fall back to legacy behavior.
fmenozzicd9a1d02016-08-15 07:03:47 -07001278 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001279 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001280
Florin Malita14a8dd72017-11-08 15:46:42 -05001281 SkBitmap bitmap;
1282 shader.getGradientTableBitmap(&bitmap, bitmapType);
1283 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
fmenozzicd9a1d02016-08-15 07:03:47 -07001284
Robert Phillips41a3b872018-03-09 12:00:34 -05001285 auto atlasManager = args.fContext->contextPriv().textureStripAtlasManager();
Florin Malita14a8dd72017-11-08 15:46:42 -05001286
1287 GrTextureStripAtlas::Desc desc;
1288 desc.fWidth = bitmap.width();
1289 desc.fHeight = 32;
Robert Phillips7a926392018-02-01 15:49:54 -05001290 desc.fRowHeight = bitmap.height(); // always 1 here
Brian Osman2b23c4b2018-06-01 12:25:08 -04001291 desc.fConfig = SkColorType2GrPixelConfig(bitmap.colorType());
Robert Phillips96b6d532018-03-19 10:57:42 -04001292 fAtlas = atlasManager->refAtlas(desc);
Florin Malita14a8dd72017-11-08 15:46:42 -05001293 SkASSERT(fAtlas);
1294
1295 // We always filter the gradient table. Each table is one row of a texture, always
1296 // y-clamp.
1297 GrSamplerState samplerState(args.fWrapMode, GrSamplerState::Filter::kBilerp);
1298
Robert Phillips41a3b872018-03-09 12:00:34 -05001299 fRow = fAtlas->lockRow(args.fContext, bitmap);
Florin Malita14a8dd72017-11-08 15:46:42 -05001300 if (-1 != fRow) {
1301 fYCoord = fAtlas->getYOffset(fRow)+SK_ScalarHalf*fAtlas->getNormalizedTexelHeight();
1302 // This is 1/2 places where auto-normalization is disabled
1303 fCoordTransform.reset(*args.fMatrix, fAtlas->asTextureProxyRef().get(), false);
1304 fTextureSampler.reset(fAtlas->asTextureProxyRef(), samplerState);
1305 } else {
1306 // In this instance we know the samplerState state is:
1307 // clampY, bilerp
1308 // and the proxy is:
1309 // exact fit, power of two in both dimensions
1310 // Only the x-tileMode is unknown. However, given all the other knowns we know
Robert Phillips7a926392018-02-01 15:49:54 -05001311 // that GrMakeCachedImageProxy is sufficient (i.e., it won't need to be
Florin Malita14a8dd72017-11-08 15:46:42 -05001312 // extracted to a subset or mipmapped).
Robert Phillips7a926392018-02-01 15:49:54 -05001313
1314 SkASSERT(bitmap.isImmutable());
1315 sk_sp<SkImage> srcImage = SkImage::MakeFromBitmap(bitmap);
1316 if (!srcImage) {
1317 return;
1318 }
1319
1320 sk_sp<GrTextureProxy> proxy = GrMakeCachedImageProxy(
Robert Phillips1afd4cd2018-01-08 13:40:32 -05001321 args.fContext->contextPriv().proxyProvider(),
Robert Phillips7a926392018-02-01 15:49:54 -05001322 std::move(srcImage));
Florin Malita14a8dd72017-11-08 15:46:42 -05001323 if (!proxy) {
1324 SkDebugf("Gradient won't draw. Could not create texture.");
1325 return;
1326 }
1327 // This is 2/2 places where auto-normalization is disabled
1328 fCoordTransform.reset(*args.fMatrix, proxy.get(), false);
1329 fTextureSampler.reset(std::move(proxy), samplerState);
1330 fYCoord = SK_ScalarHalf;
1331 }
1332
1333 this->addTextureSampler(&fTextureSampler);
fmenozzicd9a1d02016-08-15 07:03:47 -07001334 }
1335
bsalomon@google.com77af6802013-10-02 13:04:56 +00001336 this->addCoordTransform(&fCoordTransform);
rileya@google.comd7cc6512012-07-27 14:00:39 +00001337}
1338
Brian Salomonf8480b92017-07-27 15:45:59 -04001339GrGradientEffect::GrGradientEffect(const GrGradientEffect& that)
Ethan Nicholasabff9562017-10-09 10:54:08 -04001340 : INHERITED(that.classID(), OptFlags(that.fIsOpaque))
Florin Malita14a8dd72017-11-08 15:46:42 -05001341 , fIntervals(that.fIntervals)
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001342 , fWrapMode(that.fWrapMode)
Brian Salomonf8480b92017-07-27 15:45:59 -04001343 , fCoordTransform(that.fCoordTransform)
1344 , fTextureSampler(that.fTextureSampler)
1345 , fYCoord(that.fYCoord)
1346 , fAtlas(that.fAtlas)
1347 , fRow(that.fRow)
1348 , fIsOpaque(that.fIsOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001349 , fStrategy(that.fStrategy)
1350 , fThreshold(that.fThreshold)
Brian Salomonf8480b92017-07-27 15:45:59 -04001351 , fPremulType(that.fPremulType) {
1352 this->addCoordTransform(&fCoordTransform);
Florin Malita14a8dd72017-11-08 15:46:42 -05001353 if (fStrategy == InterpolationStrategy::kTexture) {
Brian Salomonf8480b92017-07-27 15:45:59 -04001354 this->addTextureSampler(&fTextureSampler);
1355 }
1356 if (this->useAtlas()) {
1357 fAtlas->lockRow(fRow);
1358 }
1359}
1360
rileya@google.comd7cc6512012-07-27 14:00:39 +00001361GrGradientEffect::~GrGradientEffect() {
rileya@google.comb3e50f22012-08-20 17:43:08 +00001362 if (this->useAtlas()) {
1363 fAtlas->unlockRow(fRow);
rileya@google.comb3e50f22012-08-20 17:43:08 +00001364 }
rileya@google.comd7cc6512012-07-27 14:00:39 +00001365}
1366
bsalomon0e08fc12014-10-15 08:19:04 -07001367bool GrGradientEffect::onIsEqual(const GrFragmentProcessor& processor) const {
fmenozzicd9a1d02016-08-15 07:03:47 -07001368 const GrGradientEffect& ge = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +00001369
Florin Malita14a8dd72017-11-08 15:46:42 -05001370 if (fWrapMode != ge.fWrapMode || fStrategy != ge.fStrategy) {
Brian Salomon466ad992016-10-13 16:08:36 -04001371 return false;
1372 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001373
Brian Salomon466ad992016-10-13 16:08:36 -04001374 SkASSERT(this->useAtlas() == ge.useAtlas());
Florin Malita14a8dd72017-11-08 15:46:42 -05001375 if (fStrategy == InterpolationStrategy::kTexture) {
1376 if (fYCoord != ge.fYCoord) {
Brian Salomon466ad992016-10-13 16:08:36 -04001377 return false;
1378 }
1379 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001380 if (fThreshold != ge.fThreshold ||
1381 fIntervals != ge.fIntervals ||
1382 fPremulType != ge.fPremulType) {
Brian Salomon466ad992016-10-13 16:08:36 -04001383 return false;
1384 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001385 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001386 return true;
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001387}
1388
Hal Canary6f6961e2017-01-31 13:50:44 -05001389#if GR_TEST_UTILS
Brian Osman3f748602016-10-03 18:29:03 -04001390GrGradientEffect::RandomGradientParams::RandomGradientParams(SkRandom* random) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -05001391 // Set color count to min of 2 so that we don't trigger the const color optimization and make
1392 // a non-gradient processor.
1393 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
Brian Osmana2196532016-10-17 12:48:13 -04001394 fUseColors4f = random->nextBool();
bsalomon@google.comd4726202012-08-03 14:34:46 +00001395
1396 // if one color, omit stops, otherwise randomly decide whether or not to
Brian Osman3f748602016-10-03 18:29:03 -04001397 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
1398 fStops = nullptr;
1399 } else {
1400 fStops = fStopStorage;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001401 }
1402
Brian Osmana2196532016-10-17 12:48:13 -04001403 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
1404 if (fUseColors4f) {
1405 fColorSpace = GrTest::TestColorSpace(random);
1406 if (fColorSpace) {
Brian Osman36703d92017-12-12 14:09:31 -05001407 fColorSpace = fColorSpace->makeLinearGamma();
Brian Osmana2196532016-10-17 12:48:13 -04001408 }
1409 }
1410
bsalomon@google.com81712882012-11-01 17:12:34 +00001411 SkScalar stop = 0.f;
Brian Osman3f748602016-10-03 18:29:03 -04001412 for (int i = 0; i < fColorCount; ++i) {
Brian Osmana2196532016-10-17 12:48:13 -04001413 if (fUseColors4f) {
1414 fColors4f[i].fR = random->nextUScalar1();
1415 fColors4f[i].fG = random->nextUScalar1();
1416 fColors4f[i].fB = random->nextUScalar1();
1417 fColors4f[i].fA = random->nextUScalar1();
1418 } else {
1419 fColors[i] = random->nextU();
1420 }
Brian Osman3f748602016-10-03 18:29:03 -04001421 if (fStops) {
1422 fStops[i] = stop;
1423 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001424 }
1425 }
Brian Osman3f748602016-10-03 18:29:03 -04001426 fTileMode = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
bsalomon@google.comd4726202012-08-03 14:34:46 +00001427}
Hal Canary6f6961e2017-01-31 13:50:44 -05001428#endif
bsalomon@google.comd4726202012-08-03 14:34:46 +00001429
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001430#endif