blob: dff2d8cd4338ab421514d6e960584bd4a0a42838 [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
8#include "SkGradientShaderPriv.h"
9#include "SkLinearGradient.h"
10#include "SkRadialGradient.h"
11#include "SkTwoPointRadialGradient.h"
12#include "SkTwoPointConicalGradient.h"
13#include "SkSweepGradient.h"
14
reed@google.com437d6eb2013-05-23 19:03:05 +000015SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc) {
16 SkASSERT(desc.fCount > 1);
rileya@google.com589708b2012-07-26 20:04:23 +000017
18 fCacheAlpha = 256; // init to a value that paint.getAlpha() can't return
19
reed@google.com437d6eb2013-05-23 19:03:05 +000020 fMapper = desc.fMapper;
21 SkSafeRef(fMapper);
reed@google.com3d3a8602013-05-24 14:58:44 +000022 fGradFlags = SkToU8(desc.fFlags);
rileya@google.com589708b2012-07-26 20:04:23 +000023
reed@google.com437d6eb2013-05-23 19:03:05 +000024 SkASSERT((unsigned)desc.fTileMode < SkShader::kTileModeCount);
rileya@google.com589708b2012-07-26 20:04:23 +000025 SkASSERT(SkShader::kTileModeCount == SK_ARRAY_COUNT(gTileProcs));
reed@google.com437d6eb2013-05-23 19:03:05 +000026 fTileMode = desc.fTileMode;
27 fTileProc = gTileProcs[desc.fTileMode];
rileya@google.com589708b2012-07-26 20:04:23 +000028
29 fCache16 = fCache16Storage = NULL;
30 fCache32 = NULL;
31 fCache32PixelRef = NULL;
32
33 /* Note: we let the caller skip the first and/or last position.
34 i.e. pos[0] = 0.3, pos[1] = 0.7
35 In these cases, we insert dummy entries to ensure that the final data
36 will be bracketed by [0, 1].
37 i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
38
39 Thus colorCount (the caller's value, and fColorCount (our value) may
40 differ by up to 2. In the above example:
41 colorCount = 2
42 fColorCount = 4
43 */
reed@google.com437d6eb2013-05-23 19:03:05 +000044 fColorCount = desc.fCount;
rileya@google.com589708b2012-07-26 20:04:23 +000045 // check if we need to add in dummy start and/or end position/colors
46 bool dummyFirst = false;
47 bool dummyLast = false;
reed@google.com437d6eb2013-05-23 19:03:05 +000048 if (desc.fPos) {
49 dummyFirst = desc.fPos[0] != 0;
50 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
rileya@google.com589708b2012-07-26 20:04:23 +000051 fColorCount += dummyFirst + dummyLast;
52 }
53
54 if (fColorCount > kColorStorageCount) {
55 size_t size = sizeof(SkColor) + sizeof(Rec);
56 fOrigColors = reinterpret_cast<SkColor*>(
57 sk_malloc_throw(size * fColorCount));
58 }
59 else {
60 fOrigColors = fStorage;
61 }
62
63 // Now copy over the colors, adding the dummies as needed
64 {
65 SkColor* origColors = fOrigColors;
66 if (dummyFirst) {
reed@google.com437d6eb2013-05-23 19:03:05 +000067 *origColors++ = desc.fColors[0];
rileya@google.com589708b2012-07-26 20:04:23 +000068 }
reed@google.com437d6eb2013-05-23 19:03:05 +000069 memcpy(origColors, desc.fColors, desc.fCount * sizeof(SkColor));
rileya@google.com589708b2012-07-26 20:04:23 +000070 if (dummyLast) {
reed@google.com437d6eb2013-05-23 19:03:05 +000071 origColors += desc.fCount;
72 *origColors = desc.fColors[desc.fCount - 1];
rileya@google.com589708b2012-07-26 20:04:23 +000073 }
74 }
75
76 fRecs = (Rec*)(fOrigColors + fColorCount);
77 if (fColorCount > 2) {
78 Rec* recs = fRecs;
79 recs->fPos = 0;
80 // recs->fScale = 0; // unused;
81 recs += 1;
reed@google.com437d6eb2013-05-23 19:03:05 +000082 if (desc.fPos) {
rileya@google.com589708b2012-07-26 20:04:23 +000083 /* We need to convert the user's array of relative positions into
84 fixed-point positions and scale factors. We need these results
85 to be strictly monotonic (no two values equal or out of order).
86 Hence this complex loop that just jams a zero for the scale
87 value if it sees a segment out of order, and it assures that
88 we start at 0 and end at 1.0
89 */
90 SkFixed prev = 0;
91 int startIndex = dummyFirst ? 0 : 1;
reed@google.com437d6eb2013-05-23 19:03:05 +000092 int count = desc.fCount + dummyLast;
rileya@google.com589708b2012-07-26 20:04:23 +000093 for (int i = startIndex; i < count; i++) {
94 // force the last value to be 1.0
95 SkFixed curr;
reed@google.com437d6eb2013-05-23 19:03:05 +000096 if (i == desc.fCount) { // we're really at the dummyLast
rileya@google.com589708b2012-07-26 20:04:23 +000097 curr = SK_Fixed1;
98 } else {
reed@google.com437d6eb2013-05-23 19:03:05 +000099 curr = SkScalarToFixed(desc.fPos[i]);
rileya@google.com589708b2012-07-26 20:04:23 +0000100 }
101 // pin curr withing range
102 if (curr < 0) {
103 curr = 0;
104 } else if (curr > SK_Fixed1) {
105 curr = SK_Fixed1;
106 }
107 recs->fPos = curr;
108 if (curr > prev) {
109 recs->fScale = (1 << 24) / (curr - prev);
110 } else {
111 recs->fScale = 0; // ignore this segment
112 }
113 // get ready for the next value
114 prev = curr;
115 recs += 1;
116 }
117 } else { // assume even distribution
reed@google.com437d6eb2013-05-23 19:03:05 +0000118 SkFixed dp = SK_Fixed1 / (desc.fCount - 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000119 SkFixed p = dp;
reed@google.com437d6eb2013-05-23 19:03:05 +0000120 SkFixed scale = (desc.fCount - 1) << 8; // (1 << 24) / dp
121 for (int i = 1; i < desc.fCount; i++) {
rileya@google.com589708b2012-07-26 20:04:23 +0000122 recs->fPos = p;
123 recs->fScale = scale;
124 recs += 1;
125 p += dp;
126 }
127 }
128 }
129 this->initCommon();
130}
131
reed@google.com3d3a8602013-05-24 14:58:44 +0000132static uint32_t pack_mode_flags(SkShader::TileMode mode, uint32_t flags) {
133 SkASSERT(0 == (flags >> 28));
134 SkASSERT(0 == ((uint32_t)mode >> 4));
135 return (flags << 4) | mode;
136}
137
138static SkShader::TileMode unpack_mode(uint32_t packed) {
139 return (SkShader::TileMode)(packed & 0xF);
140}
141
142static uint32_t unpack_flags(uint32_t packed) {
143 return packed >> 4;
144}
145
146SkGradientShaderBase::SkGradientShaderBase(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {
rileya@google.com589708b2012-07-26 20:04:23 +0000147 fCacheAlpha = 256;
148
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000149 fMapper = buffer.readFlattenableT<SkUnitMapper>();
rileya@google.com589708b2012-07-26 20:04:23 +0000150
151 fCache16 = fCache16Storage = NULL;
152 fCache32 = NULL;
153 fCache32PixelRef = NULL;
154
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000155 int colorCount = fColorCount = buffer.getArrayCount();
rileya@google.com589708b2012-07-26 20:04:23 +0000156 if (colorCount > kColorStorageCount) {
157 size_t size = sizeof(SkColor) + sizeof(SkPMColor) + sizeof(Rec);
158 fOrigColors = (SkColor*)sk_malloc_throw(size * colorCount);
159 } else {
160 fOrigColors = fStorage;
161 }
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000162 buffer.readColorArray(fOrigColors);
rileya@google.com589708b2012-07-26 20:04:23 +0000163
reed@google.com3d3a8602013-05-24 14:58:44 +0000164 {
165 uint32_t packed = buffer.readUInt();
166 fGradFlags = SkToU8(unpack_flags(packed));
167 fTileMode = unpack_mode(packed);
168 }
rileya@google.com589708b2012-07-26 20:04:23 +0000169 fTileProc = gTileProcs[fTileMode];
170 fRecs = (Rec*)(fOrigColors + colorCount);
171 if (colorCount > 2) {
172 Rec* recs = fRecs;
173 recs[0].fPos = 0;
174 for (int i = 1; i < colorCount; i++) {
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000175 recs[i].fPos = buffer.readInt();
176 recs[i].fScale = buffer.readUInt();
rileya@google.com589708b2012-07-26 20:04:23 +0000177 }
178 }
179 buffer.readMatrix(&fPtsToUnit);
180 this->initCommon();
181}
182
183SkGradientShaderBase::~SkGradientShaderBase() {
184 if (fCache16Storage) {
185 sk_free(fCache16Storage);
186 }
187 SkSafeUnref(fCache32PixelRef);
188 if (fOrigColors != fStorage) {
189 sk_free(fOrigColors);
190 }
191 SkSafeUnref(fMapper);
192}
193
194void SkGradientShaderBase::initCommon() {
195 fFlags = 0;
196 unsigned colorAlpha = 0xFF;
197 for (int i = 0; i < fColorCount; i++) {
198 colorAlpha &= SkColorGetA(fOrigColors[i]);
199 }
200 fColorsAreOpaque = colorAlpha == 0xFF;
201}
202
203void SkGradientShaderBase::flatten(SkFlattenableWriteBuffer& buffer) const {
204 this->INHERITED::flatten(buffer);
205 buffer.writeFlattenable(fMapper);
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000206 buffer.writeColorArray(fOrigColors, fColorCount);
reed@google.com3d3a8602013-05-24 14:58:44 +0000207 buffer.writeUInt(pack_mode_flags(fTileMode, fGradFlags));
rileya@google.com589708b2012-07-26 20:04:23 +0000208 if (fColorCount > 2) {
209 Rec* recs = fRecs;
210 for (int i = 1; i < fColorCount; i++) {
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000211 buffer.writeInt(recs[i].fPos);
212 buffer.writeUInt(recs[i].fScale);
rileya@google.com589708b2012-07-26 20:04:23 +0000213 }
214 }
215 buffer.writeMatrix(fPtsToUnit);
216}
217
218bool SkGradientShaderBase::isOpaque() const {
219 return fColorsAreOpaque;
220}
221
222bool SkGradientShaderBase::setContext(const SkBitmap& device,
223 const SkPaint& paint,
224 const SkMatrix& matrix) {
225 if (!this->INHERITED::setContext(device, paint, matrix)) {
226 return false;
227 }
228
229 const SkMatrix& inverse = this->getTotalInverse();
230
231 if (!fDstToIndex.setConcat(fPtsToUnit, inverse)) {
reed@google.coma641f3f2012-12-13 22:16:30 +0000232 // need to keep our set/end context calls balanced.
233 this->INHERITED::endContext();
rileya@google.com589708b2012-07-26 20:04:23 +0000234 return false;
235 }
236
237 fDstToIndexProc = fDstToIndex.getMapXYProc();
238 fDstToIndexClass = (uint8_t)SkShader::ComputeMatrixClass(fDstToIndex);
239
240 // now convert our colors in to PMColors
241 unsigned paintAlpha = this->getPaintAlpha();
242
243 fFlags = this->INHERITED::getFlags();
244 if (fColorsAreOpaque && paintAlpha == 0xFF) {
245 fFlags |= kOpaqueAlpha_Flag;
246 }
247 // we can do span16 as long as our individual colors are opaque,
248 // regardless of the paint's alpha
249 if (fColorsAreOpaque) {
250 fFlags |= kHasSpan16_Flag;
251 }
252
253 this->setCacheAlpha(paintAlpha);
254 return true;
255}
256
257void SkGradientShaderBase::setCacheAlpha(U8CPU alpha) const {
258 // if the new alpha differs from the previous time we were called, inval our cache
259 // this will trigger the cache to be rebuilt.
260 // we don't care about the first time, since the cache ptrs will already be NULL
261 if (fCacheAlpha != alpha) {
262 fCache16 = NULL; // inval the cache
263 fCache32 = NULL; // inval the cache
264 fCacheAlpha = alpha; // record the new alpha
265 // inform our subclasses
266 if (fCache32PixelRef) {
267 fCache32PixelRef->notifyPixelsChanged();
268 }
269 }
270}
271
272#define Fixed_To_Dot8(x) (((x) + 0x80) >> 8)
273
274/** We take the original colors, not our premultiplied PMColors, since we can
275 build a 16bit table as long as the original colors are opaque, even if the
276 paint specifies a non-opaque alpha.
277*/
278void SkGradientShaderBase::Build16bitCache(uint16_t cache[], SkColor c0, SkColor c1,
279 int count) {
280 SkASSERT(count > 1);
281 SkASSERT(SkColorGetA(c0) == 0xFF);
282 SkASSERT(SkColorGetA(c1) == 0xFF);
283
284 SkFixed r = SkColorGetR(c0);
285 SkFixed g = SkColorGetG(c0);
286 SkFixed b = SkColorGetB(c0);
287
288 SkFixed dr = SkIntToFixed(SkColorGetR(c1) - r) / (count - 1);
289 SkFixed dg = SkIntToFixed(SkColorGetG(c1) - g) / (count - 1);
290 SkFixed db = SkIntToFixed(SkColorGetB(c1) - b) / (count - 1);
291
292 r = SkIntToFixed(r) + 0x8000;
293 g = SkIntToFixed(g) + 0x8000;
294 b = SkIntToFixed(b) + 0x8000;
295
296 do {
297 unsigned rr = r >> 16;
298 unsigned gg = g >> 16;
299 unsigned bb = b >> 16;
300 cache[0] = SkPackRGB16(SkR32ToR16(rr), SkG32ToG16(gg), SkB32ToB16(bb));
301 cache[kCache16Count] = SkDitherPack888ToRGB16(rr, gg, bb);
302 cache += 1;
303 r += dr;
304 g += dg;
305 b += db;
306 } while (--count != 0);
307}
308
reed@google.com3d3a8602013-05-24 14:58:44 +0000309/*
310 * r,g,b used to be SkFixed, but on gcc (4.2.1 mac and 4.6.3 goobuntu) in
311 * release builds, we saw a compiler error where the 0xFF parameter in
312 * SkPackARGB32() was being totally ignored whenever it was called with
313 * a non-zero add (e.g. 0x8000).
314 *
315 * We found two work-arounds:
316 * 1. change r,g,b to unsigned (or just one of them)
317 * 2. change SkPackARGB32 to + its (a << SK_A32_SHIFT) value instead
318 * of using |
319 *
320 * We chose #1 just because it was more localized.
321 * See http://code.google.com/p/skia/issues/detail?id=1113
322 *
323 * The type SkUFixed encapsulate this need for unsigned, but logically Fixed.
324 */
325typedef uint32_t SkUFixed;
326
rileya@google.com589708b2012-07-26 20:04:23 +0000327void SkGradientShaderBase::Build32bitCache(SkPMColor cache[], SkColor c0, SkColor c1,
reed@google.com3d3a8602013-05-24 14:58:44 +0000328 int count, U8CPU paintAlpha, uint32_t gradFlags) {
rileya@google.com589708b2012-07-26 20:04:23 +0000329 SkASSERT(count > 1);
330
331 // need to apply paintAlpha to our two endpoints
reed@google.com3d3a8602013-05-24 14:58:44 +0000332 uint32_t a0 = SkMulDiv255Round(SkColorGetA(c0), paintAlpha);
333 uint32_t a1 = SkMulDiv255Round(SkColorGetA(c1), paintAlpha);
334
335
336 const bool interpInPremul = SkToBool(gradFlags &
337 SkGradientShader::kInterpolateColorsInPremul_Flag);
338
339 uint32_t r0 = SkColorGetR(c0);
340 uint32_t g0 = SkColorGetG(c0);
341 uint32_t b0 = SkColorGetB(c0);
342
343 uint32_t r1 = SkColorGetR(c1);
344 uint32_t g1 = SkColorGetG(c1);
345 uint32_t b1 = SkColorGetB(c1);
346
347 if (interpInPremul) {
348 r0 = SkMulDiv255Round(r0, a0);
349 g0 = SkMulDiv255Round(g0, a0);
350 b0 = SkMulDiv255Round(b0, a0);
351
352 r1 = SkMulDiv255Round(r1, a1);
353 g1 = SkMulDiv255Round(g1, a1);
354 b1 = SkMulDiv255Round(b1, a1);
rileya@google.com589708b2012-07-26 20:04:23 +0000355 }
356
reed@google.com3d3a8602013-05-24 14:58:44 +0000357 SkFixed da = SkIntToFixed(a1 - a0) / (count - 1);
358 SkFixed dr = SkIntToFixed(r1 - r0) / (count - 1);
359 SkFixed dg = SkIntToFixed(g1 - g0) / (count - 1);
360 SkFixed db = SkIntToFixed(b1 - b0) / (count - 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000361
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000362 /* We pre-add 1/8 to avoid having to add this to our [0] value each time
363 in the loop. Without this, the bias for each would be
364 0x2000 0xA000 0xE000 0x6000
365 With this trick, we can add 0 for the first (no-op) and just adjust the
366 others.
367 */
reed@google.com3d3a8602013-05-24 14:58:44 +0000368 SkUFixed a = SkIntToFixed(a0) + 0x2000;
369 SkUFixed r = SkIntToFixed(r0) + 0x2000;
370 SkUFixed g = SkIntToFixed(g0) + 0x2000;
371 SkUFixed b = SkIntToFixed(b0) + 0x2000;
rileya@google.com589708b2012-07-26 20:04:23 +0000372
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000373 /*
374 * Our dither-cell (spatially) is
375 * 0 2
376 * 3 1
377 * Where
378 * [0] -> [-1/8 ... 1/8 ) values near 0
379 * [1] -> [ 1/8 ... 3/8 ) values near 1/4
380 * [2] -> [ 3/8 ... 5/8 ) values near 1/2
381 * [3] -> [ 5/8 ... 7/8 ) values near 3/4
382 */
383
reed@google.com3d3a8602013-05-24 14:58:44 +0000384 if (0xFF == a0 && 0 == da) {
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000385 do {
386 cache[kCache32Count*0] = SkPackARGB32(0xFF, (r + 0 ) >> 16,
387 (g + 0 ) >> 16,
388 (b + 0 ) >> 16);
389 cache[kCache32Count*1] = SkPackARGB32(0xFF, (r + 0x8000) >> 16,
390 (g + 0x8000) >> 16,
391 (b + 0x8000) >> 16);
392 cache[kCache32Count*2] = SkPackARGB32(0xFF, (r + 0xC000) >> 16,
393 (g + 0xC000) >> 16,
394 (b + 0xC000) >> 16);
395 cache[kCache32Count*3] = SkPackARGB32(0xFF, (r + 0x4000) >> 16,
396 (g + 0x4000) >> 16,
397 (b + 0x4000) >> 16);
398 cache += 1;
399 r += dr;
400 g += dg;
401 b += db;
402 } while (--count != 0);
reed@google.com3d3a8602013-05-24 14:58:44 +0000403 } else if (interpInPremul) {
404 do {
405 cache[kCache32Count*0] = SkPackARGB32((a + 0 ) >> 16,
406 (r + 0 ) >> 16,
407 (g + 0 ) >> 16,
408 (b + 0 ) >> 16);
409 cache[kCache32Count*1] = SkPackARGB32((a + 0x8000) >> 16,
410 (r + 0x8000) >> 16,
411 (g + 0x8000) >> 16,
412 (b + 0x8000) >> 16);
413 cache[kCache32Count*2] = SkPackARGB32((a + 0xC000) >> 16,
414 (r + 0xC000) >> 16,
415 (g + 0xC000) >> 16,
416 (b + 0xC000) >> 16);
417 cache[kCache32Count*3] = SkPackARGB32((a + 0x4000) >> 16,
418 (r + 0x4000) >> 16,
419 (g + 0x4000) >> 16,
420 (b + 0x4000) >> 16);
421 cache += 1;
422 a += da;
423 r += dr;
424 g += dg;
425 b += db;
426 } while (--count != 0);
427 } else { // interpolate in unpreml space
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000428 do {
429 cache[kCache32Count*0] = SkPremultiplyARGBInline((a + 0 ) >> 16,
430 (r + 0 ) >> 16,
431 (g + 0 ) >> 16,
432 (b + 0 ) >> 16);
433 cache[kCache32Count*1] = SkPremultiplyARGBInline((a + 0x8000) >> 16,
434 (r + 0x8000) >> 16,
435 (g + 0x8000) >> 16,
436 (b + 0x8000) >> 16);
437 cache[kCache32Count*2] = SkPremultiplyARGBInline((a + 0xC000) >> 16,
438 (r + 0xC000) >> 16,
439 (g + 0xC000) >> 16,
440 (b + 0xC000) >> 16);
441 cache[kCache32Count*3] = SkPremultiplyARGBInline((a + 0x4000) >> 16,
442 (r + 0x4000) >> 16,
443 (g + 0x4000) >> 16,
444 (b + 0x4000) >> 16);
445 cache += 1;
446 a += da;
447 r += dr;
448 g += dg;
449 b += db;
450 } while (--count != 0);
451 }
rileya@google.com589708b2012-07-26 20:04:23 +0000452}
453
454static inline int SkFixedToFFFF(SkFixed x) {
455 SkASSERT((unsigned)x <= SK_Fixed1);
456 return x - (x >> 16);
457}
458
459static inline U16CPU bitsTo16(unsigned x, const unsigned bits) {
460 SkASSERT(x < (1U << bits));
461 if (6 == bits) {
462 return (x << 10) | (x << 4) | (x >> 2);
463 }
464 if (8 == bits) {
465 return (x << 8) | x;
466 }
467 sk_throw();
468 return 0;
469}
470
rileya@google.com589708b2012-07-26 20:04:23 +0000471const uint16_t* SkGradientShaderBase::getCache16() const {
472 if (fCache16 == NULL) {
473 // double the count for dither entries
474 const int entryCount = kCache16Count * 2;
475 const size_t allocSize = sizeof(uint16_t) * entryCount;
476
477 if (fCache16Storage == NULL) { // set the storage and our working ptr
478 fCache16Storage = (uint16_t*)sk_malloc_throw(allocSize);
479 }
480 fCache16 = fCache16Storage;
481 if (fColorCount == 2) {
482 Build16bitCache(fCache16, fOrigColors[0], fOrigColors[1],
reed@google.com3c2102c2013-02-01 12:59:40 +0000483 kCache16Count);
rileya@google.com589708b2012-07-26 20:04:23 +0000484 } else {
485 Rec* rec = fRecs;
486 int prevIndex = 0;
487 for (int i = 1; i < fColorCount; i++) {
488 int nextIndex = SkFixedToFFFF(rec[i].fPos) >> kCache16Shift;
489 SkASSERT(nextIndex < kCache16Count);
490
491 if (nextIndex > prevIndex)
492 Build16bitCache(fCache16 + prevIndex, fOrigColors[i-1], fOrigColors[i], nextIndex - prevIndex + 1);
493 prevIndex = nextIndex;
494 }
rileya@google.com589708b2012-07-26 20:04:23 +0000495 }
496
497 if (fMapper) {
498 fCache16Storage = (uint16_t*)sk_malloc_throw(allocSize);
499 uint16_t* linear = fCache16; // just computed linear data
500 uint16_t* mapped = fCache16Storage; // storage for mapped data
501 SkUnitMapper* map = fMapper;
reed@google.com3c2102c2013-02-01 12:59:40 +0000502 for (int i = 0; i < kCache16Count; i++) {
rileya@google.com589708b2012-07-26 20:04:23 +0000503 int index = map->mapUnit16(bitsTo16(i, kCache16Bits)) >> kCache16Shift;
504 mapped[i] = linear[index];
505 mapped[i + kCache16Count] = linear[index + kCache16Count];
506 }
507 sk_free(fCache16);
508 fCache16 = fCache16Storage;
509 }
rileya@google.com589708b2012-07-26 20:04:23 +0000510 }
511 return fCache16;
512}
513
rileya@google.com589708b2012-07-26 20:04:23 +0000514const SkPMColor* SkGradientShaderBase::getCache32() const {
515 if (fCache32 == NULL) {
516 // double the count for dither entries
reed@google.com60040292013-02-04 18:21:23 +0000517 const int entryCount = kCache32Count * 4;
rileya@google.com589708b2012-07-26 20:04:23 +0000518 const size_t allocSize = sizeof(SkPMColor) * entryCount;
519
520 if (NULL == fCache32PixelRef) {
521 fCache32PixelRef = SkNEW_ARGS(SkMallocPixelRef,
522 (NULL, allocSize, NULL));
523 }
524 fCache32 = (SkPMColor*)fCache32PixelRef->getAddr();
525 if (fColorCount == 2) {
526 Build32bitCache(fCache32, fOrigColors[0], fOrigColors[1],
reed@google.com3d3a8602013-05-24 14:58:44 +0000527 kCache32Count, fCacheAlpha, fGradFlags);
rileya@google.com589708b2012-07-26 20:04:23 +0000528 } else {
529 Rec* rec = fRecs;
530 int prevIndex = 0;
531 for (int i = 1; i < fColorCount; i++) {
532 int nextIndex = SkFixedToFFFF(rec[i].fPos) >> kCache32Shift;
reed@google.com3c2102c2013-02-01 12:59:40 +0000533 SkASSERT(nextIndex < kCache32Count);
rileya@google.com589708b2012-07-26 20:04:23 +0000534
535 if (nextIndex > prevIndex)
536 Build32bitCache(fCache32 + prevIndex, fOrigColors[i-1],
reed@google.com3d3a8602013-05-24 14:58:44 +0000537 fOrigColors[i], nextIndex - prevIndex + 1,
538 fCacheAlpha, fGradFlags);
rileya@google.com589708b2012-07-26 20:04:23 +0000539 prevIndex = nextIndex;
540 }
rileya@google.com589708b2012-07-26 20:04:23 +0000541 }
542
543 if (fMapper) {
544 SkMallocPixelRef* newPR = SkNEW_ARGS(SkMallocPixelRef,
545 (NULL, allocSize, NULL));
546 SkPMColor* linear = fCache32; // just computed linear data
547 SkPMColor* mapped = (SkPMColor*)newPR->getAddr(); // storage for mapped data
548 SkUnitMapper* map = fMapper;
reed@google.com3c2102c2013-02-01 12:59:40 +0000549 for (int i = 0; i < kCache32Count; i++) {
rileya@google.com589708b2012-07-26 20:04:23 +0000550 int index = map->mapUnit16((i << 8) | i) >> 8;
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000551 mapped[i + kCache32Count*0] = linear[index + kCache32Count*0];
552 mapped[i + kCache32Count*1] = linear[index + kCache32Count*1];
reed@google.com60040292013-02-04 18:21:23 +0000553 mapped[i + kCache32Count*2] = linear[index + kCache32Count*2];
554 mapped[i + kCache32Count*3] = linear[index + kCache32Count*3];
rileya@google.com589708b2012-07-26 20:04:23 +0000555 }
556 fCache32PixelRef->unref();
557 fCache32PixelRef = newPR;
558 fCache32 = (SkPMColor*)newPR->getAddr();
559 }
rileya@google.com589708b2012-07-26 20:04:23 +0000560 }
561 return fCache32;
562}
563
564/*
565 * Because our caller might rebuild the same (logically the same) gradient
566 * over and over, we'd like to return exactly the same "bitmap" if possible,
567 * allowing the client to utilize a cache of our bitmap (e.g. with a GPU).
568 * To do that, we maintain a private cache of built-bitmaps, based on our
569 * colors and positions. Note: we don't try to flatten the fMapper, so if one
570 * is present, we skip the cache for now.
571 */
rileya@google.com1c6d64b2012-07-27 15:49:05 +0000572void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000573 // our caller assumes no external alpha, so we ensure that our cache is
574 // built with 0xFF
575 this->setCacheAlpha(0xFF);
576
577 // don't have a way to put the mapper into our cache-key yet
578 if (fMapper) {
579 // force our cahce32pixelref to be built
580 (void)this->getCache32();
reed@google.com3c2102c2013-02-01 12:59:40 +0000581 bitmap->setConfig(SkBitmap::kARGB_8888_Config, kCache32Count, 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000582 bitmap->setPixelRef(fCache32PixelRef);
583 return;
584 }
585
reed@google.com3d3a8602013-05-24 14:58:44 +0000586 // build our key: [numColors + colors[] + {positions[]} + flags ]
587 int count = 1 + fColorCount + 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000588 if (fColorCount > 2) {
589 count += fColorCount - 1; // fRecs[].fPos
590 }
591
592 SkAutoSTMalloc<16, int32_t> storage(count);
593 int32_t* buffer = storage.get();
594
595 *buffer++ = fColorCount;
596 memcpy(buffer, fOrigColors, fColorCount * sizeof(SkColor));
597 buffer += fColorCount;
598 if (fColorCount > 2) {
599 for (int i = 1; i < fColorCount; i++) {
600 *buffer++ = fRecs[i].fPos;
601 }
602 }
reed@google.com3d3a8602013-05-24 14:58:44 +0000603 *buffer++ = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000604 SkASSERT(buffer - storage.get() == count);
605
606 ///////////////////////////////////
607
608 SK_DECLARE_STATIC_MUTEX(gMutex);
609 static SkBitmapCache* gCache;
610 // each cache cost 1K of RAM, since each bitmap will be 1x256 at 32bpp
611 static const int MAX_NUM_CACHED_GRADIENT_BITMAPS = 32;
612 SkAutoMutexAcquire ama(gMutex);
613
614 if (NULL == gCache) {
615 gCache = SkNEW_ARGS(SkBitmapCache, (MAX_NUM_CACHED_GRADIENT_BITMAPS));
616 }
617 size_t size = count * sizeof(int32_t);
618
619 if (!gCache->find(storage.get(), size, bitmap)) {
620 // force our cahce32pixelref to be built
621 (void)this->getCache32();
reed@google.com3c2102c2013-02-01 12:59:40 +0000622 bitmap->setConfig(SkBitmap::kARGB_8888_Config, kCache32Count, 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000623 bitmap->setPixelRef(fCache32PixelRef);
624
625 gCache->add(storage.get(), size, *bitmap);
626 }
627}
628
629void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
630 if (info) {
631 if (info->fColorCount >= fColorCount) {
632 if (info->fColors) {
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000633 memcpy(info->fColors, fOrigColors, fColorCount * sizeof(SkColor));
rileya@google.com589708b2012-07-26 20:04:23 +0000634 }
635 if (info->fColorOffsets) {
636 if (fColorCount == 2) {
637 info->fColorOffsets[0] = 0;
638 info->fColorOffsets[1] = SK_Scalar1;
639 } else if (fColorCount > 2) {
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000640 for (int i = 0; i < fColorCount; ++i) {
rileya@google.com589708b2012-07-26 20:04:23 +0000641 info->fColorOffsets[i] = SkFixedToScalar(fRecs[i].fPos);
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000642 }
rileya@google.com589708b2012-07-26 20:04:23 +0000643 }
644 }
645 }
646 info->fColorCount = fColorCount;
647 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000648 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000649 }
650}
651
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000652#ifdef SK_DEVELOPER
653void SkGradientShaderBase::toString(SkString* str) const {
654
655 str->appendf("%d colors: ", fColorCount);
656
657 for (int i = 0; i < fColorCount; ++i) {
658 str->appendHex(fOrigColors[i]);
659 if (i < fColorCount-1) {
660 str->append(", ");
661 }
662 }
663
664 if (fColorCount > 2) {
665 str->append(" points: (");
666 for (int i = 0; i < fColorCount; ++i) {
667 str->appendScalar(SkFixedToScalar(fRecs[i].fPos));
668 if (i < fColorCount-1) {
669 str->append(", ");
670 }
671 }
672 str->append(")");
673 }
674
675 static const char* gTileModeName[SkShader::kTileModeCount] = {
676 "clamp", "repeat", "mirror"
677 };
678
679 str->append(" ");
680 str->append(gTileModeName[fTileMode]);
681
682 // TODO: add "fMapper->toString(str);" when SkUnitMapper::toString is added
683
684 this->INHERITED::toString(str);
685}
686#endif
687
rileya@google.com589708b2012-07-26 20:04:23 +0000688///////////////////////////////////////////////////////////////////////////////
689///////////////////////////////////////////////////////////////////////////////
690
691#include "SkEmptyShader.h"
692
693// assumes colors is SkColor* and pos is SkScalar*
694#define EXPAND_1_COLOR(count) \
695 SkColor tmp[2]; \
696 do { \
697 if (1 == count) { \
698 tmp[0] = tmp[1] = colors[0]; \
699 colors = tmp; \
700 pos = NULL; \
701 count = 2; \
702 } \
703 } while (0)
704
reed@google.com437d6eb2013-05-23 19:03:05 +0000705static void desc_init(SkGradientShaderBase::Descriptor* desc,
706 const SkColor colors[],
707 const SkScalar pos[], int colorCount,
708 SkShader::TileMode mode,
reed@google.com3d3a8602013-05-24 14:58:44 +0000709 SkUnitMapper* mapper, uint32_t flags) {
reed@google.com437d6eb2013-05-23 19:03:05 +0000710 desc->fColors = colors;
711 desc->fPos = pos;
712 desc->fCount = colorCount;
713 desc->fTileMode = mode;
714 desc->fMapper = mapper;
reed@google.com3d3a8602013-05-24 14:58:44 +0000715 desc->fFlags = flags;
reed@google.com437d6eb2013-05-23 19:03:05 +0000716}
717
rileya@google.com589708b2012-07-26 20:04:23 +0000718SkShader* SkGradientShader::CreateLinear(const SkPoint pts[2],
719 const SkColor colors[],
720 const SkScalar pos[], int colorCount,
721 SkShader::TileMode mode,
reed@google.com3d3a8602013-05-24 14:58:44 +0000722 SkUnitMapper* mapper,
723 uint32_t flags) {
rileya@google.com589708b2012-07-26 20:04:23 +0000724 if (NULL == pts || NULL == colors || colorCount < 1) {
725 return NULL;
726 }
727 EXPAND_1_COLOR(colorCount);
728
reed@google.com437d6eb2013-05-23 19:03:05 +0000729 SkGradientShaderBase::Descriptor desc;
reed@google.com3d3a8602013-05-24 14:58:44 +0000730 desc_init(&desc, colors, pos, colorCount, mode, mapper, flags);
reed@google.com437d6eb2013-05-23 19:03:05 +0000731 return SkNEW_ARGS(SkLinearGradient, (pts, desc));
rileya@google.com589708b2012-07-26 20:04:23 +0000732}
733
734SkShader* SkGradientShader::CreateRadial(const SkPoint& center, SkScalar radius,
735 const SkColor colors[],
736 const SkScalar pos[], int colorCount,
737 SkShader::TileMode mode,
reed@google.com3d3a8602013-05-24 14:58:44 +0000738 SkUnitMapper* mapper,
739 uint32_t flags) {
rileya@google.com589708b2012-07-26 20:04:23 +0000740 if (radius <= 0 || NULL == colors || colorCount < 1) {
741 return NULL;
742 }
743 EXPAND_1_COLOR(colorCount);
744
reed@google.com437d6eb2013-05-23 19:03:05 +0000745 SkGradientShaderBase::Descriptor desc;
reed@google.com3d3a8602013-05-24 14:58:44 +0000746 desc_init(&desc, colors, pos, colorCount, mode, mapper, flags);
reed@google.com437d6eb2013-05-23 19:03:05 +0000747 return SkNEW_ARGS(SkRadialGradient, (center, radius, desc));
rileya@google.com589708b2012-07-26 20:04:23 +0000748}
749
750SkShader* SkGradientShader::CreateTwoPointRadial(const SkPoint& start,
751 SkScalar startRadius,
752 const SkPoint& end,
753 SkScalar endRadius,
754 const SkColor colors[],
755 const SkScalar pos[],
756 int colorCount,
757 SkShader::TileMode mode,
reed@google.com3d3a8602013-05-24 14:58:44 +0000758 SkUnitMapper* mapper,
759 uint32_t flags) {
rileya@google.com589708b2012-07-26 20:04:23 +0000760 if (startRadius < 0 || endRadius < 0 || NULL == colors || colorCount < 1) {
761 return NULL;
762 }
763 EXPAND_1_COLOR(colorCount);
rmistry@google.comfbfcd562012-08-23 18:09:54 +0000764
reed@google.com437d6eb2013-05-23 19:03:05 +0000765 SkGradientShaderBase::Descriptor desc;
reed@google.com3d3a8602013-05-24 14:58:44 +0000766 desc_init(&desc, colors, pos, colorCount, mode, mapper, flags);
rileya@google.com589708b2012-07-26 20:04:23 +0000767 return SkNEW_ARGS(SkTwoPointRadialGradient,
reed@google.com437d6eb2013-05-23 19:03:05 +0000768 (start, startRadius, end, endRadius, desc));
rileya@google.com589708b2012-07-26 20:04:23 +0000769}
770
771SkShader* SkGradientShader::CreateTwoPointConical(const SkPoint& start,
reed@google.com3d3a8602013-05-24 14:58:44 +0000772 SkScalar startRadius,
773 const SkPoint& end,
774 SkScalar endRadius,
775 const SkColor colors[],
776 const SkScalar pos[],
777 int colorCount,
778 SkShader::TileMode mode,
779 SkUnitMapper* mapper,
780 uint32_t flags) {
rileya@google.com589708b2012-07-26 20:04:23 +0000781 if (startRadius < 0 || endRadius < 0 || NULL == colors || colorCount < 1) {
782 return NULL;
783 }
784 if (start == end && startRadius == endRadius) {
785 return SkNEW(SkEmptyShader);
786 }
rileya@google.com1ee7c6a2012-07-31 16:00:13 +0000787 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000788
reed@google.com437d6eb2013-05-23 19:03:05 +0000789 SkGradientShaderBase::Descriptor desc;
reed@google.com3d3a8602013-05-24 14:58:44 +0000790 desc_init(&desc, colors, pos, colorCount, mode, mapper, flags);
rileya@google.com589708b2012-07-26 20:04:23 +0000791 return SkNEW_ARGS(SkTwoPointConicalGradient,
reed@google.com437d6eb2013-05-23 19:03:05 +0000792 (start, startRadius, end, endRadius, desc));
rileya@google.com589708b2012-07-26 20:04:23 +0000793}
794
795SkShader* SkGradientShader::CreateSweep(SkScalar cx, SkScalar cy,
796 const SkColor colors[],
797 const SkScalar pos[],
reed@google.com3d3a8602013-05-24 14:58:44 +0000798 int colorCount, SkUnitMapper* mapper,
799 uint32_t flags) {
reed@google.com437d6eb2013-05-23 19:03:05 +0000800 if (NULL == colors || colorCount < 1) {
rileya@google.com589708b2012-07-26 20:04:23 +0000801 return NULL;
802 }
reed@google.com437d6eb2013-05-23 19:03:05 +0000803 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000804
reed@google.com437d6eb2013-05-23 19:03:05 +0000805 SkGradientShaderBase::Descriptor desc;
reed@google.com3d3a8602013-05-24 14:58:44 +0000806 desc_init(&desc, colors, pos, colorCount, SkShader::kClamp_TileMode, mapper, flags);
reed@google.com437d6eb2013-05-23 19:03:05 +0000807 return SkNEW_ARGS(SkSweepGradient, (cx, cy, desc));
rileya@google.com589708b2012-07-26 20:04:23 +0000808}
809
810SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
811 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
812 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
813 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
814 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointRadialGradient)
815 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
816SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
rileya@google.comd7cc6512012-07-27 14:00:39 +0000817
818///////////////////////////////////////////////////////////////////////////////
819
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000820#if SK_SUPPORT_GPU
821
rileya@google.comb3e50f22012-08-20 17:43:08 +0000822#include "effects/GrTextureStripAtlas.h"
bsalomon@google.comc7818882013-03-20 19:19:53 +0000823#include "GrTBackendEffectFactory.h"
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000824#include "SkGr.h"
825
bsalomon@google.com0707c292012-10-25 21:45:42 +0000826GrGLGradientEffect::GrGLGradientEffect(const GrBackendEffectFactory& factory)
rileya@google.comb3e50f22012-08-20 17:43:08 +0000827 : INHERITED(factory)
bsalomon@google.com77af6802013-10-02 13:04:56 +0000828 , fCachedYCoord(SK_ScalarMax) {
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000829}
rileya@google.comd7cc6512012-07-27 14:00:39 +0000830
bsalomon@google.com0707c292012-10-25 21:45:42 +0000831GrGLGradientEffect::~GrGLGradientEffect() { }
rileya@google.comd7cc6512012-07-27 14:00:39 +0000832
bsalomon@google.com82d12232013-09-09 15:36:26 +0000833void GrGLGradientEffect::emitUniforms(GrGLShaderBuilder* builder, EffectKey key) {
834
835 if (GrGradientEffect::kTwo_ColorType == ColorTypeFromKey(key)) { // 2 Color case
836 fColorStartUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
837 kVec4f_GrSLType, "GradientStartColor");
838 fColorEndUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
839 kVec4f_GrSLType, "GradientEndColor");
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +0000840
bsalomon@google.com82d12232013-09-09 15:36:26 +0000841 } else if (GrGradientEffect::kThree_ColorType == ColorTypeFromKey(key)){ // 3 Color Case
842 fColorStartUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
843 kVec4f_GrSLType, "GradientStartColor");
844 fColorMidUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
845 kVec4f_GrSLType, "GradientMidColor");
846 fColorEndUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
847 kVec4f_GrSLType, "GradientEndColor");
848
849 } else { // if not a fast case
850 fFSYUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
851 kFloat_GrSLType, "GradientYCoordFS");
852 }
853}
854
855static inline void set_color_uni(const GrGLUniformManager& uman,
856 const GrGLUniformManager::UniformHandle uni,
857 const SkColor* color) {
858 uman.set4f(uni,
859 SkColorGetR(*color) / 255.f,
860 SkColorGetG(*color) / 255.f,
861 SkColorGetB(*color) / 255.f,
862 SkColorGetA(*color) / 255.f);
863}
864
865static inline void set_mul_color_uni(const GrGLUniformManager& uman,
866 const GrGLUniformManager::UniformHandle uni,
867 const SkColor* color){
868 float a = SkColorGetA(*color) / 255.f;
869 float aDiv255 = a / 255.f;
870 uman.set4f(uni,
871 SkColorGetR(*color) * aDiv255,
872 SkColorGetG(*color) * aDiv255,
873 SkColorGetB(*color) * aDiv255,
874 a);
rileya@google.comb3e50f22012-08-20 17:43:08 +0000875}
876
bsalomon@google.comc7818882013-03-20 19:19:53 +0000877void GrGLGradientEffect::setData(const GrGLUniformManager& uman,
878 const GrDrawEffect& drawEffect) {
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000879
bsalomon@google.com82d12232013-09-09 15:36:26 +0000880 const GrGradientEffect& e = drawEffect.castEffect<GrGradientEffect>();
881
882
883 if (GrGradientEffect::kTwo_ColorType == e.getColorType()){
884
bsalomon@google.com82d12232013-09-09 15:36:26 +0000885 if (GrGradientEffect::kBeforeInterp_PremulType == e.getPremulType()) {
886 set_mul_color_uni(uman, fColorStartUni, e.getColors(0));
887 set_mul_color_uni(uman, fColorEndUni, e.getColors(1));
888 } else {
889 set_color_uni(uman, fColorStartUni, e.getColors(0));
890 set_color_uni(uman, fColorEndUni, e.getColors(1));
891 }
892
893 } else if (GrGradientEffect::kThree_ColorType == e.getColorType()){
894
bsalomon@google.com82d12232013-09-09 15:36:26 +0000895 if (GrGradientEffect::kBeforeInterp_PremulType == e.getPremulType()) {
896 set_mul_color_uni(uman, fColorStartUni, e.getColors(0));
897 set_mul_color_uni(uman, fColorMidUni, e.getColors(1));
898 set_mul_color_uni(uman, fColorEndUni, e.getColors(2));
899 } else {
900 set_color_uni(uman, fColorStartUni, e.getColors(0));
901 set_color_uni(uman, fColorMidUni, e.getColors(1));
902 set_color_uni(uman, fColorEndUni, e.getColors(2));
903 }
904 } else {
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +0000905
bsalomon@google.com82d12232013-09-09 15:36:26 +0000906 SkScalar yCoord = e.getYCoord();
907 if (yCoord != fCachedYCoord) {
908 uman.set1f(fFSYUni, yCoord);
909 fCachedYCoord = yCoord;
910 }
rileya@google.comb3e50f22012-08-20 17:43:08 +0000911 }
912}
913
bsalomon@google.com82d12232013-09-09 15:36:26 +0000914
915GrGLEffect::EffectKey GrGLGradientEffect::GenBaseGradientKey(const GrDrawEffect& drawEffect) {
bsalomon@google.comc7818882013-03-20 19:19:53 +0000916 const GrGradientEffect& e = drawEffect.castEffect<GrGradientEffect>();
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +0000917
bsalomon@google.com77af6802013-10-02 13:04:56 +0000918 EffectKey key = 0;
bsalomon@google.com82d12232013-09-09 15:36:26 +0000919
920 if (GrGradientEffect::kTwo_ColorType == e.getColorType()) {
921 key |= kTwoColorKey;
922 } else if (GrGradientEffect::kThree_ColorType == e.getColorType()){
923 key |= kThreeColorKey;
924 }
925
926 if (GrGradientEffect::kBeforeInterp_PremulType == e.getPremulType()) {
927 key |= kPremulBeforeInterpKey;
928 }
929
930 return key;
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000931}
932
bsalomon@google.com82d12232013-09-09 15:36:26 +0000933void GrGLGradientEffect::emitColor(GrGLShaderBuilder* builder,
934 const char* gradientTValue,
935 EffectKey key,
936 const char* outputColor,
937 const char* inputColor,
commit-bot@chromium.org3390b9a2013-10-03 15:17:58 +0000938 const TextureSamplerArray& samplers) {
bsalomon@google.com82d12232013-09-09 15:36:26 +0000939 if (GrGradientEffect::kTwo_ColorType == ColorTypeFromKey(key)){
940 builder->fsCodeAppendf("\tvec4 colorTemp = mix(%s, %s, clamp(%s, 0.0, 1.0));\n",
941 builder->getUniformVariable(fColorStartUni).c_str(),
942 builder->getUniformVariable(fColorEndUni).c_str(),
943 gradientTValue);
944 // Note that we could skip this step if both colors are known to be opaque. Two
945 // considerations:
946 // The gradient SkShader reporting opaque is more restrictive than necessary in the two pt
947 // case. Make sure the key reflects this optimization (and note that it can use the same
948 // shader as thekBeforeIterp case). This same optimization applies to the 3 color case below.
949 if (GrGradientEffect::kAfterInterp_PremulType == PremulTypeFromKey(key)) {
950 builder->fsCodeAppend("\tcolorTemp.rgb *= colorTemp.a;\n");
951 }
bsalomon@google.com34bcb9f2012-08-28 18:20:18 +0000952
bsalomon@google.com82d12232013-09-09 15:36:26 +0000953 SkString output;
954 builder->fsCodeAppendf("\t%s = ", outputColor);
955 GrGLSLModulatef<4>(&output, inputColor, "colorTemp");
956 builder->fsCodeAppend(output.c_str());
957 builder->fsCodeAppend(";\n");
958 } else if (GrGradientEffect::kThree_ColorType == ColorTypeFromKey(key)){
959 builder->fsCodeAppendf("\tfloat oneMinus2t = 1.0 - (2.0 * (%s));\n",
960 gradientTValue);
commit-bot@chromium.org0694ea72013-09-18 13:00:28 +0000961 builder->fsCodeAppendf("\tvec4 colorTemp = clamp(oneMinus2t, 0.0, 1.0) * %s;\n",
962 builder->getUniformVariable(fColorStartUni).c_str());
963 if (kTegra3_GrGLRenderer == builder->ctxInfo().renderer()) {
964 // The Tegra3 compiler will sometimes never return if we have
965 // min(abs(oneMinus2t), 1.0), or do the abs first in a separate expression.
966 builder->fsCodeAppend("\tfloat minAbs = abs(oneMinus2t);\n");
967 builder->fsCodeAppend("\tminAbs = minAbs > 1.0 ? 1.0 : minAbs;\n");
968 builder->fsCodeAppendf("\tcolorTemp += (1.0 - minAbs) * %s;\n",
969 builder->getUniformVariable(fColorMidUni).c_str());
970 } else {
971 builder->fsCodeAppendf("\tcolorTemp += (1.0 - min(abs(oneMinus2t), 1.0)) * %s;\n",
972 builder->getUniformVariable(fColorMidUni).c_str());
973 }
974 builder->fsCodeAppendf("\tcolorTemp += clamp(-oneMinus2t, 0.0, 1.0) * %s;\n",
bsalomon@google.com82d12232013-09-09 15:36:26 +0000975 builder->getUniformVariable(fColorEndUni).c_str());
976 if (GrGradientEffect::kAfterInterp_PremulType == PremulTypeFromKey(key)) {
977 builder->fsCodeAppend("\tcolorTemp.rgb *= colorTemp.a;\n");
978 }
979
980 SkString output;
981 builder->fsCodeAppendf("\t%s = ", outputColor);
982 GrGLSLModulatef<4>(&output, inputColor, "colorTemp");
983 builder->fsCodeAppend(output.c_str());
984 builder->fsCodeAppend(";\n");
985 } else {
986 builder->fsCodeAppendf("\tvec2 coord = vec2(%s, %s);\n",
987 gradientTValue,
988 builder->getUniformVariable(fFSYUni).c_str());
989 builder->fsCodeAppendf("\t%s = ", outputColor);
990 builder->fsAppendTextureLookupAndModulate(inputColor,
991 samplers[0],
992 "coord");
993 builder->fsCodeAppend(";\n");
994 }
rileya@google.comd7cc6512012-07-27 14:00:39 +0000995}
996
997/////////////////////////////////////////////////////////////////////
998
rmistry@google.comfbfcd562012-08-23 18:09:54 +0000999GrGradientEffect::GrGradientEffect(GrContext* ctx,
rileya@google.com1c6d64b2012-07-27 15:49:05 +00001000 const SkGradientShaderBase& shader,
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +00001001 const SkMatrix& matrix,
bsalomon@google.com50db75c2013-01-11 13:54:30 +00001002 SkShader::TileMode tileMode) {
bsalomon@google.com82d12232013-09-09 15:36:26 +00001003
bsalomon@google.com371e1052013-01-11 21:08:55 +00001004 fIsOpaque = shader.isOpaque();
1005
bsalomon@google.com82d12232013-09-09 15:36:26 +00001006 SkShader::GradientInfo info;
1007 SkScalar pos[3] = {0};
rmistry@google.comfbfcd562012-08-23 18:09:54 +00001008
bsalomon@google.com82d12232013-09-09 15:36:26 +00001009 info.fColorCount = 3;
1010 info.fColors = &fColors[0];
1011 info.fColorOffsets = &pos[0];
1012 shader.asAGradient(&info);
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +00001013
bsalomon@google.com82d12232013-09-09 15:36:26 +00001014 // The two and three color specializations do not currently support tiling.
1015 bool foundSpecialCase = false;
1016 if (SkShader::kClamp_TileMode == info.fTileMode) {
1017 if (2 == info.fColorCount) {
1018 fRow = -1; // flag for no atlas
1019 fColorType = kTwo_ColorType;
1020 foundSpecialCase = true;
1021 } else if (3 == info.fColorCount &&
1022 (SkScalarAbs(pos[1] - SK_ScalarHalf) < SK_Scalar1 / 1000)) { // 3 color symmetric
1023 fRow = -1; // flag for no atlas
1024 fColorType = kThree_ColorType;
1025 foundSpecialCase = true;
1026 }
rileya@google.comb3e50f22012-08-20 17:43:08 +00001027 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001028 if (foundSpecialCase) {
1029 if (SkGradientShader::kInterpolateColorsInPremul_Flag & info.fGradientFlags) {
1030 fPremulType = kBeforeInterp_PremulType;
1031 } else {
1032 fPremulType = kAfterInterp_PremulType;
1033 }
bsalomon@google.com77af6802013-10-02 13:04:56 +00001034 fCoordTransform.reset(kCoordSet, matrix);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001035 } else {
1036 // doesn't matter how this is set, just be consistent because it is part of the effect key.
1037 fPremulType = kBeforeInterp_PremulType;
1038 SkBitmap bitmap;
1039 shader.getGradientTableBitmap(&bitmap);
1040 fColorType = kTexture_ColorType;
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001041
bsalomon@google.com82d12232013-09-09 15:36:26 +00001042 GrTextureStripAtlas::Desc desc;
1043 desc.fWidth = bitmap.width();
1044 desc.fHeight = 32;
1045 desc.fRowHeight = bitmap.height();
1046 desc.fContext = ctx;
1047 desc.fConfig = SkBitmapConfig2GrPixelConfig(bitmap.config());
1048 fAtlas = GrTextureStripAtlas::GetAtlas(desc);
1049 SkASSERT(NULL != fAtlas);
1050
1051 // We always filter the gradient table. Each table is one row of a texture, always y-clamp.
1052 GrTextureParams params;
1053 params.setFilterMode(GrTextureParams::kBilerp_FilterMode);
1054 params.setTileModeX(tileMode);
1055
1056 fRow = fAtlas->lockRow(bitmap);
1057 if (-1 != fRow) {
1058 fYCoord = fAtlas->getYOffset(fRow) + SK_ScalarHalf *
1059 fAtlas->getVerticalScaleFactor();
bsalomon@google.com77af6802013-10-02 13:04:56 +00001060 fCoordTransform.reset(kCoordSet, matrix, fAtlas->getTexture());
bsalomon@google.com82d12232013-09-09 15:36:26 +00001061 fTextureAccess.reset(fAtlas->getTexture(), params);
1062 } else {
1063 GrTexture* texture = GrLockAndRefCachedBitmapTexture(ctx, bitmap, &params);
bsalomon@google.com77af6802013-10-02 13:04:56 +00001064 fCoordTransform.reset(kCoordSet, matrix, texture);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001065 fTextureAccess.reset(texture, params);
1066 fYCoord = SK_ScalarHalf;
1067
1068 // Unlock immediately, this is not great, but we don't have a way of
1069 // knowing when else to unlock it currently, so it may get purged from
1070 // the cache, but it'll still be ref'd until it's no longer being used.
1071 GrUnlockAndUnrefCachedBitmapTexture(texture);
1072 }
1073 this->addTextureAccess(&fTextureAccess);
1074 }
bsalomon@google.com77af6802013-10-02 13:04:56 +00001075 this->addCoordTransform(&fCoordTransform);
rileya@google.comd7cc6512012-07-27 14:00:39 +00001076}
1077
1078GrGradientEffect::~GrGradientEffect() {
rileya@google.comb3e50f22012-08-20 17:43:08 +00001079 if (this->useAtlas()) {
1080 fAtlas->unlockRow(fRow);
rileya@google.comb3e50f22012-08-20 17:43:08 +00001081 }
rileya@google.comd7cc6512012-07-27 14:00:39 +00001082}
1083
bsalomon@google.com8a252f72013-01-22 20:35:13 +00001084bool GrGradientEffect::onIsEqual(const GrEffect& effect) const {
bsalomon@google.com6340a412013-01-22 19:55:59 +00001085 const GrGradientEffect& s = CastEffect<GrGradientEffect>(effect);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001086
1087 if (this->fColorType == s.getColorType()){
1088
1089 if (kTwo_ColorType == fColorType) {
1090 if (*this->getColors(0) != *s.getColors(0) ||
1091 *this->getColors(1) != *s.getColors(1)) {
1092 return false;
1093 }
1094 } else if (kThree_ColorType == fColorType) {
1095 if (*this->getColors(0) != *s.getColors(0) ||
1096 *this->getColors(1) != *s.getColors(1) ||
1097 *this->getColors(2) != *s.getColors(2)) {
1098 return false;
1099 }
robertphillips@google.comc0de5d62013-10-08 19:15:58 +00001100 } else {
1101 if (fYCoord != s.getYCoord()) {
1102 return false;
1103 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001104 }
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001105
bsalomon@google.com82d12232013-09-09 15:36:26 +00001106 return fTextureAccess.getTexture() == s.fTextureAccess.getTexture() &&
1107 fTextureAccess.getParams().getTileModeX() ==
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001108 s.fTextureAccess.getParams().getTileModeX() &&
bsalomon@google.com82d12232013-09-09 15:36:26 +00001109 this->useAtlas() == s.useAtlas() &&
bsalomon@google.com77af6802013-10-02 13:04:56 +00001110 fCoordTransform.getMatrix().cheapEqualTo(s.fCoordTransform.getMatrix());
bsalomon@google.com82d12232013-09-09 15:36:26 +00001111 }
1112
1113 return false;
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001114}
1115
1116void GrGradientEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const {
bsalomon@google.comb8eb2e82013-03-28 13:46:42 +00001117 if (fIsOpaque && (kA_GrColorComponentFlag & *validFlags) && 0xff == GrColorUnpackA(*color)) {
1118 *validFlags = kA_GrColorComponentFlag;
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001119 } else {
1120 *validFlags = 0;
1121 }
1122}
1123
commit-bot@chromium.orge0e7cfe2013-09-09 20:09:12 +00001124int GrGradientEffect::RandomGradientParams(SkRandom* random,
bsalomon@google.comd4726202012-08-03 14:34:46 +00001125 SkColor colors[],
1126 SkScalar** stops,
1127 SkShader::TileMode* tm) {
1128 int outColors = random->nextRangeU(1, kMaxRandomGradientColors);
1129
1130 // if one color, omit stops, otherwise randomly decide whether or not to
1131 if (outColors == 1 || (outColors >= 2 && random->nextBool())) {
1132 *stops = NULL;
1133 }
1134
bsalomon@google.com81712882012-11-01 17:12:34 +00001135 SkScalar stop = 0.f;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001136 for (int i = 0; i < outColors; ++i) {
1137 colors[i] = random->nextU();
1138 if (NULL != *stops) {
1139 (*stops)[i] = stop;
1140 stop = i < outColors - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
1141 }
1142 }
1143 *tm = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
1144
1145 return outColors;
1146}
1147
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001148#endif