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