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