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.readUnitMapper();
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, colorCount);
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        SkImageInfo info;
517        info.fWidth = kCache32Count;
518        info.fHeight = 4;   // for our 4 dither rows
519        info.fAlphaType = kPremul_SkAlphaType;
520        info.fColorType = kPMColor_SkColorType;
521
522        if (NULL == fCache32PixelRef) {
523            fCache32PixelRef = SkMallocPixelRef::NewAllocate(info, 0, NULL);
524        }
525        fCache32 = (SkPMColor*)fCache32PixelRef->getAddr();
526        if (fColorCount == 2) {
527            Build32bitCache(fCache32, fOrigColors[0], fOrigColors[1],
528                            kCache32Count, fCacheAlpha, fGradFlags);
529        } else {
530            Rec* rec = fRecs;
531            int prevIndex = 0;
532            for (int i = 1; i < fColorCount; i++) {
533                int nextIndex = SkFixedToFFFF(rec[i].fPos) >> kCache32Shift;
534                SkASSERT(nextIndex < kCache32Count);
535
536                if (nextIndex > prevIndex)
537                    Build32bitCache(fCache32 + prevIndex, fOrigColors[i-1],
538                                    fOrigColors[i], nextIndex - prevIndex + 1,
539                                    fCacheAlpha, fGradFlags);
540                prevIndex = nextIndex;
541            }
542        }
543
544        if (fMapper) {
545            SkMallocPixelRef* newPR = SkMallocPixelRef::NewAllocate(info, 0, 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}
830
831GrGLGradientEffect::~GrGLGradientEffect() { }
832
833void 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");
840
841    } 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);
875}
876
877void GrGLGradientEffect::setData(const GrGLUniformManager& uman,
878                                 const GrDrawEffect& drawEffect) {
879
880    const GrGradientEffect& e = drawEffect.castEffect<GrGradientEffect>();
881
882
883    if (GrGradientEffect::kTwo_ColorType == e.getColorType()){
884
885        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
895        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 {
905
906        SkScalar yCoord = e.getYCoord();
907        if (yCoord != fCachedYCoord) {
908            uman.set1f(fFSYUni, yCoord);
909            fCachedYCoord = yCoord;
910        }
911    }
912}
913
914
915GrGLEffect::EffectKey GrGLGradientEffect::GenBaseGradientKey(const GrDrawEffect& drawEffect) {
916    const GrGradientEffect& e = drawEffect.castEffect<GrGradientEffect>();
917
918    EffectKey key = 0;
919
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;
931}
932
933void GrGLGradientEffect::emitColor(GrGLShaderBuilder* builder,
934                                   const char* gradientTValue,
935                                   EffectKey key,
936                                   const char* outputColor,
937                                   const char* inputColor,
938                                   const TextureSamplerArray& samplers) {
939    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        }
952
953        builder->fsCodeAppendf("\t%s = %s;\n", outputColor,
954                               (GrGLSLExpr4(inputColor) * GrGLSLExpr4("colorTemp")).c_str());
955    } else if (GrGradientEffect::kThree_ColorType == ColorTypeFromKey(key)){
956        builder->fsCodeAppendf("\tfloat oneMinus2t = 1.0 - (2.0 * (%s));\n",
957                               gradientTValue);
958        builder->fsCodeAppendf("\tvec4 colorTemp = clamp(oneMinus2t, 0.0, 1.0) * %s;\n",
959                               builder->getUniformVariable(fColorStartUni).c_str());
960        if (kTegra3_GrGLRenderer == builder->ctxInfo().renderer()) {
961            // The Tegra3 compiler will sometimes never return if we have
962            // min(abs(oneMinus2t), 1.0), or do the abs first in a separate expression.
963            builder->fsCodeAppend("\tfloat minAbs = abs(oneMinus2t);\n");
964            builder->fsCodeAppend("\tminAbs = minAbs > 1.0 ? 1.0 : minAbs;\n");
965            builder->fsCodeAppendf("\tcolorTemp += (1.0 - minAbs) * %s;\n",
966                                   builder->getUniformVariable(fColorMidUni).c_str());
967        } else {
968            builder->fsCodeAppendf("\tcolorTemp += (1.0 - min(abs(oneMinus2t), 1.0)) * %s;\n",
969                                   builder->getUniformVariable(fColorMidUni).c_str());
970        }
971        builder->fsCodeAppendf("\tcolorTemp += clamp(-oneMinus2t, 0.0, 1.0) * %s;\n",
972                               builder->getUniformVariable(fColorEndUni).c_str());
973        if (GrGradientEffect::kAfterInterp_PremulType == PremulTypeFromKey(key)) {
974            builder->fsCodeAppend("\tcolorTemp.rgb *= colorTemp.a;\n");
975        }
976
977        builder->fsCodeAppendf("\t%s = %s;\n", outputColor,
978                               (GrGLSLExpr4(inputColor) * GrGLSLExpr4("colorTemp")).c_str());
979    } else {
980        builder->fsCodeAppendf("\tvec2 coord = vec2(%s, %s);\n",
981                               gradientTValue,
982                               builder->getUniformVariable(fFSYUni).c_str());
983        builder->fsCodeAppendf("\t%s = ", outputColor);
984        builder->fsAppendTextureLookupAndModulate(inputColor,
985                                                  samplers[0],
986                                                  "coord");
987        builder->fsCodeAppend(";\n");
988    }
989}
990
991/////////////////////////////////////////////////////////////////////
992
993GrGradientEffect::GrGradientEffect(GrContext* ctx,
994                                   const SkGradientShaderBase& shader,
995                                   const SkMatrix& matrix,
996                                   SkShader::TileMode tileMode) {
997
998    fIsOpaque = shader.isOpaque();
999
1000    SkShader::GradientInfo info;
1001    SkScalar pos[3] = {0};
1002
1003    info.fColorCount = 3;
1004    info.fColors = &fColors[0];
1005    info.fColorOffsets = &pos[0];
1006    shader.asAGradient(&info);
1007
1008    // The two and three color specializations do not currently support tiling.
1009    bool foundSpecialCase = false;
1010    if (SkShader::kClamp_TileMode == info.fTileMode) {
1011        if (2 == info.fColorCount) {
1012            fRow = -1; // flag for no atlas
1013            fColorType = kTwo_ColorType;
1014            foundSpecialCase = true;
1015        } else if (3 == info.fColorCount &&
1016                   (SkScalarAbs(pos[1] - SK_ScalarHalf) < SK_Scalar1 / 1000)) { // 3 color symmetric
1017            fRow = -1; // flag for no atlas
1018            fColorType = kThree_ColorType;
1019            foundSpecialCase = true;
1020        }
1021    }
1022    if (foundSpecialCase) {
1023        if (SkGradientShader::kInterpolateColorsInPremul_Flag & info.fGradientFlags) {
1024            fPremulType = kBeforeInterp_PremulType;
1025        } else {
1026            fPremulType = kAfterInterp_PremulType;
1027        }
1028        fCoordTransform.reset(kCoordSet, matrix);
1029    } else {
1030        // doesn't matter how this is set, just be consistent because it is part of the effect key.
1031        fPremulType = kBeforeInterp_PremulType;
1032        SkBitmap bitmap;
1033        shader.getGradientTableBitmap(&bitmap);
1034        fColorType = kTexture_ColorType;
1035
1036        GrTextureStripAtlas::Desc desc;
1037        desc.fWidth  = bitmap.width();
1038        desc.fHeight = 32;
1039        desc.fRowHeight = bitmap.height();
1040        desc.fContext = ctx;
1041        desc.fConfig = SkBitmapConfig2GrPixelConfig(bitmap.config());
1042        fAtlas = GrTextureStripAtlas::GetAtlas(desc);
1043        SkASSERT(NULL != fAtlas);
1044
1045        // We always filter the gradient table. Each table is one row of a texture, always y-clamp.
1046        GrTextureParams params;
1047        params.setFilterMode(GrTextureParams::kBilerp_FilterMode);
1048        params.setTileModeX(tileMode);
1049
1050        fRow = fAtlas->lockRow(bitmap);
1051        if (-1 != fRow) {
1052            fYCoord = fAtlas->getYOffset(fRow) + SK_ScalarHalf *
1053            fAtlas->getVerticalScaleFactor();
1054            fCoordTransform.reset(kCoordSet, matrix, fAtlas->getTexture());
1055            fTextureAccess.reset(fAtlas->getTexture(), params);
1056        } else {
1057            GrTexture* texture = GrLockAndRefCachedBitmapTexture(ctx, bitmap, &params);
1058            fCoordTransform.reset(kCoordSet, matrix, texture);
1059            fTextureAccess.reset(texture, params);
1060            fYCoord = SK_ScalarHalf;
1061
1062            // Unlock immediately, this is not great, but we don't have a way of
1063            // knowing when else to unlock it currently, so it may get purged from
1064            // the cache, but it'll still be ref'd until it's no longer being used.
1065            GrUnlockAndUnrefCachedBitmapTexture(texture);
1066        }
1067        this->addTextureAccess(&fTextureAccess);
1068    }
1069    this->addCoordTransform(&fCoordTransform);
1070}
1071
1072GrGradientEffect::~GrGradientEffect() {
1073    if (this->useAtlas()) {
1074        fAtlas->unlockRow(fRow);
1075    }
1076}
1077
1078bool GrGradientEffect::onIsEqual(const GrEffect& effect) const {
1079    const GrGradientEffect& s = CastEffect<GrGradientEffect>(effect);
1080
1081    if (this->fColorType == s.getColorType()){
1082
1083        if (kTwo_ColorType == fColorType) {
1084            if (*this->getColors(0) != *s.getColors(0) ||
1085                *this->getColors(1) != *s.getColors(1)) {
1086                return false;
1087            }
1088        } else if (kThree_ColorType == fColorType) {
1089            if (*this->getColors(0) != *s.getColors(0) ||
1090                *this->getColors(1) != *s.getColors(1) ||
1091                *this->getColors(2) != *s.getColors(2)) {
1092                return false;
1093            }
1094        } else {
1095            if (fYCoord != s.getYCoord()) {
1096                return false;
1097            }
1098        }
1099
1100        return fTextureAccess.getTexture() == s.fTextureAccess.getTexture()  &&
1101            fTextureAccess.getParams().getTileModeX() ==
1102                s.fTextureAccess.getParams().getTileModeX() &&
1103            this->useAtlas() == s.useAtlas() &&
1104            fCoordTransform.getMatrix().cheapEqualTo(s.fCoordTransform.getMatrix());
1105    }
1106
1107    return false;
1108}
1109
1110void GrGradientEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const {
1111    if (fIsOpaque && (kA_GrColorComponentFlag & *validFlags) && 0xff == GrColorUnpackA(*color)) {
1112        *validFlags = kA_GrColorComponentFlag;
1113    } else {
1114        *validFlags = 0;
1115    }
1116}
1117
1118int GrGradientEffect::RandomGradientParams(SkRandom* random,
1119                                           SkColor colors[],
1120                                           SkScalar** stops,
1121                                           SkShader::TileMode* tm) {
1122    int outColors = random->nextRangeU(1, kMaxRandomGradientColors);
1123
1124    // if one color, omit stops, otherwise randomly decide whether or not to
1125    if (outColors == 1 || (outColors >= 2 && random->nextBool())) {
1126        *stops = NULL;
1127    }
1128
1129    SkScalar stop = 0.f;
1130    for (int i = 0; i < outColors; ++i) {
1131        colors[i] = random->nextU();
1132        if (NULL != *stops) {
1133            (*stops)[i] = stop;
1134            stop = i < outColors - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
1135        }
1136    }
1137    *tm = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
1138
1139    return outColors;
1140}
1141
1142#endif
1143