DeferredDisplayList.cpp revision d0afeac6dfc0856eeb72e6176ad6335e81871d24
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 <utils/Trace.h>
21
22#include "Debug.h"
23#include "DisplayListOp.h"
24#include "OpenGLRenderer.h"
25
26#if DEBUG_DEFER
27    #define DEFER_LOGD(...) ALOGD(__VA_ARGS__)
28#else
29    #define DEFER_LOGD(...)
30#endif
31
32namespace android {
33namespace uirenderer {
34
35/////////////////////////////////////////////////////////////////////////////////
36// Operation Batches
37/////////////////////////////////////////////////////////////////////////////////
38
39class DrawOpBatch {
40public:
41    DrawOpBatch() { mOps.clear(); }
42
43    virtual ~DrawOpBatch() { mOps.clear(); }
44
45    void add(DrawOp* op) {
46        // NOTE: ignore empty bounds special case, since we don't merge across those ops
47        mBounds.unionWith(op->state.mBounds);
48        mOps.add(op);
49    }
50
51    virtual bool intersects(Rect& rect) {
52        if (!rect.intersects(mBounds)) return false;
53
54        for (unsigned int i = 0; i < mOps.size(); i++) {
55            if (rect.intersects(mOps[i]->state.mBounds)) {
56#if DEBUG_DEFER
57                DEFER_LOGD("op intersects with op %p with bounds %f %f %f %f:", mOps[i],
58                        mOps[i]->state.mBounds.left, mOps[i]->state.mBounds.top,
59                        mOps[i]->state.mBounds.right, mOps[i]->state.mBounds.bottom);
60                mOps[i]->output(2);
61#endif
62                return true;
63            }
64        }
65        return false;
66    }
67
68    virtual status_t replay(OpenGLRenderer& renderer, Rect& dirty) {
69        DEFER_LOGD("replaying draw batch %p", this);
70
71        status_t status = DrawGlInfo::kStatusDone;
72        DisplayListLogBuffer& logBuffer = DisplayListLogBuffer::getInstance();
73        for (unsigned int i = 0; i < mOps.size(); i++) {
74            DrawOp* op = mOps[i];
75
76            renderer.restoreDisplayState(op->state, kStateDeferFlag_Draw);
77
78#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS
79            renderer.eventMark(strlen(op->name()), op->name());
80#endif
81            status |= op->applyDraw(renderer, dirty, 0, op->state.mMultipliedAlpha);
82            logBuffer.writeCommand(0, op->name());
83        }
84        return status;
85    }
86
87    inline int count() const { return mOps.size(); }
88private:
89    Vector<DrawOp*> mOps;
90    Rect mBounds;
91};
92
93class StateOpBatch : public DrawOpBatch {
94public:
95    // creates a single operation batch
96    StateOpBatch(StateOp* op) : mOp(op) {}
97
98    bool intersects(Rect& rect) {
99        // if something checks for intersection, it's trying to go backwards across a state op,
100        // something not currently supported - state ops are always barriers
101        CRASH();
102        return false;
103    }
104
105    virtual status_t replay(OpenGLRenderer& renderer, Rect& dirty) {
106        DEFER_LOGD("replaying state op batch %p", this);
107        renderer.restoreDisplayState(mOp->state, 0);
108
109        // use invalid save count because it won't be used at flush time - RestoreToCountOp is the
110        // only one to use it, and we don't use that class at flush time, instead calling
111        // renderer.restoreToCount directly
112        int saveCount = -1;
113        mOp->applyState(renderer, saveCount);
114        return DrawGlInfo::kStatusDone;
115    }
116
117private:
118    StateOp* mOp;
119};
120
121class RestoreToCountBatch : public DrawOpBatch {
122public:
123    RestoreToCountBatch(int restoreCount) : mRestoreCount(restoreCount) {}
124
125    bool intersects(Rect& rect) {
126        // if something checks for intersection, it's trying to go backwards across a state op,
127        // something not currently supported - state ops are always barriers
128        CRASH();
129        return false;
130    }
131
132    virtual status_t replay(OpenGLRenderer& renderer, Rect& dirty) {
133        DEFER_LOGD("batch %p restoring to count %d", this, mRestoreCount);
134        renderer.restoreToCount(mRestoreCount);
135
136        return DrawGlInfo::kStatusDone;
137    }
138
139private:
140    /*
141     * The count used here represents the flush() time saveCount. This is as opposed to the
142     * DisplayList record time, or defer() time values (which are RestoreToCountOp's mCount, and
143     * (saveCount + mCount) respectively). Since the count is different from the original
144     * RestoreToCountOp, we don't store a pointer to the op, as elsewhere.
145     */
146    const int mRestoreCount;
147};
148
149/////////////////////////////////////////////////////////////////////////////////
150// DeferredDisplayList
151/////////////////////////////////////////////////////////////////////////////////
152
153void DeferredDisplayList::resetBatchingState() {
154    for (int i = 0; i < kOpBatch_Count; i++) {
155        mBatchIndices[i] = -1;
156    }
157}
158
159void DeferredDisplayList::clear() {
160    resetBatchingState();
161    mComplexClipStackStart = -1;
162
163    for (unsigned int i = 0; i < mBatches.size(); i++) {
164        delete mBatches[i];
165    }
166    mBatches.clear();
167    mSaveStack.clear();
168}
169
170/////////////////////////////////////////////////////////////////////////////////
171// Operation adding
172/////////////////////////////////////////////////////////////////////////////////
173
174int DeferredDisplayList::getStateOpDeferFlags() const {
175    // For both clipOp and save(Layer)Op, we don't want to save drawing info, and only want to save
176    // the clip if we aren't recording a complex clip (and can thus trust it to be a rect)
177    return recordingComplexClip() ? 0 : kStateDeferFlag_Clip;
178}
179
180int DeferredDisplayList::getDrawOpDeferFlags() const {
181    return kStateDeferFlag_Draw | getStateOpDeferFlags();
182}
183
184/**
185 * When an clipping operation occurs that could cause a complex clip, record the operation and all
186 * subsequent clipOps, save/restores (if the clip flag is set). During a flush, instead of loading
187 * the clip from deferred state, we play back all of the relevant state operations that generated
188 * the complex clip.
189 *
190 * Note that we don't need to record the associated restore operation, since operations at defer
191 * time record whether they should store the renderer's current clip
192 */
193void DeferredDisplayList::addClip(OpenGLRenderer& renderer, ClipOp* op) {
194    if (recordingComplexClip() || op->canCauseComplexClip() || !renderer.hasRectToRectTransform()) {
195        DEFER_LOGD("%p Received complex clip operation %p", this, op);
196
197        // NOTE: defer clip op before setting mComplexClipStackStart so previous clip is recorded
198        storeStateOpBarrier(renderer, op);
199
200        if (!recordingComplexClip()) {
201            mComplexClipStackStart = renderer.getSaveCount() - 1;
202            DEFER_LOGD("    Starting complex clip region, start is %d", mComplexClipStackStart);
203        }
204    }
205}
206
207/**
208 * For now, we record save layer operations as barriers in the batch list, preventing drawing
209 * operations from reordering around the saveLayer and it's associated restore()
210 *
211 * In the future, we should send saveLayer commands (if they can be played out of order) and their
212 * contained drawing operations to a seperate list of batches, so that they may draw at the
213 * beginning of the frame. This would avoid targetting and removing an FBO in the middle of a frame.
214 *
215 * saveLayer operations should be pulled to the beginning of the frame if the canvas doesn't have a
216 * complex clip, and if the flags (kClip_SaveFlag & kClipToLayer_SaveFlag) are set.
217 */
218void DeferredDisplayList::addSaveLayer(OpenGLRenderer& renderer,
219        SaveLayerOp* op, int newSaveCount) {
220    DEFER_LOGD("%p adding saveLayerOp %p, flags %x, new count %d",
221            this, op, op->getFlags(), newSaveCount);
222
223    storeStateOpBarrier(renderer, op);
224    mSaveStack.push(newSaveCount);
225}
226
227/**
228 * Takes save op and it's return value - the new save count - and stores it into the stream as a
229 * barrier if it's needed to properly modify a complex clip
230 */
231void DeferredDisplayList::addSave(OpenGLRenderer& renderer, SaveOp* op, int newSaveCount) {
232    int saveFlags = op->getFlags();
233    DEFER_LOGD("%p adding saveOp %p, flags %x, new count %d", this, op, saveFlags, newSaveCount);
234
235    if (recordingComplexClip() && (saveFlags & SkCanvas::kClip_SaveFlag)) {
236        // store and replay the save operation, as it may be needed to correctly playback the clip
237        DEFER_LOGD("    adding save barrier with new save count %d", newSaveCount);
238        storeStateOpBarrier(renderer, op);
239        mSaveStack.push(newSaveCount);
240    }
241}
242
243/**
244 * saveLayer() commands must be associated with a restoreToCount batch that will clean up and draw
245 * the layer in the deferred list
246 *
247 * other save() commands which occur as children of a snapshot with complex clip will be deferred,
248 * and must be restored
249 *
250 * Either will act as a barrier to draw operation reordering, as we want to play back layer
251 * save/restore and complex canvas modifications (including save/restore) in order.
252 */
253void DeferredDisplayList::addRestoreToCount(OpenGLRenderer& renderer, int newSaveCount) {
254    DEFER_LOGD("%p addRestoreToCount %d", this, newSaveCount);
255
256    if (recordingComplexClip() && newSaveCount <= mComplexClipStackStart) {
257        mComplexClipStackStart = -1;
258        resetBatchingState();
259    }
260
261    if (mSaveStack.isEmpty() || newSaveCount > mSaveStack.top()) {
262        return;
263    }
264
265    while (!mSaveStack.isEmpty() && mSaveStack.top() >= newSaveCount) mSaveStack.pop();
266
267    storeRestoreToCountBarrier(mSaveStack.size() + 1);
268}
269
270void DeferredDisplayList::addDrawOp(OpenGLRenderer& renderer, DrawOp* op) {
271    if (renderer.storeDisplayState(op->state, getDrawOpDeferFlags())) {
272        return; // quick rejected
273    }
274
275    op->onDrawOpDeferred(renderer);
276
277    if (CC_UNLIKELY(renderer.getCaches().drawReorderDisabled)) {
278        // TODO: elegant way to reuse batches?
279        DrawOpBatch* b = new DrawOpBatch();
280        b->add(op);
281        mBatches.add(b);
282        return;
283    }
284
285    // disallowReorder isn't set, so find the latest batch of the new op's type, and try to merge
286    // the new op into it
287    DrawOpBatch* targetBatch = NULL;
288    int batchId = op->getBatchId();
289
290    if (!mBatches.isEmpty()) {
291        if (op->state.mBounds.isEmpty()) {
292            // don't know the bounds for op, so add to last batch and start from scratch on next op
293            mBatches.top()->add(op);
294            for (int i = 0; i < kOpBatch_Count; i++) {
295                mBatchIndices[i] = -1;
296            }
297#if DEBUG_DEFER
298            DEFER_LOGD("Warning: Encountered op with empty bounds, resetting batches");
299            op->output(2);
300#endif
301            return;
302        }
303
304        if (batchId >= 0 && mBatchIndices[batchId] != -1) {
305            int targetIndex = mBatchIndices[batchId];
306            targetBatch = mBatches[targetIndex];
307            // iterate back toward target to see if anything drawn since should overlap the new op
308            for (int i = mBatches.size() - 1; i > targetIndex; i--) {
309                DrawOpBatch* overBatch = mBatches[i];
310                if (overBatch->intersects(op->state.mBounds)) {
311                    targetBatch = NULL;
312#if DEBUG_DEFER
313                    DEFER_LOGD("op couldn't join batch %d, was intersected by batch %d",
314                            targetIndex, i);
315                    op->output(2);
316#endif
317                    break;
318                }
319            }
320        }
321    }
322    if (!targetBatch) {
323        targetBatch = new DrawOpBatch();
324        mBatches.add(targetBatch);
325        if (batchId >= 0) {
326            mBatchIndices[batchId] = mBatches.size() - 1;
327        }
328    }
329    targetBatch->add(op);
330}
331
332void DeferredDisplayList::storeStateOpBarrier(OpenGLRenderer& renderer, StateOp* op) {
333    DEFER_LOGD("%p adding state op barrier at pos %d", this, mBatches.size());
334
335    renderer.storeDisplayState(op->state, getStateOpDeferFlags());
336    mBatches.add(new StateOpBatch(op));
337    resetBatchingState();
338}
339
340void DeferredDisplayList::storeRestoreToCountBarrier(int newSaveCount) {
341    DEFER_LOGD("%p adding restore to count %d barrier, pos %d",
342            this, newSaveCount, mBatches.size());
343
344    mBatches.add(new RestoreToCountBatch(newSaveCount));
345    resetBatchingState();
346}
347
348/////////////////////////////////////////////////////////////////////////////////
349// Replay / flush
350/////////////////////////////////////////////////////////////////////////////////
351
352static status_t replayBatchList(Vector<DrawOpBatch*>& batchList,
353        OpenGLRenderer& renderer, Rect& dirty) {
354    status_t status = DrawGlInfo::kStatusDone;
355
356    int opCount = 0;
357    for (unsigned int i = 0; i < batchList.size(); i++) {
358        status |= batchList[i]->replay(renderer, dirty);
359        opCount += batchList[i]->count();
360    }
361    DEFER_LOGD("--flushed, drew %d batches (total %d ops)", batchList.size(), opCount);
362    return status;
363}
364
365status_t DeferredDisplayList::flush(OpenGLRenderer& renderer, Rect& dirty) {
366    ATRACE_NAME("flush drawing commands");
367    status_t status = DrawGlInfo::kStatusDone;
368
369    if (isEmpty()) return status; // nothing to flush
370
371    DEFER_LOGD("--flushing");
372    renderer.eventMark("Flush");
373
374    renderer.restoreToCount(1);
375    status |= replayBatchList(mBatches, renderer, dirty);
376    renderer.resetDrawModifiers();
377
378    DEFER_LOGD("--flush complete, returning %x", status);
379
380    clear();
381    return status;
382}
383
384}; // namespace uirenderer
385}; // namespace android
386