DisplayListOp.h revision b7b93e00893f5c690a96bd3e0e10583bc5721f83
1/*
2 * Copyright (C) 2013 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#ifndef ANDROID_HWUI_DISPLAY_OPERATION_H
18#define ANDROID_HWUI_DISPLAY_OPERATION_H
19
20#ifndef LOG_TAG
21    #define LOG_TAG "OpenGLRenderer"
22#endif
23
24#include <SkXfermode.h>
25
26#include <private/hwui/DrawGlInfo.h>
27
28#include "OpenGLRenderer.h"
29#include "AssetAtlas.h"
30#include "DeferredDisplayList.h"
31#include "DisplayListRenderer.h"
32#include "UvMapper.h"
33#include "utils/LinearAllocator.h"
34
35#define CRASH() do { \
36    *(int *)(uintptr_t) 0xbbadbeef = 0; \
37    ((void(*)())0)(); /* More reliable, but doesn't say BBADBEEF */ \
38} while(false)
39
40// Use OP_LOG for logging with arglist, OP_LOGS if just printing char*
41#define OP_LOGS(s) OP_LOG("%s", (s))
42#define OP_LOG(s, ...) ALOGD( "%*s" s, level * 2, "", __VA_ARGS__ )
43
44namespace android {
45namespace uirenderer {
46
47/**
48 * Structure for storing canvas operations when they are recorded into a DisplayList, so that they
49 * may be replayed to an OpenGLRenderer.
50 *
51 * To avoid individual memory allocations, DisplayListOps may only be allocated into a
52 * LinearAllocator's managed memory buffers.  Each pointer held by a DisplayListOp is either a
53 * pointer into memory also allocated in the LinearAllocator (mostly for text and float buffers) or
54 * references a externally refcounted object (Sk... and Skia... objects). ~DisplayListOp() is
55 * never called as LinearAllocators are simply discarded, so no memory management should be done in
56 * this class.
57 */
58class DisplayListOp {
59public:
60    // These objects should always be allocated with a LinearAllocator, and never destroyed/deleted.
61    // standard new() intentionally not implemented, and delete/deconstructor should never be used.
62    virtual ~DisplayListOp() { CRASH(); }
63    static void operator delete(void* ptr) { CRASH(); }
64    /** static void* operator new(size_t size); PURPOSELY OMITTED **/
65    static void* operator new(size_t size, LinearAllocator& allocator) {
66        return allocator.alloc(size);
67    }
68
69    enum OpLogFlag {
70        kOpLogFlag_Recurse = 0x1,
71        kOpLogFlag_JSON = 0x2 // TODO: add?
72    };
73
74    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
75            bool useQuickReject) = 0;
76
77    virtual void replay(ReplayStateStruct& replayStruct, int saveCount, int level,
78            bool useQuickReject) = 0;
79
80    virtual void output(int level, uint32_t logFlags = 0) const = 0;
81
82    // NOTE: it would be nice to declare constants and overriding the implementation in each op to
83    // point at the constants, but that seems to require a .cpp file
84    virtual const char* name() = 0;
85
86    /**
87     * Stores the relevant canvas state of the object between deferral and replay (if the canvas
88     * state supports being stored) See OpenGLRenderer::simpleClipAndState()
89     *
90     * TODO: don't reserve space for StateOps that won't be deferred
91     */
92    DeferredDisplayState state;
93
94};
95
96class StateOp : public DisplayListOp {
97public:
98    StateOp() {};
99
100    virtual ~StateOp() {}
101
102    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
103            bool useQuickReject) {
104        // default behavior only affects immediate, deferrable state, issue directly to renderer
105        applyState(deferStruct.mRenderer, saveCount);
106    }
107
108    /**
109     * State operations are applied directly to the renderer, but can cause the deferred drawing op
110     * list to flush
111     */
112    virtual void replay(ReplayStateStruct& replayStruct, int saveCount, int level,
113            bool useQuickReject) {
114        applyState(replayStruct.mRenderer, saveCount);
115    }
116
117    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const = 0;
118};
119
120class DrawOp : public DisplayListOp {
121friend class MergingDrawBatch;
122public:
123    DrawOp(SkPaint* paint)
124            : mPaint(paint), mQuickRejected(false) {}
125
126    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
127            bool useQuickReject) {
128        if (mQuickRejected && CC_LIKELY(useQuickReject)) {
129            return;
130        }
131
132        if (getLocalBounds(state.mBounds)) {
133            // valid empty bounds, don't bother deferring
134            if (state.mBounds.isEmpty()) return;
135        } else {
136            // empty bounds signify bounds can't be calculated
137            state.mBounds.setEmpty();
138        }
139
140        deferStruct.mDeferredList.addDrawOp(deferStruct.mRenderer, this);
141    }
142
143    virtual void replay(ReplayStateStruct& replayStruct, int saveCount, int level,
144            bool useQuickReject) {
145        if (mQuickRejected && CC_LIKELY(useQuickReject)) {
146            return;
147        }
148
149        replayStruct.mDrawGlStatus |= applyDraw(replayStruct.mRenderer, replayStruct.mDirty);
150    }
151
152    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) = 0;
153
154    /**
155     * Draw multiple instances of an operation, must be overidden for operations that merge
156     *
157     * Currently guarantees certain similarities between ops (see MergingDrawBatch::canMergeWith),
158     * and pure translation transformations. Other guarantees of similarity should be enforced by
159     * reducing which operations are tagged as mergeable.
160     */
161    virtual status_t multiDraw(OpenGLRenderer& renderer, Rect& dirty,
162            const Vector<DrawOp*>& ops, const Rect& bounds) {
163        status_t status = DrawGlInfo::kStatusDone;
164        for (unsigned int i = 0; i < ops.size(); i++) {
165            renderer.restoreDisplayState(ops[i]->state, true);
166            status |= ops[i]->applyDraw(renderer, dirty);
167        }
168        return status;
169    }
170
171    /**
172     * When this method is invoked the state field is initialized to have the
173     * final rendering state. We can thus use it to process data as it will be
174     * used at draw time.
175     *
176     * Additionally, this method allows subclasses to provide defer-time preferences for batching
177     * and merging.
178     *
179     * if a subclass can set deferInfo.mergeable to true, it should implement multiDraw()
180     */
181    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {}
182
183    // returns true if bounds exist
184    virtual bool getLocalBounds(Rect& localBounds) { return false; }
185
186    // TODO: better refine localbounds usage
187    void setQuickRejected(bool quickRejected) { mQuickRejected = quickRejected; }
188    bool getQuickRejected() { return mQuickRejected; }
189
190    inline int getPaintAlpha() {
191        return OpenGLRenderer::getAlphaDirect(mPaint);
192    }
193
194    inline float strokeWidthOutset() {
195        float width = mPaint->getStrokeWidth();
196        if (width == 0) return 0.5f; // account for hairline
197        return width * 0.5f;
198    }
199
200protected:
201    SkPaint* getPaint(OpenGLRenderer& renderer) {
202        return renderer.filterPaint(mPaint);
203    }
204
205    // Helper method for determining op opaqueness. Assumes op fills its bounds in local
206    // coordinates, and that paint's alpha is used
207    inline bool isOpaqueOverBounds() {
208        // ensure that local bounds cover mapped bounds
209        if (!state.mMatrix.isSimple()) return false;
210
211        // check state/paint for transparency
212        if (state.mDrawModifiers.mShader ||
213                state.mAlpha != 1.0f ||
214                (mPaint && mPaint->getAlpha() != 0xFF)) return false;
215
216        SkXfermode::Mode mode = OpenGLRenderer::getXfermodeDirect(mPaint);
217        return (mode == SkXfermode::kSrcOver_Mode ||
218                mode == SkXfermode::kSrc_Mode);
219
220    }
221
222    SkPaint* mPaint; // should be accessed via getPaint() when applying
223    bool mQuickRejected;
224};
225
226class DrawBoundedOp : public DrawOp {
227public:
228    DrawBoundedOp(float left, float top, float right, float bottom, SkPaint* paint)
229            : DrawOp(paint), mLocalBounds(left, top, right, bottom) {}
230
231    DrawBoundedOp(const Rect& localBounds, SkPaint* paint)
232            : DrawOp(paint), mLocalBounds(localBounds) {}
233
234    // Calculates bounds as smallest rect encompassing all points
235    // NOTE: requires at least 1 vertex, and doesn't account for stroke size (should be handled in
236    // subclass' constructor)
237    DrawBoundedOp(const float* points, int count, SkPaint* paint)
238            : DrawOp(paint), mLocalBounds(points[0], points[1], points[0], points[1]) {
239        for (int i = 2; i < count; i += 2) {
240            mLocalBounds.left = fminf(mLocalBounds.left, points[i]);
241            mLocalBounds.right = fmaxf(mLocalBounds.right, points[i]);
242            mLocalBounds.top = fminf(mLocalBounds.top, points[i + 1]);
243            mLocalBounds.bottom = fmaxf(mLocalBounds.bottom, points[i + 1]);
244        }
245    }
246
247    // default empty constructor for bounds, to be overridden in child constructor body
248    DrawBoundedOp(SkPaint* paint)
249            : DrawOp(paint) {}
250
251    bool getLocalBounds(Rect& localBounds) {
252        localBounds.set(mLocalBounds);
253        return true;
254    }
255
256protected:
257    Rect mLocalBounds; // displayed area in LOCAL coord. doesn't incorporate stroke, so check paint
258};
259
260///////////////////////////////////////////////////////////////////////////////
261// STATE OPERATIONS - these may affect the state of the canvas/renderer, but do
262//         not directly draw or alter output
263///////////////////////////////////////////////////////////////////////////////
264
265class SaveOp : public StateOp {
266    friend class DisplayList; // give DisplayList private constructor/reinit access
267public:
268    SaveOp(int flags)
269            : mFlags(flags) {}
270
271    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
272            bool useQuickReject) {
273        int newSaveCount = deferStruct.mRenderer.save(mFlags);
274        deferStruct.mDeferredList.addSave(deferStruct.mRenderer, this, newSaveCount);
275    }
276
277    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
278        renderer.save(mFlags);
279    }
280
281    virtual void output(int level, uint32_t logFlags) const {
282        OP_LOG("Save flags %x", mFlags);
283    }
284
285    virtual const char* name() { return "Save"; }
286
287    int getFlags() const { return mFlags; }
288private:
289    SaveOp() {}
290    DisplayListOp* reinit(int flags) {
291        mFlags = flags;
292        return this;
293    }
294
295    int mFlags;
296};
297
298class RestoreToCountOp : public StateOp {
299    friend class DisplayList; // give DisplayList private constructor/reinit access
300public:
301    RestoreToCountOp(int count)
302            : mCount(count) {}
303
304    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
305            bool useQuickReject) {
306        deferStruct.mDeferredList.addRestoreToCount(deferStruct.mRenderer,
307                this, saveCount + mCount);
308        deferStruct.mRenderer.restoreToCount(saveCount + mCount);
309    }
310
311    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
312        renderer.restoreToCount(saveCount + mCount);
313    }
314
315    virtual void output(int level, uint32_t logFlags) const {
316        OP_LOG("Restore to count %d", mCount);
317    }
318
319    virtual const char* name() { return "RestoreToCount"; }
320
321private:
322    RestoreToCountOp() {}
323    DisplayListOp* reinit(int count) {
324        mCount = count;
325        return this;
326    }
327
328    int mCount;
329};
330
331class SaveLayerOp : public StateOp {
332    friend class DisplayList; // give DisplayList private constructor/reinit access
333public:
334    SaveLayerOp(float left, float top, float right, float bottom,
335            int alpha, SkXfermode::Mode mode, int flags)
336            : mArea(left, top, right, bottom), mAlpha(alpha), mMode(mode), mFlags(flags) {}
337
338    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
339            bool useQuickReject) {
340        // NOTE: don't bother with actual saveLayer, instead issuing it at flush time
341        int newSaveCount = deferStruct.mRenderer.getSaveCount();
342        deferStruct.mDeferredList.addSaveLayer(deferStruct.mRenderer, this, newSaveCount);
343
344        // NOTE: don't issue full saveLayer, since that has side effects/is costly. instead just
345        // setup the snapshot for deferral, and re-issue the op at flush time
346        deferStruct.mRenderer.saveLayerDeferred(mArea.left, mArea.top, mArea.right, mArea.bottom,
347                mAlpha, mMode, mFlags);
348    }
349
350    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
351        renderer.saveLayer(mArea.left, mArea.top, mArea.right, mArea.bottom, mAlpha, mMode, mFlags);
352    }
353
354    virtual void output(int level, uint32_t logFlags) const {
355        OP_LOG("SaveLayer%s of area " RECT_STRING,
356                (isSaveLayerAlpha() ? "Alpha" : ""),RECT_ARGS(mArea));
357    }
358
359    virtual const char* name() { return isSaveLayerAlpha() ? "SaveLayerAlpha" : "SaveLayer"; }
360
361    int getFlags() { return mFlags; }
362
363private:
364    // Special case, reserved for direct DisplayList usage
365    SaveLayerOp() {}
366    DisplayListOp* reinit(float left, float top, float right, float bottom,
367            int alpha, SkXfermode::Mode mode, int flags) {
368        mArea.set(left, top, right, bottom);
369        mAlpha = alpha;
370        mMode = mode;
371        mFlags = flags;
372        return this;
373    }
374
375    bool isSaveLayerAlpha() const { return mAlpha < 255 && mMode == SkXfermode::kSrcOver_Mode; }
376    Rect mArea;
377    int mAlpha;
378    SkXfermode::Mode mMode;
379    int mFlags;
380};
381
382class TranslateOp : public StateOp {
383public:
384    TranslateOp(float dx, float dy)
385            : mDx(dx), mDy(dy) {}
386
387    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
388        renderer.translate(mDx, mDy);
389    }
390
391    virtual void output(int level, uint32_t logFlags) const {
392        OP_LOG("Translate by %f %f", mDx, mDy);
393    }
394
395    virtual const char* name() { return "Translate"; }
396
397private:
398    float mDx;
399    float mDy;
400};
401
402class RotateOp : public StateOp {
403public:
404    RotateOp(float degrees)
405            : mDegrees(degrees) {}
406
407    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
408        renderer.rotate(mDegrees);
409    }
410
411    virtual void output(int level, uint32_t logFlags) const {
412        OP_LOG("Rotate by %f degrees", mDegrees);
413    }
414
415    virtual const char* name() { return "Rotate"; }
416
417private:
418    float mDegrees;
419};
420
421class ScaleOp : public StateOp {
422public:
423    ScaleOp(float sx, float sy)
424            : mSx(sx), mSy(sy) {}
425
426    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
427        renderer.scale(mSx, mSy);
428    }
429
430    virtual void output(int level, uint32_t logFlags) const {
431        OP_LOG("Scale by %f %f", mSx, mSy);
432    }
433
434    virtual const char* name() { return "Scale"; }
435
436private:
437    float mSx;
438    float mSy;
439};
440
441class SkewOp : public StateOp {
442public:
443    SkewOp(float sx, float sy)
444            : mSx(sx), mSy(sy) {}
445
446    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
447        renderer.skew(mSx, mSy);
448    }
449
450    virtual void output(int level, uint32_t logFlags) const {
451        OP_LOG("Skew by %f %f", mSx, mSy);
452    }
453
454    virtual const char* name() { return "Skew"; }
455
456private:
457    float mSx;
458    float mSy;
459};
460
461class SetMatrixOp : public StateOp {
462public:
463    SetMatrixOp(SkMatrix* matrix)
464            : mMatrix(matrix) {}
465
466    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
467        renderer.setMatrix(mMatrix);
468    }
469
470    virtual void output(int level, uint32_t logFlags) const {
471        if (mMatrix) {
472            OP_LOG("SetMatrix " MATRIX_STRING, MATRIX_ARGS(mMatrix));
473        } else {
474            OP_LOGS("SetMatrix (reset)");
475        }
476    }
477
478    virtual const char* name() { return "SetMatrix"; }
479
480private:
481    SkMatrix* mMatrix;
482};
483
484class ConcatMatrixOp : public StateOp {
485public:
486    ConcatMatrixOp(SkMatrix* matrix)
487            : mMatrix(matrix) {}
488
489    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
490        renderer.concatMatrix(mMatrix);
491    }
492
493    virtual void output(int level, uint32_t logFlags) const {
494        OP_LOG("ConcatMatrix " MATRIX_STRING, MATRIX_ARGS(mMatrix));
495    }
496
497    virtual const char* name() { return "ConcatMatrix"; }
498
499private:
500    SkMatrix* mMatrix;
501};
502
503class ClipOp : public StateOp {
504public:
505    ClipOp(SkRegion::Op op) : mOp(op) {}
506
507    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
508            bool useQuickReject) {
509        // NOTE: must defer op BEFORE applying state, since it may read clip
510        deferStruct.mDeferredList.addClip(deferStruct.mRenderer, this);
511
512        // TODO: Can we avoid applying complex clips at defer time?
513        applyState(deferStruct.mRenderer, saveCount);
514    }
515
516    bool canCauseComplexClip() {
517        return ((mOp != SkRegion::kIntersect_Op) && (mOp != SkRegion::kReplace_Op)) || !isRect();
518    }
519
520protected:
521    ClipOp() {}
522    virtual bool isRect() { return false; }
523
524    SkRegion::Op mOp;
525};
526
527class ClipRectOp : public ClipOp {
528    friend class DisplayList; // give DisplayList private constructor/reinit access
529public:
530    ClipRectOp(float left, float top, float right, float bottom, SkRegion::Op op)
531            : ClipOp(op), mArea(left, top, right, bottom) {}
532
533    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
534        renderer.clipRect(mArea.left, mArea.top, mArea.right, mArea.bottom, mOp);
535    }
536
537    virtual void output(int level, uint32_t logFlags) const {
538        OP_LOG("ClipRect " RECT_STRING, RECT_ARGS(mArea));
539    }
540
541    virtual const char* name() { return "ClipRect"; }
542
543protected:
544    virtual bool isRect() { return true; }
545
546private:
547    ClipRectOp() {}
548    DisplayListOp* reinit(float left, float top, float right, float bottom, SkRegion::Op op) {
549        mOp = op;
550        mArea.set(left, top, right, bottom);
551        return this;
552    }
553
554    Rect mArea;
555};
556
557class ClipPathOp : public ClipOp {
558public:
559    ClipPathOp(SkPath* path, SkRegion::Op op)
560            : ClipOp(op), mPath(path) {}
561
562    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
563        renderer.clipPath(mPath, mOp);
564    }
565
566    virtual void output(int level, uint32_t logFlags) const {
567        SkRect bounds = mPath->getBounds();
568        OP_LOG("ClipPath bounds " RECT_STRING,
569                bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
570    }
571
572    virtual const char* name() { return "ClipPath"; }
573
574private:
575    SkPath* mPath;
576};
577
578class ClipRegionOp : public ClipOp {
579public:
580    ClipRegionOp(SkRegion* region, SkRegion::Op op)
581            : ClipOp(op), mRegion(region) {}
582
583    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
584        renderer.clipRegion(mRegion, mOp);
585    }
586
587    virtual void output(int level, uint32_t logFlags) const {
588        SkIRect bounds = mRegion->getBounds();
589        OP_LOG("ClipRegion bounds %d %d %d %d",
590                bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
591    }
592
593    virtual const char* name() { return "ClipRegion"; }
594
595private:
596    SkRegion* mRegion;
597};
598
599class ResetShaderOp : public StateOp {
600public:
601    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
602        renderer.resetShader();
603    }
604
605    virtual void output(int level, uint32_t logFlags) const {
606        OP_LOGS("ResetShader");
607    }
608
609    virtual const char* name() { return "ResetShader"; }
610};
611
612class SetupShaderOp : public StateOp {
613public:
614    SetupShaderOp(SkiaShader* shader)
615            : mShader(shader) {}
616    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
617        renderer.setupShader(mShader);
618    }
619
620    virtual void output(int level, uint32_t logFlags) const {
621        OP_LOG("SetupShader, shader %p", mShader);
622    }
623
624    virtual const char* name() { return "SetupShader"; }
625
626private:
627    SkiaShader* mShader;
628};
629
630class ResetColorFilterOp : public StateOp {
631public:
632    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
633        renderer.resetColorFilter();
634    }
635
636    virtual void output(int level, uint32_t logFlags) const {
637        OP_LOGS("ResetColorFilter");
638    }
639
640    virtual const char* name() { return "ResetColorFilter"; }
641};
642
643class SetupColorFilterOp : public StateOp {
644public:
645    SetupColorFilterOp(SkiaColorFilter* colorFilter)
646            : mColorFilter(colorFilter) {}
647
648    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
649        renderer.setupColorFilter(mColorFilter);
650    }
651
652    virtual void output(int level, uint32_t logFlags) const {
653        OP_LOG("SetupColorFilter, filter %p", mColorFilter);
654    }
655
656    virtual const char* name() { return "SetupColorFilter"; }
657
658private:
659    SkiaColorFilter* mColorFilter;
660};
661
662class ResetShadowOp : public StateOp {
663public:
664    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
665        renderer.resetShadow();
666    }
667
668    virtual void output(int level, uint32_t logFlags) const {
669        OP_LOGS("ResetShadow");
670    }
671
672    virtual const char* name() { return "ResetShadow"; }
673};
674
675class SetupShadowOp : public StateOp {
676public:
677    SetupShadowOp(float radius, float dx, float dy, int color)
678            : mRadius(radius), mDx(dx), mDy(dy), mColor(color) {}
679
680    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
681        renderer.setupShadow(mRadius, mDx, mDy, mColor);
682    }
683
684    virtual void output(int level, uint32_t logFlags) const {
685        OP_LOG("SetupShadow, radius %f, %f, %f, color %#x", mRadius, mDx, mDy, mColor);
686    }
687
688    virtual const char* name() { return "SetupShadow"; }
689
690private:
691    float mRadius;
692    float mDx;
693    float mDy;
694    int mColor;
695};
696
697class ResetPaintFilterOp : public StateOp {
698public:
699    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
700        renderer.resetPaintFilter();
701    }
702
703    virtual void output(int level, uint32_t logFlags) const {
704        OP_LOGS("ResetPaintFilter");
705    }
706
707    virtual const char* name() { return "ResetPaintFilter"; }
708};
709
710class SetupPaintFilterOp : public StateOp {
711public:
712    SetupPaintFilterOp(int clearBits, int setBits)
713            : mClearBits(clearBits), mSetBits(setBits) {}
714
715    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
716        renderer.setupPaintFilter(mClearBits, mSetBits);
717    }
718
719    virtual void output(int level, uint32_t logFlags) const {
720        OP_LOG("SetupPaintFilter, clear %#x, set %#x", mClearBits, mSetBits);
721    }
722
723    virtual const char* name() { return "SetupPaintFilter"; }
724
725private:
726    int mClearBits;
727    int mSetBits;
728};
729
730///////////////////////////////////////////////////////////////////////////////
731// DRAW OPERATIONS - these are operations that can draw to the canvas's device
732///////////////////////////////////////////////////////////////////////////////
733
734class DrawBitmapOp : public DrawBoundedOp {
735public:
736    DrawBitmapOp(SkBitmap* bitmap, float left, float top, SkPaint* paint)
737            : DrawBoundedOp(left, top, left + bitmap->width(), top + bitmap->height(), paint),
738            mBitmap(bitmap), mAtlas(Caches::getInstance().assetAtlas) {
739        mEntry = mAtlas.getEntry(bitmap);
740        if (mEntry) {
741            mEntryGenerationId = mAtlas.getGenerationId();
742            mUvMapper = mEntry->uvMapper;
743        }
744    }
745
746    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
747        return renderer.drawBitmap(mBitmap, mLocalBounds.left, mLocalBounds.top,
748                getPaint(renderer));
749    }
750
751    AssetAtlas::Entry* getAtlasEntry() {
752        // The atlas entry is stale, let's get a new one
753        if (mEntry && mEntryGenerationId != mAtlas.getGenerationId()) {
754            mEntryGenerationId = mAtlas.getGenerationId();
755            mEntry = mAtlas.getEntry(mBitmap);
756            mUvMapper = mEntry->uvMapper;
757        }
758        return mEntry;
759    }
760
761#define SET_TEXTURE(ptr, posRect, offsetRect, texCoordsRect, xDim, yDim) \
762    TextureVertex::set(ptr++, posRect.xDim - offsetRect.left, posRect.yDim - offsetRect.top, \
763            texCoordsRect.xDim, texCoordsRect.yDim)
764
765    /**
766     * This multi-draw operation builds a mesh on the stack by generating a quad
767     * for each bitmap in the batch. This method is also responsible for dirtying
768     * the current layer, if any.
769     */
770    virtual status_t multiDraw(OpenGLRenderer& renderer, Rect& dirty,
771            const Vector<DrawOp*>& ops, const Rect& bounds) {
772        renderer.restoreDisplayState(state, true); // restore all but the clip
773        TextureVertex vertices[6 * ops.size()];
774        TextureVertex* vertex = &vertices[0];
775
776        const bool hasLayer = renderer.hasLayer();
777        bool transformed = false;
778
779        // TODO: manually handle rect clip for bitmaps by adjusting texCoords per op,
780        // and allowing them to be merged in getBatchId()
781        for (unsigned int i = 0; i < ops.size(); i++) {
782            const Rect& opBounds = ops[i]->state.mBounds;
783            // When we reach multiDraw(), the matrix can be either
784            // pureTranslate or simple (translate and/or scale).
785            // If the matrix is not pureTranslate, then we have a scale
786            if (!ops[i]->state.mMatrix.isPureTranslate()) transformed = true;
787
788            Rect texCoords(0, 0, 1, 1);
789            ((DrawBitmapOp*) ops[i])->mUvMapper.map(texCoords);
790
791            SET_TEXTURE(vertex, opBounds, bounds, texCoords, left, top);
792            SET_TEXTURE(vertex, opBounds, bounds, texCoords, right, top);
793            SET_TEXTURE(vertex, opBounds, bounds, texCoords, left, bottom);
794
795            SET_TEXTURE(vertex, opBounds, bounds, texCoords, left, bottom);
796            SET_TEXTURE(vertex, opBounds, bounds, texCoords, right, top);
797            SET_TEXTURE(vertex, opBounds, bounds, texCoords, right, bottom);
798
799            if (hasLayer) {
800                const Rect& dirty = ops[i]->state.mBounds;
801                renderer.dirtyLayer(dirty.left, dirty.top, dirty.right, dirty.bottom);
802            }
803        }
804
805        return renderer.drawBitmaps(mBitmap, mEntry, ops.size(), &vertices[0],
806                transformed, bounds, mPaint);
807    }
808
809    virtual void output(int level, uint32_t logFlags) const {
810        OP_LOG("Draw bitmap %p at %f %f", mBitmap, mLocalBounds.left, mLocalBounds.top);
811    }
812
813    virtual const char* name() { return "DrawBitmap"; }
814
815    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
816        deferInfo.batchId = DeferredDisplayList::kOpBatch_Bitmap;
817        deferInfo.mergeId = getAtlasEntry() ? (mergeid_t) &mEntry->atlas : (mergeid_t) mBitmap;
818
819        // Don't merge A8 bitmaps - the paint's color isn't compared by mergeId, or in
820        // MergingDrawBatch::canMergeWith()
821        // TODO: support clipped bitmaps by handling them in SET_TEXTURE
822        deferInfo.mergeable = state.mMatrix.isSimple() && !state.mClipSideFlags &&
823                OpenGLRenderer::getXfermodeDirect(mPaint) == SkXfermode::kSrcOver_Mode &&
824                (mBitmap->getConfig() != SkBitmap::kA8_Config);
825    }
826
827    const SkBitmap* bitmap() { return mBitmap; }
828protected:
829    SkBitmap* mBitmap;
830    const AssetAtlas& mAtlas;
831    uint32_t mEntryGenerationId;
832    AssetAtlas::Entry* mEntry;
833    UvMapper mUvMapper;
834};
835
836class DrawBitmapMatrixOp : public DrawBoundedOp {
837public:
838    DrawBitmapMatrixOp(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint)
839            : DrawBoundedOp(paint), mBitmap(bitmap), mMatrix(matrix) {
840        mLocalBounds.set(0, 0, bitmap->width(), bitmap->height());
841        const mat4 transform(*matrix);
842        transform.mapRect(mLocalBounds);
843    }
844
845    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
846        return renderer.drawBitmap(mBitmap, mMatrix, getPaint(renderer));
847    }
848
849    virtual void output(int level, uint32_t logFlags) const {
850        OP_LOG("Draw bitmap %p matrix " MATRIX_STRING, mBitmap, MATRIX_ARGS(mMatrix));
851    }
852
853    virtual const char* name() { return "DrawBitmapMatrix"; }
854
855    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
856        deferInfo.batchId = DeferredDisplayList::kOpBatch_Bitmap;
857    }
858
859private:
860    SkBitmap* mBitmap;
861    SkMatrix* mMatrix;
862};
863
864class DrawBitmapRectOp : public DrawBoundedOp {
865public:
866    DrawBitmapRectOp(SkBitmap* bitmap, float srcLeft, float srcTop, float srcRight, float srcBottom,
867            float dstLeft, float dstTop, float dstRight, float dstBottom, SkPaint* paint)
868            : DrawBoundedOp(dstLeft, dstTop, dstRight, dstBottom, paint),
869            mBitmap(bitmap), mSrc(srcLeft, srcTop, srcRight, srcBottom) {}
870
871    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
872        return renderer.drawBitmap(mBitmap, mSrc.left, mSrc.top, mSrc.right, mSrc.bottom,
873                mLocalBounds.left, mLocalBounds.top, mLocalBounds.right, mLocalBounds.bottom,
874                getPaint(renderer));
875    }
876
877    virtual void output(int level, uint32_t logFlags) const {
878        OP_LOG("Draw bitmap %p src="RECT_STRING", dst="RECT_STRING,
879                mBitmap, RECT_ARGS(mSrc), RECT_ARGS(mLocalBounds));
880    }
881
882    virtual const char* name() { return "DrawBitmapRect"; }
883
884    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
885        deferInfo.batchId = DeferredDisplayList::kOpBatch_Bitmap;
886    }
887
888private:
889    SkBitmap* mBitmap;
890    Rect mSrc;
891};
892
893class DrawBitmapDataOp : public DrawBitmapOp {
894public:
895    DrawBitmapDataOp(SkBitmap* bitmap, float left, float top, SkPaint* paint)
896            : DrawBitmapOp(bitmap, left, top, paint) {}
897
898    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
899        return renderer.drawBitmapData(mBitmap, mLocalBounds.left,
900                mLocalBounds.top, getPaint(renderer));
901    }
902
903    virtual void output(int level, uint32_t logFlags) const {
904        OP_LOG("Draw bitmap %p", mBitmap);
905    }
906
907    virtual const char* name() { return "DrawBitmapData"; }
908
909    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
910        deferInfo.batchId = DeferredDisplayList::kOpBatch_Bitmap;
911    }
912};
913
914class DrawBitmapMeshOp : public DrawBoundedOp {
915public:
916    DrawBitmapMeshOp(SkBitmap* bitmap, int meshWidth, int meshHeight,
917            float* vertices, int* colors, SkPaint* paint)
918            : DrawBoundedOp(vertices, 2 * (meshWidth + 1) * (meshHeight + 1), paint),
919            mBitmap(bitmap), mMeshWidth(meshWidth), mMeshHeight(meshHeight),
920            mVertices(vertices), mColors(colors) {}
921
922    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
923        return renderer.drawBitmapMesh(mBitmap, mMeshWidth, mMeshHeight,
924                mVertices, mColors, getPaint(renderer));
925    }
926
927    virtual void output(int level, uint32_t logFlags) const {
928        OP_LOG("Draw bitmap %p mesh %d x %d", mBitmap, mMeshWidth, mMeshHeight);
929    }
930
931    virtual const char* name() { return "DrawBitmapMesh"; }
932
933    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
934        deferInfo.batchId = DeferredDisplayList::kOpBatch_Bitmap;
935    }
936
937private:
938    SkBitmap* mBitmap;
939    int mMeshWidth;
940    int mMeshHeight;
941    float* mVertices;
942    int* mColors;
943};
944
945class DrawPatchOp : public DrawBoundedOp {
946public:
947    DrawPatchOp(SkBitmap* bitmap, Res_png_9patch* patch,
948            float left, float top, float right, float bottom, SkPaint* paint)
949            : DrawBoundedOp(left, top, right, bottom, paint),
950            mBitmap(bitmap), mPatch(patch), mGenerationId(0), mMesh(NULL),
951            mAtlas(Caches::getInstance().assetAtlas) {
952        mEntry = mAtlas.getEntry(bitmap);
953        if (mEntry) {
954            mEntryGenerationId = mAtlas.getGenerationId();
955        }
956    };
957
958    AssetAtlas::Entry* getAtlasEntry() {
959        // The atlas entry is stale, let's get a new one
960        if (mEntry && mEntryGenerationId != mAtlas.getGenerationId()) {
961            mEntryGenerationId = mAtlas.getGenerationId();
962            mEntry = mAtlas.getEntry(mBitmap);
963        }
964        return mEntry;
965    }
966
967    const Patch* getMesh(OpenGLRenderer& renderer) {
968        if (!mMesh || renderer.getCaches().patchCache.getGenerationId() != mGenerationId) {
969            PatchCache& cache = renderer.getCaches().patchCache;
970            mMesh = cache.get(getAtlasEntry(), mBitmap->width(), mBitmap->height(),
971                    mLocalBounds.getWidth(), mLocalBounds.getHeight(), mPatch);
972            mGenerationId = cache.getGenerationId();
973        }
974        return mMesh;
975    }
976
977    /**
978     * This multi-draw operation builds an indexed mesh on the stack by copying
979     * and transforming the vertices of each 9-patch in the batch. This method
980     * is also responsible for dirtying the current layer, if any.
981     */
982    virtual status_t multiDraw(OpenGLRenderer& renderer, Rect& dirty,
983            const Vector<DrawOp*>& ops, const Rect& bounds) {
984        renderer.restoreDisplayState(state, true);
985
986        // Batches will usually contain a small number of items so it's
987        // worth performing a first iteration to count the exact number
988        // of vertices we need in the new mesh
989        uint32_t totalVertices = 0;
990        for (unsigned int i = 0; i < ops.size(); i++) {
991            totalVertices += ((DrawPatchOp*) ops[i])->getMesh(renderer)->verticesCount;
992        }
993
994        const bool hasLayer = renderer.hasLayer();
995
996        uint32_t indexCount = 0;
997
998        TextureVertex vertices[totalVertices];
999        TextureVertex* vertex = &vertices[0];
1000
1001        // Create a mesh that contains the transformed vertices for all the
1002        // 9-patch objects that are part of the batch. Note that onDefer()
1003        // enforces ops drawn by this function to have a pure translate or
1004        // identity matrix
1005        for (unsigned int i = 0; i < ops.size(); i++) {
1006            DrawPatchOp* patchOp = (DrawPatchOp*) ops[i];
1007            const Patch* opMesh = patchOp->getMesh(renderer);
1008            uint32_t vertexCount = opMesh->verticesCount;
1009            if (vertexCount == 0) continue;
1010
1011            // We use the bounds to know where to translate our vertices
1012            // Using patchOp->state.mBounds wouldn't work because these
1013            // bounds are clipped
1014            const float tx = (int) floorf(patchOp->state.mMatrix.getTranslateX() +
1015                    patchOp->mLocalBounds.left + 0.5f);
1016            const float ty = (int) floorf(patchOp->state.mMatrix.getTranslateY() +
1017                    patchOp->mLocalBounds.top + 0.5f);
1018
1019            // Copy & transform all the vertices for the current operation
1020            TextureVertex* opVertices = opMesh->vertices;
1021            for (uint32_t j = 0; j < vertexCount; j++, opVertices++) {
1022                TextureVertex::set(vertex++,
1023                        opVertices->position[0] + tx, opVertices->position[1] + ty,
1024                        opVertices->texture[0], opVertices->texture[1]);
1025            }
1026
1027            // Dirty the current layer if possible. When the 9-patch does not
1028            // contain empty quads we can take a shortcut and simply set the
1029            // dirty rect to the object's bounds.
1030            if (hasLayer) {
1031                if (!opMesh->hasEmptyQuads) {
1032                    renderer.dirtyLayer(tx, ty,
1033                            tx + patchOp->mLocalBounds.getWidth(),
1034                            ty + patchOp->mLocalBounds.getHeight());
1035                } else {
1036                    const size_t count = opMesh->quads.size();
1037                    for (size_t i = 0; i < count; i++) {
1038                        const Rect& quadBounds = opMesh->quads[i];
1039                        const float x = tx + quadBounds.left;
1040                        const float y = ty + quadBounds.top;
1041                        renderer.dirtyLayer(x, y,
1042                                x + quadBounds.getWidth(), y + quadBounds.getHeight());
1043                    }
1044                }
1045            }
1046
1047            indexCount += opMesh->indexCount;
1048        }
1049
1050        return renderer.drawPatches(mBitmap, getAtlasEntry(),
1051                &vertices[0], indexCount, getPaint(renderer));
1052    }
1053
1054    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1055        // We're not calling the public variant of drawPatch() here
1056        // This method won't perform the quickReject() since we've already done it at this point
1057        return renderer.drawPatch(mBitmap, getMesh(renderer), getAtlasEntry(),
1058                mLocalBounds.left, mLocalBounds.top, mLocalBounds.right, mLocalBounds.bottom,
1059                getPaint(renderer));
1060    }
1061
1062    virtual void output(int level, uint32_t logFlags) const {
1063        OP_LOG("Draw patch "RECT_STRING, RECT_ARGS(mLocalBounds));
1064    }
1065
1066    virtual const char* name() { return "DrawPatch"; }
1067
1068    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
1069        deferInfo.batchId = DeferredDisplayList::kOpBatch_Patch;
1070        deferInfo.mergeId = getAtlasEntry() ? (mergeid_t) &mEntry->atlas : (mergeid_t) mBitmap;
1071        deferInfo.mergeable = state.mMatrix.isPureTranslate() &&
1072                OpenGLRenderer::getXfermodeDirect(mPaint) == SkXfermode::kSrcOver_Mode;
1073        deferInfo.opaqueOverBounds = isOpaqueOverBounds() && mBitmap->isOpaque();
1074    }
1075
1076private:
1077    SkBitmap* mBitmap;
1078    Res_png_9patch* mPatch;
1079
1080    uint32_t mGenerationId;
1081    const Patch* mMesh;
1082
1083    const AssetAtlas& mAtlas;
1084    uint32_t mEntryGenerationId;
1085    AssetAtlas::Entry* mEntry;
1086};
1087
1088class DrawColorOp : public DrawOp {
1089public:
1090    DrawColorOp(int color, SkXfermode::Mode mode)
1091            : DrawOp(0), mColor(color), mMode(mode) {};
1092
1093    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1094        return renderer.drawColor(mColor, mMode);
1095    }
1096
1097    virtual void output(int level, uint32_t logFlags) const {
1098        OP_LOG("Draw color %#x, mode %d", mColor, mMode);
1099    }
1100
1101    virtual const char* name() { return "DrawColor"; }
1102
1103private:
1104    int mColor;
1105    SkXfermode::Mode mMode;
1106};
1107
1108class DrawStrokableOp : public DrawBoundedOp {
1109public:
1110    DrawStrokableOp(float left, float top, float right, float bottom, SkPaint* paint)
1111            : DrawBoundedOp(left, top, right, bottom, paint) {};
1112
1113    bool getLocalBounds(Rect& localBounds) {
1114        localBounds.set(mLocalBounds);
1115        if (mPaint && mPaint->getStyle() != SkPaint::kFill_Style) {
1116            localBounds.outset(strokeWidthOutset());
1117        }
1118        return true;
1119    }
1120
1121    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
1122        if (mPaint->getPathEffect()) {
1123            deferInfo.batchId = DeferredDisplayList::kOpBatch_AlphaMaskTexture;
1124        } else {
1125            deferInfo.batchId = mPaint->isAntiAlias() ?
1126                    DeferredDisplayList::kOpBatch_AlphaVertices :
1127                    DeferredDisplayList::kOpBatch_Vertices;
1128        }
1129    }
1130};
1131
1132class DrawRectOp : public DrawStrokableOp {
1133public:
1134    DrawRectOp(float left, float top, float right, float bottom, SkPaint* paint)
1135            : DrawStrokableOp(left, top, right, bottom, paint) {}
1136
1137    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1138        return renderer.drawRect(mLocalBounds.left, mLocalBounds.top,
1139                mLocalBounds.right, mLocalBounds.bottom, getPaint(renderer));
1140    }
1141
1142    virtual void output(int level, uint32_t logFlags) const {
1143        OP_LOG("Draw Rect "RECT_STRING, RECT_ARGS(mLocalBounds));
1144    }
1145
1146    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
1147        DrawStrokableOp::onDefer(renderer, deferInfo);
1148        deferInfo.opaqueOverBounds = isOpaqueOverBounds() &&
1149                mPaint->getStyle() == SkPaint::kFill_Style;
1150    }
1151
1152    virtual const char* name() { return "DrawRect"; }
1153};
1154
1155class DrawRectsOp : public DrawBoundedOp {
1156public:
1157    DrawRectsOp(const float* rects, int count, SkPaint* paint)
1158            : DrawBoundedOp(rects, count, paint),
1159            mRects(rects), mCount(count) {}
1160
1161    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1162        return renderer.drawRects(mRects, mCount, getPaint(renderer));
1163    }
1164
1165    virtual void output(int level, uint32_t logFlags) const {
1166        OP_LOG("Draw Rects count %d", mCount);
1167    }
1168
1169    virtual const char* name() { return "DrawRects"; }
1170
1171    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
1172        deferInfo.batchId = DeferredDisplayList::kOpBatch_Vertices;
1173    }
1174
1175private:
1176    const float* mRects;
1177    int mCount;
1178};
1179
1180class DrawRoundRectOp : public DrawStrokableOp {
1181public:
1182    DrawRoundRectOp(float left, float top, float right, float bottom,
1183            float rx, float ry, SkPaint* paint)
1184            : DrawStrokableOp(left, top, right, bottom, paint), mRx(rx), mRy(ry) {}
1185
1186    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1187        return renderer.drawRoundRect(mLocalBounds.left, mLocalBounds.top,
1188                mLocalBounds.right, mLocalBounds.bottom, mRx, mRy, getPaint(renderer));
1189    }
1190
1191    virtual void output(int level, uint32_t logFlags) const {
1192        OP_LOG("Draw RoundRect "RECT_STRING", rx %f, ry %f", RECT_ARGS(mLocalBounds), mRx, mRy);
1193    }
1194
1195    virtual const char* name() { return "DrawRoundRect"; }
1196
1197private:
1198    float mRx;
1199    float mRy;
1200};
1201
1202class DrawCircleOp : public DrawStrokableOp {
1203public:
1204    DrawCircleOp(float x, float y, float radius, SkPaint* paint)
1205            : DrawStrokableOp(x - radius, y - radius, x + radius, y + radius, paint),
1206            mX(x), mY(y), mRadius(radius) {}
1207
1208    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1209        return renderer.drawCircle(mX, mY, mRadius, getPaint(renderer));
1210    }
1211
1212    virtual void output(int level, uint32_t logFlags) const {
1213        OP_LOG("Draw Circle x %f, y %f, r %f", mX, mY, mRadius);
1214    }
1215
1216    virtual const char* name() { return "DrawCircle"; }
1217
1218private:
1219    float mX;
1220    float mY;
1221    float mRadius;
1222};
1223
1224class DrawOvalOp : public DrawStrokableOp {
1225public:
1226    DrawOvalOp(float left, float top, float right, float bottom, SkPaint* paint)
1227            : DrawStrokableOp(left, top, right, bottom, paint) {}
1228
1229    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1230        return renderer.drawOval(mLocalBounds.left, mLocalBounds.top,
1231                mLocalBounds.right, mLocalBounds.bottom, getPaint(renderer));
1232    }
1233
1234    virtual void output(int level, uint32_t logFlags) const {
1235        OP_LOG("Draw Oval "RECT_STRING, RECT_ARGS(mLocalBounds));
1236    }
1237
1238    virtual const char* name() { return "DrawOval"; }
1239};
1240
1241class DrawArcOp : public DrawStrokableOp {
1242public:
1243    DrawArcOp(float left, float top, float right, float bottom,
1244            float startAngle, float sweepAngle, bool useCenter, SkPaint* paint)
1245            : DrawStrokableOp(left, top, right, bottom, paint),
1246            mStartAngle(startAngle), mSweepAngle(sweepAngle), mUseCenter(useCenter) {}
1247
1248    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1249        return renderer.drawArc(mLocalBounds.left, mLocalBounds.top,
1250                mLocalBounds.right, mLocalBounds.bottom,
1251                mStartAngle, mSweepAngle, mUseCenter, getPaint(renderer));
1252    }
1253
1254    virtual void output(int level, uint32_t logFlags) const {
1255        OP_LOG("Draw Arc "RECT_STRING", start %f, sweep %f, useCenter %d",
1256                RECT_ARGS(mLocalBounds), mStartAngle, mSweepAngle, mUseCenter);
1257    }
1258
1259    virtual const char* name() { return "DrawArc"; }
1260
1261private:
1262    float mStartAngle;
1263    float mSweepAngle;
1264    bool mUseCenter;
1265};
1266
1267class DrawPathOp : public DrawBoundedOp {
1268public:
1269    DrawPathOp(SkPath* path, SkPaint* paint)
1270            : DrawBoundedOp(paint), mPath(path) {
1271        float left, top, offset;
1272        uint32_t width, height;
1273        PathCache::computePathBounds(path, paint, left, top, offset, width, height);
1274        left -= offset;
1275        top -= offset;
1276        mLocalBounds.set(left, top, left + width, top + height);
1277    }
1278
1279    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1280        return renderer.drawPath(mPath, getPaint(renderer));
1281    }
1282
1283    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
1284        SkPaint* paint = getPaint(renderer);
1285        renderer.getCaches().pathCache.precache(mPath, paint);
1286
1287        deferInfo.batchId = DeferredDisplayList::kOpBatch_AlphaMaskTexture;
1288    }
1289
1290    virtual void output(int level, uint32_t logFlags) const {
1291        OP_LOG("Draw Path %p in "RECT_STRING, mPath, RECT_ARGS(mLocalBounds));
1292    }
1293
1294    virtual const char* name() { return "DrawPath"; }
1295
1296private:
1297    SkPath* mPath;
1298};
1299
1300class DrawLinesOp : public DrawBoundedOp {
1301public:
1302    DrawLinesOp(float* points, int count, SkPaint* paint)
1303            : DrawBoundedOp(points, count, paint),
1304            mPoints(points), mCount(count) {
1305        mLocalBounds.outset(strokeWidthOutset());
1306    }
1307
1308    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1309        return renderer.drawLines(mPoints, mCount, getPaint(renderer));
1310    }
1311
1312    virtual void output(int level, uint32_t logFlags) const {
1313        OP_LOG("Draw Lines count %d", mCount);
1314    }
1315
1316    virtual const char* name() { return "DrawLines"; }
1317
1318    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
1319        deferInfo.batchId = mPaint->isAntiAlias() ?
1320                DeferredDisplayList::kOpBatch_AlphaVertices :
1321                DeferredDisplayList::kOpBatch_Vertices;
1322    }
1323
1324protected:
1325    float* mPoints;
1326    int mCount;
1327};
1328
1329class DrawPointsOp : public DrawLinesOp {
1330public:
1331    DrawPointsOp(float* points, int count, SkPaint* paint)
1332            : DrawLinesOp(points, count, paint) {}
1333
1334    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1335        return renderer.drawPoints(mPoints, mCount, getPaint(renderer));
1336    }
1337
1338    virtual void output(int level, uint32_t logFlags) const {
1339        OP_LOG("Draw Points count %d", mCount);
1340    }
1341
1342    virtual const char* name() { return "DrawPoints"; }
1343};
1344
1345class DrawSomeTextOp : public DrawOp {
1346public:
1347    DrawSomeTextOp(const char* text, int bytesCount, int count, SkPaint* paint)
1348            : DrawOp(paint), mText(text), mBytesCount(bytesCount), mCount(count) {};
1349
1350    virtual void output(int level, uint32_t logFlags) const {
1351        OP_LOG("Draw some text, %d bytes", mBytesCount);
1352    }
1353
1354    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
1355        SkPaint* paint = getPaint(renderer);
1356        FontRenderer& fontRenderer = renderer.getCaches().fontRenderer->getFontRenderer(paint);
1357        fontRenderer.precache(paint, mText, mCount, mat4::identity());
1358
1359        deferInfo.batchId = mPaint->getColor() == 0xff000000 ?
1360                DeferredDisplayList::kOpBatch_Text :
1361                DeferredDisplayList::kOpBatch_ColorText;
1362    }
1363
1364protected:
1365    const char* mText;
1366    int mBytesCount;
1367    int mCount;
1368};
1369
1370class DrawTextOnPathOp : public DrawSomeTextOp {
1371public:
1372    DrawTextOnPathOp(const char* text, int bytesCount, int count,
1373            SkPath* path, float hOffset, float vOffset, SkPaint* paint)
1374            : DrawSomeTextOp(text, bytesCount, count, paint),
1375            mPath(path), mHOffset(hOffset), mVOffset(vOffset) {
1376        /* TODO: inherit from DrawBounded and init mLocalBounds */
1377    }
1378
1379    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1380        return renderer.drawTextOnPath(mText, mBytesCount, mCount, mPath,
1381                mHOffset, mVOffset, getPaint(renderer));
1382    }
1383
1384    virtual const char* name() { return "DrawTextOnPath"; }
1385
1386private:
1387    SkPath* mPath;
1388    float mHOffset;
1389    float mVOffset;
1390};
1391
1392class DrawPosTextOp : public DrawSomeTextOp {
1393public:
1394    DrawPosTextOp(const char* text, int bytesCount, int count,
1395            const float* positions, SkPaint* paint)
1396            : DrawSomeTextOp(text, bytesCount, count, paint), mPositions(positions) {
1397        /* TODO: inherit from DrawBounded and init mLocalBounds */
1398    }
1399
1400    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1401        return renderer.drawPosText(mText, mBytesCount, mCount, mPositions, getPaint(renderer));
1402    }
1403
1404    virtual const char* name() { return "DrawPosText"; }
1405
1406private:
1407    const float* mPositions;
1408};
1409
1410class DrawTextOp : public DrawBoundedOp {
1411public:
1412    DrawTextOp(const char* text, int bytesCount, int count, float x, float y,
1413            const float* positions, SkPaint* paint, float totalAdvance, const Rect& bounds)
1414            : DrawBoundedOp(bounds, paint), mText(text), mBytesCount(bytesCount), mCount(count),
1415            mX(x), mY(y), mPositions(positions), mTotalAdvance(totalAdvance) {
1416        memset(&mPrecacheTransform.data[0], 0xff, 16 * sizeof(float));
1417    }
1418
1419    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo) {
1420        SkPaint* paint = getPaint(renderer);
1421        FontRenderer& fontRenderer = renderer.getCaches().fontRenderer->getFontRenderer(paint);
1422        const mat4& transform = renderer.findBestFontTransform(state.mMatrix);
1423        if (mPrecacheTransform != transform) {
1424            fontRenderer.precache(paint, mText, mCount, transform);
1425            mPrecacheTransform = transform;
1426        }
1427        deferInfo.batchId = mPaint->getColor() == 0xff000000 ?
1428                DeferredDisplayList::kOpBatch_Text :
1429                DeferredDisplayList::kOpBatch_ColorText;
1430
1431        deferInfo.mergeId = (mergeid_t)mPaint->getColor();
1432
1433        // don't merge decorated text - the decorations won't draw in order
1434        bool noDecorations = !(mPaint->getFlags() & (SkPaint::kUnderlineText_Flag |
1435                        SkPaint::kStrikeThruText_Flag));
1436        deferInfo.mergeable = state.mMatrix.isPureTranslate() && noDecorations &&
1437                OpenGLRenderer::getXfermodeDirect(mPaint) == SkXfermode::kSrcOver_Mode;
1438    }
1439
1440    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1441        return renderer.drawText(mText, mBytesCount, mCount, mX, mY,
1442                mPositions, getPaint(renderer), mTotalAdvance, mLocalBounds);
1443    }
1444
1445    virtual status_t multiDraw(OpenGLRenderer& renderer, Rect& dirty,
1446            const Vector<DrawOp*>& ops, const Rect& bounds) {
1447        status_t status = DrawGlInfo::kStatusDone;
1448        for (unsigned int i = 0; i < ops.size(); i++) {
1449            DrawOpMode drawOpMode = (i == ops.size() - 1) ? kDrawOpMode_Flush : kDrawOpMode_Defer;
1450            renderer.restoreDisplayState(ops[i]->state, true); // restore all but the clip
1451
1452            DrawTextOp& op = *((DrawTextOp*)ops[i]);
1453            status |= renderer.drawText(op.mText, op.mBytesCount, op.mCount, op.mX, op.mY,
1454                    op.mPositions, op.getPaint(renderer), op.mTotalAdvance, op.mLocalBounds,
1455                    drawOpMode);
1456        }
1457        return status;
1458    }
1459
1460    virtual void output(int level, uint32_t logFlags) const {
1461        OP_LOG("Draw Text of count %d, bytes %d", mCount, mBytesCount);
1462    }
1463
1464    virtual const char* name() { return "DrawText"; }
1465
1466private:
1467    const char* mText;
1468    int mBytesCount;
1469    int mCount;
1470    float mX;
1471    float mY;
1472    const float* mPositions;
1473    float mTotalAdvance;
1474    mat4 mPrecacheTransform;
1475};
1476
1477///////////////////////////////////////////////////////////////////////////////
1478// SPECIAL DRAW OPERATIONS
1479///////////////////////////////////////////////////////////////////////////////
1480
1481class DrawFunctorOp : public DrawOp {
1482public:
1483    DrawFunctorOp(Functor* functor)
1484            : DrawOp(0), mFunctor(functor) {}
1485
1486    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1487        renderer.startMark("GL functor");
1488        status_t ret = renderer.callDrawGLFunction(mFunctor, dirty);
1489        renderer.endMark();
1490        return ret;
1491    }
1492
1493    virtual void output(int level, uint32_t logFlags) const {
1494        OP_LOG("Draw Functor %p", mFunctor);
1495    }
1496
1497    virtual const char* name() { return "DrawFunctor"; }
1498
1499private:
1500    Functor* mFunctor;
1501};
1502
1503class DrawDisplayListOp : public DrawBoundedOp {
1504public:
1505    DrawDisplayListOp(DisplayList* displayList, int flags)
1506            : DrawBoundedOp(0, 0, displayList->getWidth(), displayList->getHeight(), 0),
1507            mDisplayList(displayList), mFlags(flags) {}
1508
1509    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
1510            bool useQuickReject) {
1511        if (mDisplayList && mDisplayList->isRenderable()) {
1512            mDisplayList->defer(deferStruct, level + 1);
1513        }
1514    }
1515    virtual void replay(ReplayStateStruct& replayStruct, int saveCount, int level,
1516            bool useQuickReject) {
1517        if (mDisplayList && mDisplayList->isRenderable()) {
1518            mDisplayList->replay(replayStruct, level + 1);
1519        }
1520    }
1521
1522    // NOT USED since replay() is overridden
1523    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1524        return DrawGlInfo::kStatusDone;
1525    }
1526
1527    virtual void output(int level, uint32_t logFlags) const {
1528        OP_LOG("Draw Display List %p, flags %#x", mDisplayList, mFlags);
1529        if (mDisplayList && (logFlags & kOpLogFlag_Recurse)) {
1530            mDisplayList->output(level + 1);
1531        }
1532    }
1533
1534    virtual const char* name() { return "DrawDisplayList"; }
1535
1536private:
1537    DisplayList* mDisplayList;
1538    int mFlags;
1539};
1540
1541class DrawLayerOp : public DrawOp {
1542public:
1543    DrawLayerOp(Layer* layer, float x, float y)
1544            : DrawOp(0), mLayer(layer), mX(x), mY(y) {}
1545
1546    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1547        return renderer.drawLayer(mLayer, mX, mY);
1548    }
1549
1550    virtual void output(int level, uint32_t logFlags) const {
1551        OP_LOG("Draw Layer %p at %f %f", mLayer, mX, mY);
1552    }
1553
1554    virtual const char* name() { return "DrawLayer"; }
1555
1556private:
1557    Layer* mLayer;
1558    float mX;
1559    float mY;
1560};
1561
1562}; // namespace uirenderer
1563}; // namespace android
1564
1565#endif // ANDROID_HWUI_DISPLAY_OPERATION_H
1566