blob: d1ab539c076a716279cb888857e75ee4850686ad [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);
rileya@google.com589708b2012-07-26 20:04:23 +000022
reed@google.com437d6eb2013-05-23 19:03:05 +000023 SkASSERT((unsigned)desc.fTileMode < SkShader::kTileModeCount);
rileya@google.com589708b2012-07-26 20:04:23 +000024 SkASSERT(SkShader::kTileModeCount == SK_ARRAY_COUNT(gTileProcs));
reed@google.com437d6eb2013-05-23 19:03:05 +000025 fTileMode = desc.fTileMode;
26 fTileProc = gTileProcs[desc.fTileMode];
rileya@google.com589708b2012-07-26 20:04:23 +000027
28 fCache16 = fCache16Storage = NULL;
29 fCache32 = NULL;
30 fCache32PixelRef = NULL;
31
32 /* Note: we let the caller skip the first and/or last position.
33 i.e. pos[0] = 0.3, pos[1] = 0.7
34 In these cases, we insert dummy entries to ensure that the final data
35 will be bracketed by [0, 1].
36 i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
37
38 Thus colorCount (the caller's value, and fColorCount (our value) may
39 differ by up to 2. In the above example:
40 colorCount = 2
41 fColorCount = 4
42 */
reed@google.com437d6eb2013-05-23 19:03:05 +000043 fColorCount = desc.fCount;
rileya@google.com589708b2012-07-26 20:04:23 +000044 // check if we need to add in dummy start and/or end position/colors
45 bool dummyFirst = false;
46 bool dummyLast = false;
reed@google.com437d6eb2013-05-23 19:03:05 +000047 if (desc.fPos) {
48 dummyFirst = desc.fPos[0] != 0;
49 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
rileya@google.com589708b2012-07-26 20:04:23 +000050 fColorCount += dummyFirst + dummyLast;
51 }
52
53 if (fColorCount > kColorStorageCount) {
54 size_t size = sizeof(SkColor) + sizeof(Rec);
55 fOrigColors = reinterpret_cast<SkColor*>(
56 sk_malloc_throw(size * fColorCount));
57 }
58 else {
59 fOrigColors = fStorage;
60 }
61
62 // Now copy over the colors, adding the dummies as needed
63 {
64 SkColor* origColors = fOrigColors;
65 if (dummyFirst) {
reed@google.com437d6eb2013-05-23 19:03:05 +000066 *origColors++ = desc.fColors[0];
rileya@google.com589708b2012-07-26 20:04:23 +000067 }
reed@google.com437d6eb2013-05-23 19:03:05 +000068 memcpy(origColors, desc.fColors, desc.fCount * sizeof(SkColor));
rileya@google.com589708b2012-07-26 20:04:23 +000069 if (dummyLast) {
reed@google.com437d6eb2013-05-23 19:03:05 +000070 origColors += desc.fCount;
71 *origColors = desc.fColors[desc.fCount - 1];
rileya@google.com589708b2012-07-26 20:04:23 +000072 }
73 }
74
75 fRecs = (Rec*)(fOrigColors + fColorCount);
76 if (fColorCount > 2) {
77 Rec* recs = fRecs;
78 recs->fPos = 0;
79 // recs->fScale = 0; // unused;
80 recs += 1;
reed@google.com437d6eb2013-05-23 19:03:05 +000081 if (desc.fPos) {
rileya@google.com589708b2012-07-26 20:04:23 +000082 /* We need to convert the user's array of relative positions into
83 fixed-point positions and scale factors. We need these results
84 to be strictly monotonic (no two values equal or out of order).
85 Hence this complex loop that just jams a zero for the scale
86 value if it sees a segment out of order, and it assures that
87 we start at 0 and end at 1.0
88 */
89 SkFixed prev = 0;
90 int startIndex = dummyFirst ? 0 : 1;
reed@google.com437d6eb2013-05-23 19:03:05 +000091 int count = desc.fCount + dummyLast;
rileya@google.com589708b2012-07-26 20:04:23 +000092 for (int i = startIndex; i < count; i++) {
93 // force the last value to be 1.0
94 SkFixed curr;
reed@google.com437d6eb2013-05-23 19:03:05 +000095 if (i == desc.fCount) { // we're really at the dummyLast
rileya@google.com589708b2012-07-26 20:04:23 +000096 curr = SK_Fixed1;
97 } else {
reed@google.com437d6eb2013-05-23 19:03:05 +000098 curr = SkScalarToFixed(desc.fPos[i]);
rileya@google.com589708b2012-07-26 20:04:23 +000099 }
100 // pin curr withing range
101 if (curr < 0) {
102 curr = 0;
103 } else if (curr > SK_Fixed1) {
104 curr = SK_Fixed1;
105 }
106 recs->fPos = curr;
107 if (curr > prev) {
108 recs->fScale = (1 << 24) / (curr - prev);
109 } else {
110 recs->fScale = 0; // ignore this segment
111 }
112 // get ready for the next value
113 prev = curr;
114 recs += 1;
115 }
116 } else { // assume even distribution
reed@google.com437d6eb2013-05-23 19:03:05 +0000117 SkFixed dp = SK_Fixed1 / (desc.fCount - 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000118 SkFixed p = dp;
reed@google.com437d6eb2013-05-23 19:03:05 +0000119 SkFixed scale = (desc.fCount - 1) << 8; // (1 << 24) / dp
120 for (int i = 1; i < desc.fCount; i++) {
rileya@google.com589708b2012-07-26 20:04:23 +0000121 recs->fPos = p;
122 recs->fScale = scale;
123 recs += 1;
124 p += dp;
125 }
126 }
127 }
128 this->initCommon();
129}
130
131SkGradientShaderBase::SkGradientShaderBase(SkFlattenableReadBuffer& buffer) :
132 INHERITED(buffer) {
133 fCacheAlpha = 256;
134
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000135 fMapper = buffer.readFlattenableT<SkUnitMapper>();
rileya@google.com589708b2012-07-26 20:04:23 +0000136
137 fCache16 = fCache16Storage = NULL;
138 fCache32 = NULL;
139 fCache32PixelRef = NULL;
140
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000141 int colorCount = fColorCount = buffer.getArrayCount();
rileya@google.com589708b2012-07-26 20:04:23 +0000142 if (colorCount > kColorStorageCount) {
143 size_t size = sizeof(SkColor) + sizeof(SkPMColor) + sizeof(Rec);
144 fOrigColors = (SkColor*)sk_malloc_throw(size * colorCount);
145 } else {
146 fOrigColors = fStorage;
147 }
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000148 buffer.readColorArray(fOrigColors);
rileya@google.com589708b2012-07-26 20:04:23 +0000149
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000150 fTileMode = (TileMode)buffer.readUInt();
rileya@google.com589708b2012-07-26 20:04:23 +0000151 fTileProc = gTileProcs[fTileMode];
152 fRecs = (Rec*)(fOrigColors + colorCount);
153 if (colorCount > 2) {
154 Rec* recs = fRecs;
155 recs[0].fPos = 0;
156 for (int i = 1; i < colorCount; i++) {
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000157 recs[i].fPos = buffer.readInt();
158 recs[i].fScale = buffer.readUInt();
rileya@google.com589708b2012-07-26 20:04:23 +0000159 }
160 }
161 buffer.readMatrix(&fPtsToUnit);
162 this->initCommon();
163}
164
165SkGradientShaderBase::~SkGradientShaderBase() {
166 if (fCache16Storage) {
167 sk_free(fCache16Storage);
168 }
169 SkSafeUnref(fCache32PixelRef);
170 if (fOrigColors != fStorage) {
171 sk_free(fOrigColors);
172 }
173 SkSafeUnref(fMapper);
174}
175
176void SkGradientShaderBase::initCommon() {
177 fFlags = 0;
178 unsigned colorAlpha = 0xFF;
179 for (int i = 0; i < fColorCount; i++) {
180 colorAlpha &= SkColorGetA(fOrigColors[i]);
181 }
182 fColorsAreOpaque = colorAlpha == 0xFF;
183}
184
185void SkGradientShaderBase::flatten(SkFlattenableWriteBuffer& buffer) const {
186 this->INHERITED::flatten(buffer);
187 buffer.writeFlattenable(fMapper);
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000188 buffer.writeColorArray(fOrigColors, fColorCount);
189 buffer.writeUInt(fTileMode);
rileya@google.com589708b2012-07-26 20:04:23 +0000190 if (fColorCount > 2) {
191 Rec* recs = fRecs;
192 for (int i = 1; i < fColorCount; i++) {
djsollen@google.comc73dd5c2012-08-07 15:54:32 +0000193 buffer.writeInt(recs[i].fPos);
194 buffer.writeUInt(recs[i].fScale);
rileya@google.com589708b2012-07-26 20:04:23 +0000195 }
196 }
197 buffer.writeMatrix(fPtsToUnit);
198}
199
200bool SkGradientShaderBase::isOpaque() const {
201 return fColorsAreOpaque;
202}
203
204bool SkGradientShaderBase::setContext(const SkBitmap& device,
205 const SkPaint& paint,
206 const SkMatrix& matrix) {
207 if (!this->INHERITED::setContext(device, paint, matrix)) {
208 return false;
209 }
210
211 const SkMatrix& inverse = this->getTotalInverse();
212
213 if (!fDstToIndex.setConcat(fPtsToUnit, inverse)) {
reed@google.coma641f3f2012-12-13 22:16:30 +0000214 // need to keep our set/end context calls balanced.
215 this->INHERITED::endContext();
rileya@google.com589708b2012-07-26 20:04:23 +0000216 return false;
217 }
218
219 fDstToIndexProc = fDstToIndex.getMapXYProc();
220 fDstToIndexClass = (uint8_t)SkShader::ComputeMatrixClass(fDstToIndex);
221
222 // now convert our colors in to PMColors
223 unsigned paintAlpha = this->getPaintAlpha();
224
225 fFlags = this->INHERITED::getFlags();
226 if (fColorsAreOpaque && paintAlpha == 0xFF) {
227 fFlags |= kOpaqueAlpha_Flag;
228 }
229 // we can do span16 as long as our individual colors are opaque,
230 // regardless of the paint's alpha
231 if (fColorsAreOpaque) {
232 fFlags |= kHasSpan16_Flag;
233 }
234
235 this->setCacheAlpha(paintAlpha);
236 return true;
237}
238
239void SkGradientShaderBase::setCacheAlpha(U8CPU alpha) const {
240 // if the new alpha differs from the previous time we were called, inval our cache
241 // this will trigger the cache to be rebuilt.
242 // we don't care about the first time, since the cache ptrs will already be NULL
243 if (fCacheAlpha != alpha) {
244 fCache16 = NULL; // inval the cache
245 fCache32 = NULL; // inval the cache
246 fCacheAlpha = alpha; // record the new alpha
247 // inform our subclasses
248 if (fCache32PixelRef) {
249 fCache32PixelRef->notifyPixelsChanged();
250 }
251 }
252}
253
254#define Fixed_To_Dot8(x) (((x) + 0x80) >> 8)
255
256/** We take the original colors, not our premultiplied PMColors, since we can
257 build a 16bit table as long as the original colors are opaque, even if the
258 paint specifies a non-opaque alpha.
259*/
260void SkGradientShaderBase::Build16bitCache(uint16_t cache[], SkColor c0, SkColor c1,
261 int count) {
262 SkASSERT(count > 1);
263 SkASSERT(SkColorGetA(c0) == 0xFF);
264 SkASSERT(SkColorGetA(c1) == 0xFF);
265
266 SkFixed r = SkColorGetR(c0);
267 SkFixed g = SkColorGetG(c0);
268 SkFixed b = SkColorGetB(c0);
269
270 SkFixed dr = SkIntToFixed(SkColorGetR(c1) - r) / (count - 1);
271 SkFixed dg = SkIntToFixed(SkColorGetG(c1) - g) / (count - 1);
272 SkFixed db = SkIntToFixed(SkColorGetB(c1) - b) / (count - 1);
273
274 r = SkIntToFixed(r) + 0x8000;
275 g = SkIntToFixed(g) + 0x8000;
276 b = SkIntToFixed(b) + 0x8000;
277
278 do {
279 unsigned rr = r >> 16;
280 unsigned gg = g >> 16;
281 unsigned bb = b >> 16;
282 cache[0] = SkPackRGB16(SkR32ToR16(rr), SkG32ToG16(gg), SkB32ToB16(bb));
283 cache[kCache16Count] = SkDitherPack888ToRGB16(rr, gg, bb);
284 cache += 1;
285 r += dr;
286 g += dg;
287 b += db;
288 } while (--count != 0);
289}
290
rileya@google.com589708b2012-07-26 20:04:23 +0000291void SkGradientShaderBase::Build32bitCache(SkPMColor cache[], SkColor c0, SkColor c1,
292 int count, U8CPU paintAlpha) {
293 SkASSERT(count > 1);
294
295 // need to apply paintAlpha to our two endpoints
296 SkFixed a = SkMulDiv255Round(SkColorGetA(c0), paintAlpha);
297 SkFixed da;
298 {
299 int tmp = SkMulDiv255Round(SkColorGetA(c1), paintAlpha);
300 da = SkIntToFixed(tmp - a) / (count - 1);
301 }
302
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000303 /*
304 * r,g,b used to be SkFixed, but on gcc (4.2.1 mac and 4.6.3 goobuntu) in
305 * release builds, we saw a compiler error where the 0xFF parameter in
306 * SkPackARGB32() was being totally ignored whenever it was called with
307 * a non-zero add (e.g. 0x8000).
308 *
309 * We found two work-arounds:
310 * 1. change r,g,b to unsigned (or just one of them)
311 * 2. change SkPackARGB32 to + its (a << SK_A32_SHIFT) value instead
312 * of using |
313 *
314 * We chose #1 just because it was more localized.
315 * See http://code.google.com/p/skia/issues/detail?id=1113
316 */
317 uint32_t r = SkColorGetR(c0);
318 uint32_t g = SkColorGetG(c0);
319 uint32_t b = SkColorGetB(c0);
320
rileya@google.com589708b2012-07-26 20:04:23 +0000321 SkFixed dr = SkIntToFixed(SkColorGetR(c1) - r) / (count - 1);
322 SkFixed dg = SkIntToFixed(SkColorGetG(c1) - g) / (count - 1);
323 SkFixed db = SkIntToFixed(SkColorGetB(c1) - b) / (count - 1);
324
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000325 /* We pre-add 1/8 to avoid having to add this to our [0] value each time
326 in the loop. Without this, the bias for each would be
327 0x2000 0xA000 0xE000 0x6000
328 With this trick, we can add 0 for the first (no-op) and just adjust the
329 others.
330 */
331 r = SkIntToFixed(r) + 0x2000;
332 g = SkIntToFixed(g) + 0x2000;
333 b = SkIntToFixed(b) + 0x2000;
rileya@google.com589708b2012-07-26 20:04:23 +0000334
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000335 /*
336 * Our dither-cell (spatially) is
337 * 0 2
338 * 3 1
339 * Where
340 * [0] -> [-1/8 ... 1/8 ) values near 0
341 * [1] -> [ 1/8 ... 3/8 ) values near 1/4
342 * [2] -> [ 3/8 ... 5/8 ) values near 1/2
343 * [3] -> [ 5/8 ... 7/8 ) values near 3/4
344 */
345
346 if (0xFF == a && 0 == da) {
347 do {
348 cache[kCache32Count*0] = SkPackARGB32(0xFF, (r + 0 ) >> 16,
349 (g + 0 ) >> 16,
350 (b + 0 ) >> 16);
351 cache[kCache32Count*1] = SkPackARGB32(0xFF, (r + 0x8000) >> 16,
352 (g + 0x8000) >> 16,
353 (b + 0x8000) >> 16);
354 cache[kCache32Count*2] = SkPackARGB32(0xFF, (r + 0xC000) >> 16,
355 (g + 0xC000) >> 16,
356 (b + 0xC000) >> 16);
357 cache[kCache32Count*3] = SkPackARGB32(0xFF, (r + 0x4000) >> 16,
358 (g + 0x4000) >> 16,
359 (b + 0x4000) >> 16);
360 cache += 1;
361 r += dr;
362 g += dg;
363 b += db;
364 } while (--count != 0);
365 } else {
366 a = SkIntToFixed(a) + 0x2000;
367 do {
368 cache[kCache32Count*0] = SkPremultiplyARGBInline((a + 0 ) >> 16,
369 (r + 0 ) >> 16,
370 (g + 0 ) >> 16,
371 (b + 0 ) >> 16);
372 cache[kCache32Count*1] = SkPremultiplyARGBInline((a + 0x8000) >> 16,
373 (r + 0x8000) >> 16,
374 (g + 0x8000) >> 16,
375 (b + 0x8000) >> 16);
376 cache[kCache32Count*2] = SkPremultiplyARGBInline((a + 0xC000) >> 16,
377 (r + 0xC000) >> 16,
378 (g + 0xC000) >> 16,
379 (b + 0xC000) >> 16);
380 cache[kCache32Count*3] = SkPremultiplyARGBInline((a + 0x4000) >> 16,
381 (r + 0x4000) >> 16,
382 (g + 0x4000) >> 16,
383 (b + 0x4000) >> 16);
384 cache += 1;
385 a += da;
386 r += dr;
387 g += dg;
388 b += db;
389 } while (--count != 0);
390 }
rileya@google.com589708b2012-07-26 20:04:23 +0000391}
392
393static inline int SkFixedToFFFF(SkFixed x) {
394 SkASSERT((unsigned)x <= SK_Fixed1);
395 return x - (x >> 16);
396}
397
398static inline U16CPU bitsTo16(unsigned x, const unsigned bits) {
399 SkASSERT(x < (1U << bits));
400 if (6 == bits) {
401 return (x << 10) | (x << 4) | (x >> 2);
402 }
403 if (8 == bits) {
404 return (x << 8) | x;
405 }
406 sk_throw();
407 return 0;
408}
409
rileya@google.com589708b2012-07-26 20:04:23 +0000410const uint16_t* SkGradientShaderBase::getCache16() const {
411 if (fCache16 == NULL) {
412 // double the count for dither entries
413 const int entryCount = kCache16Count * 2;
414 const size_t allocSize = sizeof(uint16_t) * entryCount;
415
416 if (fCache16Storage == NULL) { // set the storage and our working ptr
417 fCache16Storage = (uint16_t*)sk_malloc_throw(allocSize);
418 }
419 fCache16 = fCache16Storage;
420 if (fColorCount == 2) {
421 Build16bitCache(fCache16, fOrigColors[0], fOrigColors[1],
reed@google.com3c2102c2013-02-01 12:59:40 +0000422 kCache16Count);
rileya@google.com589708b2012-07-26 20:04:23 +0000423 } else {
424 Rec* rec = fRecs;
425 int prevIndex = 0;
426 for (int i = 1; i < fColorCount; i++) {
427 int nextIndex = SkFixedToFFFF(rec[i].fPos) >> kCache16Shift;
428 SkASSERT(nextIndex < kCache16Count);
429
430 if (nextIndex > prevIndex)
431 Build16bitCache(fCache16 + prevIndex, fOrigColors[i-1], fOrigColors[i], nextIndex - prevIndex + 1);
432 prevIndex = nextIndex;
433 }
rileya@google.com589708b2012-07-26 20:04:23 +0000434 }
435
436 if (fMapper) {
437 fCache16Storage = (uint16_t*)sk_malloc_throw(allocSize);
438 uint16_t* linear = fCache16; // just computed linear data
439 uint16_t* mapped = fCache16Storage; // storage for mapped data
440 SkUnitMapper* map = fMapper;
reed@google.com3c2102c2013-02-01 12:59:40 +0000441 for (int i = 0; i < kCache16Count; i++) {
rileya@google.com589708b2012-07-26 20:04:23 +0000442 int index = map->mapUnit16(bitsTo16(i, kCache16Bits)) >> kCache16Shift;
443 mapped[i] = linear[index];
444 mapped[i + kCache16Count] = linear[index + kCache16Count];
445 }
446 sk_free(fCache16);
447 fCache16 = fCache16Storage;
448 }
rileya@google.com589708b2012-07-26 20:04:23 +0000449 }
450 return fCache16;
451}
452
rileya@google.com589708b2012-07-26 20:04:23 +0000453const SkPMColor* SkGradientShaderBase::getCache32() const {
454 if (fCache32 == NULL) {
455 // double the count for dither entries
reed@google.com60040292013-02-04 18:21:23 +0000456 const int entryCount = kCache32Count * 4;
rileya@google.com589708b2012-07-26 20:04:23 +0000457 const size_t allocSize = sizeof(SkPMColor) * entryCount;
458
459 if (NULL == fCache32PixelRef) {
460 fCache32PixelRef = SkNEW_ARGS(SkMallocPixelRef,
461 (NULL, allocSize, NULL));
462 }
463 fCache32 = (SkPMColor*)fCache32PixelRef->getAddr();
464 if (fColorCount == 2) {
465 Build32bitCache(fCache32, fOrigColors[0], fOrigColors[1],
reed@google.com3c2102c2013-02-01 12:59:40 +0000466 kCache32Count, fCacheAlpha);
rileya@google.com589708b2012-07-26 20:04:23 +0000467 } else {
468 Rec* rec = fRecs;
469 int prevIndex = 0;
470 for (int i = 1; i < fColorCount; i++) {
471 int nextIndex = SkFixedToFFFF(rec[i].fPos) >> kCache32Shift;
reed@google.com3c2102c2013-02-01 12:59:40 +0000472 SkASSERT(nextIndex < kCache32Count);
rileya@google.com589708b2012-07-26 20:04:23 +0000473
474 if (nextIndex > prevIndex)
475 Build32bitCache(fCache32 + prevIndex, fOrigColors[i-1],
476 fOrigColors[i],
477 nextIndex - prevIndex + 1, fCacheAlpha);
478 prevIndex = nextIndex;
479 }
rileya@google.com589708b2012-07-26 20:04:23 +0000480 }
481
482 if (fMapper) {
483 SkMallocPixelRef* newPR = SkNEW_ARGS(SkMallocPixelRef,
484 (NULL, allocSize, NULL));
485 SkPMColor* linear = fCache32; // just computed linear data
486 SkPMColor* mapped = (SkPMColor*)newPR->getAddr(); // storage for mapped data
487 SkUnitMapper* map = fMapper;
reed@google.com3c2102c2013-02-01 12:59:40 +0000488 for (int i = 0; i < kCache32Count; i++) {
rileya@google.com589708b2012-07-26 20:04:23 +0000489 int index = map->mapUnit16((i << 8) | i) >> 8;
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000490 mapped[i + kCache32Count*0] = linear[index + kCache32Count*0];
491 mapped[i + kCache32Count*1] = linear[index + kCache32Count*1];
reed@google.com60040292013-02-04 18:21:23 +0000492 mapped[i + kCache32Count*2] = linear[index + kCache32Count*2];
493 mapped[i + kCache32Count*3] = linear[index + kCache32Count*3];
rileya@google.com589708b2012-07-26 20:04:23 +0000494 }
495 fCache32PixelRef->unref();
496 fCache32PixelRef = newPR;
497 fCache32 = (SkPMColor*)newPR->getAddr();
498 }
rileya@google.com589708b2012-07-26 20:04:23 +0000499 }
500 return fCache32;
501}
502
503/*
504 * Because our caller might rebuild the same (logically the same) gradient
505 * over and over, we'd like to return exactly the same "bitmap" if possible,
506 * allowing the client to utilize a cache of our bitmap (e.g. with a GPU).
507 * To do that, we maintain a private cache of built-bitmaps, based on our
508 * colors and positions. Note: we don't try to flatten the fMapper, so if one
509 * is present, we skip the cache for now.
510 */
rileya@google.com1c6d64b2012-07-27 15:49:05 +0000511void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000512 // our caller assumes no external alpha, so we ensure that our cache is
513 // built with 0xFF
514 this->setCacheAlpha(0xFF);
515
516 // don't have a way to put the mapper into our cache-key yet
517 if (fMapper) {
518 // force our cahce32pixelref to be built
519 (void)this->getCache32();
reed@google.com3c2102c2013-02-01 12:59:40 +0000520 bitmap->setConfig(SkBitmap::kARGB_8888_Config, kCache32Count, 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000521 bitmap->setPixelRef(fCache32PixelRef);
522 return;
523 }
524
525 // build our key: [numColors + colors[] + {positions[]} ]
526 int count = 1 + fColorCount;
527 if (fColorCount > 2) {
528 count += fColorCount - 1; // fRecs[].fPos
529 }
530
531 SkAutoSTMalloc<16, int32_t> storage(count);
532 int32_t* buffer = storage.get();
533
534 *buffer++ = fColorCount;
535 memcpy(buffer, fOrigColors, fColorCount * sizeof(SkColor));
536 buffer += fColorCount;
537 if (fColorCount > 2) {
538 for (int i = 1; i < fColorCount; i++) {
539 *buffer++ = fRecs[i].fPos;
540 }
541 }
542 SkASSERT(buffer - storage.get() == count);
543
544 ///////////////////////////////////
545
546 SK_DECLARE_STATIC_MUTEX(gMutex);
547 static SkBitmapCache* gCache;
548 // each cache cost 1K of RAM, since each bitmap will be 1x256 at 32bpp
549 static const int MAX_NUM_CACHED_GRADIENT_BITMAPS = 32;
550 SkAutoMutexAcquire ama(gMutex);
551
552 if (NULL == gCache) {
553 gCache = SkNEW_ARGS(SkBitmapCache, (MAX_NUM_CACHED_GRADIENT_BITMAPS));
554 }
555 size_t size = count * sizeof(int32_t);
556
557 if (!gCache->find(storage.get(), size, bitmap)) {
558 // force our cahce32pixelref to be built
559 (void)this->getCache32();
reed@google.com3c2102c2013-02-01 12:59:40 +0000560 bitmap->setConfig(SkBitmap::kARGB_8888_Config, kCache32Count, 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000561 bitmap->setPixelRef(fCache32PixelRef);
562
563 gCache->add(storage.get(), size, *bitmap);
564 }
565}
566
567void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
568 if (info) {
569 if (info->fColorCount >= fColorCount) {
570 if (info->fColors) {
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000571 memcpy(info->fColors, fOrigColors, fColorCount * sizeof(SkColor));
rileya@google.com589708b2012-07-26 20:04:23 +0000572 }
573 if (info->fColorOffsets) {
574 if (fColorCount == 2) {
575 info->fColorOffsets[0] = 0;
576 info->fColorOffsets[1] = SK_Scalar1;
577 } else if (fColorCount > 2) {
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000578 for (int i = 0; i < fColorCount; ++i) {
rileya@google.com589708b2012-07-26 20:04:23 +0000579 info->fColorOffsets[i] = SkFixedToScalar(fRecs[i].fPos);
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000580 }
rileya@google.com589708b2012-07-26 20:04:23 +0000581 }
582 }
583 }
584 info->fColorCount = fColorCount;
585 info->fTileMode = fTileMode;
586 }
587}
588
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000589#ifdef SK_DEVELOPER
590void SkGradientShaderBase::toString(SkString* str) const {
591
592 str->appendf("%d colors: ", fColorCount);
593
594 for (int i = 0; i < fColorCount; ++i) {
595 str->appendHex(fOrigColors[i]);
596 if (i < fColorCount-1) {
597 str->append(", ");
598 }
599 }
600
601 if (fColorCount > 2) {
602 str->append(" points: (");
603 for (int i = 0; i < fColorCount; ++i) {
604 str->appendScalar(SkFixedToScalar(fRecs[i].fPos));
605 if (i < fColorCount-1) {
606 str->append(", ");
607 }
608 }
609 str->append(")");
610 }
611
612 static const char* gTileModeName[SkShader::kTileModeCount] = {
613 "clamp", "repeat", "mirror"
614 };
615
616 str->append(" ");
617 str->append(gTileModeName[fTileMode]);
618
619 // TODO: add "fMapper->toString(str);" when SkUnitMapper::toString is added
620
621 this->INHERITED::toString(str);
622}
623#endif
624
rileya@google.com589708b2012-07-26 20:04:23 +0000625///////////////////////////////////////////////////////////////////////////////
626///////////////////////////////////////////////////////////////////////////////
627
628#include "SkEmptyShader.h"
629
630// assumes colors is SkColor* and pos is SkScalar*
631#define EXPAND_1_COLOR(count) \
632 SkColor tmp[2]; \
633 do { \
634 if (1 == count) { \
635 tmp[0] = tmp[1] = colors[0]; \
636 colors = tmp; \
637 pos = NULL; \
638 count = 2; \
639 } \
640 } while (0)
641
reed@google.com437d6eb2013-05-23 19:03:05 +0000642static void desc_init(SkGradientShaderBase::Descriptor* desc,
643 const SkColor colors[],
644 const SkScalar pos[], int colorCount,
645 SkShader::TileMode mode,
646 SkUnitMapper* mapper) {
647 desc->fColors = colors;
648 desc->fPos = pos;
649 desc->fCount = colorCount;
650 desc->fTileMode = mode;
651 desc->fMapper = mapper;
652}
653
rileya@google.com589708b2012-07-26 20:04:23 +0000654SkShader* SkGradientShader::CreateLinear(const SkPoint pts[2],
655 const SkColor colors[],
656 const SkScalar pos[], int colorCount,
657 SkShader::TileMode mode,
658 SkUnitMapper* mapper) {
659 if (NULL == pts || NULL == colors || colorCount < 1) {
660 return NULL;
661 }
662 EXPAND_1_COLOR(colorCount);
663
reed@google.com437d6eb2013-05-23 19:03:05 +0000664 SkGradientShaderBase::Descriptor desc;
665 desc_init(&desc, colors, pos, colorCount, mode, mapper);
666 return SkNEW_ARGS(SkLinearGradient, (pts, desc));
rileya@google.com589708b2012-07-26 20:04:23 +0000667}
668
669SkShader* SkGradientShader::CreateRadial(const SkPoint& center, SkScalar radius,
670 const SkColor colors[],
671 const SkScalar pos[], int colorCount,
672 SkShader::TileMode mode,
673 SkUnitMapper* mapper) {
674 if (radius <= 0 || NULL == colors || colorCount < 1) {
675 return NULL;
676 }
677 EXPAND_1_COLOR(colorCount);
678
reed@google.com437d6eb2013-05-23 19:03:05 +0000679 SkGradientShaderBase::Descriptor desc;
680 desc_init(&desc, colors, pos, colorCount, mode, mapper);
681 return SkNEW_ARGS(SkRadialGradient, (center, radius, desc));
rileya@google.com589708b2012-07-26 20:04:23 +0000682}
683
684SkShader* SkGradientShader::CreateTwoPointRadial(const SkPoint& start,
685 SkScalar startRadius,
686 const SkPoint& end,
687 SkScalar endRadius,
688 const SkColor colors[],
689 const SkScalar pos[],
690 int colorCount,
691 SkShader::TileMode mode,
692 SkUnitMapper* mapper) {
693 if (startRadius < 0 || endRadius < 0 || NULL == colors || colorCount < 1) {
694 return NULL;
695 }
696 EXPAND_1_COLOR(colorCount);
rmistry@google.comfbfcd562012-08-23 18:09:54 +0000697
reed@google.com437d6eb2013-05-23 19:03:05 +0000698 SkGradientShaderBase::Descriptor desc;
699 desc_init(&desc, colors, pos, colorCount, mode, mapper);
rileya@google.com589708b2012-07-26 20:04:23 +0000700 return SkNEW_ARGS(SkTwoPointRadialGradient,
reed@google.com437d6eb2013-05-23 19:03:05 +0000701 (start, startRadius, end, endRadius, desc));
rileya@google.com589708b2012-07-26 20:04:23 +0000702}
703
704SkShader* SkGradientShader::CreateTwoPointConical(const SkPoint& start,
705 SkScalar startRadius,
706 const SkPoint& end,
707 SkScalar endRadius,
708 const SkColor colors[],
709 const SkScalar pos[],
710 int colorCount,
711 SkShader::TileMode mode,
712 SkUnitMapper* mapper) {
713 if (startRadius < 0 || endRadius < 0 || NULL == colors || colorCount < 1) {
714 return NULL;
715 }
716 if (start == end && startRadius == endRadius) {
717 return SkNEW(SkEmptyShader);
718 }
rileya@google.com1ee7c6a2012-07-31 16:00:13 +0000719 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000720
reed@google.com437d6eb2013-05-23 19:03:05 +0000721 SkGradientShaderBase::Descriptor desc;
722 desc_init(&desc, colors, pos, colorCount, mode, mapper);
rileya@google.com589708b2012-07-26 20:04:23 +0000723 return SkNEW_ARGS(SkTwoPointConicalGradient,
reed@google.com437d6eb2013-05-23 19:03:05 +0000724 (start, startRadius, end, endRadius, desc));
rileya@google.com589708b2012-07-26 20:04:23 +0000725}
726
727SkShader* SkGradientShader::CreateSweep(SkScalar cx, SkScalar cy,
728 const SkColor colors[],
729 const SkScalar pos[],
reed@google.com437d6eb2013-05-23 19:03:05 +0000730 int colorCount, SkUnitMapper* mapper) {
731 if (NULL == colors || colorCount < 1) {
rileya@google.com589708b2012-07-26 20:04:23 +0000732 return NULL;
733 }
reed@google.com437d6eb2013-05-23 19:03:05 +0000734 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000735
reed@google.com437d6eb2013-05-23 19:03:05 +0000736 SkGradientShaderBase::Descriptor desc;
737 desc_init(&desc, colors, pos, colorCount, SkShader::kClamp_TileMode, mapper);
738 return SkNEW_ARGS(SkSweepGradient, (cx, cy, desc));
rileya@google.com589708b2012-07-26 20:04:23 +0000739}
740
741SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
742 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
743 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
744 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
745 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointRadialGradient)
746 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
747SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
rileya@google.comd7cc6512012-07-27 14:00:39 +0000748
749///////////////////////////////////////////////////////////////////////////////
750
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000751#if SK_SUPPORT_GPU
752
rileya@google.comb3e50f22012-08-20 17:43:08 +0000753#include "effects/GrTextureStripAtlas.h"
bsalomon@google.comc7818882013-03-20 19:19:53 +0000754#include "GrTBackendEffectFactory.h"
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000755#include "SkGr.h"
756
bsalomon@google.com0707c292012-10-25 21:45:42 +0000757GrGLGradientEffect::GrGLGradientEffect(const GrBackendEffectFactory& factory)
rileya@google.comb3e50f22012-08-20 17:43:08 +0000758 : INHERITED(factory)
bsalomon@google.com81712882012-11-01 17:12:34 +0000759 , fCachedYCoord(SK_ScalarMax)
bsalomon@google.comc7818882013-03-20 19:19:53 +0000760 , fFSYUni(GrGLUniformManager::kInvalidUniformHandle)
761 , fEffectMatrix(kCoordsType) {
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000762}
rileya@google.comd7cc6512012-07-27 14:00:39 +0000763
bsalomon@google.com0707c292012-10-25 21:45:42 +0000764GrGLGradientEffect::~GrGLGradientEffect() { }
rileya@google.comd7cc6512012-07-27 14:00:39 +0000765
bsalomon@google.comf78df332012-10-29 12:43:38 +0000766void GrGLGradientEffect::emitYCoordUniform(GrGLShaderBuilder* builder) {
rileya@google.comb3e50f22012-08-20 17:43:08 +0000767 fFSYUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
768 kFloat_GrSLType, "GradientYCoordFS");
769}
770
bsalomon@google.comc7818882013-03-20 19:19:53 +0000771void GrGLGradientEffect::setData(const GrGLUniformManager& uman,
772 const GrDrawEffect& drawEffect) {
773 const GrGradientEffect& e = drawEffect.castEffect<GrGradientEffect>();
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000774 const GrTexture* texture = e.texture(0);
bsalomon@google.comc7818882013-03-20 19:19:53 +0000775 fEffectMatrix.setData(uman, e.getMatrix(), drawEffect, texture);
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000776
bsalomon@google.com81712882012-11-01 17:12:34 +0000777 SkScalar yCoord = e.getYCoord();
rileya@google.comb3e50f22012-08-20 17:43:08 +0000778 if (yCoord != fCachedYCoord) {
779 uman.set1f(fFSYUni, yCoord);
780 fCachedYCoord = yCoord;
781 }
782}
783
bsalomon@google.comc7818882013-03-20 19:19:53 +0000784GrGLEffect::EffectKey GrGLGradientEffect::GenMatrixKey(const GrDrawEffect& drawEffect) {
785 const GrGradientEffect& e = drawEffect.castEffect<GrGradientEffect>();
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000786 const GrTexture* texture = e.texture(0);
bsalomon@google.comc7818882013-03-20 19:19:53 +0000787 return GrGLEffectMatrix::GenKey(e.getMatrix(), drawEffect, kCoordsType, texture);
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000788}
789
790void GrGLGradientEffect::setupMatrix(GrGLShaderBuilder* builder,
791 EffectKey key,
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000792 const char** fsCoordName,
793 const char** vsVaryingName,
794 GrSLType* vsVaryingType) {
795 fEffectMatrix.emitCodeMakeFSCoords2D(builder,
796 key & kMatrixKeyMask,
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000797 fsCoordName,
798 vsVaryingName,
799 vsVaryingType);
800}
801
bsalomon@google.com0707c292012-10-25 21:45:42 +0000802void GrGLGradientEffect::emitColorLookup(GrGLShaderBuilder* builder,
803 const char* gradientTValue,
804 const char* outputColor,
805 const char* inputColor,
806 const GrGLShaderBuilder::TextureSampler& sampler) {
bsalomon@google.com34bcb9f2012-08-28 18:20:18 +0000807
bsalomon@google.comf910d3b2013-03-07 17:06:57 +0000808 builder->fsCodeAppendf("\tvec2 coord = vec2(%s, %s);\n",
809 gradientTValue,
810 builder->getUniformVariable(fFSYUni).c_str());
811 builder->fsCodeAppendf("\t%s = ", outputColor);
812 builder->appendTextureLookupAndModulate(GrGLShaderBuilder::kFragment_ShaderType,
813 inputColor,
814 sampler,
815 "coord");
816 builder->fsCodeAppend(";\n");
rileya@google.comd7cc6512012-07-27 14:00:39 +0000817}
818
819/////////////////////////////////////////////////////////////////////
820
rmistry@google.comfbfcd562012-08-23 18:09:54 +0000821GrGradientEffect::GrGradientEffect(GrContext* ctx,
rileya@google.com1c6d64b2012-07-27 15:49:05 +0000822 const SkGradientShaderBase& shader,
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000823 const SkMatrix& matrix,
bsalomon@google.com50db75c2013-01-11 13:54:30 +0000824 SkShader::TileMode tileMode) {
rileya@google.comd7cc6512012-07-27 14:00:39 +0000825 // TODO: check for simple cases where we don't need a texture:
826 //GradientInfo info;
827 //shader.asAGradient(&info);
828 //if (info.fColorCount == 2) { ...
829
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +0000830 fMatrix = matrix;
831
rileya@google.comd7cc6512012-07-27 14:00:39 +0000832 SkBitmap bitmap;
rileya@google.com1c6d64b2012-07-27 15:49:05 +0000833 shader.getGradientTableBitmap(&bitmap);
rileya@google.comd7cc6512012-07-27 14:00:39 +0000834
bsalomon@google.com371e1052013-01-11 21:08:55 +0000835 fIsOpaque = shader.isOpaque();
836
rileya@google.comb3e50f22012-08-20 17:43:08 +0000837 GrTextureStripAtlas::Desc desc;
838 desc.fWidth = bitmap.width();
839 desc.fHeight = 32;
840 desc.fRowHeight = bitmap.height();
841 desc.fContext = ctx;
842 desc.fConfig = SkBitmapConfig2GrPixelConfig(bitmap.config());
843 fAtlas = GrTextureStripAtlas::GetAtlas(desc);
844 GrAssert(NULL != fAtlas);
rmistry@google.comfbfcd562012-08-23 18:09:54 +0000845
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +0000846 // We always filter the gradient table. Each table is one row of a texture, so always y-clamp.
847 GrTextureParams params;
848 params.setBilerp(true);
849 params.setTileModeX(tileMode);
850
rileya@google.comb3e50f22012-08-20 17:43:08 +0000851 fRow = fAtlas->lockRow(bitmap);
852 if (-1 != fRow) {
bsalomon@google.com81712882012-11-01 17:12:34 +0000853 fYCoord = fAtlas->getYOffset(fRow) + SK_ScalarHalf *
rileya@google.comb3e50f22012-08-20 17:43:08 +0000854 fAtlas->getVerticalScaleFactor();
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +0000855 fTextureAccess.reset(fAtlas->getTexture(), params);
rileya@google.comb3e50f22012-08-20 17:43:08 +0000856 } else {
bsalomon@google.com95ed55a2013-01-24 14:46:47 +0000857 GrTexture* texture = GrLockAndRefCachedBitmapTexture(ctx, bitmap, &params);
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +0000858 fTextureAccess.reset(texture, params);
bsalomon@google.com81712882012-11-01 17:12:34 +0000859 fYCoord = SK_ScalarHalf;
rmistry@google.comfbfcd562012-08-23 18:09:54 +0000860
rileya@google.comb3e50f22012-08-20 17:43:08 +0000861 // Unlock immediately, this is not great, but we don't have a way of
862 // knowing when else to unlock it currently, so it may get purged from
863 // the cache, but it'll still be ref'd until it's no longer being used.
bsalomon@google.com95ed55a2013-01-24 14:46:47 +0000864 GrUnlockAndUnrefCachedBitmapTexture(texture);
rileya@google.comb3e50f22012-08-20 17:43:08 +0000865 }
bsalomon@google.com50db75c2013-01-11 13:54:30 +0000866 this->addTextureAccess(&fTextureAccess);
rileya@google.comd7cc6512012-07-27 14:00:39 +0000867}
868
869GrGradientEffect::~GrGradientEffect() {
rileya@google.comb3e50f22012-08-20 17:43:08 +0000870 if (this->useAtlas()) {
871 fAtlas->unlockRow(fRow);
rileya@google.comb3e50f22012-08-20 17:43:08 +0000872 }
rileya@google.comd7cc6512012-07-27 14:00:39 +0000873}
874
bsalomon@google.com8a252f72013-01-22 20:35:13 +0000875bool GrGradientEffect::onIsEqual(const GrEffect& effect) const {
bsalomon@google.com6340a412013-01-22 19:55:59 +0000876 const GrGradientEffect& s = CastEffect<GrGradientEffect>(effect);
bsalomon@google.com68b58c92013-01-17 16:50:08 +0000877 return fTextureAccess.getTexture() == s.fTextureAccess.getTexture() &&
878 fTextureAccess.getParams().getTileModeX() ==
879 s.fTextureAccess.getParams().getTileModeX() &&
880 this->useAtlas() == s.useAtlas() &&
881 fYCoord == s.getYCoord() &&
882 fMatrix.cheapEqualTo(s.getMatrix());
883}
884
885void GrGradientEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const {
bsalomon@google.comb8eb2e82013-03-28 13:46:42 +0000886 if (fIsOpaque && (kA_GrColorComponentFlag & *validFlags) && 0xff == GrColorUnpackA(*color)) {
887 *validFlags = kA_GrColorComponentFlag;
bsalomon@google.com68b58c92013-01-17 16:50:08 +0000888 } else {
889 *validFlags = 0;
890 }
891}
892
bsalomon@google.com73a96942013-02-13 16:31:19 +0000893int GrGradientEffect::RandomGradientParams(SkMWCRandom* random,
bsalomon@google.comd4726202012-08-03 14:34:46 +0000894 SkColor colors[],
895 SkScalar** stops,
896 SkShader::TileMode* tm) {
897 int outColors = random->nextRangeU(1, kMaxRandomGradientColors);
898
899 // if one color, omit stops, otherwise randomly decide whether or not to
900 if (outColors == 1 || (outColors >= 2 && random->nextBool())) {
901 *stops = NULL;
902 }
903
bsalomon@google.com81712882012-11-01 17:12:34 +0000904 SkScalar stop = 0.f;
bsalomon@google.comd4726202012-08-03 14:34:46 +0000905 for (int i = 0; i < outColors; ++i) {
906 colors[i] = random->nextU();
907 if (NULL != *stops) {
908 (*stops)[i] = stop;
909 stop = i < outColors - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
910 }
911 }
912 *tm = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
913
914 return outColors;
915}
916
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000917#endif