SkiaCanvas.cpp revision 6578a989566e585eee053095dc80e2552e125db2
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "Canvas.h"
18
19#include <SkCanvas.h>
20#include <SkClipStack.h>
21#include <SkDevice.h>
22#include <SkDeque.h>
23#include <SkDrawFilter.h>
24#include <SkGraphics.h>
25#include <SkShader.h>
26#include <SkTArray.h>
27#include <SkTemplates.h>
28
29namespace android {
30
31// Holds an SkCanvas reference plus additional native data.
32class SkiaCanvas : public Canvas {
33public:
34    explicit SkiaCanvas(const SkBitmap& bitmap);
35
36    /**
37     *  Create a new SkiaCanvas.
38     *
39     *  @param canvas SkCanvas to handle calls made to this SkiaCanvas. Must
40     *      not be NULL. This constructor will ref() the SkCanvas, and unref()
41     *      it in its destructor.
42     */
43    explicit SkiaCanvas(SkCanvas* canvas) : mCanvas(canvas) {
44        SkASSERT(canvas);
45        canvas->ref();
46    }
47
48    virtual SkCanvas* asSkCanvas() override {
49        return mCanvas.get();
50    }
51
52    virtual void setBitmap(const SkBitmap& bitmap) override;
53
54    virtual bool isOpaque() override;
55    virtual int width() override;
56    virtual int height() override;
57
58    virtual void setHighContrastText(bool highContrastText) override {
59        mHighContrastText = highContrastText;
60    }
61    virtual bool isHighContrastText() override { return mHighContrastText; }
62
63    virtual int getSaveCount() const override;
64    virtual int save(SkCanvas::SaveFlags flags) override;
65    virtual void restore() override;
66    virtual void restoreToCount(int saveCount) override;
67
68    virtual int saveLayer(float left, float top, float right, float bottom,
69                const SkPaint* paint, SkCanvas::SaveFlags flags) override;
70    virtual int saveLayerAlpha(float left, float top, float right, float bottom,
71            int alpha, SkCanvas::SaveFlags flags) override;
72
73    virtual void getMatrix(SkMatrix* outMatrix) const override;
74    virtual void setMatrix(const SkMatrix& matrix) override;
75    virtual void setLocalMatrix(const SkMatrix& matrix) override { this->setMatrix(matrix); }
76    virtual void concat(const SkMatrix& matrix) override;
77    virtual void rotate(float degrees) override;
78    virtual void scale(float sx, float sy) override;
79    virtual void skew(float sx, float sy) override;
80    virtual void translate(float dx, float dy) override;
81
82    virtual bool getClipBounds(SkRect* outRect) const override;
83    virtual bool quickRejectRect(float left, float top, float right, float bottom) const override;
84    virtual bool quickRejectPath(const SkPath& path) const override;
85    virtual bool clipRect(float left, float top, float right, float bottom,
86            SkRegion::Op op) override;
87    virtual bool clipPath(const SkPath* path, SkRegion::Op op) override;
88    virtual bool clipRegion(const SkRegion* region, SkRegion::Op op) override;
89
90    virtual SkDrawFilter* getDrawFilter() override;
91    virtual void setDrawFilter(SkDrawFilter* drawFilter) override;
92
93    virtual void drawColor(int color, SkXfermode::Mode mode) override;
94    virtual void drawPaint(const SkPaint& paint) override;
95
96    virtual void drawPoint(float x, float y, const SkPaint& paint) override;
97    virtual void drawPoints(const float* points, int count, const SkPaint& paint) override;
98    virtual void drawLine(float startX, float startY, float stopX, float stopY,
99            const SkPaint& paint) override;
100    virtual void drawLines(const float* points, int count, const SkPaint& paint) override;
101    virtual void drawRect(float left, float top, float right, float bottom,
102            const SkPaint& paint) override;
103    virtual void drawRegion(const SkRegion& region, const SkPaint& paint) override;
104    virtual void drawRoundRect(float left, float top, float right, float bottom,
105            float rx, float ry, const SkPaint& paint) override;
106    virtual void drawCircle(float x, float y, float radius, const SkPaint& paint) override;
107    virtual void drawOval(float left, float top, float right, float bottom,
108            const SkPaint& paint) override;
109    virtual void drawArc(float left, float top, float right, float bottom,
110            float startAngle, float sweepAngle, bool useCenter, const SkPaint& paint) override;
111    virtual void drawPath(const SkPath& path, const SkPaint& paint) override;
112    virtual void drawVertices(SkCanvas::VertexMode vertexMode, int vertexCount,
113            const float* verts, const float* tex, const int* colors,
114            const uint16_t* indices, int indexCount, const SkPaint& paint) override;
115
116    virtual void drawBitmap(const SkBitmap& bitmap, float left, float top,
117            const SkPaint* paint) override;
118    virtual void drawBitmap(const SkBitmap& bitmap, const SkMatrix& matrix,
119            const SkPaint* paint) override;
120    virtual void drawBitmap(const SkBitmap& bitmap, float srcLeft, float srcTop,
121            float srcRight, float srcBottom, float dstLeft, float dstTop,
122            float dstRight, float dstBottom, const SkPaint* paint) override;
123    virtual void drawBitmapMesh(const SkBitmap& bitmap, int meshWidth, int meshHeight,
124            const float* vertices, const int* colors, const SkPaint* paint) override;
125
126    virtual void drawText(const uint16_t* text, const float* positions, int count,
127            const SkPaint& paint, float x, float y,
128            float boundsLeft, float boundsTop, float boundsRight, float boundsBottom,
129            float totalAdvance) override;
130    virtual void drawPosText(const uint16_t* text, const float* positions, int count,
131            int posCount, const SkPaint& paint) override;
132    virtual void drawTextOnPath(const uint16_t* glyphs, int count, const SkPath& path,
133            float hOffset, float vOffset, const SkPaint& paint) override;
134
135    virtual bool drawTextAbsolutePos() const  override { return true; }
136
137private:
138    struct SaveRec {
139        int                 saveCount;
140        SkCanvas::SaveFlags saveFlags;
141    };
142
143    bool mHighContrastText = false;
144
145    void recordPartialSave(SkCanvas::SaveFlags flags);
146    void saveClipsForFrame(SkTArray<SkClipStack::Element>& clips, int frameSaveCount);
147    void applyClips(const SkTArray<SkClipStack::Element>& clips);
148
149    void drawPoints(const float* points, int count, const SkPaint& paint,
150                    SkCanvas::PointMode mode);
151    void drawTextDecorations(float x, float y, float length, const SkPaint& paint);
152
153    SkAutoTUnref<SkCanvas> mCanvas;
154    SkAutoTDelete<SkDeque> mSaveStack; // lazily allocated, tracks partial saves.
155};
156
157Canvas* Canvas::create_canvas(const SkBitmap& bitmap) {
158    return new SkiaCanvas(bitmap);
159}
160
161Canvas* Canvas::create_canvas(SkCanvas* skiaCanvas) {
162    return new SkiaCanvas(skiaCanvas);
163}
164
165SkiaCanvas::SkiaCanvas(const SkBitmap& bitmap) {
166    mCanvas.reset(new SkCanvas(bitmap));
167}
168
169// ----------------------------------------------------------------------------
170// Canvas state operations: Replace Bitmap
171// ----------------------------------------------------------------------------
172
173class ClipCopier : public SkCanvas::ClipVisitor {
174public:
175    ClipCopier(SkCanvas* dstCanvas) : m_dstCanvas(dstCanvas) {}
176
177    virtual void clipRect(const SkRect& rect, SkRegion::Op op, bool antialias) {
178        m_dstCanvas->clipRect(rect, op, antialias);
179    }
180    virtual void clipRRect(const SkRRect& rrect, SkRegion::Op op, bool antialias) {
181        m_dstCanvas->clipRRect(rrect, op, antialias);
182    }
183    virtual void clipPath(const SkPath& path, SkRegion::Op op, bool antialias) {
184        m_dstCanvas->clipPath(path, op, antialias);
185    }
186
187private:
188    SkCanvas* m_dstCanvas;
189};
190
191void SkiaCanvas::setBitmap(const SkBitmap& bitmap) {
192    SkCanvas* newCanvas = new SkCanvas(bitmap);
193    SkASSERT(newCanvas);
194
195    if (!bitmap.isNull()) {
196        // Copy the canvas matrix & clip state.
197        newCanvas->setMatrix(mCanvas->getTotalMatrix());
198        if (NULL != mCanvas->getDevice() && NULL != newCanvas->getDevice()) {
199            ClipCopier copier(newCanvas);
200            mCanvas->replayClips(&copier);
201        }
202    }
203
204    // unrefs the existing canvas
205    mCanvas.reset(newCanvas);
206
207    // clean up the old save stack
208    mSaveStack.reset(NULL);
209}
210
211// ----------------------------------------------------------------------------
212// Canvas state operations
213// ----------------------------------------------------------------------------
214
215bool SkiaCanvas::isOpaque() {
216    return mCanvas->getDevice()->accessBitmap(false).isOpaque();
217}
218
219int SkiaCanvas::width() {
220    return mCanvas->getBaseLayerSize().width();
221}
222
223int SkiaCanvas::height() {
224    return mCanvas->getBaseLayerSize().height();
225}
226
227// ----------------------------------------------------------------------------
228// Canvas state operations: Save (layer)
229// ----------------------------------------------------------------------------
230
231int SkiaCanvas::getSaveCount() const {
232    return mCanvas->getSaveCount();
233}
234
235int SkiaCanvas::save(SkCanvas::SaveFlags flags) {
236    int count = mCanvas->save();
237    recordPartialSave(flags);
238    return count;
239}
240
241void SkiaCanvas::restore() {
242    const SaveRec* rec = (NULL == mSaveStack.get())
243            ? NULL
244            : static_cast<SaveRec*>(mSaveStack->back());
245    int currentSaveCount = mCanvas->getSaveCount() - 1;
246    SkASSERT(NULL == rec || currentSaveCount >= rec->saveCount);
247
248    if (NULL == rec || rec->saveCount != currentSaveCount) {
249        // Fast path - no record for this frame.
250        mCanvas->restore();
251        return;
252    }
253
254    bool preserveMatrix = !(rec->saveFlags & SkCanvas::kMatrix_SaveFlag);
255    bool preserveClip   = !(rec->saveFlags & SkCanvas::kClip_SaveFlag);
256
257    SkMatrix savedMatrix;
258    if (preserveMatrix) {
259        savedMatrix = mCanvas->getTotalMatrix();
260    }
261
262    SkTArray<SkClipStack::Element> savedClips;
263    if (preserveClip) {
264        saveClipsForFrame(savedClips, currentSaveCount);
265    }
266
267    mCanvas->restore();
268
269    if (preserveMatrix) {
270        mCanvas->setMatrix(savedMatrix);
271    }
272
273    if (preserveClip && !savedClips.empty()) {
274        applyClips(savedClips);
275    }
276
277    mSaveStack->pop_back();
278}
279
280void SkiaCanvas::restoreToCount(int restoreCount) {
281    while (mCanvas->getSaveCount() > restoreCount) {
282        this->restore();
283    }
284}
285
286int SkiaCanvas::saveLayer(float left, float top, float right, float bottom,
287            const SkPaint* paint, SkCanvas::SaveFlags flags) {
288    SkRect bounds = SkRect::MakeLTRB(left, top, right, bottom);
289    int count = mCanvas->saveLayer(&bounds, paint, flags | SkCanvas::kMatrixClip_SaveFlag);
290    recordPartialSave(flags);
291    return count;
292}
293
294int SkiaCanvas::saveLayerAlpha(float left, float top, float right, float bottom,
295        int alpha, SkCanvas::SaveFlags flags) {
296    SkRect bounds = SkRect::MakeLTRB(left, top, right, bottom);
297    int count = mCanvas->saveLayerAlpha(&bounds, alpha, flags | SkCanvas::kMatrixClip_SaveFlag);
298    recordPartialSave(flags);
299    return count;
300}
301
302// ----------------------------------------------------------------------------
303// functions to emulate legacy SaveFlags (i.e. independent matrix/clip flags)
304// ----------------------------------------------------------------------------
305
306void SkiaCanvas::recordPartialSave(SkCanvas::SaveFlags flags) {
307    // A partial save is a save operation which doesn't capture the full canvas state.
308    // (either kMatrix_SaveFlags or kClip_SaveFlag is missing).
309
310    // Mask-out non canvas state bits.
311    flags = static_cast<SkCanvas::SaveFlags>(flags & SkCanvas::kMatrixClip_SaveFlag);
312
313    if (SkCanvas::kMatrixClip_SaveFlag == flags) {
314        // not a partial save.
315        return;
316    }
317
318    if (NULL == mSaveStack.get()) {
319        mSaveStack.reset(SkNEW_ARGS(SkDeque, (sizeof(struct SaveRec), 8)));
320    }
321
322    SaveRec* rec = static_cast<SaveRec*>(mSaveStack->push_back());
323    // Store the save counter in the SkClipStack domain.
324    // (0-based, equal to the number of save ops on the stack).
325    rec->saveCount = mCanvas->getSaveCount() - 1;
326    rec->saveFlags = flags;
327}
328
329void SkiaCanvas::saveClipsForFrame(SkTArray<SkClipStack::Element>& clips, int frameSaveCount) {
330    SkClipStack::Iter clipIterator(*mCanvas->getClipStack(),
331                                   SkClipStack::Iter::kTop_IterStart);
332    while (const SkClipStack::Element* elem = clipIterator.next()) {
333        if (elem->getSaveCount() < frameSaveCount) {
334            // done with the current frame.
335            break;
336        }
337        SkASSERT(elem->getSaveCount() == frameSaveCount);
338        clips.push_back(*elem);
339    }
340}
341
342void SkiaCanvas::applyClips(const SkTArray<SkClipStack::Element>& clips) {
343    ClipCopier clipCopier(mCanvas);
344
345    // The clip stack stores clips in device space.
346    SkMatrix origMatrix = mCanvas->getTotalMatrix();
347    mCanvas->resetMatrix();
348
349    // We pushed the clips in reverse order.
350    for (int i = clips.count() - 1; i >= 0; --i) {
351        clips[i].replay(&clipCopier);
352    }
353
354    mCanvas->setMatrix(origMatrix);
355}
356
357// ----------------------------------------------------------------------------
358// Canvas state operations: Matrix
359// ----------------------------------------------------------------------------
360
361void SkiaCanvas::getMatrix(SkMatrix* outMatrix) const {
362    *outMatrix = mCanvas->getTotalMatrix();
363}
364
365void SkiaCanvas::setMatrix(const SkMatrix& matrix) {
366    mCanvas->setMatrix(matrix);
367}
368
369void SkiaCanvas::concat(const SkMatrix& matrix) {
370    mCanvas->concat(matrix);
371}
372
373void SkiaCanvas::rotate(float degrees) {
374    mCanvas->rotate(degrees);
375}
376
377void SkiaCanvas::scale(float sx, float sy) {
378    mCanvas->scale(sx, sy);
379}
380
381void SkiaCanvas::skew(float sx, float sy) {
382    mCanvas->skew(sx, sy);
383}
384
385void SkiaCanvas::translate(float dx, float dy) {
386    mCanvas->translate(dx, dy);
387}
388
389// ----------------------------------------------------------------------------
390// Canvas state operations: Clips
391// ----------------------------------------------------------------------------
392
393// This function is a mirror of SkCanvas::getClipBounds except that it does
394// not outset the edge of the clip to account for anti-aliasing. There is
395// a skia bug to investigate pushing this logic into back into skia.
396// (see https://code.google.com/p/skia/issues/detail?id=1303)
397bool SkiaCanvas::getClipBounds(SkRect* outRect) const {
398    SkIRect ibounds;
399    if (!mCanvas->getClipDeviceBounds(&ibounds)) {
400        return false;
401    }
402
403    SkMatrix inverse;
404    // if we can't invert the CTM, we can't return local clip bounds
405    if (!mCanvas->getTotalMatrix().invert(&inverse)) {
406        if (outRect) {
407            outRect->setEmpty();
408        }
409        return false;
410    }
411
412    if (NULL != outRect) {
413        SkRect r = SkRect::Make(ibounds);
414        inverse.mapRect(outRect, r);
415    }
416    return true;
417}
418
419bool SkiaCanvas::quickRejectRect(float left, float top, float right, float bottom) const {
420    SkRect bounds = SkRect::MakeLTRB(left, top, right, bottom);
421    return mCanvas->quickReject(bounds);
422}
423
424bool SkiaCanvas::quickRejectPath(const SkPath& path) const {
425    return mCanvas->quickReject(path);
426}
427
428bool SkiaCanvas::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
429    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
430    mCanvas->clipRect(rect, op);
431    return !mCanvas->isClipEmpty();
432}
433
434bool SkiaCanvas::clipPath(const SkPath* path, SkRegion::Op op) {
435    mCanvas->clipPath(*path, op);
436    return !mCanvas->isClipEmpty();
437}
438
439bool SkiaCanvas::clipRegion(const SkRegion* region, SkRegion::Op op) {
440    SkPath rgnPath;
441    if (region->getBoundaryPath(&rgnPath)) {
442        // The region is specified in device space.
443        SkMatrix savedMatrix = mCanvas->getTotalMatrix();
444        mCanvas->resetMatrix();
445        mCanvas->clipPath(rgnPath, op);
446        mCanvas->setMatrix(savedMatrix);
447    } else {
448        mCanvas->clipRect(SkRect::MakeEmpty(), op);
449    }
450    return !mCanvas->isClipEmpty();
451}
452
453// ----------------------------------------------------------------------------
454// Canvas state operations: Filters
455// ----------------------------------------------------------------------------
456
457SkDrawFilter* SkiaCanvas::getDrawFilter() {
458    return mCanvas->getDrawFilter();
459}
460
461void SkiaCanvas::setDrawFilter(SkDrawFilter* drawFilter) {
462    mCanvas->setDrawFilter(drawFilter);
463}
464
465// ----------------------------------------------------------------------------
466// Canvas draw operations
467// ----------------------------------------------------------------------------
468
469void SkiaCanvas::drawColor(int color, SkXfermode::Mode mode) {
470    mCanvas->drawColor(color, mode);
471}
472
473void SkiaCanvas::drawPaint(const SkPaint& paint) {
474    mCanvas->drawPaint(paint);
475}
476
477// ----------------------------------------------------------------------------
478// Canvas draw operations: Geometry
479// ----------------------------------------------------------------------------
480
481void SkiaCanvas::drawPoints(const float* points, int count, const SkPaint& paint,
482                            SkCanvas::PointMode mode) {
483    // convert the floats into SkPoints
484    count >>= 1;    // now it is the number of points
485    SkAutoSTMalloc<32, SkPoint> storage(count);
486    SkPoint* pts = storage.get();
487    for (int i = 0; i < count; i++) {
488        pts[i].set(points[0], points[1]);
489        points += 2;
490    }
491    mCanvas->drawPoints(mode, count, pts, paint);
492}
493
494
495void SkiaCanvas::drawPoint(float x, float y, const SkPaint& paint) {
496    mCanvas->drawPoint(x, y, paint);
497}
498
499void SkiaCanvas::drawPoints(const float* points, int count, const SkPaint& paint) {
500    this->drawPoints(points, count, paint, SkCanvas::kPoints_PointMode);
501}
502
503void SkiaCanvas::drawLine(float startX, float startY, float stopX, float stopY,
504                          const SkPaint& paint) {
505    mCanvas->drawLine(startX, startY, stopX, stopY, paint);
506}
507
508void SkiaCanvas::drawLines(const float* points, int count, const SkPaint& paint) {
509    this->drawPoints(points, count, paint, SkCanvas::kLines_PointMode);
510}
511
512void SkiaCanvas::drawRect(float left, float top, float right, float bottom,
513        const SkPaint& paint) {
514    mCanvas->drawRectCoords(left, top, right, bottom, paint);
515
516}
517
518void SkiaCanvas::drawRegion(const SkRegion& region, const SkPaint& paint) {
519    SkRegion::Iterator it(region);
520    while (!it.done()) {
521        mCanvas->drawRect(SkRect::Make(it.rect()), paint);
522        it.next();
523    }
524}
525
526void SkiaCanvas::drawRoundRect(float left, float top, float right, float bottom,
527        float rx, float ry, const SkPaint& paint) {
528    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
529    mCanvas->drawRoundRect(rect, rx, ry, paint);
530}
531
532void SkiaCanvas::drawCircle(float x, float y, float radius, const SkPaint& paint) {
533    mCanvas->drawCircle(x, y, radius, paint);
534}
535
536void SkiaCanvas::drawOval(float left, float top, float right, float bottom, const SkPaint& paint) {
537    SkRect oval = SkRect::MakeLTRB(left, top, right, bottom);
538    mCanvas->drawOval(oval, paint);
539}
540
541void SkiaCanvas::drawArc(float left, float top, float right, float bottom,
542        float startAngle, float sweepAngle, bool useCenter, const SkPaint& paint) {
543    SkRect arc = SkRect::MakeLTRB(left, top, right, bottom);
544    mCanvas->drawArc(arc, startAngle, sweepAngle, useCenter, paint);
545}
546
547void SkiaCanvas::drawPath(const SkPath& path, const SkPaint& paint) {
548    mCanvas->drawPath(path, paint);
549}
550
551void SkiaCanvas::drawVertices(SkCanvas::VertexMode vertexMode, int vertexCount,
552                              const float* verts, const float* texs, const int* colors,
553                              const uint16_t* indices, int indexCount, const SkPaint& paint) {
554#ifndef SK_SCALAR_IS_FLOAT
555    SkDEBUGFAIL("SkScalar must be a float for these conversions to be valid");
556#endif
557    const int ptCount = vertexCount >> 1;
558    mCanvas->drawVertices(vertexMode, ptCount, (SkPoint*)verts, (SkPoint*)texs,
559                          (SkColor*)colors, NULL, indices, indexCount, paint);
560}
561
562// ----------------------------------------------------------------------------
563// Canvas draw operations: Bitmaps
564// ----------------------------------------------------------------------------
565
566void SkiaCanvas::drawBitmap(const SkBitmap& bitmap, float left, float top, const SkPaint* paint) {
567    mCanvas->drawBitmap(bitmap, left, top, paint);
568}
569
570void SkiaCanvas::drawBitmap(const SkBitmap& bitmap, const SkMatrix& matrix, const SkPaint* paint) {
571    SkAutoCanvasRestore acr(mCanvas, true);
572    mCanvas->concat(matrix);
573    mCanvas->drawBitmap(bitmap, 0, 0, paint);
574}
575
576void SkiaCanvas::drawBitmap(const SkBitmap& bitmap, float srcLeft, float srcTop,
577                            float srcRight, float srcBottom, float dstLeft, float dstTop,
578                            float dstRight, float dstBottom, const SkPaint* paint) {
579    SkRect srcRect = SkRect::MakeLTRB(srcLeft, srcTop, srcRight, srcBottom);
580    SkRect dstRect = SkRect::MakeLTRB(dstLeft, dstTop, dstRight, dstBottom);
581    mCanvas->drawBitmapRectToRect(bitmap, &srcRect, dstRect, paint);
582}
583
584void SkiaCanvas::drawBitmapMesh(const SkBitmap& bitmap, int meshWidth, int meshHeight,
585        const float* vertices, const int* colors, const SkPaint* paint) {
586
587    const int ptCount = (meshWidth + 1) * (meshHeight + 1);
588    const int indexCount = meshWidth * meshHeight * 6;
589
590    /*  Our temp storage holds 2 or 3 arrays.
591        texture points [ptCount * sizeof(SkPoint)]
592        optionally vertex points [ptCount * sizeof(SkPoint)] if we need a
593            copy to convert from float to fixed
594        indices [ptCount * sizeof(uint16_t)]
595    */
596    ssize_t storageSize = ptCount * sizeof(SkPoint); // texs[]
597    storageSize += indexCount * sizeof(uint16_t);  // indices[]
598
599
600#ifndef SK_SCALAR_IS_FLOAT
601    SkDEBUGFAIL("SkScalar must be a float for these conversions to be valid");
602#endif
603    SkAutoMalloc storage(storageSize);
604    SkPoint* texs = (SkPoint*)storage.get();
605    uint16_t* indices = (uint16_t*)(texs + ptCount);
606
607    // cons up texture coordinates and indices
608    {
609        const SkScalar w = SkIntToScalar(bitmap.width());
610        const SkScalar h = SkIntToScalar(bitmap.height());
611        const SkScalar dx = w / meshWidth;
612        const SkScalar dy = h / meshHeight;
613
614        SkPoint* texsPtr = texs;
615        SkScalar y = 0;
616        for (int i = 0; i <= meshHeight; i++) {
617            if (i == meshHeight) {
618                y = h;  // to ensure numerically we hit h exactly
619            }
620            SkScalar x = 0;
621            for (int j = 0; j < meshWidth; j++) {
622                texsPtr->set(x, y);
623                texsPtr += 1;
624                x += dx;
625            }
626            texsPtr->set(w, y);
627            texsPtr += 1;
628            y += dy;
629        }
630        SkASSERT(texsPtr - texs == ptCount);
631    }
632
633    // cons up indices
634    {
635        uint16_t* indexPtr = indices;
636        int index = 0;
637        for (int i = 0; i < meshHeight; i++) {
638            for (int j = 0; j < meshWidth; j++) {
639                // lower-left triangle
640                *indexPtr++ = index;
641                *indexPtr++ = index + meshWidth + 1;
642                *indexPtr++ = index + meshWidth + 2;
643                // upper-right triangle
644                *indexPtr++ = index;
645                *indexPtr++ = index + meshWidth + 2;
646                *indexPtr++ = index + 1;
647                // bump to the next cell
648                index += 1;
649            }
650            // bump to the next row
651            index += 1;
652        }
653        SkASSERT(indexPtr - indices == indexCount);
654        SkASSERT((char*)indexPtr - (char*)storage.get() == storageSize);
655    }
656
657    // double-check that we have legal indices
658#ifdef SK_DEBUG
659    {
660        for (int i = 0; i < indexCount; i++) {
661            SkASSERT((unsigned)indices[i] < (unsigned)ptCount);
662        }
663    }
664#endif
665
666    // cons-up a shader for the bitmap
667    SkPaint tmpPaint;
668    if (paint) {
669        tmpPaint = *paint;
670    }
671    SkShader* shader = SkShader::CreateBitmapShader(bitmap,
672                                                    SkShader::kClamp_TileMode,
673                                                    SkShader::kClamp_TileMode);
674    SkSafeUnref(tmpPaint.setShader(shader));
675
676    mCanvas->drawVertices(SkCanvas::kTriangles_VertexMode, ptCount, (SkPoint*)vertices,
677                         texs, (const SkColor*)colors, NULL, indices,
678                         indexCount, tmpPaint);
679}
680
681// ----------------------------------------------------------------------------
682// Canvas draw operations: Text
683// ----------------------------------------------------------------------------
684
685void SkiaCanvas::drawText(const uint16_t* text, const float* positions, int count,
686        const SkPaint& paint, float x, float y,
687        float boundsLeft, float boundsTop, float boundsRight, float boundsBottom,
688        float totalAdvance) {
689    // Set align to left for drawing, as we don't want individual
690    // glyphs centered or right-aligned; the offset above takes
691    // care of all alignment.
692    SkPaint paintCopy(paint);
693    paintCopy.setTextAlign(SkPaint::kLeft_Align);
694
695    SK_COMPILE_ASSERT(sizeof(SkPoint) == sizeof(float)*2, SkPoint_is_no_longer_2_floats);
696    mCanvas->drawPosText(text, count << 1, reinterpret_cast<const SkPoint*>(positions), paintCopy);
697}
698
699void SkiaCanvas::drawPosText(const uint16_t* text, const float* positions, int count, int posCount,
700        const SkPaint& paint) {
701    SkPoint* posPtr = posCount > 0 ? new SkPoint[posCount] : NULL;
702    int indx;
703    for (indx = 0; indx < posCount; indx++) {
704        posPtr[indx].fX = positions[indx << 1];
705        posPtr[indx].fY = positions[(indx << 1) + 1];
706    }
707
708    SkPaint paintCopy(paint);
709    paintCopy.setTextEncoding(SkPaint::kUTF16_TextEncoding);
710    mCanvas->drawPosText(text, count, posPtr, paintCopy);
711
712    delete[] posPtr;
713}
714
715void SkiaCanvas::drawTextOnPath(const uint16_t* glyphs, int count, const SkPath& path,
716        float hOffset, float vOffset, const SkPaint& paint) {
717    mCanvas->drawTextOnPathHV(glyphs, count << 1, path, hOffset, vOffset, paint);
718}
719
720} // namespace android
721