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 "SkGradientShaderPriv.h"
9#include "SkLinearGradient.h"
10#include "SkRadialGradient.h"
11#include "SkTwoPointRadialGradient.h"
12#include "SkTwoPointConicalGradient.h"
13#include "SkSweepGradient.h"
14
15SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc) {
16    SkASSERT(desc.fCount > 1);
17
18    fCacheAlpha = 256;  // init to a value that paint.getAlpha() can't return
19
20    fMapper = desc.fMapper;
21    SkSafeRef(fMapper);
22    fGradFlags = SkToU8(desc.fFlags);
23
24    SkASSERT((unsigned)desc.fTileMode < SkShader::kTileModeCount);
25    SkASSERT(SkShader::kTileModeCount == SK_ARRAY_COUNT(gTileProcs));
26    fTileMode = desc.fTileMode;
27    fTileProc = gTileProcs[desc.fTileMode];
28
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     */
44    fColorCount = desc.fCount;
45    // check if we need to add in dummy start and/or end position/colors
46    bool dummyFirst = false;
47    bool dummyLast = false;
48    if (desc.fPos) {
49        dummyFirst = desc.fPos[0] != 0;
50        dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
51        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) {
67            *origColors++ = desc.fColors[0];
68        }
69        memcpy(origColors, desc.fColors, desc.fCount * sizeof(SkColor));
70        if (dummyLast) {
71            origColors += desc.fCount;
72            *origColors = desc.fColors[desc.fCount - 1];
73        }
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;
82        if (desc.fPos) {
83            /*  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;
92            int count = desc.fCount + dummyLast;
93            for (int i = startIndex; i < count; i++) {
94                // force the last value to be 1.0
95                SkFixed curr;
96                if (i == desc.fCount) {  // we're really at the dummyLast
97                    curr = SK_Fixed1;
98                } else {
99                    curr = SkScalarToFixed(desc.fPos[i]);
100                }
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
118            SkFixed dp = SK_Fixed1 / (desc.fCount - 1);
119            SkFixed p = dp;
120            SkFixed scale = (desc.fCount - 1) << 8;  // (1 << 24) / dp
121            for (int i = 1; i < desc.fCount; i++) {
122                recs->fPos   = p;
123                recs->fScale = scale;
124                recs += 1;
125                p += dp;
126            }
127        }
128    }
129    this->initCommon();
130}
131
132static 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) {
147    fCacheAlpha = 256;
148
149    fMapper = buffer.readFlattenableT<SkUnitMapper>();
150
151    fCache16 = fCache16Storage = NULL;
152    fCache32 = NULL;
153    fCache32PixelRef = NULL;
154
155    int colorCount = fColorCount = buffer.getArrayCount();
156    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    }
162    buffer.readColorArray(fOrigColors);
163
164    {
165        uint32_t packed = buffer.readUInt();
166        fGradFlags = SkToU8(unpack_flags(packed));
167        fTileMode = unpack_mode(packed);
168    }
169    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++) {
175            recs[i].fPos = buffer.readInt();
176            recs[i].fScale = buffer.readUInt();
177        }
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);
206    buffer.writeColorArray(fOrigColors, fColorCount);
207    buffer.writeUInt(pack_mode_flags(fTileMode, fGradFlags));
208    if (fColorCount > 2) {
209        Rec* recs = fRecs;
210        for (int i = 1; i < fColorCount; i++) {
211            buffer.writeInt(recs[i].fPos);
212            buffer.writeUInt(recs[i].fScale);
213        }
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)) {
232        // need to keep our set/end context calls balanced.
233        this->INHERITED::endContext();
234        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
309/*
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
327void SkGradientShaderBase::Build32bitCache(SkPMColor cache[], SkColor c0, SkColor c1,
328                                      int count, U8CPU paintAlpha, uint32_t gradFlags) {
329    SkASSERT(count > 1);
330
331    // need to apply paintAlpha to our two endpoints
332    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);
355    }
356
357    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);
361
362    /*  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     */
368    SkUFixed a = SkIntToFixed(a0) + 0x2000;
369    SkUFixed r = SkIntToFixed(r0) + 0x2000;
370    SkUFixed g = SkIntToFixed(g0) + 0x2000;
371    SkUFixed b = SkIntToFixed(b0) + 0x2000;
372
373    /*
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
384    if (0xFF == a0 && 0 == da) {
385        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);
403    } 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
428        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    }
452}
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
471const 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],
483                            kCache16Count);
484        } 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            }
495        }
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;
502            for (int i = 0; i < kCache16Count; i++) {
503                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        }
510    }
511    return fCache16;
512}
513
514const SkPMColor* SkGradientShaderBase::getCache32() const {
515    if (fCache32 == NULL) {
516        // double the count for dither entries
517        const int entryCount = kCache32Count * 4;
518        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],
527                            kCache32Count, fCacheAlpha, fGradFlags);
528        } 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;
533                SkASSERT(nextIndex < kCache32Count);
534
535                if (nextIndex > prevIndex)
536                    Build32bitCache(fCache32 + prevIndex, fOrigColors[i-1],
537                                    fOrigColors[i], nextIndex - prevIndex + 1,
538                                    fCacheAlpha, fGradFlags);
539                prevIndex = nextIndex;
540            }
541        }
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;
549            for (int i = 0; i < kCache32Count; i++) {
550                int index = map->mapUnit16((i << 8) | i) >> 8;
551                mapped[i + kCache32Count*0] = linear[index + kCache32Count*0];
552                mapped[i + kCache32Count*1] = linear[index + kCache32Count*1];
553                mapped[i + kCache32Count*2] = linear[index + kCache32Count*2];
554                mapped[i + kCache32Count*3] = linear[index + kCache32Count*3];
555            }
556            fCache32PixelRef->unref();
557            fCache32PixelRef = newPR;
558            fCache32 = (SkPMColor*)newPR->getAddr();
559        }
560    }
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 */
572void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap) const {
573    // 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();
581        bitmap->setConfig(SkBitmap::kARGB_8888_Config, kCache32Count, 1);
582        bitmap->setPixelRef(fCache32PixelRef);
583        return;
584    }
585
586    // build our key: [numColors + colors[] + {positions[]} + flags ]
587    int count = 1 + fColorCount + 1;
588    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    }
603    *buffer++ = fGradFlags;
604    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();
622        bitmap->setConfig(SkBitmap::kARGB_8888_Config, kCache32Count, 1);
623        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) {
633                memcpy(info->fColors, fOrigColors, fColorCount * sizeof(SkColor));
634            }
635            if (info->fColorOffsets) {
636                if (fColorCount == 2) {
637                    info->fColorOffsets[0] = 0;
638                    info->fColorOffsets[1] = SK_Scalar1;
639                } else if (fColorCount > 2) {
640                    for (int i = 0; i < fColorCount; ++i) {
641                        info->fColorOffsets[i] = SkFixedToScalar(fRecs[i].fPos);
642                    }
643                }
644            }
645        }
646        info->fColorCount = fColorCount;
647        info->fTileMode = fTileMode;
648        info->fGradientFlags = fGradFlags;
649    }
650}
651
652#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
688///////////////////////////////////////////////////////////////////////////////
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
705static void desc_init(SkGradientShaderBase::Descriptor* desc,
706                      const SkColor colors[],
707                      const SkScalar pos[], int colorCount,
708                      SkShader::TileMode mode,
709                      SkUnitMapper* mapper, uint32_t flags) {
710    desc->fColors   = colors;
711    desc->fPos      = pos;
712    desc->fCount    = colorCount;
713    desc->fTileMode = mode;
714    desc->fMapper   = mapper;
715    desc->fFlags    = flags;
716}
717
718SkShader* SkGradientShader::CreateLinear(const SkPoint pts[2],
719                                         const SkColor colors[],
720                                         const SkScalar pos[], int colorCount,
721                                         SkShader::TileMode mode,
722                                         SkUnitMapper* mapper,
723                                         uint32_t flags) {
724    if (NULL == pts || NULL == colors || colorCount < 1) {
725        return NULL;
726    }
727    EXPAND_1_COLOR(colorCount);
728
729    SkGradientShaderBase::Descriptor desc;
730    desc_init(&desc, colors, pos, colorCount, mode, mapper, flags);
731    return SkNEW_ARGS(SkLinearGradient, (pts, desc));
732}
733
734SkShader* SkGradientShader::CreateRadial(const SkPoint& center, SkScalar radius,
735                                         const SkColor colors[],
736                                         const SkScalar pos[], int colorCount,
737                                         SkShader::TileMode mode,
738                                         SkUnitMapper* mapper,
739                                         uint32_t flags) {
740    if (radius <= 0 || NULL == colors || colorCount < 1) {
741        return NULL;
742    }
743    EXPAND_1_COLOR(colorCount);
744
745    SkGradientShaderBase::Descriptor desc;
746    desc_init(&desc, colors, pos, colorCount, mode, mapper, flags);
747    return SkNEW_ARGS(SkRadialGradient, (center, radius, desc));
748}
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,
758                                                 SkUnitMapper* mapper,
759                                                 uint32_t flags) {
760    if (startRadius < 0 || endRadius < 0 || NULL == colors || colorCount < 1) {
761        return NULL;
762    }
763    EXPAND_1_COLOR(colorCount);
764
765    SkGradientShaderBase::Descriptor desc;
766    desc_init(&desc, colors, pos, colorCount, mode, mapper, flags);
767    return SkNEW_ARGS(SkTwoPointRadialGradient,
768                      (start, startRadius, end, endRadius, desc));
769}
770
771SkShader* SkGradientShader::CreateTwoPointConical(const SkPoint& start,
772                                                  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) {
781    if (startRadius < 0 || endRadius < 0 || NULL == colors || colorCount < 1) {
782        return NULL;
783    }
784    if (start == end && startRadius == endRadius) {
785        return SkNEW(SkEmptyShader);
786    }
787    EXPAND_1_COLOR(colorCount);
788
789    SkGradientShaderBase::Descriptor desc;
790    desc_init(&desc, colors, pos, colorCount, mode, mapper, flags);
791    return SkNEW_ARGS(SkTwoPointConicalGradient,
792                      (start, startRadius, end, endRadius, desc));
793}
794
795SkShader* SkGradientShader::CreateSweep(SkScalar cx, SkScalar cy,
796                                        const SkColor colors[],
797                                        const SkScalar pos[],
798                                        int colorCount, SkUnitMapper* mapper,
799                                        uint32_t flags) {
800    if (NULL == colors || colorCount < 1) {
801        return NULL;
802    }
803    EXPAND_1_COLOR(colorCount);
804
805    SkGradientShaderBase::Descriptor desc;
806    desc_init(&desc, colors, pos, colorCount, SkShader::kClamp_TileMode, mapper, flags);
807    return SkNEW_ARGS(SkSweepGradient, (cx, cy, desc));
808}
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
817
818///////////////////////////////////////////////////////////////////////////////
819
820#if SK_SUPPORT_GPU
821
822#include "effects/GrTextureStripAtlas.h"
823#include "GrTBackendEffectFactory.h"
824#include "SkGr.h"
825
826GrGLGradientEffect::GrGLGradientEffect(const GrBackendEffectFactory& factory)
827    : INHERITED(factory)
828    , fCachedYCoord(SK_ScalarMax)
829    , fFSYUni(GrGLUniformManager::kInvalidUniformHandle)
830    , fEffectMatrix(kCoordsType) {
831}
832
833GrGLGradientEffect::~GrGLGradientEffect() { }
834
835void GrGLGradientEffect::emitYCoordUniform(GrGLShaderBuilder* builder) {
836    fFSYUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
837                                  kFloat_GrSLType, "GradientYCoordFS");
838}
839
840void GrGLGradientEffect::setData(const GrGLUniformManager& uman,
841                                 const GrDrawEffect& drawEffect) {
842    const GrGradientEffect& e = drawEffect.castEffect<GrGradientEffect>();
843    const GrTexture* texture = e.texture(0);
844    fEffectMatrix.setData(uman, e.getMatrix(), drawEffect, texture);
845
846    SkScalar yCoord = e.getYCoord();
847    if (yCoord != fCachedYCoord) {
848        uman.set1f(fFSYUni, yCoord);
849        fCachedYCoord = yCoord;
850    }
851}
852
853GrGLEffect::EffectKey GrGLGradientEffect::GenMatrixKey(const GrDrawEffect& drawEffect) {
854    const GrGradientEffect& e = drawEffect.castEffect<GrGradientEffect>();
855    const GrTexture* texture = e.texture(0);
856    return GrGLEffectMatrix::GenKey(e.getMatrix(), drawEffect, kCoordsType, texture);
857}
858
859void GrGLGradientEffect::setupMatrix(GrGLShaderBuilder* builder,
860                                     EffectKey key,
861                                     const char** fsCoordName,
862                                     const char** vsVaryingName,
863                                     GrSLType* vsVaryingType) {
864    fEffectMatrix.emitCodeMakeFSCoords2D(builder,
865                                         key & kMatrixKeyMask,
866                                         fsCoordName,
867                                         vsVaryingName,
868                                         vsVaryingType);
869}
870
871void GrGLGradientEffect::emitColorLookup(GrGLShaderBuilder* builder,
872                                         const char* gradientTValue,
873                                         const char* outputColor,
874                                         const char* inputColor,
875                                         const GrGLShaderBuilder::TextureSampler& sampler) {
876
877    builder->fsCodeAppendf("\tvec2 coord = vec2(%s, %s);\n",
878                           gradientTValue,
879                           builder->getUniformVariable(fFSYUni).c_str());
880    builder->fsCodeAppendf("\t%s = ", outputColor);
881    builder->appendTextureLookupAndModulate(GrGLShaderBuilder::kFragment_ShaderType,
882                                            inputColor,
883                                            sampler,
884                                            "coord");
885    builder->fsCodeAppend(";\n");
886}
887
888/////////////////////////////////////////////////////////////////////
889
890GrGradientEffect::GrGradientEffect(GrContext* ctx,
891                                   const SkGradientShaderBase& shader,
892                                   const SkMatrix& matrix,
893                                   SkShader::TileMode tileMode) {
894    // TODO: check for simple cases where we don't need a texture:
895    //GradientInfo info;
896    //shader.asAGradient(&info);
897    //if (info.fColorCount == 2) { ...
898
899    fMatrix = matrix;
900
901    SkBitmap bitmap;
902    shader.getGradientTableBitmap(&bitmap);
903
904    fIsOpaque = shader.isOpaque();
905
906    GrTextureStripAtlas::Desc desc;
907    desc.fWidth  = bitmap.width();
908    desc.fHeight = 32;
909    desc.fRowHeight = bitmap.height();
910    desc.fContext = ctx;
911    desc.fConfig = SkBitmapConfig2GrPixelConfig(bitmap.config());
912    fAtlas = GrTextureStripAtlas::GetAtlas(desc);
913    GrAssert(NULL != fAtlas);
914
915    // We always filter the gradient table. Each table is one row of a texture, so always y-clamp.
916    GrTextureParams params;
917    params.setFilterMode(GrTextureParams::kBilerp_FilterMode);
918    params.setTileModeX(tileMode);
919
920    fRow = fAtlas->lockRow(bitmap);
921    if (-1 != fRow) {
922        fYCoord = fAtlas->getYOffset(fRow) + SK_ScalarHalf *
923                  fAtlas->getVerticalScaleFactor();
924        fTextureAccess.reset(fAtlas->getTexture(), params);
925    } else {
926        GrTexture* texture = GrLockAndRefCachedBitmapTexture(ctx, bitmap, &params);
927        fTextureAccess.reset(texture, params);
928        fYCoord = SK_ScalarHalf;
929
930        // Unlock immediately, this is not great, but we don't have a way of
931        // knowing when else to unlock it currently, so it may get purged from
932        // the cache, but it'll still be ref'd until it's no longer being used.
933        GrUnlockAndUnrefCachedBitmapTexture(texture);
934    }
935    this->addTextureAccess(&fTextureAccess);
936}
937
938GrGradientEffect::~GrGradientEffect() {
939    if (this->useAtlas()) {
940        fAtlas->unlockRow(fRow);
941    }
942}
943
944bool GrGradientEffect::onIsEqual(const GrEffect& effect) const {
945    const GrGradientEffect& s = CastEffect<GrGradientEffect>(effect);
946    return fTextureAccess.getTexture() == s.fTextureAccess.getTexture()  &&
947           fTextureAccess.getParams().getTileModeX() ==
948                s.fTextureAccess.getParams().getTileModeX() &&
949           this->useAtlas() == s.useAtlas() &&
950           fYCoord == s.getYCoord() &&
951           fMatrix.cheapEqualTo(s.getMatrix());
952}
953
954void GrGradientEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const {
955    if (fIsOpaque && (kA_GrColorComponentFlag & *validFlags) && 0xff == GrColorUnpackA(*color)) {
956        *validFlags = kA_GrColorComponentFlag;
957    } else {
958        *validFlags = 0;
959    }
960}
961
962int GrGradientEffect::RandomGradientParams(SkMWCRandom* random,
963                                           SkColor colors[],
964                                           SkScalar** stops,
965                                           SkShader::TileMode* tm) {
966    int outColors = random->nextRangeU(1, kMaxRandomGradientColors);
967
968    // if one color, omit stops, otherwise randomly decide whether or not to
969    if (outColors == 1 || (outColors >= 2 && random->nextBool())) {
970        *stops = NULL;
971    }
972
973    SkScalar stop = 0.f;
974    for (int i = 0; i < outColors; ++i) {
975        colors[i] = random->nextU();
976        if (NULL != *stops) {
977            (*stops)[i] = stop;
978            stop = i < outColors - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
979        }
980    }
981    *tm = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
982
983    return outColors;
984}
985
986#endif
987