1/*
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
8#include <algorithm>
9#include "include/core/SkMallocPixelRef.h"
10#include "include/private/SkFloatBits.h"
11#include "include/private/SkHalf.h"
12#include "include/private/SkVx.h"
13#include "src/core/SkColorSpacePriv.h"
14#include "src/core/SkConvertPixels.h"
15#include "src/core/SkReadBuffer.h"
16#include "src/core/SkVM.h"
17#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"
24
25enum 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
42void SkGradientShaderBase::Descriptor::flatten(SkWriteBuffer& buffer) const {
43 uint32_t flags = 0;
44 if (fPos) {
45 flags |= kHasPosition_GSF;
46 }
47 if (fLocalMatrix) {
48 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);
55 flags |= ((unsigned)fTileMode << kTileModeShift_GSF);
56 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) {
69 buffer.writeMatrix(*fLocalMatrix);
70 }
71}
72
73template <int N, typename T, bool MEM_MOVE>
74static bool validate_array(SkReadBuffer& buffer, size_t count, SkSTArray<N, T, MEM_MOVE>* array) {
75 if (!buffer.validateCanReadN<T>(count)) {
76 return false;
77 }
78
79 array->resize_back(count);
80 return true;
81}
82
83bool SkGradientShaderBase::DescriptorScope::unflatten(SkReadBuffer& buffer) {
84 // New gradient format. Includes floating point color, color space, densely packed flags
85 uint32_t flags = buffer.readUInt();
86
87 fTileMode = (SkTileMode)((flags >> kTileModeShift_GSF) & kTileModeMask_GSF);
88 fGradFlags = (flags >> kGradFlagsShift_GSF) & kGradFlagsMask_GSF;
89
90 fCount = buffer.getArrayCount();
91
92 if (!(validate_array(buffer, fCount, &fColorStorage) &&
93 buffer.readColor4fArray(fColorStorage.begin(), fCount))) {
94 return false;
95 }
96 fColors = fColorStorage.begin();
97
98 if (SkToBool(flags & kHasColorSpace_GSF)) {
99 sk_sp<SkData> data = buffer.readByteArrayAsData();
100 fColorSpace = data ? SkColorSpace::Deserialize(data->data(), data->size()) : nullptr;
101 } else {
102 fColorSpace = nullptr;
103 }
104 if (SkToBool(flags & kHasPosition_GSF)) {
105 if (!(validate_array(buffer, fCount, &fPosStorage) &&
106 buffer.readScalarArray(fPosStorage.begin(), fCount))) {
107 return false;
108 }
109 fPos = fPosStorage.begin();
110 } else {
111 fPos = nullptr;
112 }
113 if (SkToBool(flags & kHasLocalMatrix_GSF)) {
114 fLocalMatrix = &fLocalMatrixStorage;
115 buffer.readMatrix(&fLocalMatrixStorage);
116 } else {
117 fLocalMatrix = nullptr;
118 }
119 return buffer.isValid();
120}
121
122////////////////////////////////////////////////////////////////////////////////////////////
123
124SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc, const SkMatrix& ptsToUnit)
125 : INHERITED(desc.fLocalMatrix)
126 , fPtsToUnit(ptsToUnit)
127 , fColorSpace(desc.fColorSpace ? desc.fColorSpace : SkColorSpace::MakeSRGB())
128 , fColorsAreOpaque(true)
129{
130 fPtsToUnit.getType(); // Precache so reads are threadsafe.
131 SkASSERT(desc.fCount > 1);
132
133 fGradFlags = static_cast<uint8_t>(desc.fGradFlags);
134
135 SkASSERT((unsigned)desc.fTileMode < kSkTileModeCount);
136 fTileMode = desc.fTileMode;
137
138 /* 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 */
149 fColorCount = desc.fCount;
150 // check if we need to add in dummy start and/or end position/colors
151 bool dummyFirst = false;
152 bool dummyLast = false;
153 if (desc.fPos) {
154 dummyFirst = desc.fPos[0] != 0;
155 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
156 fColorCount += dummyFirst + dummyLast;
157 }
158
159 size_t storageSize = fColorCount * (sizeof(SkColor4f) + (desc.fPos ? sizeof(SkScalar) : 0));
160 fOrigColors4f = reinterpret_cast<SkColor4f*>(fStorage.reset(storageSize));
161 fOrigPos = desc.fPos ? reinterpret_cast<SkScalar*>(fOrigColors4f + fColorCount)
162 : nullptr;
163
164 // Now copy over the colors, adding the dummies as needed
165 SkColor4f* origColors = fOrigColors4f;
166 if (dummyFirst) {
167 *origColors++ = desc.fColors[0];
168 }
169 for (int i = 0; i < desc.fCount; ++i) {
170 origColors[i] = desc.fColors[i];
171 fColorsAreOpaque = fColorsAreOpaque && (desc.fColors[i].fA == 1);
172 }
173 if (dummyLast) {
174 origColors += desc.fCount;
175 *origColors = desc.fColors[desc.fCount - 1];
176 }
177
178 if (desc.fPos) {
179 SkScalar prev = 0;
180 SkScalar* origPosPtr = fOrigPos;
181 *origPosPtr++ = prev; // force the first pos to 0
182
183 int startIndex = dummyFirst ? 0 : 1;
184 int count = desc.fCount + dummyLast;
185
186 bool uniformStops = true;
187 const SkScalar uniformStep = desc.fPos[startIndex] - prev;
188 for (int i = startIndex; i < count; i++) {
189 // Pin the last value to 1.0, and make sure pos is monotonic.
190 auto curr = (i == desc.fCount) ? 1 : SkTPin(desc.fPos[i], prev, 1.0f);
191 uniformStops &= SkScalarNearlyEqual(uniformStep, curr - prev);
192
193 *origPosPtr++ = prev = curr;
194 }
195
196 // If the stops are uniform, treat them as implicit.
197 if (uniformStops) {
198 fOrigPos = nullptr;
199 }
200 }
201}
202
203SkGradientShaderBase::~SkGradientShaderBase() {}
204
205void SkGradientShaderBase::flatten(SkWriteBuffer& buffer) const {
206 Descriptor desc;
207 desc.fColors = fOrigColors4f;
208 desc.fColorSpace = fColorSpace;
209 desc.fPos = fOrigPos;
210 desc.fCount = fColorCount;
211 desc.fTileMode = fTileMode;
212 desc.fGradFlags = fGradFlags;
213
214 const SkMatrix& m = this->getLocalMatrix();
215 desc.fLocalMatrix = m.isIdentity() ? nullptr : &m;
216 desc.flatten(buffer);
217}
218
219static void add_stop_color(SkRasterPipeline_GradientCtx* ctx, size_t stop, SkPMColor4f Fs, SkPMColor4f Bs) {
220 (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;
224
225 (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;
229}
230
231static void add_const_color(SkRasterPipeline_GradientCtx* ctx, size_t stop, SkPMColor4f color) {
232 add_stop_color(ctx, stop, { 0, 0, 0, 0 }, color);
233}
234
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(
238 SkRasterPipeline_GradientCtx* ctx, float gapCount, size_t stop, SkPMColor4f c_l, SkPMColor4f c_r) {
239 // Clankium's GCC 4.9 targeting ARMv7 is barfing when we use Sk4f math here, so go scalar...
240 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 };
252 add_stop_color(ctx, stop, Fs, Bs);
253}
254
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(
258 SkRasterPipeline_GradientCtx* ctx, size_t stop, float t_l, float t_r, SkPMColor4f c_l, SkPMColor4f c_r) {
259 // See note about Clankium's old compiler in init_stop_evenly().
260 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 };
272 ctx->ts[stop] = t_l;
273 add_stop_color(ctx, stop, Fs, Bs);
274}
275
276bool SkGradientShaderBase::onAppendStages(const SkStageRec& rec) const {
277 SkRasterPipeline* p = rec.fPipeline;
278 SkArenaAlloc* alloc = rec.fAlloc;
279 SkRasterPipeline_DecalTileCtx* decal_ctx = nullptr;
280
281 SkMatrix matrix;
282 if (!this->computeTotalInverse(rec.fCTM, rec.fLocalM, &matrix)) {
283 return false;
284 }
285 matrix.postConcat(fPtsToUnit);
286
287 SkRasterPipeline_<256> postPipeline;
288
289 p->append(SkRasterPipeline::seed_shader);
290 p->append_matrix(alloc, matrix);
291 this->appendGradientStages(alloc, p, &postPipeline);
292
293 switch(fTileMode) {
294 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:
297 decal_ctx = alloc->make<SkRasterPipeline_DecalTileCtx>();
298 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
302 case SkTileMode::kClamp:
303 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.
306 // In that case, we must make sure we're using the general "gradient" stage,
307 // which is the only stage that will correctly handle unclamped t.
308 p->append(SkRasterPipeline::clamp_x_1);
309 }
310 break;
311 }
312
313 const bool premulGrad = fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag;
314
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];
320 return premulGrad ? c.premul()
321 : SkPMColor4f{ c.fR, c.fG, c.fB, c.fA };
322 };
323
324 // The two-stop case with stops at 0 and 1.
325 if (fColorCount == 2 && fOrigPos == nullptr) {
326 const SkPMColor4f c_l = prepareColor(0),
327 c_r = prepareColor(1);
328
329 // See F and B below.
330 auto ctx = alloc->make<SkRasterPipeline_EvenlySpaced2StopGradientCtx>();
331 (Sk4f::Load(c_r.vec()) - Sk4f::Load(c_l.vec())).store(ctx->f);
332 ( Sk4f::Load(c_l.vec())).store(ctx->b);
333 ctx->interpolatedInPremul = premulGrad;
334
335 p->append(SkRasterPipeline::evenly_spaced_2_stop_gradient, ctx);
336 } else {
337 auto* ctx = alloc->make<SkRasterPipeline_GradientCtx>();
338 ctx->interpolatedInPremul = premulGrad;
339
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
348 if (fOrigPos == nullptr) {
349 // Handle evenly distributed stops.
350
351 size_t stopCount = fColorCount;
352 float gapCount = stopCount - 1;
353
354 SkPMColor4f c_l = prepareColor(0);
355 for (size_t i = 0; i < stopCount - 1; i++) {
356 SkPMColor4f c_r = prepareColor(i + 1);
357 init_stop_evenly(ctx, gapCount, i, c_l, c_r);
358 c_l = c_r;
359 }
360 add_const_color(ctx, stopCount - 1, c_l);
361
362 ctx->stopCount = stopCount;
363 p->append(SkRasterPipeline::evenly_spaced_gradient, ctx);
364 } else {
365 // Handle arbitrary stops.
366
367 ctx->ts = alloc->makeArray<float>(fColorCount+1);
368
369 // 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 }
381
382 size_t stopCount = 0;
383 float t_l = fOrigPos[firstStop];
384 SkPMColor4f c_l = prepareColor(firstStop);
385 add_const_color(ctx, stopCount++, c_l);
386 // 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];
389 SkPMColor4f c_r = prepareColor(i + 1);
390 SkASSERT(t_l <= t_r);
391 if (t_l < t_r) {
392 init_stop_pos(ctx, stopCount, t_l, t_r, c_l, c_r);
393 stopCount += 1;
394 }
395 t_l = t_r;
396 c_l = c_r;
397 }
398
399 ctx->ts[stopCount] = t_l;
400 add_const_color(ctx, stopCount++, c_l);
401
402 ctx->stopCount = stopCount;
403 p->append(SkRasterPipeline::gradient, ctx);
404 }
405 }
406
407 if (decal_ctx) {
408 p->append(SkRasterPipeline::check_decal_mask, decal_ctx);
409 }
410
411 if (!premulGrad && !this->colorsAreOpaque()) {
412 p->append(SkRasterPipeline::premul);
413 }
414
415 p->extend(postPipeline);
416
417 return true;
418}
419
420skvm::Color SkGradientShaderBase::onProgram(skvm::Builder* p,
421 skvm::F32 x, skvm::F32 y, skvm::Color /*paint*/,
422 const SkMatrix& ctm, const SkMatrix* localM,
423 SkFilterQuality quality, const SkColorInfo& dstInfo,
424 skvm::Uniforms* uniforms, SkArenaAlloc* alloc) const {
425 SkMatrix inv;
426 if (!this->computeTotalInverse(ctm, localM, &inv)) {
427 return {};
428 }
429 inv.postConcat(fPtsToUnit);
430 inv.normalizePerspective();
431
432 SkShaderBase::ApplyMatrix(p, inv, &x,&y,uniforms);
433
434 skvm::I32 mask = p->splat(~0);
435 skvm::F32 t = this->transformT(p,uniforms, x,y, &mask);
436
437 // Perhaps unexpectedly, clamping is handled naturally by our search, so we
438 // don't explicitly clamp t to [0,1]. That clamp would break hard stops
439 // right at 0 or 1 boundaries in kClamp mode. (kRepeat and kMirror always
440 // produce values in [0,1].)
441 switch(fTileMode) {
442 case SkTileMode::kClamp:
443 break;
444
445 case SkTileMode::kDecal:
446 mask &= (t == clamp01(t));
447 break;
448
449 case SkTileMode::kRepeat:
450 t = fract(t);
451 break;
452
453 case SkTileMode::kMirror: {
454 // t = | (t-1) - 2*(floor( (t-1)*0.5 )) - 1 |
455 // {-A-} {--------B-------}
456 skvm::F32 A = t - 1.0f,
457 B = floor(A * 0.5f);
458 t = abs(A - (B + B) - 1.0f);
459 } break;
460 }
461
462 // Transform our colors as we want them interpolated, in dst color space, possibly premul.
463 SkImageInfo common = SkImageInfo::Make(fColorCount,1, kRGBA_F32_SkColorType
464 , kUnpremul_SkAlphaType),
465 src = common.makeColorSpace(fColorSpace),
466 dst = common.makeColorSpace(dstInfo.refColorSpace());
467 if (fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag) {
468 dst = dst.makeAlphaType(kPremul_SkAlphaType);
469 }
470
471 std::vector<float> rgba(4*fColorCount); // TODO: SkSTArray?
472 SkConvertPixels(dst, rgba.data(), dst.minRowBytes(),
473 src, fOrigColors4f, src.minRowBytes());
474
475 // Transform our colors into a scale factor f and bias b such that for
476 // any t between stops i and i+1, the color we want is mad(t, f[i], b[i]).
477 using F4 = skvx::Vec<4,float>;
478 struct FB { F4 f,b; };
479 skvm::Color color;
480
481 auto uniformF = [&](float x) { return p->uniformF(uniforms->pushF(x)); };
482
483 if (fColorCount == 2) {
484 // 2-stop gradients have colors at 0 and 1, and so must be evenly spaced.
485 SkASSERT(fOrigPos == nullptr);
486
487 // With 2 stops, we upload the single FB as uniforms and interpolate directly with t.
488 F4 lo = F4::Load(rgba.data() + 0),
489 hi = F4::Load(rgba.data() + 4);
490 F4 F = hi - lo,
491 B = lo;
492
493 auto T = clamp01(t);
494 color = {
495 T * uniformF(F[0]) + uniformF(B[0]),
496 T * uniformF(F[1]) + uniformF(B[1]),
497 T * uniformF(F[2]) + uniformF(B[2]),
498 T * uniformF(F[3]) + uniformF(B[3]),
499 };
500 } else {
501 // To handle clamps in search we add a conceptual stop at t=-inf, so we
502 // may need up to fColorCount+1 FBs and fColorCount t stops between them:
503 //
504 // FBs: [color 0] [color 0->1] [color 1->2] [color 2->3] ...
505 // stops: (-inf) t0 t1 t2 ...
506 //
507 // Both these arrays could end up shorter if any hard stops share the same t.
508 FB* fb = alloc->makeArrayDefault<FB>(fColorCount+1);
509 std::vector<float> stops; // TODO: SkSTArray?
510 stops.reserve(fColorCount);
511
512 // Here's our conceptual stop at t=-inf covering all t<=0, clamping to our first color.
513 float t_lo = this->getPos(0);
514 F4 color_lo = F4::Load(rgba.data());
515 fb[0] = { 0.0f, color_lo };
516 // N.B. No stops[] entry for this implicit -inf.
517
518 // Now the non-edge cases, calculating scale and bias between adjacent normal stops.
519 for (int i = 1; i < fColorCount; i++) {
520 float t_hi = this->getPos(i);
521 F4 color_hi = F4::Load(rgba.data() + 4*i);
522
523 // If t_lo == t_hi, we're on a hard stop, and transition immediately to the next color.
524 SkASSERT(t_lo <= t_hi);
525 if (t_lo < t_hi) {
526 F4 f = (color_hi - color_lo) / (t_hi - t_lo),
527 b = color_lo - f*t_lo;
528 stops.push_back(t_lo);
529 fb[stops.size()] = {f,b};
530 }
531
532 t_lo = t_hi;
533 color_lo = color_hi;
534 }
535 // Anything >= our final t clamps to our final color.
536 stops.push_back(t_lo);
537 fb[stops.size()] = { 0.0f, color_lo };
538
539 // We'll gather FBs from that array we just created.
540 skvm::Uniform fbs = uniforms->pushPtr(fb);
541
542 // Find the two stops we need to interpolate.
543 skvm::I32 ix;
544 if (fOrigPos == nullptr) {
545 // Evenly spaced stops... we can calculate ix directly.
546 // Of note: we need to clamp t and skip over that conceptual -inf stop we made up.
547 ix = trunc(clamp01(t) * uniformF(stops.size() - 1) + 1.0f);
548 } else {
549 // Starting ix at 0 bakes in our conceptual first stop at -inf.
550 // TODO: good place to experiment with a loop in skvm.... stops.size() can be huge.
551 ix = p->splat(0);
552 for (float stop : stops) {
553 // ix += (t >= stop) ? +1 : 0 ~~>
554 // ix -= (t >= stop) ? -1 : 0
555 ix -= (t >= uniformF(stop));
556 }
557 // TODO: we could skip any of the dummy stops GradientShaderBase's ctor added
558 // to ensure the full [0,1] span is covered. This linear search doesn't need
559 // them for correctness, and it'd be up to two fewer stops to check.
560 // N.B. we do still need those stops for the fOrigPos == nullptr direct math path.
561 }
562
563 // A scale factor and bias for each lane, 8 total.
564 // TODO: simpler, faster, tidier to push 8 uniform pointers, one for each struct lane?
565 ix = shl(ix, 3);
566 skvm::F32 Fr = gatherF(fbs, ix + 0);
567 skvm::F32 Fg = gatherF(fbs, ix + 1);
568 skvm::F32 Fb = gatherF(fbs, ix + 2);
569 skvm::F32 Fa = gatherF(fbs, ix + 3);
570
571 skvm::F32 Br = gatherF(fbs, ix + 4);
572 skvm::F32 Bg = gatherF(fbs, ix + 5);
573 skvm::F32 Bb = gatherF(fbs, ix + 6);
574 skvm::F32 Ba = gatherF(fbs, ix + 7);
575
576 // This is what we've been building towards!
577 color = {
578 t * Fr + Br,
579 t * Fg + Bg,
580 t * Fb + Bb,
581 t * Fa + Ba,
582 };
583 }
584
585 // If we interpolated unpremul, premul now to match our output convention.
586 if (0 == (fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag)
587 && !fColorsAreOpaque) {
588 color = premul(color);
589 }
590
591 return {
592 bit_cast(mask & bit_cast(color.r)),
593 bit_cast(mask & bit_cast(color.g)),
594 bit_cast(mask & bit_cast(color.b)),
595 bit_cast(mask & bit_cast(color.a)),
596 };
597}
598
599
600bool SkGradientShaderBase::isOpaque() const {
601 return fColorsAreOpaque && (this->getTileMode() != SkTileMode::kDecal);
602}
603
604static unsigned rounded_divide(unsigned numer, unsigned denom) {
605 return (numer + (denom >> 1)) / denom;
606}
607
608bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
609 // we just compute an average color.
610 // possibly we could weight this based on the proportional width for each color
611 // assuming they are not evenly distributed in the fPos array.
612 int r = 0;
613 int g = 0;
614 int b = 0;
615 const int n = fColorCount;
616 // TODO: use linear colors?
617 for (int i = 0; i < n; ++i) {
618 SkColor c = this->getLegacyColor(i);
619 r += SkColorGetR(c);
620 g += SkColorGetG(c);
621 b += SkColorGetB(c);
622 }
623 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
624 return true;
625}
626
627SkColor4fXformer::SkColor4fXformer(const SkColor4f* colors, int colorCount,
628 SkColorSpace* src, SkColorSpace* dst) {
629 fColors = colors;
630
631 if (dst && !SkColorSpace::Equals(src, dst)) {
632 fStorage.reset(colorCount);
633
634 auto info = SkImageInfo::Make(colorCount,1, kRGBA_F32_SkColorType, kUnpremul_SkAlphaType);
635
636 SkConvertPixels(info.makeColorSpace(sk_ref_sp(dst)), fStorage.begin(), info.minRowBytes(),
637 info.makeColorSpace(sk_ref_sp(src)), fColors , info.minRowBytes());
638
639 fColors = fStorage.begin();
640 }
641}
642
643void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
644 if (info) {
645 if (info->fColorCount >= fColorCount) {
646 if (info->fColors) {
647 for (int i = 0; i < fColorCount; ++i) {
648 info->fColors[i] = this->getLegacyColor(i);
649 }
650 }
651 if (info->fColorOffsets) {
652 for (int i = 0; i < fColorCount; ++i) {
653 info->fColorOffsets[i] = this->getPos(i);
654 }
655 }
656 }
657 info->fColorCount = fColorCount;
658 info->fTileMode = fTileMode;
659 info->fGradientFlags = fGradFlags;
660 }
661}
662
663///////////////////////////////////////////////////////////////////////////////
664///////////////////////////////////////////////////////////////////////////////
665
666// Return true if these parameters are valid/legal/safe to construct a gradient
667//
668static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
669 SkTileMode tileMode) {
670 return nullptr != colors && count >= 1 && (unsigned)tileMode < kSkTileModeCount;
671}
672
673static void desc_init(SkGradientShaderBase::Descriptor* desc,
674 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
675 const SkScalar pos[], int colorCount,
676 SkTileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
677 SkASSERT(colorCount > 1);
678
679 desc->fColors = colors;
680 desc->fColorSpace = std::move(colorSpace);
681 desc->fPos = pos;
682 desc->fCount = colorCount;
683 desc->fTileMode = mode;
684 desc->fGradFlags = flags;
685 desc->fLocalMatrix = localMatrix;
686}
687
688static SkColor4f average_gradient_color(const SkColor4f colors[], const SkScalar pos[],
689 int colorCount) {
690 // The gradient is a piecewise linear interpolation between colors. For a given interval,
691 // the integral between the two endpoints is 0.5 * (ci + cj) * (pj - pi), which provides that
692 // intervals average color. The overall average color is thus the sum of each piece. The thing
693 // to keep in mind is that the provided gradient definition may implicitly use p=0 and p=1.
694 Sk4f blend(0.0);
695 // Bake 1/(colorCount - 1) uniform stop difference into this scale factor
696 SkScalar wScale = pos ? 0.5 : 0.5 / (colorCount - 1);
697 for (int i = 0; i < colorCount - 1; ++i) {
698 // Calculate the average color for the interval between pos(i) and pos(i+1)
699 Sk4f c0 = Sk4f::Load(&colors[i]);
700 Sk4f c1 = Sk4f::Load(&colors[i + 1]);
701 // when pos == null, there are colorCount uniformly distributed stops, going from 0 to 1,
702 // so pos[i + 1] - pos[i] = 1/(colorCount-1)
703 SkScalar w = pos ? (pos[i + 1] - pos[i]) : SK_Scalar1;
704 blend += wScale * w * (c1 + c0);
705 }
706
707 // Now account for any implicit intervals at the start or end of the stop definitions
708 if (pos) {
709 if (pos[0] > 0.0) {
710 // The first color is fixed between p = 0 to pos[0], so 0.5 * (ci + cj) * (pj - pi)
711 // becomes 0.5 * (c + c) * (pj - 0) = c * pj
712 Sk4f c = Sk4f::Load(&colors[0]);
713 blend += pos[0] * c;
714 }
715 if (pos[colorCount - 1] < SK_Scalar1) {
716 // The last color is fixed between pos[n-1] to p = 1, so 0.5 * (ci + cj) * (pj - pi)
717 // becomes 0.5 * (c + c) * (1 - pi) = c * (1 - pi)
718 Sk4f c = Sk4f::Load(&colors[colorCount - 1]);
719 blend += (1 - pos[colorCount - 1]) * c;
720 }
721 }
722
723 SkColor4f avg;
724 blend.store(&avg);
725 return avg;
726}
727
728// The default SkScalarNearlyZero threshold of .0024 is too big and causes regressions for svg
729// gradients defined in the wild.
730static constexpr SkScalar kDegenerateThreshold = SK_Scalar1 / (1 << 15);
731
732// Except for special circumstances of clamped gradients, every gradient shape--when degenerate--
733// can be mapped to the same fallbacks. The specific shape factories must account for special
734// clamped conditions separately, this will always return the last color for clamped gradients.
735static sk_sp<SkShader> make_degenerate_gradient(const SkColor4f colors[], const SkScalar pos[],
736 int colorCount, sk_sp<SkColorSpace> colorSpace,
737 SkTileMode mode) {
738 switch(mode) {
739 case SkTileMode::kDecal:
740 // normally this would reject the area outside of the interpolation region, so since
741 // inside region is empty when the radii are equal, the entire draw region is empty
742 return SkShaders::Empty();
743 case SkTileMode::kRepeat:
744 case SkTileMode::kMirror:
745 // repeat and mirror are treated the same: the border colors are never visible,
746 // but approximate the final color as infinite repetitions of the colors, so
747 // it can be represented as the average color of the gradient.
748 return SkShaders::Color(
749 average_gradient_color(colors, pos, colorCount), std::move(colorSpace));
750 case SkTileMode::kClamp:
751 // Depending on how the gradient shape degenerates, there may be a more specialized
752 // fallback representation for the factories to use, but this is a reasonable default.
753 return SkShaders::Color(colors[colorCount - 1], std::move(colorSpace));
754 }
755 SkDEBUGFAIL("Should not be reached");
756 return nullptr;
757}
758
759// assumes colors is SkColor4f* and pos is SkScalar*
760#define EXPAND_1_COLOR(count) \
761 SkColor4f tmp[2]; \
762 do { \
763 if (1 == count) { \
764 tmp[0] = tmp[1] = colors[0]; \
765 colors = tmp; \
766 pos = nullptr; \
767 count = 2; \
768 } \
769 } while (0)
770
771struct ColorStopOptimizer {
772 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos, int count, SkTileMode mode)
773 : fColors(colors)
774 , fPos(pos)
775 , fCount(count) {
776
777 if (!pos || count != 3) {
778 return;
779 }
780
781 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
782 SkScalarNearlyEqual(pos[1], 0.0f) &&
783 SkScalarNearlyEqual(pos[2], 1.0f)) {
784
785 if (SkTileMode::kRepeat == mode || SkTileMode::kMirror == mode ||
786 colors[0] == colors[1]) {
787
788 // Ignore the leftmost color/pos.
789 fColors += 1;
790 fPos += 1;
791 fCount = 2;
792 }
793 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
794 SkScalarNearlyEqual(pos[1], 1.0f) &&
795 SkScalarNearlyEqual(pos[2], 1.0f)) {
796
797 if (SkTileMode::kRepeat == mode || SkTileMode::kMirror == mode ||
798 colors[1] == colors[2]) {
799
800 // Ignore the rightmost color/pos.
801 fCount = 2;
802 }
803 }
804 }
805
806 const SkColor4f* fColors;
807 const SkScalar* fPos;
808 int fCount;
809};
810
811struct ColorConverter {
812 ColorConverter(const SkColor* colors, int count) {
813 const float ONE_OVER_255 = 1.f / 255;
814 for (int i = 0; i < count; ++i) {
815 fColors4f.push_back({
816 SkColorGetR(colors[i]) * ONE_OVER_255,
817 SkColorGetG(colors[i]) * ONE_OVER_255,
818 SkColorGetB(colors[i]) * ONE_OVER_255,
819 SkColorGetA(colors[i]) * ONE_OVER_255 });
820 }
821 }
822
823 SkSTArray<2, SkColor4f, true> fColors4f;
824};
825
826sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
827 const SkColor colors[],
828 const SkScalar pos[], int colorCount,
829 SkTileMode mode,
830 uint32_t flags,
831 const SkMatrix* localMatrix) {
832 ColorConverter converter(colors, colorCount);
833 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
834 localMatrix);
835}
836
837sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
838 const SkColor4f colors[],
839 sk_sp<SkColorSpace> colorSpace,
840 const SkScalar pos[], int colorCount,
841 SkTileMode mode,
842 uint32_t flags,
843 const SkMatrix* localMatrix) {
844 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
845 return nullptr;
846 }
847 if (!valid_grad(colors, pos, colorCount, mode)) {
848 return nullptr;
849 }
850 if (1 == colorCount) {
851 return SkShaders::Color(colors[0], std::move(colorSpace));
852 }
853 if (localMatrix && !localMatrix->invert(nullptr)) {
854 return nullptr;
855 }
856
857 if (SkScalarNearlyZero((pts[1] - pts[0]).length(), kDegenerateThreshold)) {
858 // Degenerate gradient, the only tricky complication is when in clamp mode, the limit of
859 // the gradient approaches two half planes of solid color (first and last). However, they
860 // are divided by the line perpendicular to the start and end point, which becomes undefined
861 // once start and end are exactly the same, so just use the end color for a stable solution.
862 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
863 }
864
865 ColorStopOptimizer opt(colors, pos, colorCount, mode);
866
867 SkGradientShaderBase::Descriptor desc;
868 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
869 localMatrix);
870 return sk_make_sp<SkLinearGradient>(pts, desc);
871}
872
873sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
874 const SkColor colors[],
875 const SkScalar pos[], int colorCount,
876 SkTileMode mode,
877 uint32_t flags,
878 const SkMatrix* localMatrix) {
879 ColorConverter converter(colors, colorCount);
880 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
881 flags, localMatrix);
882}
883
884sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
885 const SkColor4f colors[],
886 sk_sp<SkColorSpace> colorSpace,
887 const SkScalar pos[], int colorCount,
888 SkTileMode mode,
889 uint32_t flags,
890 const SkMatrix* localMatrix) {
891 if (radius < 0) {
892 return nullptr;
893 }
894 if (!valid_grad(colors, pos, colorCount, mode)) {
895 return nullptr;
896 }
897 if (1 == colorCount) {
898 return SkShaders::Color(colors[0], std::move(colorSpace));
899 }
900 if (localMatrix && !localMatrix->invert(nullptr)) {
901 return nullptr;
902 }
903
904 if (SkScalarNearlyZero(radius, kDegenerateThreshold)) {
905 // Degenerate gradient optimization, and no special logic needed for clamped radial gradient
906 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
907 }
908
909 ColorStopOptimizer opt(colors, pos, colorCount, mode);
910
911 SkGradientShaderBase::Descriptor desc;
912 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
913 localMatrix);
914 return sk_make_sp<SkRadialGradient>(center, radius, desc);
915}
916
917sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
918 SkScalar startRadius,
919 const SkPoint& end,
920 SkScalar endRadius,
921 const SkColor colors[],
922 const SkScalar pos[],
923 int colorCount,
924 SkTileMode mode,
925 uint32_t flags,
926 const SkMatrix* localMatrix) {
927 ColorConverter converter(colors, colorCount);
928 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
929 nullptr, pos, colorCount, mode, flags, localMatrix);
930}
931
932sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
933 SkScalar startRadius,
934 const SkPoint& end,
935 SkScalar endRadius,
936 const SkColor4f colors[],
937 sk_sp<SkColorSpace> colorSpace,
938 const SkScalar pos[],
939 int colorCount,
940 SkTileMode mode,
941 uint32_t flags,
942 const SkMatrix* localMatrix) {
943 if (startRadius < 0 || endRadius < 0) {
944 return nullptr;
945 }
946 if (!valid_grad(colors, pos, colorCount, mode)) {
947 return nullptr;
948 }
949 if (SkScalarNearlyZero((start - end).length(), kDegenerateThreshold)) {
950 // If the center positions are the same, then the gradient is the radial variant of a 2 pt
951 // conical gradient, an actual radial gradient (startRadius == 0), or it is fully degenerate
952 // (startRadius == endRadius).
953 if (SkScalarNearlyEqual(startRadius, endRadius, kDegenerateThreshold)) {
954 // Degenerate case, where the interpolation region area approaches zero. The proper
955 // behavior depends on the tile mode, which is consistent with the default degenerate
956 // gradient behavior, except when mode = clamp and the radii > 0.
957 if (mode == SkTileMode::kClamp && endRadius > kDegenerateThreshold) {
958 // The interpolation region becomes an infinitely thin ring at the radius, so the
959 // final gradient will be the first color repeated from p=0 to 1, and then a hard
960 // stop switching to the last color at p=1.
961 static constexpr SkScalar circlePos[3] = {0, 1, 1};
962 SkColor4f reColors[3] = {colors[0], colors[0], colors[colorCount - 1]};
963 return MakeRadial(start, endRadius, reColors, std::move(colorSpace),
964 circlePos, 3, mode, flags, localMatrix);
965 } else {
966 // Otherwise use the default degenerate case
967 return make_degenerate_gradient(
968 colors, pos, colorCount, std::move(colorSpace), mode);
969 }
970 } else if (SkScalarNearlyZero(startRadius, kDegenerateThreshold)) {
971 // We can treat this gradient as radial, which is faster. If we got here, we know
972 // that endRadius is not equal to 0, so this produces a meaningful gradient
973 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
974 mode, flags, localMatrix);
975 }
976 // Else it's the 2pt conical radial variant with no degenerate radii, so fall through to the
977 // regular 2pt constructor.
978 }
979
980 if (localMatrix && !localMatrix->invert(nullptr)) {
981 return nullptr;
982 }
983 EXPAND_1_COLOR(colorCount);
984
985 ColorStopOptimizer opt(colors, pos, colorCount, mode);
986
987 SkGradientShaderBase::Descriptor desc;
988 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
989 localMatrix);
990 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
991}
992
993sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
994 const SkColor colors[],
995 const SkScalar pos[],
996 int colorCount,
997 SkTileMode mode,
998 SkScalar startAngle,
999 SkScalar endAngle,
1000 uint32_t flags,
1001 const SkMatrix* localMatrix) {
1002 ColorConverter converter(colors, colorCount);
1003 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
1004 mode, startAngle, endAngle, flags, localMatrix);
1005}
1006
1007sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
1008 const SkColor4f colors[],
1009 sk_sp<SkColorSpace> colorSpace,
1010 const SkScalar pos[],
1011 int colorCount,
1012 SkTileMode mode,
1013 SkScalar startAngle,
1014 SkScalar endAngle,
1015 uint32_t flags,
1016 const SkMatrix* localMatrix) {
1017 if (!valid_grad(colors, pos, colorCount, mode)) {
1018 return nullptr;
1019 }
1020 if (1 == colorCount) {
1021 return SkShaders::Color(colors[0], std::move(colorSpace));
1022 }
1023 if (!SkScalarIsFinite(startAngle) || !SkScalarIsFinite(endAngle) || startAngle > endAngle) {
1024 return nullptr;
1025 }
1026 if (localMatrix && !localMatrix->invert(nullptr)) {
1027 return nullptr;
1028 }
1029
1030 if (SkScalarNearlyEqual(startAngle, endAngle, kDegenerateThreshold)) {
1031 // Degenerate gradient, which should follow default degenerate behavior unless it is
1032 // clamped and the angle is greater than 0.
1033 if (mode == SkTileMode::kClamp && endAngle > kDegenerateThreshold) {
1034 // In this case, the first color is repeated from 0 to the angle, then a hardstop
1035 // switches to the last color (all other colors are compressed to the infinitely thin
1036 // interpolation region).
1037 static constexpr SkScalar clampPos[3] = {0, 1, 1};
1038 SkColor4f reColors[3] = {colors[0], colors[0], colors[colorCount - 1]};
1039 return MakeSweep(cx, cy, reColors, std::move(colorSpace), clampPos, 3, mode, 0,
1040 endAngle, flags, localMatrix);
1041 } else {
1042 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
1043 }
1044 }
1045
1046 if (startAngle <= 0 && endAngle >= 360) {
1047 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
1048 mode = SkTileMode::kClamp;
1049 }
1050
1051 ColorStopOptimizer opt(colors, pos, colorCount, mode);
1052
1053 SkGradientShaderBase::Descriptor desc;
1054 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
1055 localMatrix);
1056
1057 const SkScalar t0 = startAngle / 360,
1058 t1 = endAngle / 360;
1059
1060 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
1061}
1062
1063void SkGradientShader::RegisterFlattenables() {
1064 SK_REGISTER_FLATTENABLE(SkLinearGradient);
1065 SK_REGISTER_FLATTENABLE(SkRadialGradient);
1066 SK_REGISTER_FLATTENABLE(SkSweepGradient);
1067 SK_REGISTER_FLATTENABLE(SkTwoPointConicalGradient);
1068}
1069