DeferredDisplayList.cpp revision d1ad5e62fda248c6d185cde3cb6d9f01a223066c
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#define LOG_TAG "OpenGLRenderer"
18#define ATRACE_TAG ATRACE_TAG_VIEW
19
20#include <SkCanvas.h>
21
22#include <utils/Trace.h>
23#include <ui/Rect.h>
24#include <ui/Region.h>
25
26#include "Caches.h"
27#include "Debug.h"
28#include "DeferredDisplayList.h"
29#include "DisplayListOp.h"
30#include "OpenGLRenderer.h"
31
32#if DEBUG_DEFER
33    #define DEFER_LOGD(...) ALOGD(__VA_ARGS__)
34#else
35    #define DEFER_LOGD(...)
36#endif
37
38namespace android {
39namespace uirenderer {
40
41// Depth of the save stack at the beginning of batch playback at flush time
42#define FLUSH_SAVE_STACK_DEPTH 2
43
44#define DEBUG_COLOR_BARRIER          0x1f000000
45#define DEBUG_COLOR_MERGEDBATCH      0x5f7f7fff
46#define DEBUG_COLOR_MERGEDBATCH_SOLO 0x5f7fff7f
47
48/////////////////////////////////////////////////////////////////////////////////
49// Operation Batches
50/////////////////////////////////////////////////////////////////////////////////
51
52class Batch {
53public:
54    virtual status_t replay(OpenGLRenderer& renderer, Rect& dirty, int index) = 0;
55    virtual ~Batch() {}
56    virtual bool purelyDrawBatch() { return false; }
57    virtual bool coversBounds(const Rect& bounds) { return false; }
58};
59
60class DrawBatch : public Batch {
61public:
62    DrawBatch(const DeferInfo& deferInfo) : mAllOpsOpaque(true),
63            mBatchId(deferInfo.batchId), mMergeId(deferInfo.mergeId) {
64        mOps.clear();
65    }
66
67    virtual ~DrawBatch() { mOps.clear(); }
68
69    virtual void add(DrawOp* op, const DeferredDisplayState* state, bool opaqueOverBounds) {
70        // NOTE: ignore empty bounds special case, since we don't merge across those ops
71        mBounds.unionWith(state->mBounds);
72        mAllOpsOpaque &= opaqueOverBounds;
73        mOps.add(OpStatePair(op, state));
74    }
75
76    bool intersects(const Rect& rect) {
77        if (!rect.intersects(mBounds)) return false;
78
79        for (unsigned int i = 0; i < mOps.size(); i++) {
80            if (rect.intersects(mOps[i].state->mBounds)) {
81#if DEBUG_DEFER
82                DEFER_LOGD("op intersects with op %p with bounds %f %f %f %f:", mOps[i].op,
83                        mOps[i].state->mBounds.left, mOps[i].state->mBounds.top,
84                        mOps[i].state->mBounds.right, mOps[i].state->mBounds.bottom);
85                mOps[i].op->output(2);
86#endif
87                return true;
88            }
89        }
90        return false;
91    }
92
93    virtual status_t replay(OpenGLRenderer& renderer, Rect& dirty, int index) {
94        DEFER_LOGD("%d  replaying DrawBatch %p, with %d ops (batch id %x, merge id %p)",
95                index, this, mOps.size(), getBatchId(), getMergeId());
96
97        status_t status = DrawGlInfo::kStatusDone;
98        DisplayListLogBuffer& logBuffer = DisplayListLogBuffer::getInstance();
99        for (unsigned int i = 0; i < mOps.size(); i++) {
100            DrawOp* op = mOps[i].op;
101            const DeferredDisplayState* state = mOps[i].state;
102            renderer.restoreDisplayState(*state);
103
104#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS
105            renderer.eventMark(op->name());
106#endif
107            logBuffer.writeCommand(0, op->name());
108            status |= op->applyDraw(renderer, dirty);
109
110#if DEBUG_MERGE_BEHAVIOR
111            const Rect& bounds = state->mBounds;
112            int batchColor = 0x1f000000;
113            if (getBatchId() & 0x1) batchColor |= 0x0000ff;
114            if (getBatchId() & 0x2) batchColor |= 0x00ff00;
115            if (getBatchId() & 0x4) batchColor |= 0xff0000;
116            renderer.drawScreenSpaceColorRect(bounds.left, bounds.top, bounds.right, bounds.bottom,
117                    batchColor);
118#endif
119        }
120        return status;
121    }
122
123    virtual bool purelyDrawBatch() { return true; }
124
125    virtual bool coversBounds(const Rect& bounds) {
126        if (CC_LIKELY(!mAllOpsOpaque || !mBounds.contains(bounds) || count() == 1)) return false;
127
128        Region uncovered(android::Rect(bounds.left, bounds.top, bounds.right, bounds.bottom));
129        for (unsigned int i = 0; i < mOps.size(); i++) {
130            const Rect &r = mOps[i].state->mBounds;
131            uncovered.subtractSelf(android::Rect(r.left, r.top, r.right, r.bottom));
132        }
133        return uncovered.isEmpty();
134    }
135
136    inline int getBatchId() const { return mBatchId; }
137    inline mergeid_t getMergeId() const { return mMergeId; }
138    inline int count() const { return mOps.size(); }
139
140protected:
141    Vector<OpStatePair> mOps;
142    Rect mBounds; // union of bounds of contained ops
143private:
144    bool mAllOpsOpaque;
145    int mBatchId;
146    mergeid_t mMergeId;
147};
148
149// compare alphas approximately, with a small margin
150#define NEQ_FALPHA(lhs, rhs) \
151        fabs((float)lhs - (float)rhs) > 0.001f
152
153class MergingDrawBatch : public DrawBatch {
154public:
155    MergingDrawBatch(DeferInfo& deferInfo, int width, int height) :
156            DrawBatch(deferInfo), mClipRect(width, height),
157            mClipSideFlags(kClipSide_None) {}
158
159    /*
160     * Helper for determining if a new op can merge with a MergingDrawBatch based on their bounds
161     * and clip side flags. Positive bounds delta means new bounds fit in old.
162     */
163    static inline bool checkSide(const int currentFlags, const int newFlags, const int side,
164            float boundsDelta) {
165        bool currentClipExists = currentFlags & side;
166        bool newClipExists = newFlags & side;
167
168        // if current is clipped, we must be able to fit new bounds in current
169        if (boundsDelta > 0 && currentClipExists) return false;
170
171        // if new is clipped, we must be able to fit current bounds in new
172        if (boundsDelta < 0 && newClipExists) return false;
173
174        return true;
175    }
176
177    /*
178     * Checks if a (mergeable) op can be merged into this batch
179     *
180     * If true, the op's multiDraw must be guaranteed to handle both ops simultaneously, so it is
181     * important to consider all paint attributes used in the draw calls in deciding both a) if an
182     * op tries to merge at all, and b) if the op can merge with another set of ops
183     *
184     * False positives can lead to information from the paints of subsequent merged operations being
185     * dropped, so we make simplifying qualifications on the ops that can merge, per op type.
186     */
187    bool canMergeWith(const DrawOp* op, const DeferredDisplayState* state) {
188        bool isTextBatch = getBatchId() == DeferredDisplayList::kOpBatch_Text ||
189                getBatchId() == DeferredDisplayList::kOpBatch_ColorText;
190
191        // Overlapping other operations is only allowed for text without shadow. For other ops,
192        // multiDraw isn't guaranteed to overdraw correctly
193        if (!isTextBatch || op->hasTextShadow()) {
194            if (intersects(state->mBounds)) return false;
195        }
196        const DeferredDisplayState* lhs = state;
197        const DeferredDisplayState* rhs = mOps[0].state;
198
199        if (NEQ_FALPHA(lhs->mAlpha, rhs->mAlpha)) return false;
200
201        /* Clipping compatibility check
202         *
203         * Exploits the fact that if a op or batch is clipped on a side, its bounds will equal its
204         * clip for that side.
205         */
206        const int currentFlags = mClipSideFlags;
207        const int newFlags = state->mClipSideFlags;
208        if (currentFlags != kClipSide_None || newFlags != kClipSide_None) {
209            const Rect& opBounds = state->mBounds;
210            float boundsDelta = mBounds.left - opBounds.left;
211            if (!checkSide(currentFlags, newFlags, kClipSide_Left, boundsDelta)) return false;
212            boundsDelta = mBounds.top - opBounds.top;
213            if (!checkSide(currentFlags, newFlags, kClipSide_Top, boundsDelta)) return false;
214
215            // right and bottom delta calculation reversed to account for direction
216            boundsDelta = opBounds.right - mBounds.right;
217            if (!checkSide(currentFlags, newFlags, kClipSide_Right, boundsDelta)) return false;
218            boundsDelta = opBounds.bottom - mBounds.bottom;
219            if (!checkSide(currentFlags, newFlags, kClipSide_Bottom, boundsDelta)) return false;
220        }
221
222        // if paints are equal, then modifiers + paint attribs don't need to be compared
223        if (op->mPaint == mOps[0].op->mPaint) return true;
224
225        if (op->getPaintAlpha() != mOps[0].op->getPaintAlpha()) return false;
226
227        if (op->mPaint && mOps[0].op->mPaint &&
228            op->mPaint->getColorFilter() != mOps[0].op->mPaint->getColorFilter()) {
229            return false;
230        }
231
232        if (op->mPaint && mOps[0].op->mPaint &&
233            op->mPaint->getShader() != mOps[0].op->mPaint->getShader()) {
234            return false;
235        }
236
237        /* Draw Modifiers compatibility check
238         *
239         * Shadows are ignored, as only text uses them, and in that case they are drawn
240         * per-DrawTextOp, before the unified text draw. Because of this, it's always safe to merge
241         * text UNLESS a later draw's shadow should overlays a previous draw's text. This is covered
242         * above with the intersection check.
243         *
244         * OverrideLayerAlpha is also ignored, as it's only used for drawing layers, which are never
245         * merged.
246         *
247         * These ignore cases prevent us from simply memcmp'ing the drawModifiers
248         */
249        const DrawModifiers& lhsMod = lhs->mDrawModifiers;
250        const DrawModifiers& rhsMod = rhs->mDrawModifiers;
251
252        // Draw filter testing expects bit fields to be clear if filter not set.
253        if (lhsMod.mHasDrawFilter != rhsMod.mHasDrawFilter) return false;
254        if (lhsMod.mPaintFilterClearBits != rhsMod.mPaintFilterClearBits) return false;
255        if (lhsMod.mPaintFilterSetBits != rhsMod.mPaintFilterSetBits) return false;
256
257        return true;
258    }
259
260    virtual void add(DrawOp* op, const DeferredDisplayState* state, bool opaqueOverBounds) {
261        DrawBatch::add(op, state, opaqueOverBounds);
262
263        const int newClipSideFlags = state->mClipSideFlags;
264        mClipSideFlags |= newClipSideFlags;
265        if (newClipSideFlags & kClipSide_Left) mClipRect.left = state->mClip.left;
266        if (newClipSideFlags & kClipSide_Top) mClipRect.top = state->mClip.top;
267        if (newClipSideFlags & kClipSide_Right) mClipRect.right = state->mClip.right;
268        if (newClipSideFlags & kClipSide_Bottom) mClipRect.bottom = state->mClip.bottom;
269    }
270
271    virtual status_t replay(OpenGLRenderer& renderer, Rect& dirty, int index) {
272        DEFER_LOGD("%d  replaying MergingDrawBatch %p, with %d ops,"
273                " clip flags %x (batch id %x, merge id %p)",
274                index, this, mOps.size(), mClipSideFlags, getBatchId(), getMergeId());
275        if (mOps.size() == 1) {
276            return DrawBatch::replay(renderer, dirty, -1);
277        }
278
279        // clipping in the merged case is done ahead of time since all ops share the clip (if any)
280        renderer.setupMergedMultiDraw(mClipSideFlags ? &mClipRect : NULL);
281
282        DrawOp* op = mOps[0].op;
283        DisplayListLogBuffer& buffer = DisplayListLogBuffer::getInstance();
284        buffer.writeCommand(0, "multiDraw");
285        buffer.writeCommand(1, op->name());
286
287#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS
288        renderer.eventMark("multiDraw");
289        renderer.eventMark(op->name());
290#endif
291        status_t status = op->multiDraw(renderer, dirty, mOps, mBounds);
292
293#if DEBUG_MERGE_BEHAVIOR
294        renderer.drawScreenSpaceColorRect(mBounds.left, mBounds.top, mBounds.right, mBounds.bottom,
295                DEBUG_COLOR_MERGEDBATCH);
296#endif
297        return status;
298    }
299
300private:
301    /*
302     * Contains the effective clip rect shared by all merged ops. Initialized to the layer viewport,
303     * it will shrink if an op must be clipped on a certain side. The clipped sides are reflected in
304     * mClipSideFlags.
305     */
306    Rect mClipRect;
307    int mClipSideFlags;
308};
309
310class StateOpBatch : public Batch {
311public:
312    // creates a single operation batch
313    StateOpBatch(const StateOp* op, const DeferredDisplayState* state) : mOp(op), mState(state) {}
314
315    virtual status_t replay(OpenGLRenderer& renderer, Rect& dirty, int index) {
316        DEFER_LOGD("replaying state op batch %p", this);
317        renderer.restoreDisplayState(*mState);
318
319        // use invalid save count because it won't be used at flush time - RestoreToCountOp is the
320        // only one to use it, and we don't use that class at flush time, instead calling
321        // renderer.restoreToCount directly
322        int saveCount = -1;
323        mOp->applyState(renderer, saveCount);
324        return DrawGlInfo::kStatusDone;
325    }
326
327private:
328    const StateOp* mOp;
329    const DeferredDisplayState* mState;
330};
331
332class RestoreToCountBatch : public Batch {
333public:
334    RestoreToCountBatch(const StateOp* op, const DeferredDisplayState* state, int restoreCount) :
335            mOp(op), mState(state), mRestoreCount(restoreCount) {}
336
337    virtual status_t replay(OpenGLRenderer& renderer, Rect& dirty, int index) {
338        DEFER_LOGD("batch %p restoring to count %d", this, mRestoreCount);
339
340        renderer.restoreDisplayState(*mState);
341        renderer.restoreToCount(mRestoreCount);
342        return DrawGlInfo::kStatusDone;
343    }
344
345private:
346    // we use the state storage for the RestoreToCountOp, but don't replay the op itself
347    const StateOp* mOp;
348    const DeferredDisplayState* mState;
349
350    /*
351     * The count used here represents the flush() time saveCount. This is as opposed to the
352     * DisplayList record time, or defer() time values (which are RestoreToCountOp's mCount, and
353     * (saveCount + mCount) respectively). Since the count is different from the original
354     * RestoreToCountOp, we don't store a pointer to the op, as elsewhere.
355     */
356    const int mRestoreCount;
357};
358
359#if DEBUG_MERGE_BEHAVIOR
360class BarrierDebugBatch : public Batch {
361    virtual status_t replay(OpenGLRenderer& renderer, Rect& dirty, int index) {
362        renderer.drawScreenSpaceColorRect(0, 0, 10000, 10000, DEBUG_COLOR_BARRIER);
363        return DrawGlInfo::kStatusDrew;
364    }
365};
366#endif
367
368/////////////////////////////////////////////////////////////////////////////////
369// DeferredDisplayList
370/////////////////////////////////////////////////////////////////////////////////
371
372void DeferredDisplayList::resetBatchingState() {
373    for (int i = 0; i < kOpBatch_Count; i++) {
374        mBatchLookup[i] = NULL;
375        mMergingBatches[i].clear();
376    }
377#if DEBUG_MERGE_BEHAVIOR
378    if (mBatches.size() != 0) {
379        mBatches.add(new BarrierDebugBatch());
380    }
381#endif
382    mEarliestBatchIndex = mBatches.size();
383}
384
385void DeferredDisplayList::clear() {
386    resetBatchingState();
387    mComplexClipStackStart = -1;
388
389    for (unsigned int i = 0; i < mBatches.size(); i++) {
390        delete mBatches[i];
391    }
392    mBatches.clear();
393    mSaveStack.clear();
394    mEarliestBatchIndex = 0;
395    mEarliestUnclearedIndex = 0;
396}
397
398/////////////////////////////////////////////////////////////////////////////////
399// Operation adding
400/////////////////////////////////////////////////////////////////////////////////
401
402int DeferredDisplayList::getStateOpDeferFlags() const {
403    // For both clipOp and save(Layer)Op, we don't want to save drawing info, and only want to save
404    // the clip if we aren't recording a complex clip (and can thus trust it to be a rect)
405    return recordingComplexClip() ? 0 : kStateDeferFlag_Clip;
406}
407
408int DeferredDisplayList::getDrawOpDeferFlags() const {
409    return kStateDeferFlag_Draw | getStateOpDeferFlags();
410}
411
412/**
413 * When an clipping operation occurs that could cause a complex clip, record the operation and all
414 * subsequent clipOps, save/restores (if the clip flag is set). During a flush, instead of loading
415 * the clip from deferred state, we play back all of the relevant state operations that generated
416 * the complex clip.
417 *
418 * Note that we don't need to record the associated restore operation, since operations at defer
419 * time record whether they should store the renderer's current clip
420 */
421void DeferredDisplayList::addClip(OpenGLRenderer& renderer, ClipOp* op) {
422    if (recordingComplexClip() || op->canCauseComplexClip() || !renderer.hasRectToRectTransform()) {
423        DEFER_LOGD("%p Received complex clip operation %p", this, op);
424
425        // NOTE: defer clip op before setting mComplexClipStackStart so previous clip is recorded
426        storeStateOpBarrier(renderer, op);
427
428        if (!recordingComplexClip()) {
429            mComplexClipStackStart = renderer.getSaveCount() - 1;
430            DEFER_LOGD("    Starting complex clip region, start is %d", mComplexClipStackStart);
431        }
432    }
433}
434
435/**
436 * For now, we record save layer operations as barriers in the batch list, preventing drawing
437 * operations from reordering around the saveLayer and it's associated restore()
438 *
439 * In the future, we should send saveLayer commands (if they can be played out of order) and their
440 * contained drawing operations to a seperate list of batches, so that they may draw at the
441 * beginning of the frame. This would avoid targetting and removing an FBO in the middle of a frame.
442 *
443 * saveLayer operations should be pulled to the beginning of the frame if the canvas doesn't have a
444 * complex clip, and if the flags (kClip_SaveFlag & kClipToLayer_SaveFlag) are set.
445 */
446void DeferredDisplayList::addSaveLayer(OpenGLRenderer& renderer,
447        SaveLayerOp* op, int newSaveCount) {
448    DEFER_LOGD("%p adding saveLayerOp %p, flags %x, new count %d",
449            this, op, op->getFlags(), newSaveCount);
450
451    storeStateOpBarrier(renderer, op);
452    mSaveStack.push(newSaveCount);
453}
454
455/**
456 * Takes save op and it's return value - the new save count - and stores it into the stream as a
457 * barrier if it's needed to properly modify a complex clip
458 */
459void DeferredDisplayList::addSave(OpenGLRenderer& renderer, SaveOp* op, int newSaveCount) {
460    int saveFlags = op->getFlags();
461    DEFER_LOGD("%p adding saveOp %p, flags %x, new count %d", this, op, saveFlags, newSaveCount);
462
463    if (recordingComplexClip() && (saveFlags & SkCanvas::kClip_SaveFlag)) {
464        // store and replay the save operation, as it may be needed to correctly playback the clip
465        DEFER_LOGD("    adding save barrier with new save count %d", newSaveCount);
466        storeStateOpBarrier(renderer, op);
467        mSaveStack.push(newSaveCount);
468    }
469}
470
471/**
472 * saveLayer() commands must be associated with a restoreToCount batch that will clean up and draw
473 * the layer in the deferred list
474 *
475 * other save() commands which occur as children of a snapshot with complex clip will be deferred,
476 * and must be restored
477 *
478 * Either will act as a barrier to draw operation reordering, as we want to play back layer
479 * save/restore and complex canvas modifications (including save/restore) in order.
480 */
481void DeferredDisplayList::addRestoreToCount(OpenGLRenderer& renderer, StateOp* op,
482        int newSaveCount) {
483    DEFER_LOGD("%p addRestoreToCount %d", this, newSaveCount);
484
485    if (recordingComplexClip() && newSaveCount <= mComplexClipStackStart) {
486        mComplexClipStackStart = -1;
487        resetBatchingState();
488    }
489
490    if (mSaveStack.isEmpty() || newSaveCount > mSaveStack.top()) {
491        return;
492    }
493
494    while (!mSaveStack.isEmpty() && mSaveStack.top() >= newSaveCount) mSaveStack.pop();
495
496    storeRestoreToCountBarrier(renderer, op, mSaveStack.size() + FLUSH_SAVE_STACK_DEPTH);
497}
498
499void DeferredDisplayList::addDrawOp(OpenGLRenderer& renderer, DrawOp* op) {
500    /* 1: op calculates local bounds */
501    DeferredDisplayState* const state = createState();
502    if (op->getLocalBounds(renderer.getDrawModifiers(), state->mBounds)) {
503        if (state->mBounds.isEmpty()) {
504            // valid empty bounds, don't bother deferring
505            tryRecycleState(state);
506            return;
507        }
508    } else {
509        state->mBounds.setEmpty();
510    }
511
512    /* 2: renderer calculates global bounds + stores state */
513    if (renderer.storeDisplayState(*state, getDrawOpDeferFlags())) {
514        tryRecycleState(state);
515        return; // quick rejected
516    }
517
518    /* 3: ask op for defer info, given renderer state */
519    DeferInfo deferInfo;
520    op->onDefer(renderer, deferInfo, *state);
521
522    // complex clip has a complex set of expectations on the renderer state - for now, avoid taking
523    // the merge path in those cases
524    deferInfo.mergeable &= !recordingComplexClip();
525    deferInfo.opaqueOverBounds &= !recordingComplexClip() && mSaveStack.isEmpty();
526
527    if (CC_LIKELY(mAvoidOverdraw) && mBatches.size() &&
528            state->mClipSideFlags != kClipSide_ConservativeFull &&
529            deferInfo.opaqueOverBounds && state->mBounds.contains(mBounds)) {
530        // avoid overdraw by resetting drawing state + discarding drawing ops
531        discardDrawingBatches(mBatches.size() - 1);
532        resetBatchingState();
533    }
534
535    if (CC_UNLIKELY(renderer.getCaches().drawReorderDisabled)) {
536        // TODO: elegant way to reuse batches?
537        DrawBatch* b = new DrawBatch(deferInfo);
538        b->add(op, state, deferInfo.opaqueOverBounds);
539        mBatches.add(b);
540        return;
541    }
542
543    // find the latest batch of the new op's type, and try to merge the new op into it
544    DrawBatch* targetBatch = NULL;
545
546    // insertion point of a new batch, will hopefully be immediately after similar batch
547    // (eventually, should be similar shader)
548    int insertBatchIndex = mBatches.size();
549    if (!mBatches.isEmpty()) {
550        if (state->mBounds.isEmpty()) {
551            // don't know the bounds for op, so add to last batch and start from scratch on next op
552            DrawBatch* b = new DrawBatch(deferInfo);
553            b->add(op, state, deferInfo.opaqueOverBounds);
554            mBatches.add(b);
555            resetBatchingState();
556#if DEBUG_DEFER
557            DEFER_LOGD("Warning: Encountered op with empty bounds, resetting batches");
558            op->output(2);
559#endif
560            return;
561        }
562
563        if (deferInfo.mergeable) {
564            // Try to merge with any existing batch with same mergeId.
565            if (mMergingBatches[deferInfo.batchId].get(deferInfo.mergeId, targetBatch)) {
566                if (!((MergingDrawBatch*) targetBatch)->canMergeWith(op, state)) {
567                    targetBatch = NULL;
568                }
569            }
570        } else {
571            // join with similar, non-merging batch
572            targetBatch = (DrawBatch*)mBatchLookup[deferInfo.batchId];
573        }
574
575        if (targetBatch || deferInfo.mergeable) {
576            // iterate back toward target to see if anything drawn since should overlap the new op
577            // if no target, merging ops still interate to find similar batch to insert after
578            for (int i = mBatches.size() - 1; i >= mEarliestBatchIndex; i--) {
579                DrawBatch* overBatch = (DrawBatch*)mBatches[i];
580
581                if (overBatch == targetBatch) break;
582
583                // TODO: also consider shader shared between batch types
584                if (deferInfo.batchId == overBatch->getBatchId()) {
585                    insertBatchIndex = i + 1;
586                    if (!targetBatch) break; // found insert position, quit
587                }
588
589                if (overBatch->intersects(state->mBounds)) {
590                    // NOTE: it may be possible to optimize for special cases where two operations
591                    // of the same batch/paint could swap order, such as with a non-mergeable
592                    // (clipped) and a mergeable text operation
593                    targetBatch = NULL;
594#if DEBUG_DEFER
595                    DEFER_LOGD("op couldn't join batch %p, was intersected by batch %d",
596                            targetBatch, i);
597                    op->output(2);
598#endif
599                    break;
600                }
601            }
602        }
603    }
604
605    if (!targetBatch) {
606        if (deferInfo.mergeable) {
607            targetBatch = new MergingDrawBatch(deferInfo,
608                    renderer.getViewportWidth(), renderer.getViewportHeight());
609            mMergingBatches[deferInfo.batchId].put(deferInfo.mergeId, targetBatch);
610        } else {
611            targetBatch = new DrawBatch(deferInfo);
612            mBatchLookup[deferInfo.batchId] = targetBatch;
613        }
614
615        DEFER_LOGD("creating %singBatch %p, bid %x, at %d",
616                deferInfo.mergeable ? "Merg" : "Draw",
617                targetBatch, deferInfo.batchId, insertBatchIndex);
618        mBatches.insertAt(targetBatch, insertBatchIndex);
619    }
620
621    targetBatch->add(op, state, deferInfo.opaqueOverBounds);
622}
623
624void DeferredDisplayList::storeStateOpBarrier(OpenGLRenderer& renderer, StateOp* op) {
625    DEFER_LOGD("%p adding state op barrier at pos %d", this, mBatches.size());
626
627    DeferredDisplayState* state = createState();
628    renderer.storeDisplayState(*state, getStateOpDeferFlags());
629    mBatches.add(new StateOpBatch(op, state));
630    resetBatchingState();
631}
632
633void DeferredDisplayList::storeRestoreToCountBarrier(OpenGLRenderer& renderer, StateOp* op,
634        int newSaveCount) {
635    DEFER_LOGD("%p adding restore to count %d barrier, pos %d",
636            this, newSaveCount, mBatches.size());
637
638    // store displayState for the restore operation, as it may be associated with a saveLayer that
639    // doesn't have kClip_SaveFlag set
640    DeferredDisplayState* state = createState();
641    renderer.storeDisplayState(*state, getStateOpDeferFlags());
642    mBatches.add(new RestoreToCountBatch(op, state, newSaveCount));
643    resetBatchingState();
644}
645
646/////////////////////////////////////////////////////////////////////////////////
647// Replay / flush
648/////////////////////////////////////////////////////////////////////////////////
649
650static status_t replayBatchList(const Vector<Batch*>& batchList,
651        OpenGLRenderer& renderer, Rect& dirty) {
652    status_t status = DrawGlInfo::kStatusDone;
653
654    for (unsigned int i = 0; i < batchList.size(); i++) {
655        if (batchList[i]) {
656            status |= batchList[i]->replay(renderer, dirty, i);
657        }
658    }
659    DEFER_LOGD("--flushed, drew %d batches", batchList.size());
660    return status;
661}
662
663status_t DeferredDisplayList::flush(OpenGLRenderer& renderer, Rect& dirty) {
664    ATRACE_NAME("flush drawing commands");
665    Caches::getInstance().fontRenderer->endPrecaching();
666
667    status_t status = DrawGlInfo::kStatusDone;
668
669    if (isEmpty()) return status; // nothing to flush
670    renderer.restoreToCount(1);
671
672    DEFER_LOGD("--flushing");
673    renderer.eventMark("Flush");
674
675    // save and restore (with draw modifiers) so that reordering doesn't affect final state
676    DrawModifiers restoreDrawModifiers = renderer.getDrawModifiers();
677    renderer.save(SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
678
679    if (CC_LIKELY(mAvoidOverdraw)) {
680        for (unsigned int i = 1; i < mBatches.size(); i++) {
681            if (mBatches[i] && mBatches[i]->coversBounds(mBounds)) {
682                discardDrawingBatches(i - 1);
683            }
684        }
685    }
686    // NOTE: depth of the save stack at this point, before playback, should be reflected in
687    // FLUSH_SAVE_STACK_DEPTH, so that save/restores match up correctly
688    status |= replayBatchList(mBatches, renderer, dirty);
689
690    renderer.restoreToCount(1);
691    renderer.setDrawModifiers(restoreDrawModifiers);
692
693    DEFER_LOGD("--flush complete, returning %x", status);
694    clear();
695    return status;
696}
697
698void DeferredDisplayList::discardDrawingBatches(const unsigned int maxIndex) {
699    for (unsigned int i = mEarliestUnclearedIndex; i <= maxIndex; i++) {
700        // leave deferred state ops alone for simplicity (empty save restore pairs may now exist)
701        if (mBatches[i] && mBatches[i]->purelyDrawBatch()) {
702            DrawBatch* b = (DrawBatch*) mBatches[i];
703            delete mBatches[i];
704            mBatches.replaceAt(NULL, i);
705        }
706    }
707    mEarliestUnclearedIndex = maxIndex + 1;
708}
709
710}; // namespace uirenderer
711}; // namespace android
712