SkDraw.cpp revision 9ac6d8d9f16f8e1e523f677da4de5ebc9a2d8089
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#define __STDC_LIMIT_MACROS
8
9#include "SkDraw.h"
10#include "SkBlitter.h"
11#include "SkCanvas.h"
12#include "SkColorPriv.h"
13#include "SkDevice.h"
14#include "SkDeviceLooper.h"
15#include "SkFindAndPlaceGlyph.h"
16#include "SkFixed.h"
17#include "SkMaskFilter.h"
18#include "SkMatrix.h"
19#include "SkPaint.h"
20#include "SkPathEffect.h"
21#include "SkRasterClip.h"
22#include "SkRasterizer.h"
23#include "SkRRect.h"
24#include "SkScan.h"
25#include "SkShader.h"
26#include "SkSmallAllocator.h"
27#include "SkString.h"
28#include "SkStroke.h"
29#include "SkStrokeRec.h"
30#include "SkTemplates.h"
31#include "SkTextMapStateProc.h"
32#include "SkTLazy.h"
33#include "SkUtils.h"
34#include "SkVertState.h"
35#include "SkXfermode.h"
36
37#include "SkBitmapProcShader.h"
38#include "SkDrawProcs.h"
39#include "SkMatrixUtils.h"
40
41//#define TRACE_BITMAP_DRAWS
42
43// Helper function to fix code gen bug on ARM64.
44// See SkFindAndPlaceGlyph.h for more details.
45void FixGCC49Arm64Bug(int v) { }
46
47/** Helper for allocating small blitters on the stack.
48 */
49class SkAutoBlitterChoose : SkNoncopyable {
50public:
51    SkAutoBlitterChoose() {
52        fBlitter = nullptr;
53    }
54    SkAutoBlitterChoose(const SkPixmap& dst, const SkMatrix& matrix,
55                        const SkPaint& paint, bool drawCoverage = false) {
56        fBlitter = SkBlitter::Choose(dst, matrix, paint, &fAllocator, drawCoverage);
57    }
58
59    SkBlitter*  operator->() { return fBlitter; }
60    SkBlitter*  get() const { return fBlitter; }
61
62    void choose(const SkPixmap& dst, const SkMatrix& matrix,
63                const SkPaint& paint, bool drawCoverage = false) {
64        SkASSERT(!fBlitter);
65        fBlitter = SkBlitter::Choose(dst, matrix, paint, &fAllocator, drawCoverage);
66    }
67
68private:
69    // Owned by fAllocator, which will handle the delete.
70    SkBlitter*          fBlitter;
71    SkTBlitterAllocator fAllocator;
72};
73#define SkAutoBlitterChoose(...) SK_REQUIRE_LOCAL_VAR(SkAutoBlitterChoose)
74
75/**
76 *  Since we are providing the storage for the shader (to avoid the perf cost
77 *  of calling new) we insist that in our destructor we can account for all
78 *  owners of the shader.
79 */
80class SkAutoBitmapShaderInstall : SkNoncopyable {
81public:
82    SkAutoBitmapShaderInstall(const SkBitmap& src, const SkPaint& paint,
83                              const SkMatrix* localMatrix = nullptr)
84            : fPaint(paint) /* makes a copy of the paint */ {
85        fPaint.setShader(SkMakeBitmapShader(src, SkShader::kClamp_TileMode,
86                                            SkShader::kClamp_TileMode, localMatrix, &fAllocator));
87        // we deliberately left the shader with an owner-count of 2
88        fPaint.getShader()->ref();
89        SkASSERT(2 == fPaint.getShader()->getRefCnt());
90    }
91
92    ~SkAutoBitmapShaderInstall() {
93        // since fAllocator will destroy shader, we insist that owners == 2
94        SkASSERT(2 == fPaint.getShader()->getRefCnt());
95
96        fPaint.setShader(nullptr); // unref the shader by 1
97
98    }
99
100    // return the new paint that has the shader applied
101    const SkPaint& paintWithShader() const { return fPaint; }
102
103private:
104    // copy of caller's paint (which we then modify)
105    SkPaint             fPaint;
106    // Stores the shader.
107    SkTBlitterAllocator fAllocator;
108};
109#define SkAutoBitmapShaderInstall(...) SK_REQUIRE_LOCAL_VAR(SkAutoBitmapShaderInstall)
110
111///////////////////////////////////////////////////////////////////////////////
112
113SkDraw::SkDraw() {
114    sk_bzero(this, sizeof(*this));
115}
116
117bool SkDraw::computeConservativeLocalClipBounds(SkRect* localBounds) const {
118    if (fRC->isEmpty()) {
119        return false;
120    }
121
122    SkMatrix inverse;
123    if (!fMatrix->invert(&inverse)) {
124        return false;
125    }
126
127    SkIRect devBounds = fRC->getBounds();
128    // outset to have slop for antialasing and hairlines
129    devBounds.outset(1, 1);
130    inverse.mapRect(localBounds, SkRect::Make(devBounds));
131    return true;
132}
133
134///////////////////////////////////////////////////////////////////////////////
135
136typedef void (*BitmapXferProc)(void* pixels, size_t bytes, uint32_t data);
137
138static void D_Clear_BitmapXferProc(void* pixels, size_t bytes, uint32_t) {
139    sk_bzero(pixels, bytes);
140}
141
142static void D_Dst_BitmapXferProc(void*, size_t, uint32_t data) {}
143
144static void D32_Src_BitmapXferProc(void* pixels, size_t bytes, uint32_t data) {
145    sk_memset32((uint32_t*)pixels, data, SkToInt(bytes >> 2));
146}
147
148static void D16_Src_BitmapXferProc(void* pixels, size_t bytes, uint32_t data) {
149    sk_memset16((uint16_t*)pixels, data, SkToInt(bytes >> 1));
150}
151
152static void DA8_Src_BitmapXferProc(void* pixels, size_t bytes, uint32_t data) {
153    memset(pixels, data, bytes);
154}
155
156static BitmapXferProc ChooseBitmapXferProc(const SkPixmap& dst, const SkPaint& paint,
157                                           uint32_t* data) {
158    // todo: we can apply colorfilter up front if no shader, so we wouldn't
159    // need to abort this fastpath
160    if (paint.getShader() || paint.getColorFilter()) {
161        return nullptr;
162    }
163
164    SkXfermode::Mode mode;
165    if (!SkXfermode::AsMode(paint.getXfermode(), &mode)) {
166        return nullptr;
167    }
168
169    SkColor color = paint.getColor();
170
171    // collaps modes based on color...
172    if (SkXfermode::kSrcOver_Mode == mode) {
173        unsigned alpha = SkColorGetA(color);
174        if (0 == alpha) {
175            mode = SkXfermode::kDst_Mode;
176        } else if (0xFF == alpha) {
177            mode = SkXfermode::kSrc_Mode;
178        }
179    }
180
181    switch (mode) {
182        case SkXfermode::kClear_Mode:
183//            SkDebugf("--- D_Clear_BitmapXferProc\n");
184            return D_Clear_BitmapXferProc;  // ignore data
185        case SkXfermode::kDst_Mode:
186//            SkDebugf("--- D_Dst_BitmapXferProc\n");
187            return D_Dst_BitmapXferProc;    // ignore data
188        case SkXfermode::kSrc_Mode: {
189            /*
190                should I worry about dithering for the lower depths?
191            */
192            SkPMColor pmc = SkPreMultiplyColor(color);
193            switch (dst.colorType()) {
194                case kN32_SkColorType:
195                    if (data) {
196                        *data = pmc;
197                    }
198//                    SkDebugf("--- D32_Src_BitmapXferProc\n");
199                    return D32_Src_BitmapXferProc;
200                case kRGB_565_SkColorType:
201                    if (data) {
202                        *data = SkPixel32ToPixel16(pmc);
203                    }
204//                    SkDebugf("--- D16_Src_BitmapXferProc\n");
205                    return D16_Src_BitmapXferProc;
206                case kAlpha_8_SkColorType:
207                    if (data) {
208                        *data = SkGetPackedA32(pmc);
209                    }
210//                    SkDebugf("--- DA8_Src_BitmapXferProc\n");
211                    return DA8_Src_BitmapXferProc;
212                default:
213                    break;
214            }
215            break;
216        }
217        default:
218            break;
219    }
220    return nullptr;
221}
222
223static void CallBitmapXferProc(const SkPixmap& dst, const SkIRect& rect, BitmapXferProc proc,
224                               uint32_t procData) {
225    int shiftPerPixel;
226    switch (dst.colorType()) {
227        case kN32_SkColorType:
228            shiftPerPixel = 2;
229            break;
230        case kRGB_565_SkColorType:
231            shiftPerPixel = 1;
232            break;
233        case kAlpha_8_SkColorType:
234            shiftPerPixel = 0;
235            break;
236        default:
237            SkDEBUGFAIL("Can't use xferproc on this config");
238            return;
239    }
240
241    uint8_t* pixels = (uint8_t*)dst.writable_addr();
242    SkASSERT(pixels);
243    const size_t rowBytes = dst.rowBytes();
244    const int widthBytes = rect.width() << shiftPerPixel;
245
246    // skip down to the first scanline and X position
247    pixels += rect.fTop * rowBytes + (rect.fLeft << shiftPerPixel);
248    for (int scans = rect.height() - 1; scans >= 0; --scans) {
249        proc(pixels, widthBytes, procData);
250        pixels += rowBytes;
251    }
252}
253
254void SkDraw::drawPaint(const SkPaint& paint) const {
255    SkDEBUGCODE(this->validate();)
256
257    if (fRC->isEmpty()) {
258        return;
259    }
260
261    SkIRect    devRect;
262    devRect.set(0, 0, fDst.width(), fDst.height());
263
264    if (fRC->isBW()) {
265        /*  If we don't have a shader (i.e. we're just a solid color) we may
266            be faster to operate directly on the device bitmap, rather than invoking
267            a blitter. Esp. true for xfermodes, which require a colorshader to be
268            present, which is just redundant work. Since we're drawing everywhere
269            in the clip, we don't have to worry about antialiasing.
270        */
271        uint32_t procData = 0;  // to avoid the warning
272        BitmapXferProc proc = ChooseBitmapXferProc(fDst, paint, &procData);
273        if (proc) {
274            if (D_Dst_BitmapXferProc == proc) { // nothing to do
275                return;
276            }
277
278            SkRegion::Iterator iter(fRC->bwRgn());
279            while (!iter.done()) {
280                CallBitmapXferProc(fDst, iter.rect(), proc, procData);
281                iter.next();
282            }
283            return;
284        }
285    }
286
287    // normal case: use a blitter
288    SkAutoBlitterChoose blitter(fDst, *fMatrix, paint);
289    SkScan::FillIRect(devRect, *fRC, blitter.get());
290}
291
292///////////////////////////////////////////////////////////////////////////////
293
294struct PtProcRec {
295    SkCanvas::PointMode fMode;
296    const SkPaint*  fPaint;
297    const SkRegion* fClip;
298    const SkRasterClip* fRC;
299
300    // computed values
301    SkFixed fRadius;
302
303    typedef void (*Proc)(const PtProcRec&, const SkPoint devPts[], int count,
304                         SkBlitter*);
305
306    bool init(SkCanvas::PointMode, const SkPaint&, const SkMatrix* matrix,
307              const SkRasterClip*);
308    Proc chooseProc(SkBlitter** blitter);
309
310private:
311    SkAAClipBlitterWrapper fWrapper;
312};
313
314static void bw_pt_rect_hair_proc(const PtProcRec& rec, const SkPoint devPts[],
315                                 int count, SkBlitter* blitter) {
316    SkASSERT(rec.fClip->isRect());
317    const SkIRect& r = rec.fClip->getBounds();
318
319    for (int i = 0; i < count; i++) {
320        int x = SkScalarFloorToInt(devPts[i].fX);
321        int y = SkScalarFloorToInt(devPts[i].fY);
322        if (r.contains(x, y)) {
323            blitter->blitH(x, y, 1);
324        }
325    }
326}
327
328static void bw_pt_rect_16_hair_proc(const PtProcRec& rec,
329                                    const SkPoint devPts[], int count,
330                                    SkBlitter* blitter) {
331    SkASSERT(rec.fRC->isRect());
332    const SkIRect& r = rec.fRC->getBounds();
333    uint32_t value;
334    const SkPixmap* dst = blitter->justAnOpaqueColor(&value);
335    SkASSERT(dst);
336
337    uint16_t* addr = dst->writable_addr16(0, 0);
338    size_t    rb = dst->rowBytes();
339
340    for (int i = 0; i < count; i++) {
341        int x = SkScalarFloorToInt(devPts[i].fX);
342        int y = SkScalarFloorToInt(devPts[i].fY);
343        if (r.contains(x, y)) {
344            ((uint16_t*)((char*)addr + y * rb))[x] = SkToU16(value);
345        }
346    }
347}
348
349static void bw_pt_rect_32_hair_proc(const PtProcRec& rec,
350                                    const SkPoint devPts[], int count,
351                                    SkBlitter* blitter) {
352    SkASSERT(rec.fRC->isRect());
353    const SkIRect& r = rec.fRC->getBounds();
354    uint32_t value;
355    const SkPixmap* dst = blitter->justAnOpaqueColor(&value);
356    SkASSERT(dst);
357
358    SkPMColor* addr = dst->writable_addr32(0, 0);
359    size_t     rb = dst->rowBytes();
360
361    for (int i = 0; i < count; i++) {
362        int x = SkScalarFloorToInt(devPts[i].fX);
363        int y = SkScalarFloorToInt(devPts[i].fY);
364        if (r.contains(x, y)) {
365            ((SkPMColor*)((char*)addr + y * rb))[x] = value;
366        }
367    }
368}
369
370static void bw_pt_hair_proc(const PtProcRec& rec, const SkPoint devPts[],
371                            int count, SkBlitter* blitter) {
372    for (int i = 0; i < count; i++) {
373        int x = SkScalarFloorToInt(devPts[i].fX);
374        int y = SkScalarFloorToInt(devPts[i].fY);
375        if (rec.fClip->contains(x, y)) {
376            blitter->blitH(x, y, 1);
377        }
378    }
379}
380
381static void bw_line_hair_proc(const PtProcRec& rec, const SkPoint devPts[],
382                              int count, SkBlitter* blitter) {
383    for (int i = 0; i < count; i += 2) {
384        SkScan::HairLine(&devPts[i], 2, *rec.fRC, blitter);
385    }
386}
387
388static void bw_poly_hair_proc(const PtProcRec& rec, const SkPoint devPts[],
389                              int count, SkBlitter* blitter) {
390    SkScan::HairLine(devPts, count, *rec.fRC, blitter);
391}
392
393// aa versions
394
395static void aa_line_hair_proc(const PtProcRec& rec, const SkPoint devPts[],
396                              int count, SkBlitter* blitter) {
397    for (int i = 0; i < count; i += 2) {
398        SkScan::AntiHairLine(&devPts[i], 2, *rec.fRC, blitter);
399    }
400}
401
402static void aa_poly_hair_proc(const PtProcRec& rec, const SkPoint devPts[],
403                              int count, SkBlitter* blitter) {
404    SkScan::AntiHairLine(devPts, count, *rec.fRC, blitter);
405}
406
407// square procs (strokeWidth > 0 but matrix is square-scale (sx == sy)
408
409static void bw_square_proc(const PtProcRec& rec, const SkPoint devPts[],
410                           int count, SkBlitter* blitter) {
411    const SkFixed radius = rec.fRadius;
412    for (int i = 0; i < count; i++) {
413        SkFixed x = SkScalarToFixed(devPts[i].fX);
414        SkFixed y = SkScalarToFixed(devPts[i].fY);
415
416        SkXRect r;
417        r.fLeft = x - radius;
418        r.fTop = y - radius;
419        r.fRight = x + radius;
420        r.fBottom = y + radius;
421
422        SkScan::FillXRect(r, *rec.fRC, blitter);
423    }
424}
425
426static void aa_square_proc(const PtProcRec& rec, const SkPoint devPts[],
427                           int count, SkBlitter* blitter) {
428    const SkFixed radius = rec.fRadius;
429    for (int i = 0; i < count; i++) {
430        SkFixed x = SkScalarToFixed(devPts[i].fX);
431        SkFixed y = SkScalarToFixed(devPts[i].fY);
432
433        SkXRect r;
434        r.fLeft = x - radius;
435        r.fTop = y - radius;
436        r.fRight = x + radius;
437        r.fBottom = y + radius;
438
439        SkScan::AntiFillXRect(r, *rec.fRC, blitter);
440    }
441}
442
443// If this guy returns true, then chooseProc() must return a valid proc
444bool PtProcRec::init(SkCanvas::PointMode mode, const SkPaint& paint,
445                     const SkMatrix* matrix, const SkRasterClip* rc) {
446    if ((unsigned)mode > (unsigned)SkCanvas::kPolygon_PointMode) {
447        return false;
448    }
449
450    if (paint.getPathEffect()) {
451        return false;
452    }
453    SkScalar width = paint.getStrokeWidth();
454    if (0 == width) {
455        fMode = mode;
456        fPaint = &paint;
457        fClip = nullptr;
458        fRC = rc;
459        fRadius = SK_FixedHalf;
460        return true;
461    }
462    if (paint.getStrokeCap() != SkPaint::kRound_Cap &&
463        matrix->isScaleTranslate() && SkCanvas::kPoints_PointMode == mode) {
464        SkScalar sx = matrix->get(SkMatrix::kMScaleX);
465        SkScalar sy = matrix->get(SkMatrix::kMScaleY);
466        if (SkScalarNearlyZero(sx - sy)) {
467            if (sx < 0) {
468                sx = -sx;
469            }
470
471            fMode = mode;
472            fPaint = &paint;
473            fClip = nullptr;
474            fRC = rc;
475            fRadius = SkScalarToFixed(SkScalarMul(width, sx)) >> 1;
476            return true;
477        }
478    }
479    return false;
480}
481
482PtProcRec::Proc PtProcRec::chooseProc(SkBlitter** blitterPtr) {
483    Proc proc = nullptr;
484
485    SkBlitter* blitter = *blitterPtr;
486    if (fRC->isBW()) {
487        fClip = &fRC->bwRgn();
488    } else {
489        fWrapper.init(*fRC, blitter);
490        fClip = &fWrapper.getRgn();
491        blitter = fWrapper.getBlitter();
492        *blitterPtr = blitter;
493    }
494
495    // for our arrays
496    SkASSERT(0 == SkCanvas::kPoints_PointMode);
497    SkASSERT(1 == SkCanvas::kLines_PointMode);
498    SkASSERT(2 == SkCanvas::kPolygon_PointMode);
499    SkASSERT((unsigned)fMode <= (unsigned)SkCanvas::kPolygon_PointMode);
500
501    if (fPaint->isAntiAlias()) {
502        if (0 == fPaint->getStrokeWidth()) {
503            static const Proc gAAProcs[] = {
504                aa_square_proc, aa_line_hair_proc, aa_poly_hair_proc
505            };
506            proc = gAAProcs[fMode];
507        } else if (fPaint->getStrokeCap() != SkPaint::kRound_Cap) {
508            SkASSERT(SkCanvas::kPoints_PointMode == fMode);
509            proc = aa_square_proc;
510        }
511    } else {    // BW
512        if (fRadius <= SK_FixedHalf) {    // small radii and hairline
513            if (SkCanvas::kPoints_PointMode == fMode && fClip->isRect()) {
514                uint32_t value;
515                const SkPixmap* bm = blitter->justAnOpaqueColor(&value);
516                if (bm && kRGB_565_SkColorType == bm->colorType()) {
517                    proc = bw_pt_rect_16_hair_proc;
518                } else if (bm && kN32_SkColorType == bm->colorType()) {
519                    proc = bw_pt_rect_32_hair_proc;
520                } else {
521                    proc = bw_pt_rect_hair_proc;
522                }
523            } else {
524                static Proc gBWProcs[] = {
525                    bw_pt_hair_proc, bw_line_hair_proc, bw_poly_hair_proc
526                };
527                proc = gBWProcs[fMode];
528            }
529        } else {
530            proc = bw_square_proc;
531        }
532    }
533    return proc;
534}
535
536// each of these costs 8-bytes of stack space, so don't make it too large
537// must be even for lines/polygon to work
538#define MAX_DEV_PTS     32
539
540void SkDraw::drawPoints(SkCanvas::PointMode mode, size_t count,
541                        const SkPoint pts[], const SkPaint& paint,
542                        bool forceUseDevice) const {
543    // if we're in lines mode, force count to be even
544    if (SkCanvas::kLines_PointMode == mode) {
545        count &= ~(size_t)1;
546    }
547
548    if ((long)count <= 0) {
549        return;
550    }
551
552    SkASSERT(pts != nullptr);
553    SkDEBUGCODE(this->validate();)
554
555     // nothing to draw
556    if (fRC->isEmpty()) {
557        return;
558    }
559
560    PtProcRec rec;
561    if (!forceUseDevice && rec.init(mode, paint, fMatrix, fRC)) {
562        SkAutoBlitterChoose blitter(fDst, *fMatrix, paint);
563
564        SkPoint             devPts[MAX_DEV_PTS];
565        const SkMatrix*     matrix = fMatrix;
566        SkBlitter*          bltr = blitter.get();
567        PtProcRec::Proc     proc = rec.chooseProc(&bltr);
568        // we have to back up subsequent passes if we're in polygon mode
569        const size_t backup = (SkCanvas::kPolygon_PointMode == mode);
570
571        do {
572            int n = SkToInt(count);
573            if (n > MAX_DEV_PTS) {
574                n = MAX_DEV_PTS;
575            }
576            matrix->mapPoints(devPts, pts, n);
577            proc(rec, devPts, n, bltr);
578            pts += n - backup;
579            SkASSERT(SkToInt(count) >= n);
580            count -= n;
581            if (count > 0) {
582                count += backup;
583            }
584        } while (count != 0);
585    } else {
586        switch (mode) {
587            case SkCanvas::kPoints_PointMode: {
588                // temporarily mark the paint as filling.
589                SkPaint newPaint(paint);
590                newPaint.setStyle(SkPaint::kFill_Style);
591
592                SkScalar width = newPaint.getStrokeWidth();
593                SkScalar radius = SkScalarHalf(width);
594
595                if (newPaint.getStrokeCap() == SkPaint::kRound_Cap) {
596                    SkPath      path;
597                    SkMatrix    preMatrix;
598
599                    path.addCircle(0, 0, radius);
600                    for (size_t i = 0; i < count; i++) {
601                        preMatrix.setTranslate(pts[i].fX, pts[i].fY);
602                        // pass true for the last point, since we can modify
603                        // then path then
604                        path.setIsVolatile((count-1) == i);
605                        if (fDevice) {
606                            fDevice->drawPath(*this, path, newPaint, &preMatrix,
607                                              (count-1) == i);
608                        } else {
609                            this->drawPath(path, newPaint, &preMatrix,
610                                           (count-1) == i);
611                        }
612                    }
613                } else {
614                    SkRect  r;
615
616                    for (size_t i = 0; i < count; i++) {
617                        r.fLeft = pts[i].fX - radius;
618                        r.fTop = pts[i].fY - radius;
619                        r.fRight = r.fLeft + width;
620                        r.fBottom = r.fTop + width;
621                        if (fDevice) {
622                            fDevice->drawRect(*this, r, newPaint);
623                        } else {
624                            this->drawRect(r, newPaint);
625                        }
626                    }
627                }
628                break;
629            }
630            case SkCanvas::kLines_PointMode:
631                if (2 == count && paint.getPathEffect()) {
632                    // most likely a dashed line - see if it is one of the ones
633                    // we can accelerate
634                    SkStrokeRec rec(paint);
635                    SkPathEffect::PointData pointData;
636
637                    SkPath path;
638                    path.moveTo(pts[0]);
639                    path.lineTo(pts[1]);
640
641                    SkRect cullRect = SkRect::Make(fRC->getBounds());
642
643                    if (paint.getPathEffect()->asPoints(&pointData, path, rec,
644                                                        *fMatrix, &cullRect)) {
645                        // 'asPoints' managed to find some fast path
646
647                        SkPaint newP(paint);
648                        newP.setPathEffect(nullptr);
649                        newP.setStyle(SkPaint::kFill_Style);
650
651                        if (!pointData.fFirst.isEmpty()) {
652                            if (fDevice) {
653                                fDevice->drawPath(*this, pointData.fFirst, newP);
654                            } else {
655                                this->drawPath(pointData.fFirst, newP);
656                            }
657                        }
658
659                        if (!pointData.fLast.isEmpty()) {
660                            if (fDevice) {
661                                fDevice->drawPath(*this, pointData.fLast, newP);
662                            } else {
663                                this->drawPath(pointData.fLast, newP);
664                            }
665                        }
666
667                        if (pointData.fSize.fX == pointData.fSize.fY) {
668                            // The rest of the dashed line can just be drawn as points
669                            SkASSERT(pointData.fSize.fX == SkScalarHalf(newP.getStrokeWidth()));
670
671                            if (SkPathEffect::PointData::kCircles_PointFlag & pointData.fFlags) {
672                                newP.setStrokeCap(SkPaint::kRound_Cap);
673                            } else {
674                                newP.setStrokeCap(SkPaint::kButt_Cap);
675                            }
676
677                            if (fDevice) {
678                                fDevice->drawPoints(*this,
679                                                    SkCanvas::kPoints_PointMode,
680                                                    pointData.fNumPoints,
681                                                    pointData.fPoints,
682                                                    newP);
683                            } else {
684                                this->drawPoints(SkCanvas::kPoints_PointMode,
685                                                 pointData.fNumPoints,
686                                                 pointData.fPoints,
687                                                 newP,
688                                                 forceUseDevice);
689                            }
690                            break;
691                        } else {
692                            // The rest of the dashed line must be drawn as rects
693                            SkASSERT(!(SkPathEffect::PointData::kCircles_PointFlag &
694                                      pointData.fFlags));
695
696                            SkRect r;
697
698                            for (int i = 0; i < pointData.fNumPoints; ++i) {
699                                r.set(pointData.fPoints[i].fX - pointData.fSize.fX,
700                                      pointData.fPoints[i].fY - pointData.fSize.fY,
701                                      pointData.fPoints[i].fX + pointData.fSize.fX,
702                                      pointData.fPoints[i].fY + pointData.fSize.fY);
703                                if (fDevice) {
704                                    fDevice->drawRect(*this, r, newP);
705                                } else {
706                                    this->drawRect(r, newP);
707                                }
708                            }
709                        }
710
711                        break;
712                    }
713                }
714                // couldn't take fast path so fall through!
715            case SkCanvas::kPolygon_PointMode: {
716                count -= 1;
717                SkPath path;
718                SkPaint p(paint);
719                p.setStyle(SkPaint::kStroke_Style);
720                size_t inc = (SkCanvas::kLines_PointMode == mode) ? 2 : 1;
721                path.setIsVolatile(true);
722                for (size_t i = 0; i < count; i += inc) {
723                    path.moveTo(pts[i]);
724                    path.lineTo(pts[i+1]);
725                    if (fDevice) {
726                        fDevice->drawPath(*this, path, p, nullptr, true);
727                    } else {
728                        this->drawPath(path, p, nullptr, true);
729                    }
730                    path.rewind();
731                }
732                break;
733            }
734        }
735    }
736}
737
738static inline SkPoint compute_stroke_size(const SkPaint& paint, const SkMatrix& matrix) {
739    SkASSERT(matrix.rectStaysRect());
740    SkASSERT(SkPaint::kFill_Style != paint.getStyle());
741
742    SkVector size;
743    SkPoint pt = { paint.getStrokeWidth(), paint.getStrokeWidth() };
744    matrix.mapVectors(&size, &pt, 1);
745    return SkPoint::Make(SkScalarAbs(size.fX), SkScalarAbs(size.fY));
746}
747
748static bool easy_rect_join(const SkPaint& paint, const SkMatrix& matrix,
749                           SkPoint* strokeSize) {
750    if (SkPaint::kMiter_Join != paint.getStrokeJoin() ||
751        paint.getStrokeMiter() < SK_ScalarSqrt2) {
752        return false;
753    }
754
755    *strokeSize = compute_stroke_size(paint, matrix);
756    return true;
757}
758
759SkDraw::RectType SkDraw::ComputeRectType(const SkPaint& paint,
760                                         const SkMatrix& matrix,
761                                         SkPoint* strokeSize) {
762    RectType rtype;
763    const SkScalar width = paint.getStrokeWidth();
764    const bool zeroWidth = (0 == width);
765    SkPaint::Style style = paint.getStyle();
766
767    if ((SkPaint::kStrokeAndFill_Style == style) && zeroWidth) {
768        style = SkPaint::kFill_Style;
769    }
770
771    if (paint.getPathEffect() || paint.getMaskFilter() ||
772        paint.getRasterizer() || !matrix.rectStaysRect() ||
773        SkPaint::kStrokeAndFill_Style == style) {
774        rtype = kPath_RectType;
775    } else if (SkPaint::kFill_Style == style) {
776        rtype = kFill_RectType;
777    } else if (zeroWidth) {
778        rtype = kHair_RectType;
779    } else if (easy_rect_join(paint, matrix, strokeSize)) {
780        rtype = kStroke_RectType;
781    } else {
782        rtype = kPath_RectType;
783    }
784    return rtype;
785}
786
787static const SkPoint* rect_points(const SkRect& r) {
788    return SkTCast<const SkPoint*>(&r);
789}
790
791static SkPoint* rect_points(SkRect& r) {
792    return SkTCast<SkPoint*>(&r);
793}
794
795void SkDraw::drawRect(const SkRect& prePaintRect, const SkPaint& paint,
796                      const SkMatrix* paintMatrix, const SkRect* postPaintRect) const {
797    SkDEBUGCODE(this->validate();)
798
799    // nothing to draw
800    if (fRC->isEmpty()) {
801        return;
802    }
803
804    const SkMatrix* matrix;
805    SkMatrix combinedMatrixStorage;
806    if (paintMatrix) {
807        SkASSERT(postPaintRect);
808        combinedMatrixStorage.setConcat(*fMatrix, *paintMatrix);
809        matrix = &combinedMatrixStorage;
810    } else {
811        SkASSERT(!postPaintRect);
812        matrix = fMatrix;
813    }
814
815    SkPoint strokeSize;
816    RectType rtype = ComputeRectType(paint, *fMatrix, &strokeSize);
817
818    if (kPath_RectType == rtype) {
819        SkDraw draw(*this);
820        if (paintMatrix) {
821            draw.fMatrix = matrix;
822        }
823        SkPath  tmp;
824        tmp.addRect(prePaintRect);
825        tmp.setFillType(SkPath::kWinding_FillType);
826        draw.drawPath(tmp, paint, nullptr, true);
827        return;
828    }
829
830    SkRect devRect;
831    const SkRect& paintRect = paintMatrix ? *postPaintRect : prePaintRect;
832    // skip the paintMatrix when transforming the rect by the CTM
833    fMatrix->mapPoints(rect_points(devRect), rect_points(paintRect), 2);
834    devRect.sort();
835
836    // look for the quick exit, before we build a blitter
837    SkRect bbox = devRect;
838    if (paint.getStyle() != SkPaint::kFill_Style) {
839        // extra space for hairlines
840        if (paint.getStrokeWidth() == 0) {
841            bbox.outset(1, 1);
842        } else {
843            // For kStroke_RectType, strokeSize is already computed.
844            const SkPoint& ssize = (kStroke_RectType == rtype)
845                ? strokeSize
846                : compute_stroke_size(paint, *fMatrix);
847            bbox.outset(SkScalarHalf(ssize.x()), SkScalarHalf(ssize.y()));
848        }
849    }
850
851    SkIRect ir = bbox.roundOut();
852    if (fRC->quickReject(ir)) {
853        return;
854    }
855
856    SkDeviceLooper looper(fDst, *fRC, ir, paint.isAntiAlias());
857    while (looper.next()) {
858        SkRect localDevRect;
859        looper.mapRect(&localDevRect, devRect);
860        SkMatrix localMatrix;
861        looper.mapMatrix(&localMatrix, *matrix);
862
863        SkAutoBlitterChoose blitterStorage(looper.getPixmap(), localMatrix, paint);
864        const SkRasterClip& clip = looper.getRC();
865        SkBlitter*          blitter = blitterStorage.get();
866
867        // we want to "fill" if we are kFill or kStrokeAndFill, since in the latter
868        // case we are also hairline (if we've gotten to here), which devolves to
869        // effectively just kFill
870        switch (rtype) {
871            case kFill_RectType:
872                if (paint.isAntiAlias()) {
873                    SkScan::AntiFillRect(localDevRect, clip, blitter);
874                } else {
875                    SkScan::FillRect(localDevRect, clip, blitter);
876                }
877                break;
878            case kStroke_RectType:
879                if (paint.isAntiAlias()) {
880                    SkScan::AntiFrameRect(localDevRect, strokeSize, clip, blitter);
881                } else {
882                    SkScan::FrameRect(localDevRect, strokeSize, clip, blitter);
883                }
884                break;
885            case kHair_RectType:
886                if (paint.isAntiAlias()) {
887                    SkScan::AntiHairRect(localDevRect, clip, blitter);
888                } else {
889                    SkScan::HairRect(localDevRect, clip, blitter);
890                }
891                break;
892            default:
893                SkDEBUGFAIL("bad rtype");
894        }
895    }
896}
897
898void SkDraw::drawDevMask(const SkMask& srcM, const SkPaint& paint) const {
899    if (srcM.fBounds.isEmpty()) {
900        return;
901    }
902
903    const SkMask* mask = &srcM;
904
905    SkMask dstM;
906    if (paint.getMaskFilter() &&
907        paint.getMaskFilter()->filterMask(&dstM, srcM, *fMatrix, nullptr)) {
908        mask = &dstM;
909    }
910    SkAutoMaskFreeImage ami(dstM.fImage);
911
912    SkAutoBlitterChoose blitterChooser(fDst, *fMatrix, paint);
913    SkBlitter* blitter = blitterChooser.get();
914
915    SkAAClipBlitterWrapper wrapper;
916    const SkRegion* clipRgn;
917
918    if (fRC->isBW()) {
919        clipRgn = &fRC->bwRgn();
920    } else {
921        wrapper.init(*fRC, blitter);
922        clipRgn = &wrapper.getRgn();
923        blitter = wrapper.getBlitter();
924    }
925    blitter->blitMaskRegion(*mask, *clipRgn);
926}
927
928static SkScalar fast_len(const SkVector& vec) {
929    SkScalar x = SkScalarAbs(vec.fX);
930    SkScalar y = SkScalarAbs(vec.fY);
931    if (x < y) {
932        SkTSwap(x, y);
933    }
934    return x + SkScalarHalf(y);
935}
936
937bool SkDrawTreatAAStrokeAsHairline(SkScalar strokeWidth, const SkMatrix& matrix,
938                                   SkScalar* coverage) {
939    SkASSERT(strokeWidth > 0);
940    // We need to try to fake a thick-stroke with a modulated hairline.
941
942    if (matrix.hasPerspective()) {
943        return false;
944    }
945
946    SkVector src[2], dst[2];
947    src[0].set(strokeWidth, 0);
948    src[1].set(0, strokeWidth);
949    matrix.mapVectors(dst, src, 2);
950    SkScalar len0 = fast_len(dst[0]);
951    SkScalar len1 = fast_len(dst[1]);
952    if (len0 <= SK_Scalar1 && len1 <= SK_Scalar1) {
953        if (coverage) {
954            *coverage = SkScalarAve(len0, len1);
955        }
956        return true;
957    }
958    return false;
959}
960
961void SkDraw::drawRRect(const SkRRect& rrect, const SkPaint& paint) const {
962    SkDEBUGCODE(this->validate());
963
964    if (fRC->isEmpty()) {
965        return;
966    }
967
968    {
969        // TODO: Investigate optimizing these options. They are in the same
970        // order as SkDraw::drawPath, which handles each case. It may be
971        // that there is no way to optimize for these using the SkRRect path.
972        SkScalar coverage;
973        if (SkDrawTreatAsHairline(paint, *fMatrix, &coverage)) {
974            goto DRAW_PATH;
975        }
976
977        if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
978            goto DRAW_PATH;
979        }
980
981        if (paint.getRasterizer()) {
982            goto DRAW_PATH;
983        }
984    }
985
986    if (paint.getMaskFilter()) {
987        // Transform the rrect into device space.
988        SkRRect devRRect;
989        if (rrect.transform(*fMatrix, &devRRect)) {
990            SkAutoBlitterChoose blitter(fDst, *fMatrix, paint);
991            if (paint.getMaskFilter()->filterRRect(devRRect, *fMatrix, *fRC, blitter.get())) {
992                return; // filterRRect() called the blitter, so we're done
993            }
994        }
995    }
996
997DRAW_PATH:
998    // Now fall back to the default case of using a path.
999    SkPath path;
1000    path.addRRect(rrect);
1001    this->drawPath(path, paint, nullptr, true);
1002}
1003
1004SkScalar SkDraw::ComputeResScaleForStroking(const SkMatrix& matrix) {
1005    if (!matrix.hasPerspective()) {
1006        SkScalar sx = SkPoint::Length(matrix[SkMatrix::kMScaleX], matrix[SkMatrix::kMSkewY]);
1007        SkScalar sy = SkPoint::Length(matrix[SkMatrix::kMSkewX],  matrix[SkMatrix::kMScaleY]);
1008        if (SkScalarsAreFinite(sx, sy)) {
1009            SkScalar scale = SkTMax(sx, sy);
1010            if (scale > 0) {
1011                return scale;
1012            }
1013        }
1014    }
1015    return 1;
1016}
1017
1018void SkDraw::drawDevPath(const SkPath& devPath, const SkPaint& paint, bool drawCoverage,
1019                         SkBlitter* customBlitter, bool doFill) const {
1020    // Do a conservative quick-reject test, since a looper or other modifier may have moved us
1021    // out of range.
1022    if (!devPath.isInverseFillType()) {
1023        // If we're a H or V line, our bounds will be empty. So we bloat here just so we don't
1024        // appear empty to the intersects call. This also gives us slop in case we're antialiasing
1025        SkRect pathBounds = devPath.getBounds().makeOutset(1, 1);
1026
1027        if (paint.getMaskFilter()) {
1028            paint.getMaskFilter()->computeFastBounds(pathBounds, &pathBounds);
1029
1030            // Need to outset the path to work-around a bug in blurmaskfilter. When that is fixed
1031            // we can remove this hack. See skbug.com/5542
1032            pathBounds.outset(7, 7);
1033        }
1034
1035        // Now compare against the clip's bounds
1036        if (!SkRect::Make(fRC->getBounds()).intersects(pathBounds)) {
1037            return;
1038        }
1039    }
1040
1041    SkBlitter* blitter = nullptr;
1042    SkAutoBlitterChoose blitterStorage;
1043    if (nullptr == customBlitter) {
1044        blitterStorage.choose(fDst, *fMatrix, paint, drawCoverage);
1045        blitter = blitterStorage.get();
1046    } else {
1047        blitter = customBlitter;
1048    }
1049
1050    if (paint.getMaskFilter()) {
1051        SkStrokeRec::InitStyle style = doFill ? SkStrokeRec::kFill_InitStyle
1052        : SkStrokeRec::kHairline_InitStyle;
1053        if (paint.getMaskFilter()->filterPath(devPath, *fMatrix, *fRC, blitter, style)) {
1054            return; // filterPath() called the blitter, so we're done
1055        }
1056    }
1057
1058    void (*proc)(const SkPath&, const SkRasterClip&, SkBlitter*);
1059    if (doFill) {
1060        if (paint.isAntiAlias()) {
1061            proc = SkScan::AntiFillPath;
1062        } else {
1063            proc = SkScan::FillPath;
1064        }
1065    } else {    // hairline
1066        if (paint.isAntiAlias()) {
1067            switch (paint.getStrokeCap()) {
1068                case SkPaint::kButt_Cap:
1069                    proc = SkScan::AntiHairPath;
1070                    break;
1071                case SkPaint::kSquare_Cap:
1072                    proc = SkScan::AntiHairSquarePath;
1073                    break;
1074                case SkPaint::kRound_Cap:
1075                    proc = SkScan::AntiHairRoundPath;
1076                    break;
1077                default:
1078                    proc SK_INIT_TO_AVOID_WARNING;
1079                    SkDEBUGFAIL("unknown paint cap type");
1080            }
1081        } else {
1082            switch (paint.getStrokeCap()) {
1083                case SkPaint::kButt_Cap:
1084                    proc = SkScan::HairPath;
1085                    break;
1086                case SkPaint::kSquare_Cap:
1087                    proc = SkScan::HairSquarePath;
1088                    break;
1089                case SkPaint::kRound_Cap:
1090                    proc = SkScan::HairRoundPath;
1091                    break;
1092                default:
1093                    proc SK_INIT_TO_AVOID_WARNING;
1094                    SkDEBUGFAIL("unknown paint cap type");
1095            }
1096        }
1097    }
1098    proc(devPath, *fRC, blitter);
1099}
1100
1101void SkDraw::drawPath(const SkPath& origSrcPath, const SkPaint& origPaint,
1102                      const SkMatrix* prePathMatrix, bool pathIsMutable,
1103                      bool drawCoverage, SkBlitter* customBlitter) const {
1104    SkDEBUGCODE(this->validate();)
1105
1106    // nothing to draw
1107    if (fRC->isEmpty()) {
1108        return;
1109    }
1110
1111    SkPath*         pathPtr = (SkPath*)&origSrcPath;
1112    bool            doFill = true;
1113    SkPath          tmpPath;
1114    SkMatrix        tmpMatrix;
1115    const SkMatrix* matrix = fMatrix;
1116    tmpPath.setIsVolatile(true);
1117
1118    if (prePathMatrix) {
1119        if (origPaint.getPathEffect() || origPaint.getStyle() != SkPaint::kFill_Style ||
1120                origPaint.getRasterizer()) {
1121            SkPath* result = pathPtr;
1122
1123            if (!pathIsMutable) {
1124                result = &tmpPath;
1125                pathIsMutable = true;
1126            }
1127            pathPtr->transform(*prePathMatrix, result);
1128            pathPtr = result;
1129        } else {
1130            tmpMatrix.setConcat(*matrix, *prePathMatrix);
1131            matrix = &tmpMatrix;
1132        }
1133    }
1134    // at this point we're done with prePathMatrix
1135    SkDEBUGCODE(prePathMatrix = (const SkMatrix*)0x50FF8001;)
1136
1137    SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
1138
1139    {
1140        SkScalar coverage;
1141        if (SkDrawTreatAsHairline(origPaint, *matrix, &coverage)) {
1142            if (SK_Scalar1 == coverage) {
1143                paint.writable()->setStrokeWidth(0);
1144            } else if (SkXfermode::SupportsCoverageAsAlpha(origPaint.getXfermode())) {
1145                U8CPU newAlpha;
1146#if 0
1147                newAlpha = SkToU8(SkScalarRoundToInt(coverage *
1148                                                     origPaint.getAlpha()));
1149#else
1150                // this is the old technique, which we preserve for now so
1151                // we don't change previous results (testing)
1152                // the new way seems fine, its just (a tiny bit) different
1153                int scale = (int)SkScalarMul(coverage, 256);
1154                newAlpha = origPaint.getAlpha() * scale >> 8;
1155#endif
1156                SkPaint* writablePaint = paint.writable();
1157                writablePaint->setStrokeWidth(0);
1158                writablePaint->setAlpha(newAlpha);
1159            }
1160        }
1161    }
1162
1163    if (paint->getPathEffect() || paint->getStyle() != SkPaint::kFill_Style) {
1164        SkRect cullRect;
1165        const SkRect* cullRectPtr = nullptr;
1166        if (this->computeConservativeLocalClipBounds(&cullRect)) {
1167            cullRectPtr = &cullRect;
1168        }
1169        doFill = paint->getFillPath(*pathPtr, &tmpPath, cullRectPtr,
1170                                    ComputeResScaleForStroking(*fMatrix));
1171        pathPtr = &tmpPath;
1172    }
1173
1174    if (paint->getRasterizer()) {
1175        SkMask  mask;
1176        if (paint->getRasterizer()->rasterize(*pathPtr, *matrix,
1177                            &fRC->getBounds(), paint->getMaskFilter(), &mask,
1178                            SkMask::kComputeBoundsAndRenderImage_CreateMode)) {
1179            this->drawDevMask(mask, *paint);
1180            SkMask::FreeImage(mask.fImage);
1181        }
1182        return;
1183    }
1184
1185    // avoid possibly allocating a new path in transform if we can
1186    SkPath* devPathPtr = pathIsMutable ? pathPtr : &tmpPath;
1187
1188    // transform the path into device space
1189    pathPtr->transform(*matrix, devPathPtr);
1190
1191    this->drawDevPath(*devPathPtr, *paint, drawCoverage, customBlitter, doFill);
1192}
1193
1194void SkDraw::drawBitmapAsMask(const SkBitmap& bitmap, const SkPaint& paint) const {
1195    SkASSERT(bitmap.colorType() == kAlpha_8_SkColorType);
1196
1197    if (SkTreatAsSprite(*fMatrix, bitmap.dimensions(), paint)) {
1198        int ix = SkScalarRoundToInt(fMatrix->getTranslateX());
1199        int iy = SkScalarRoundToInt(fMatrix->getTranslateY());
1200
1201        SkAutoPixmapUnlock result;
1202        if (!bitmap.requestLock(&result)) {
1203            return;
1204        }
1205        const SkPixmap& pmap = result.pixmap();
1206        SkMask  mask;
1207        mask.fBounds.set(ix, iy, ix + pmap.width(), iy + pmap.height());
1208        mask.fFormat = SkMask::kA8_Format;
1209        mask.fRowBytes = SkToU32(pmap.rowBytes());
1210        // fImage is typed as writable, but in this case it is used read-only
1211        mask.fImage = (uint8_t*)pmap.addr8(0, 0);
1212
1213        this->drawDevMask(mask, paint);
1214    } else {    // need to xform the bitmap first
1215        SkRect  r;
1216        SkMask  mask;
1217
1218        r.set(0, 0,
1219              SkIntToScalar(bitmap.width()), SkIntToScalar(bitmap.height()));
1220        fMatrix->mapRect(&r);
1221        r.round(&mask.fBounds);
1222
1223        // set the mask's bounds to the transformed bitmap-bounds,
1224        // clipped to the actual device
1225        {
1226            SkIRect    devBounds;
1227            devBounds.set(0, 0, fDst.width(), fDst.height());
1228            // need intersect(l, t, r, b) on irect
1229            if (!mask.fBounds.intersect(devBounds)) {
1230                return;
1231            }
1232        }
1233
1234        mask.fFormat = SkMask::kA8_Format;
1235        mask.fRowBytes = SkAlign4(mask.fBounds.width());
1236        size_t size = mask.computeImageSize();
1237        if (0 == size) {
1238            // the mask is too big to allocated, draw nothing
1239            return;
1240        }
1241
1242        // allocate (and clear) our temp buffer to hold the transformed bitmap
1243        SkAutoTMalloc<uint8_t> storage(size);
1244        mask.fImage = storage.get();
1245        memset(mask.fImage, 0, size);
1246
1247        // now draw our bitmap(src) into mask(dst), transformed by the matrix
1248        {
1249            SkBitmap    device;
1250            device.installPixels(SkImageInfo::MakeA8(mask.fBounds.width(), mask.fBounds.height()),
1251                                 mask.fImage, mask.fRowBytes);
1252
1253            SkCanvas c(device);
1254            // need the unclipped top/left for the translate
1255            c.translate(-SkIntToScalar(mask.fBounds.fLeft),
1256                        -SkIntToScalar(mask.fBounds.fTop));
1257            c.concat(*fMatrix);
1258
1259            // We can't call drawBitmap, or we'll infinitely recurse. Instead
1260            // we manually build a shader and draw that into our new mask
1261            SkPaint tmpPaint;
1262            tmpPaint.setFlags(paint.getFlags());
1263            tmpPaint.setFilterQuality(paint.getFilterQuality());
1264            SkAutoBitmapShaderInstall install(bitmap, tmpPaint);
1265            SkRect rr;
1266            rr.set(0, 0, SkIntToScalar(bitmap.width()),
1267                   SkIntToScalar(bitmap.height()));
1268            c.drawRect(rr, install.paintWithShader());
1269        }
1270        this->drawDevMask(mask, paint);
1271    }
1272}
1273
1274static bool clipped_out(const SkMatrix& m, const SkRasterClip& c,
1275                        const SkRect& srcR) {
1276    SkRect  dstR;
1277    m.mapRect(&dstR, srcR);
1278    return c.quickReject(dstR.roundOut());
1279}
1280
1281static bool clipped_out(const SkMatrix& matrix, const SkRasterClip& clip,
1282                        int width, int height) {
1283    SkRect  r;
1284    r.set(0, 0, SkIntToScalar(width), SkIntToScalar(height));
1285    return clipped_out(matrix, clip, r);
1286}
1287
1288static bool clipHandlesSprite(const SkRasterClip& clip, int x, int y, const SkPixmap& pmap) {
1289    return clip.isBW() || clip.quickContains(x, y, x + pmap.width(), y + pmap.height());
1290}
1291
1292void SkDraw::drawBitmap(const SkBitmap& bitmap, const SkMatrix& prematrix,
1293                        const SkRect* dstBounds, const SkPaint& origPaint) const {
1294    SkDEBUGCODE(this->validate();)
1295
1296    // nothing to draw
1297    if (fRC->isEmpty() ||
1298            bitmap.width() == 0 || bitmap.height() == 0 ||
1299            bitmap.colorType() == kUnknown_SkColorType) {
1300        return;
1301    }
1302
1303    SkPaint paint(origPaint);
1304    paint.setStyle(SkPaint::kFill_Style);
1305
1306    SkMatrix matrix;
1307    matrix.setConcat(*fMatrix, prematrix);
1308
1309    if (clipped_out(matrix, *fRC, bitmap.width(), bitmap.height())) {
1310        return;
1311    }
1312
1313    if (bitmap.colorType() != kAlpha_8_SkColorType
1314        && SkTreatAsSprite(matrix, bitmap.dimensions(), paint)) {
1315        //
1316        // It is safe to call lock pixels now, since we know the matrix is
1317        // (more or less) identity.
1318        //
1319        SkAutoPixmapUnlock unlocker;
1320        if (!bitmap.requestLock(&unlocker)) {
1321            return;
1322        }
1323        const SkPixmap& pmap = unlocker.pixmap();
1324        int ix = SkScalarRoundToInt(matrix.getTranslateX());
1325        int iy = SkScalarRoundToInt(matrix.getTranslateY());
1326        if (clipHandlesSprite(*fRC, ix, iy, pmap)) {
1327            SkTBlitterAllocator allocator;
1328            // blitter will be owned by the allocator.
1329            SkBlitter* blitter = SkBlitter::ChooseSprite(fDst, paint, pmap, ix, iy, &allocator);
1330            if (blitter) {
1331                SkScan::FillIRect(SkIRect::MakeXYWH(ix, iy, pmap.width(), pmap.height()),
1332                                  *fRC, blitter);
1333                return;
1334            }
1335            // if !blitter, then we fall-through to the slower case
1336        }
1337    }
1338
1339    // now make a temp draw on the stack, and use it
1340    //
1341    SkDraw draw(*this);
1342    draw.fMatrix = &matrix;
1343
1344    if (bitmap.colorType() == kAlpha_8_SkColorType) {
1345        draw.drawBitmapAsMask(bitmap, paint);
1346    } else {
1347        SkAutoBitmapShaderInstall install(bitmap, paint);
1348        const SkPaint& paintWithShader = install.paintWithShader();
1349        const SkRect srcBounds = SkRect::MakeIWH(bitmap.width(), bitmap.height());
1350        if (dstBounds) {
1351            this->drawRect(srcBounds, paintWithShader, &prematrix, dstBounds);
1352        } else {
1353            draw.drawRect(srcBounds, paintWithShader);
1354        }
1355    }
1356}
1357
1358void SkDraw::drawSprite(const SkBitmap& bitmap, int x, int y, const SkPaint& origPaint) const {
1359    SkDEBUGCODE(this->validate();)
1360
1361    // nothing to draw
1362    if (fRC->isEmpty() ||
1363            bitmap.width() == 0 || bitmap.height() == 0 ||
1364            bitmap.colorType() == kUnknown_SkColorType) {
1365        return;
1366    }
1367
1368    const SkIRect bounds = SkIRect::MakeXYWH(x, y, bitmap.width(), bitmap.height());
1369
1370    if (fRC->quickReject(bounds)) {
1371        return; // nothing to draw
1372    }
1373
1374    SkPaint paint(origPaint);
1375    paint.setStyle(SkPaint::kFill_Style);
1376
1377    SkAutoPixmapUnlock unlocker;
1378    if (!bitmap.requestLock(&unlocker)) {
1379        return;
1380    }
1381    const SkPixmap& pmap = unlocker.pixmap();
1382
1383    if (nullptr == paint.getColorFilter() && clipHandlesSprite(*fRC, x, y, pmap)) {
1384        SkTBlitterAllocator allocator;
1385        // blitter will be owned by the allocator.
1386        SkBlitter* blitter = SkBlitter::ChooseSprite(fDst, paint, pmap, x, y, &allocator);
1387        if (blitter) {
1388            SkScan::FillIRect(bounds, *fRC, blitter);
1389            return;
1390        }
1391    }
1392
1393    SkMatrix        matrix;
1394    SkRect          r;
1395
1396    // get a scalar version of our rect
1397    r.set(bounds);
1398
1399    // create shader with offset
1400    matrix.setTranslate(r.fLeft, r.fTop);
1401    SkAutoBitmapShaderInstall install(bitmap, paint, &matrix);
1402    const SkPaint& shaderPaint = install.paintWithShader();
1403
1404    SkDraw draw(*this);
1405    matrix.reset();
1406    draw.fMatrix = &matrix;
1407    // call ourself with a rect
1408    // is this OK if paint has a rasterizer?
1409    draw.drawRect(r, shaderPaint);
1410}
1411
1412///////////////////////////////////////////////////////////////////////////////
1413
1414#include "SkScalerContext.h"
1415#include "SkGlyphCache.h"
1416#include "SkTextToPathIter.h"
1417#include "SkUtils.h"
1418
1419bool SkDraw::ShouldDrawTextAsPaths(const SkPaint& paint, const SkMatrix& ctm) {
1420    // hairline glyphs are fast enough so we don't need to cache them
1421    if (SkPaint::kStroke_Style == paint.getStyle() && 0 == paint.getStrokeWidth()) {
1422        return true;
1423    }
1424
1425    // we don't cache perspective
1426    if (ctm.hasPerspective()) {
1427        return true;
1428    }
1429
1430    SkMatrix textM;
1431    return SkPaint::TooBigToUseCache(ctm, *paint.setTextMatrix(&textM));
1432}
1433
1434void SkDraw::drawText_asPaths(const char text[], size_t byteLength,
1435                              SkScalar x, SkScalar y,
1436                              const SkPaint& paint) const {
1437    SkDEBUGCODE(this->validate();)
1438
1439    SkTextToPathIter iter(text, byteLength, paint, true);
1440
1441    SkMatrix    matrix;
1442    matrix.setScale(iter.getPathScale(), iter.getPathScale());
1443    matrix.postTranslate(x, y);
1444
1445    const SkPath* iterPath;
1446    SkScalar xpos, prevXPos = 0;
1447
1448    while (iter.next(&iterPath, &xpos)) {
1449        matrix.postTranslate(xpos - prevXPos, 0);
1450        if (iterPath) {
1451            const SkPaint& pnt = iter.getPaint();
1452            if (fDevice) {
1453                fDevice->drawPath(*this, *iterPath, pnt, &matrix, false);
1454            } else {
1455                this->drawPath(*iterPath, pnt, &matrix, false);
1456            }
1457        }
1458        prevXPos = xpos;
1459    }
1460}
1461
1462// disable warning : local variable used without having been initialized
1463#if defined _WIN32
1464#pragma warning ( push )
1465#pragma warning ( disable : 4701 )
1466#endif
1467
1468////////////////////////////////////////////////////////////////////////////////////////////////////
1469
1470class DrawOneGlyph {
1471public:
1472    DrawOneGlyph(const SkDraw& draw, const SkPaint& paint, SkGlyphCache* cache, SkBlitter* blitter)
1473        : fUseRegionToDraw(UsingRegionToDraw(draw.fRC))
1474        , fGlyphCache(cache)
1475        , fBlitter(blitter)
1476        , fClip(fUseRegionToDraw ? &draw.fRC->bwRgn() : nullptr)
1477        , fDraw(draw)
1478        , fPaint(paint)
1479        , fClipBounds(PickClipBounds(draw)) { }
1480
1481    void operator()(const SkGlyph& glyph, SkPoint position, SkPoint rounding) {
1482        position += rounding;
1483        // Prevent glyphs from being drawn outside of or straddling the edge of device space.
1484        // Comparisons written a little weirdly so that NaN coordinates are treated safely.
1485        auto gt = [](float a, int b) { return !(a <= (float)b); };
1486        auto lt = [](float a, int b) { return !(a >= (float)b); };
1487        if (gt(position.fX, INT_MAX - (INT16_MAX + UINT16_MAX)) ||
1488            lt(position.fX, INT_MIN - (INT16_MIN + 0 /*UINT16_MIN*/)) ||
1489            gt(position.fY, INT_MAX - (INT16_MAX + UINT16_MAX)) ||
1490            lt(position.fY, INT_MIN - (INT16_MIN + 0 /*UINT16_MIN*/))) {
1491            return;
1492        }
1493
1494        int left = SkScalarFloorToInt(position.fX);
1495        int top  = SkScalarFloorToInt(position.fY);
1496        SkASSERT(glyph.fWidth > 0 && glyph.fHeight > 0);
1497
1498        left += glyph.fLeft;
1499        top  += glyph.fTop;
1500
1501        int right   = left + glyph.fWidth;
1502        int bottom  = top  + glyph.fHeight;
1503
1504        SkMask mask;
1505        mask.fBounds.set(left, top, right, bottom);
1506        SkASSERT(!mask.fBounds.isEmpty());
1507
1508        if (fUseRegionToDraw) {
1509            SkRegion::Cliperator clipper(*fClip, mask.fBounds);
1510
1511            if (!clipper.done() && this->getImageData(glyph, &mask)) {
1512                const SkIRect& cr = clipper.rect();
1513                do {
1514                    this->blitMask(mask, cr);
1515                    clipper.next();
1516                } while (!clipper.done());
1517            }
1518        } else {
1519            SkIRect  storage;
1520            SkIRect* bounds = &mask.fBounds;
1521
1522            // this extra test is worth it, assuming that most of the time it succeeds
1523            // since we can avoid writing to storage
1524            if (!fClipBounds.containsNoEmptyCheck(mask.fBounds)) {
1525                if (!storage.intersectNoEmptyCheck(mask.fBounds, fClipBounds))
1526                    return;
1527                bounds = &storage;
1528            }
1529
1530            if (this->getImageData(glyph, &mask)) {
1531                this->blitMask(mask, *bounds);
1532            }
1533        }
1534    }
1535
1536private:
1537    static bool UsingRegionToDraw(const SkRasterClip* rClip) {
1538        return rClip->isBW() && !rClip->isRect();
1539    }
1540
1541    static SkIRect PickClipBounds(const SkDraw& draw) {
1542        const SkRasterClip& rasterClip = *draw.fRC;
1543
1544        if (rasterClip.isBW()) {
1545            return rasterClip.bwRgn().getBounds();
1546        } else {
1547            return rasterClip.aaRgn().getBounds();
1548        }
1549    }
1550
1551    bool getImageData(const SkGlyph& glyph, SkMask* mask) {
1552        uint8_t* bits = (uint8_t*)(fGlyphCache->findImage(glyph));
1553        if (nullptr == bits) {
1554            return false;  // can't rasterize glyph
1555        }
1556        mask->fImage    = bits;
1557        mask->fRowBytes = glyph.rowBytes();
1558        mask->fFormat   = static_cast<SkMask::Format>(glyph.fMaskFormat);
1559        return true;
1560    }
1561
1562    void blitMask(const SkMask& mask, const SkIRect& clip) const {
1563        if (SkMask::kARGB32_Format == mask.fFormat) {
1564            SkBitmap bm;
1565            bm.installPixels(
1566                SkImageInfo::MakeN32Premul(mask.fBounds.width(), mask.fBounds.height()),
1567                (SkPMColor*)mask.fImage, mask.fRowBytes);
1568
1569            fDraw.drawSprite(bm, mask.fBounds.x(), mask.fBounds.y(), fPaint);
1570        } else {
1571            fBlitter->blitMask(mask, clip);
1572        }
1573    }
1574
1575    const bool            fUseRegionToDraw;
1576    SkGlyphCache  * const fGlyphCache;
1577    SkBlitter     * const fBlitter;
1578    const SkRegion* const fClip;
1579    const SkDraw&         fDraw;
1580    const SkPaint&        fPaint;
1581    const SkIRect         fClipBounds;
1582};
1583
1584////////////////////////////////////////////////////////////////////////////////////////////////////
1585
1586uint32_t SkDraw::scalerContextFlags() const {
1587    uint32_t flags = SkPaint::kBoostContrast_ScalerContextFlag;
1588    if (!SkImageInfoIsGammaCorrect(fDevice->imageInfo())) {
1589        flags |= SkPaint::kFakeGamma_ScalerContextFlag;
1590    }
1591    return flags;
1592}
1593
1594void SkDraw::drawText(const char text[], size_t byteLength,
1595                      SkScalar x, SkScalar y, const SkPaint& paint) const {
1596    SkASSERT(byteLength == 0 || text != nullptr);
1597
1598    SkDEBUGCODE(this->validate();)
1599
1600    // nothing to draw
1601    if (text == nullptr || byteLength == 0 || fRC->isEmpty()) {
1602        return;
1603    }
1604
1605    // SkScalarRec doesn't currently have a way of representing hairline stroke and
1606    // will fill if its frame-width is 0.
1607    if (ShouldDrawTextAsPaths(paint, *fMatrix)) {
1608        this->drawText_asPaths(text, byteLength, x, y, paint);
1609        return;
1610    }
1611
1612    SkAutoGlyphCache cache(paint, &fDevice->surfaceProps(), this->scalerContextFlags(), fMatrix);
1613
1614    // The Blitter Choose needs to be live while using the blitter below.
1615    SkAutoBlitterChoose    blitterChooser(fDst, *fMatrix, paint);
1616    SkAAClipBlitterWrapper wrapper(*fRC, blitterChooser.get());
1617    DrawOneGlyph           drawOneGlyph(*this, paint, cache.get(), wrapper.getBlitter());
1618
1619    SkFindAndPlaceGlyph::ProcessText(
1620        paint.getTextEncoding(), text, byteLength,
1621        {x, y}, *fMatrix, paint.getTextAlign(), cache.get(), drawOneGlyph);
1622}
1623
1624//////////////////////////////////////////////////////////////////////////////
1625
1626void SkDraw::drawPosText_asPaths(const char text[], size_t byteLength,
1627                                 const SkScalar pos[], int scalarsPerPosition,
1628                                 const SkPoint& offset, const SkPaint& origPaint) const {
1629    // setup our std paint, in hopes of getting hits in the cache
1630    SkPaint paint(origPaint);
1631    SkScalar matrixScale = paint.setupForAsPaths();
1632
1633    SkMatrix matrix;
1634    matrix.setScale(matrixScale, matrixScale);
1635
1636    // Temporarily jam in kFill, so we only ever ask for the raw outline from the cache.
1637    paint.setStyle(SkPaint::kFill_Style);
1638    paint.setPathEffect(nullptr);
1639
1640    SkPaint::GlyphCacheProc glyphCacheProc = SkPaint::GetGlyphCacheProc(paint.getTextEncoding(),
1641                                                                        paint.isDevKernText(),
1642                                                                        true);
1643    SkAutoGlyphCache cache(paint, &fDevice->surfaceProps(), this->scalerContextFlags(), nullptr);
1644
1645    const char*        stop = text + byteLength;
1646    SkTextAlignProc    alignProc(paint.getTextAlign());
1647    SkTextMapStateProc tmsProc(SkMatrix::I(), offset, scalarsPerPosition);
1648
1649    // Now restore the original settings, so we "draw" with whatever style/stroking.
1650    paint.setStyle(origPaint.getStyle());
1651    paint.setPathEffect(sk_ref_sp(origPaint.getPathEffect()));
1652
1653    while (text < stop) {
1654        const SkGlyph& glyph = glyphCacheProc(cache.get(), &text);
1655        if (glyph.fWidth) {
1656            const SkPath* path = cache->findPath(glyph);
1657            if (path) {
1658                SkPoint tmsLoc;
1659                tmsProc(pos, &tmsLoc);
1660                SkPoint loc;
1661                alignProc(tmsLoc, glyph, &loc);
1662
1663                matrix[SkMatrix::kMTransX] = loc.fX;
1664                matrix[SkMatrix::kMTransY] = loc.fY;
1665                if (fDevice) {
1666                    fDevice->drawPath(*this, *path, paint, &matrix, false);
1667                } else {
1668                    this->drawPath(*path, paint, &matrix, false);
1669                }
1670            }
1671        }
1672        pos += scalarsPerPosition;
1673    }
1674}
1675
1676void SkDraw::drawPosText(const char text[], size_t byteLength,
1677                         const SkScalar pos[], int scalarsPerPosition,
1678                         const SkPoint& offset, const SkPaint& paint) const {
1679    SkASSERT(byteLength == 0 || text != nullptr);
1680    SkASSERT(1 == scalarsPerPosition || 2 == scalarsPerPosition);
1681
1682    SkDEBUGCODE(this->validate();)
1683
1684    // nothing to draw
1685    if (text == nullptr || byteLength == 0 || fRC->isEmpty()) {
1686        return;
1687    }
1688
1689    if (ShouldDrawTextAsPaths(paint, *fMatrix)) {
1690        this->drawPosText_asPaths(text, byteLength, pos, scalarsPerPosition, offset, paint);
1691        return;
1692    }
1693
1694    SkAutoGlyphCache cache(paint, &fDevice->surfaceProps(), this->scalerContextFlags(), fMatrix);
1695
1696    // The Blitter Choose needs to be live while using the blitter below.
1697    SkAutoBlitterChoose    blitterChooser(fDst, *fMatrix, paint);
1698    SkAAClipBlitterWrapper wrapper(*fRC, blitterChooser.get());
1699    DrawOneGlyph           drawOneGlyph(*this, paint, cache.get(), wrapper.getBlitter());
1700    SkPaint::Align         textAlignment = paint.getTextAlign();
1701
1702    SkFindAndPlaceGlyph::ProcessPosText(
1703        paint.getTextEncoding(), text, byteLength,
1704        offset, *fMatrix, pos, scalarsPerPosition, textAlignment, cache.get(), drawOneGlyph);
1705}
1706
1707#if defined _WIN32
1708#pragma warning ( pop )
1709#endif
1710
1711///////////////////////////////////////////////////////////////////////////////
1712
1713static SkScan::HairRCProc ChooseHairProc(bool doAntiAlias) {
1714    return doAntiAlias ? SkScan::AntiHairLine : SkScan::HairLine;
1715}
1716
1717static bool texture_to_matrix(const VertState& state, const SkPoint verts[],
1718                              const SkPoint texs[], SkMatrix* matrix) {
1719    SkPoint src[3], dst[3];
1720
1721    src[0] = texs[state.f0];
1722    src[1] = texs[state.f1];
1723    src[2] = texs[state.f2];
1724    dst[0] = verts[state.f0];
1725    dst[1] = verts[state.f1];
1726    dst[2] = verts[state.f2];
1727    return matrix->setPolyToPoly(src, dst, 3);
1728}
1729
1730class SkTriColorShader : public SkShader {
1731public:
1732    SkTriColorShader();
1733
1734    class TriColorShaderContext : public SkShader::Context {
1735    public:
1736        TriColorShaderContext(const SkTriColorShader& shader, const ContextRec&);
1737        virtual ~TriColorShaderContext();
1738        void shadeSpan(int x, int y, SkPMColor dstC[], int count) override;
1739
1740    private:
1741        bool setup(const SkPoint pts[], const SkColor colors[], int, int, int);
1742
1743        SkMatrix    fDstToUnit;
1744        SkPMColor   fColors[3];
1745        bool fSetup;
1746
1747        typedef SkShader::Context INHERITED;
1748    };
1749
1750    struct TriColorShaderData {
1751        const SkPoint* pts;
1752        const SkColor* colors;
1753        const VertState *state;
1754    };
1755
1756    SK_TO_STRING_OVERRIDE()
1757
1758    // For serialization.  This will never be called.
1759    Factory getFactory() const override { sk_throw(); return nullptr; }
1760
1761    // Supply setup data to context from drawing setup
1762    void bindSetupData(TriColorShaderData* setupData) { fSetupData = setupData; }
1763
1764    // Take the setup data from context when needed.
1765    TriColorShaderData* takeSetupData() {
1766        TriColorShaderData *data = fSetupData;
1767        fSetupData = NULL;
1768        return data;
1769    }
1770
1771protected:
1772    size_t onContextSize(const ContextRec&) const override;
1773    Context* onCreateContext(const ContextRec& rec, void* storage) const override {
1774        return new (storage) TriColorShaderContext(*this, rec);
1775    }
1776
1777private:
1778    TriColorShaderData *fSetupData;
1779
1780    typedef SkShader INHERITED;
1781};
1782
1783bool SkTriColorShader::TriColorShaderContext::setup(const SkPoint pts[], const SkColor colors[],
1784                                                    int index0, int index1, int index2) {
1785
1786    fColors[0] = SkPreMultiplyColor(colors[index0]);
1787    fColors[1] = SkPreMultiplyColor(colors[index1]);
1788    fColors[2] = SkPreMultiplyColor(colors[index2]);
1789
1790    SkMatrix m, im;
1791    m.reset();
1792    m.set(0, pts[index1].fX - pts[index0].fX);
1793    m.set(1, pts[index2].fX - pts[index0].fX);
1794    m.set(2, pts[index0].fX);
1795    m.set(3, pts[index1].fY - pts[index0].fY);
1796    m.set(4, pts[index2].fY - pts[index0].fY);
1797    m.set(5, pts[index0].fY);
1798    if (!m.invert(&im)) {
1799        return false;
1800    }
1801    // We can't call getTotalInverse(), because we explicitly don't want to look at the localmatrix
1802    // as our interators are intrinsically tied to the vertices, and nothing else.
1803    SkMatrix ctmInv;
1804    if (!this->getCTM().invert(&ctmInv)) {
1805        return false;
1806    }
1807    // TODO replace INV(m) * INV(ctm) with INV(ctm * m)
1808    fDstToUnit.setConcat(im, ctmInv);
1809    return true;
1810}
1811
1812#include "SkColorPriv.h"
1813#include "SkComposeShader.h"
1814
1815static int ScalarTo256(SkScalar v) {
1816    return static_cast<int>(SkScalarPin(v, 0, 1) * 256 + 0.5);
1817}
1818
1819SkTriColorShader::SkTriColorShader()
1820    : INHERITED(NULL)
1821    , fSetupData(NULL) {}
1822
1823SkTriColorShader::TriColorShaderContext::TriColorShaderContext(const SkTriColorShader& shader,
1824                                                               const ContextRec& rec)
1825    : INHERITED(shader, rec)
1826    , fSetup(false) {}
1827
1828SkTriColorShader::TriColorShaderContext::~TriColorShaderContext() {}
1829
1830size_t SkTriColorShader::onContextSize(const ContextRec&) const {
1831    return sizeof(TriColorShaderContext);
1832}
1833
1834void SkTriColorShader::TriColorShaderContext::shadeSpan(int x, int y, SkPMColor dstC[], int count) {
1835    SkTriColorShader* parent = static_cast<SkTriColorShader*>(const_cast<SkShader*>(&fShader));
1836    TriColorShaderData* set = parent->takeSetupData();
1837    if (set) {
1838        fSetup = setup(set->pts, set->colors, set->state->f0, set->state->f1, set->state->f2);
1839    }
1840
1841    if (!fSetup) {
1842        // Invalid matrices. Not checked before so no need to assert.
1843        return;
1844    }
1845
1846    const int alphaScale = Sk255To256(this->getPaintAlpha());
1847
1848    SkPoint src;
1849
1850    for (int i = 0; i < count; i++) {
1851        fDstToUnit.mapXY(SkIntToScalar(x), SkIntToScalar(y), &src);
1852        x += 1;
1853
1854        int scale1 = ScalarTo256(src.fX);
1855        int scale2 = ScalarTo256(src.fY);
1856        int scale0 = 256 - scale1 - scale2;
1857        if (scale0 < 0) {
1858            if (scale1 > scale2) {
1859                scale2 = 256 - scale1;
1860            } else {
1861                scale1 = 256 - scale2;
1862            }
1863            scale0 = 0;
1864        }
1865
1866        if (256 != alphaScale) {
1867            scale0 = SkAlphaMul(scale0, alphaScale);
1868            scale1 = SkAlphaMul(scale1, alphaScale);
1869            scale2 = SkAlphaMul(scale2, alphaScale);
1870        }
1871
1872        dstC[i] = SkAlphaMulQ(fColors[0], scale0) +
1873                  SkAlphaMulQ(fColors[1], scale1) +
1874                  SkAlphaMulQ(fColors[2], scale2);
1875    }
1876}
1877
1878#ifndef SK_IGNORE_TO_STRING
1879void SkTriColorShader::toString(SkString* str) const {
1880    str->append("SkTriColorShader: (");
1881
1882    this->INHERITED::toString(str);
1883
1884    str->append(")");
1885}
1886#endif
1887
1888void SkDraw::drawVertices(SkCanvas::VertexMode vmode, int count,
1889                          const SkPoint vertices[], const SkPoint textures[],
1890                          const SkColor colors[], SkXfermode* xmode,
1891                          const uint16_t indices[], int indexCount,
1892                          const SkPaint& paint) const {
1893    SkASSERT(0 == count || vertices);
1894
1895    // abort early if there is nothing to draw
1896    if (count < 3 || (indices && indexCount < 3) || fRC->isEmpty()) {
1897        return;
1898    }
1899
1900    // transform out vertices into device coordinates
1901    SkAutoSTMalloc<16, SkPoint> storage(count);
1902    SkPoint* devVerts = storage.get();
1903    fMatrix->mapPoints(devVerts, vertices, count);
1904
1905    /*
1906        We can draw the vertices in 1 of 4 ways:
1907
1908        - solid color (no shader/texture[], no colors[])
1909        - just colors (no shader/texture[], has colors[])
1910        - just texture (has shader/texture[], no colors[])
1911        - colors * texture (has shader/texture[], has colors[])
1912
1913        Thus for texture drawing, we need both texture[] and a shader.
1914    */
1915
1916    auto triShader = sk_make_sp<SkTriColorShader>();
1917    SkPaint p(paint);
1918
1919    SkShader* shader = p.getShader();
1920    if (nullptr == shader) {
1921        // if we have no shader, we ignore the texture coordinates
1922        textures = nullptr;
1923    } else if (nullptr == textures) {
1924        // if we don't have texture coordinates, ignore the shader
1925        p.setShader(nullptr);
1926        shader = nullptr;
1927    }
1928
1929    // setup the custom shader (if needed)
1930    if (colors) {
1931        if (nullptr == textures) {
1932            // just colors (no texture)
1933            p.setShader(triShader);
1934            shader = p.getShader();
1935        } else {
1936            // colors * texture
1937            SkASSERT(shader);
1938            sk_sp<SkXfermode> xfer = xmode ? sk_ref_sp(xmode)
1939                                           : SkXfermode::Make(SkXfermode::kModulate_Mode);
1940            p.setShader(SkShader::MakeComposeShader(triShader, sk_ref_sp(shader), std::move(xfer)));
1941        }
1942    }
1943
1944    SkAutoBlitterChoose blitter(fDst, *fMatrix, p);
1945    // Abort early if we failed to create a shader context.
1946    if (blitter->isNullBlitter()) {
1947        return;
1948    }
1949
1950    // setup our state and function pointer for iterating triangles
1951    VertState       state(count, indices, indexCount);
1952    VertState::Proc vertProc = state.chooseProc(vmode);
1953
1954    if (textures || colors) {
1955        SkTriColorShader::TriColorShaderData verticesSetup = { vertices, colors, &state };
1956
1957        while (vertProc(&state)) {
1958            if (textures) {
1959                SkMatrix tempM;
1960                if (texture_to_matrix(state, vertices, textures, &tempM)) {
1961                    SkShader::ContextRec rec(p, *fMatrix, &tempM,
1962                                             SkBlitter::PreferredShaderDest(fDst.info()));
1963                    if (!blitter->resetShaderContext(rec)) {
1964                        continue;
1965                    }
1966                }
1967            }
1968            if (colors) {
1969                triShader->bindSetupData(&verticesSetup);
1970            }
1971
1972            SkPoint tmp[] = {
1973                devVerts[state.f0], devVerts[state.f1], devVerts[state.f2]
1974            };
1975            SkScan::FillTriangle(tmp, *fRC, blitter.get());
1976            triShader->bindSetupData(NULL);
1977        }
1978    } else {
1979        // no colors[] and no texture, stroke hairlines with paint's color.
1980        SkScan::HairRCProc hairProc = ChooseHairProc(paint.isAntiAlias());
1981        const SkRasterClip& clip = *fRC;
1982        while (vertProc(&state)) {
1983            SkPoint array[] = {
1984                devVerts[state.f0], devVerts[state.f1], devVerts[state.f2], devVerts[state.f0]
1985            };
1986            hairProc(array, 4, clip, blitter.get());
1987        }
1988    }
1989}
1990
1991///////////////////////////////////////////////////////////////////////////////
1992///////////////////////////////////////////////////////////////////////////////
1993
1994#ifdef SK_DEBUG
1995
1996void SkDraw::validate() const {
1997    SkASSERT(fMatrix != nullptr);
1998    SkASSERT(fRC != nullptr);
1999
2000    const SkIRect&  cr = fRC->getBounds();
2001    SkIRect         br;
2002
2003    br.set(0, 0, fDst.width(), fDst.height());
2004    SkASSERT(cr.isEmpty() || br.contains(cr));
2005}
2006
2007#endif
2008
2009////////////////////////////////////////////////////////////////////////////////////////////////
2010
2011#include "SkPath.h"
2012#include "SkDraw.h"
2013#include "SkRegion.h"
2014#include "SkBlitter.h"
2015
2016static bool compute_bounds(const SkPath& devPath, const SkIRect* clipBounds,
2017                           const SkMaskFilter* filter, const SkMatrix* filterMatrix,
2018                           SkIRect* bounds) {
2019    if (devPath.isEmpty()) {
2020        return false;
2021    }
2022
2023    //  init our bounds from the path
2024    *bounds = devPath.getBounds().makeOutset(SK_ScalarHalf, SK_ScalarHalf).roundOut();
2025
2026    SkIPoint margin = SkIPoint::Make(0, 0);
2027    if (filter) {
2028        SkASSERT(filterMatrix);
2029
2030        SkMask srcM, dstM;
2031
2032        srcM.fBounds = *bounds;
2033        srcM.fFormat = SkMask::kA8_Format;
2034        if (!filter->filterMask(&dstM, srcM, *filterMatrix, &margin)) {
2035            return false;
2036        }
2037    }
2038
2039    // (possibly) trim the bounds to reflect the clip
2040    // (plus whatever slop the filter needs)
2041    if (clipBounds) {
2042        // Ugh. Guard against gigantic margins from wacky filters. Without this
2043        // check we can request arbitrary amounts of slop beyond our visible
2044        // clip, and bring down the renderer (at least on finite RAM machines
2045        // like handsets, etc.). Need to balance this invented value between
2046        // quality of large filters like blurs, and the corresponding memory
2047        // requests.
2048        static const int MAX_MARGIN = 128;
2049        if (!bounds->intersect(clipBounds->makeOutset(SkMin32(margin.fX, MAX_MARGIN),
2050                                                      SkMin32(margin.fY, MAX_MARGIN)))) {
2051            return false;
2052        }
2053    }
2054
2055    return true;
2056}
2057
2058static void draw_into_mask(const SkMask& mask, const SkPath& devPath,
2059                           SkStrokeRec::InitStyle style) {
2060    SkDraw draw;
2061    if (!draw.fDst.reset(mask)) {
2062        return;
2063    }
2064
2065    SkRasterClip    clip;
2066    SkMatrix        matrix;
2067    SkPaint         paint;
2068
2069    clip.setRect(SkIRect::MakeWH(mask.fBounds.width(), mask.fBounds.height()));
2070    matrix.setTranslate(-SkIntToScalar(mask.fBounds.fLeft),
2071                        -SkIntToScalar(mask.fBounds.fTop));
2072
2073    draw.fRC        = &clip;
2074    draw.fMatrix    = &matrix;
2075    paint.setAntiAlias(true);
2076    switch (style) {
2077        case SkStrokeRec::kHairline_InitStyle:
2078            SkASSERT(!paint.getStrokeWidth());
2079            paint.setStyle(SkPaint::kStroke_Style);
2080            break;
2081        case SkStrokeRec::kFill_InitStyle:
2082            SkASSERT(paint.getStyle() == SkPaint::kFill_Style);
2083            break;
2084
2085    }
2086    draw.drawPath(devPath, paint);
2087}
2088
2089bool SkDraw::DrawToMask(const SkPath& devPath, const SkIRect* clipBounds,
2090                        const SkMaskFilter* filter, const SkMatrix* filterMatrix,
2091                        SkMask* mask, SkMask::CreateMode mode,
2092                        SkStrokeRec::InitStyle style) {
2093    if (SkMask::kJustRenderImage_CreateMode != mode) {
2094        if (!compute_bounds(devPath, clipBounds, filter, filterMatrix, &mask->fBounds))
2095            return false;
2096    }
2097
2098    if (SkMask::kComputeBoundsAndRenderImage_CreateMode == mode) {
2099        mask->fFormat = SkMask::kA8_Format;
2100        mask->fRowBytes = mask->fBounds.width();
2101        size_t size = mask->computeImageSize();
2102        if (0 == size) {
2103            // we're too big to allocate the mask, abort
2104            return false;
2105        }
2106        mask->fImage = SkMask::AllocImage(size);
2107        memset(mask->fImage, 0, mask->computeImageSize());
2108    }
2109
2110    if (SkMask::kJustComputeBounds_CreateMode != mode) {
2111        draw_into_mask(*mask, devPath, style);
2112    }
2113
2114    return true;
2115}
2116