OpenGLRenderer.cpp revision e5e6f4837b27eefa542e65cdb89c796f28e11ec5
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "OpenGLRenderer.h"
18
19#include "DeferredDisplayList.h"
20#include "GammaFontRenderer.h"
21#include "Glop.h"
22#include "GlopBuilder.h"
23#include "Patch.h"
24#include "PathTessellator.h"
25#include "Properties.h"
26#include "RenderNode.h"
27#include "renderstate/MeshState.h"
28#include "renderstate/RenderState.h"
29#include "ShadowTessellator.h"
30#include "SkiaShader.h"
31#include "Vector.h"
32#include "VertexBuffer.h"
33#include "utils/GLUtils.h"
34#include "utils/PaintUtils.h"
35#include "utils/TraceUtils.h"
36
37#include <stdlib.h>
38#include <stdint.h>
39#include <sys/types.h>
40
41#include <SkCanvas.h>
42#include <SkColor.h>
43#include <SkPathOps.h>
44#include <SkShader.h>
45#include <SkTypeface.h>
46
47#include <utils/Log.h>
48#include <utils/StopWatch.h>
49
50#include <private/hwui/DrawGlInfo.h>
51
52#include <ui/Rect.h>
53
54#if DEBUG_DETAILED_EVENTS
55    #define EVENT_LOGD(...) eventMarkDEBUG(__VA_ARGS__)
56#else
57    #define EVENT_LOGD(...)
58#endif
59
60namespace android {
61namespace uirenderer {
62
63///////////////////////////////////////////////////////////////////////////////
64// Constructors/destructor
65///////////////////////////////////////////////////////////////////////////////
66
67OpenGLRenderer::OpenGLRenderer(RenderState& renderState)
68        : mState(*this)
69        , mCaches(Caches::getInstance())
70        , mRenderState(renderState)
71        , mFrameStarted(false)
72        , mScissorOptimizationDisabled(false)
73        , mDirty(false)
74        , mLightCenter((Vector3){FLT_MIN, FLT_MIN, FLT_MIN})
75        , mLightRadius(FLT_MIN)
76        , mAmbientShadowAlpha(0)
77        , mSpotShadowAlpha(0) {
78}
79
80OpenGLRenderer::~OpenGLRenderer() {
81    // The context has already been destroyed at this point, do not call
82    // GL APIs. All GL state should be kept in Caches.h
83}
84
85void OpenGLRenderer::initProperties() {
86    char property[PROPERTY_VALUE_MAX];
87    if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) {
88        mScissorOptimizationDisabled = !strcasecmp(property, "true");
89        INIT_LOGD("  Scissor optimization %s",
90                mScissorOptimizationDisabled ? "disabled" : "enabled");
91    } else {
92        INIT_LOGD("  Scissor optimization enabled");
93    }
94}
95
96void OpenGLRenderer::initLight(float lightRadius, uint8_t ambientShadowAlpha,
97        uint8_t spotShadowAlpha) {
98    mLightRadius = lightRadius;
99    mAmbientShadowAlpha = ambientShadowAlpha;
100    mSpotShadowAlpha = spotShadowAlpha;
101}
102
103void OpenGLRenderer::setLightCenter(const Vector3& lightCenter) {
104    mLightCenter = lightCenter;
105}
106
107///////////////////////////////////////////////////////////////////////////////
108// Setup
109///////////////////////////////////////////////////////////////////////////////
110
111void OpenGLRenderer::onViewportInitialized() {
112    glDisable(GL_DITHER);
113    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
114}
115
116void OpenGLRenderer::setupFrameState(float left, float top,
117        float right, float bottom, bool opaque) {
118    mCaches.clearGarbage();
119    mState.initializeSaveStack(left, top, right, bottom, mLightCenter);
120    mOpaque = opaque;
121    mTilingClip.set(left, top, right, bottom);
122}
123
124void OpenGLRenderer::startFrame() {
125    if (mFrameStarted) return;
126    mFrameStarted = true;
127
128    mState.setDirtyClip(true);
129
130    discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom);
131
132    mRenderState.setViewport(mState.getWidth(), mState.getHeight());
133
134    debugOverdraw(true, true);
135
136    clear(mTilingClip.left, mTilingClip.top,
137            mTilingClip.right, mTilingClip.bottom, mOpaque);
138}
139
140void OpenGLRenderer::prepareDirty(float left, float top,
141        float right, float bottom, bool opaque) {
142
143    setupFrameState(left, top, right, bottom, opaque);
144
145    // Layer renderers will start the frame immediately
146    // The framebuffer renderer will first defer the display list
147    // for each layer and wait until the first drawing command
148    // to start the frame
149    if (currentSnapshot()->fbo == 0) {
150        mRenderState.blend().syncEnabled();
151        updateLayers();
152    } else {
153        startFrame();
154    }
155}
156
157void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) {
158    // If we know that we are going to redraw the entire framebuffer,
159    // perform a discard to let the driver know we don't need to preserve
160    // the back buffer for this frame.
161    if (mCaches.extensions().hasDiscardFramebuffer() &&
162            left <= 0.0f && top <= 0.0f && right >= mState.getWidth() && bottom >= mState.getHeight()) {
163        const bool isFbo = getTargetFbo() == 0;
164        const GLenum attachments[] = {
165                isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0,
166                isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT };
167        glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
168    }
169}
170
171void OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
172    if (!opaque) {
173        mRenderState.scissor().setEnabled(true);
174        mRenderState.scissor().set(left, getViewportHeight() - bottom, right - left, bottom - top);
175        glClear(GL_COLOR_BUFFER_BIT);
176        mDirty = true;
177        return;
178    }
179
180    mRenderState.scissor().reset();
181}
182
183bool OpenGLRenderer::finish() {
184    renderOverdraw();
185    mTempPaths.clear();
186
187    // When finish() is invoked on FBO 0 we've reached the end
188    // of the current frame
189    if (getTargetFbo() == 0) {
190        mCaches.pathCache.trim();
191        mCaches.tessellationCache.trim();
192    }
193
194    if (!suppressErrorChecks()) {
195#if DEBUG_OPENGL
196        GLUtils::dumpGLErrors();
197#endif
198
199#if DEBUG_MEMORY_USAGE
200        mCaches.dumpMemoryUsage();
201#else
202        if (Properties::debugLevel & kDebugMemory) {
203            mCaches.dumpMemoryUsage();
204        }
205#endif
206    }
207
208    mFrameStarted = false;
209
210    return reportAndClearDirty();
211}
212
213void OpenGLRenderer::resumeAfterLayer() {
214    mRenderState.setViewport(getViewportWidth(), getViewportHeight());
215    mRenderState.bindFramebuffer(currentSnapshot()->fbo);
216    debugOverdraw(true, false);
217
218    mRenderState.scissor().reset();
219    dirtyClip();
220}
221
222void OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) {
223    if (mState.currentlyIgnored()) return;
224
225    Rect clip(mState.currentClipRect());
226    clip.snapToPixelBoundaries();
227
228    // Since we don't know what the functor will draw, let's dirty
229    // the entire clip region
230    if (hasLayer()) {
231        dirtyLayerUnchecked(clip, getRegion());
232    }
233
234    DrawGlInfo info;
235    info.clipLeft = clip.left;
236    info.clipTop = clip.top;
237    info.clipRight = clip.right;
238    info.clipBottom = clip.bottom;
239    info.isLayer = hasLayer();
240    info.width = getViewportWidth();
241    info.height = getViewportHeight();
242    currentTransform()->copyTo(&info.transform[0]);
243
244    bool prevDirtyClip = mState.getDirtyClip();
245    // setup GL state for functor
246    if (mState.getDirtyClip()) {
247        setStencilFromClip(); // can issue draws, so must precede enableScissor()/interrupt()
248    }
249    if (mRenderState.scissor().setEnabled(true) || prevDirtyClip) {
250        setScissorFromClip();
251    }
252
253    mRenderState.invokeFunctor(functor, DrawGlInfo::kModeDraw, &info);
254    // Scissor may have been modified, reset dirty clip
255    dirtyClip();
256
257    mDirty = true;
258}
259
260///////////////////////////////////////////////////////////////////////////////
261// Debug
262///////////////////////////////////////////////////////////////////////////////
263
264void OpenGLRenderer::eventMarkDEBUG(const char* fmt, ...) const {
265#if DEBUG_DETAILED_EVENTS
266    const int BUFFER_SIZE = 256;
267    va_list ap;
268    char buf[BUFFER_SIZE];
269
270    va_start(ap, fmt);
271    vsnprintf(buf, BUFFER_SIZE, fmt, ap);
272    va_end(ap);
273
274    eventMark(buf);
275#endif
276}
277
278
279void OpenGLRenderer::eventMark(const char* name) const {
280    mCaches.eventMark(0, name);
281}
282
283void OpenGLRenderer::startMark(const char* name) const {
284    mCaches.startMark(0, name);
285}
286
287void OpenGLRenderer::endMark() const {
288    mCaches.endMark();
289}
290
291void OpenGLRenderer::debugOverdraw(bool enable, bool clear) {
292    mRenderState.debugOverdraw(enable, clear);
293}
294
295void OpenGLRenderer::renderOverdraw() {
296    if (Properties::debugOverdraw && getTargetFbo() == 0) {
297        const Rect* clip = &mTilingClip;
298
299        mRenderState.scissor().setEnabled(true);
300        mRenderState.scissor().set(clip->left,
301                mState.firstSnapshot()->getViewportHeight() - clip->bottom,
302                clip->right - clip->left,
303                clip->bottom - clip->top);
304
305        // 1x overdraw
306        mRenderState.stencil().enableDebugTest(2);
307        drawColor(mCaches.getOverdrawColor(1), SkXfermode::kSrcOver_Mode);
308
309        // 2x overdraw
310        mRenderState.stencil().enableDebugTest(3);
311        drawColor(mCaches.getOverdrawColor(2), SkXfermode::kSrcOver_Mode);
312
313        // 3x overdraw
314        mRenderState.stencil().enableDebugTest(4);
315        drawColor(mCaches.getOverdrawColor(3), SkXfermode::kSrcOver_Mode);
316
317        // 4x overdraw and higher
318        mRenderState.stencil().enableDebugTest(4, true);
319        drawColor(mCaches.getOverdrawColor(4), SkXfermode::kSrcOver_Mode);
320
321        mRenderState.stencil().disable();
322    }
323}
324
325///////////////////////////////////////////////////////////////////////////////
326// Layers
327///////////////////////////////////////////////////////////////////////////////
328
329bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) {
330    if (layer->deferredUpdateScheduled && layer->renderer
331            && layer->renderNode.get() && layer->renderNode->isRenderable()) {
332
333        if (inFrame) {
334            debugOverdraw(false, false);
335        }
336
337        if (CC_UNLIKELY(inFrame || Properties::drawDeferDisabled)) {
338            layer->render(*this);
339        } else {
340            layer->defer(*this);
341        }
342
343        if (inFrame) {
344            resumeAfterLayer();
345        }
346
347        layer->debugDrawUpdate = Properties::debugLayersUpdates;
348        layer->hasDrawnSinceUpdate = false;
349
350        return true;
351    }
352
353    return false;
354}
355
356void OpenGLRenderer::updateLayers() {
357    // If draw deferring is enabled this method will simply defer
358    // the display list of each individual layer. The layers remain
359    // in the layer updates list which will be cleared by flushLayers().
360    int count = mLayerUpdates.size();
361    if (count > 0) {
362        if (CC_UNLIKELY(Properties::drawDeferDisabled)) {
363            startMark("Layer Updates");
364        } else {
365            startMark("Defer Layer Updates");
366        }
367
368        // Note: it is very important to update the layers in order
369        for (int i = 0; i < count; i++) {
370            Layer* layer = mLayerUpdates[i].get();
371            updateLayer(layer, false);
372        }
373
374        if (CC_UNLIKELY(Properties::drawDeferDisabled)) {
375            mLayerUpdates.clear();
376            mRenderState.bindFramebuffer(getTargetFbo());
377        }
378        endMark();
379    }
380}
381
382void OpenGLRenderer::flushLayers() {
383    int count = mLayerUpdates.size();
384    if (count > 0) {
385        startMark("Apply Layer Updates");
386
387        // Note: it is very important to update the layers in order
388        for (int i = 0; i < count; i++) {
389            mLayerUpdates[i]->flush();
390        }
391
392        mLayerUpdates.clear();
393        mRenderState.bindFramebuffer(getTargetFbo());
394
395        endMark();
396    }
397}
398
399void OpenGLRenderer::pushLayerUpdate(Layer* layer) {
400    if (layer) {
401        // Make sure we don't introduce duplicates.
402        // SortedVector would do this automatically but we need to respect
403        // the insertion order. The linear search is not an issue since
404        // this list is usually very short (typically one item, at most a few)
405        for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
406            if (mLayerUpdates[i] == layer) {
407                return;
408            }
409        }
410        mLayerUpdates.push_back(layer);
411    }
412}
413
414void OpenGLRenderer::cancelLayerUpdate(Layer* layer) {
415    if (layer) {
416        for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
417            if (mLayerUpdates[i] == layer) {
418                mLayerUpdates.erase(mLayerUpdates.begin() + i);
419                break;
420            }
421        }
422    }
423}
424
425void OpenGLRenderer::flushLayerUpdates() {
426    ATRACE_NAME("Update HW Layers");
427    mRenderState.blend().syncEnabled();
428    updateLayers();
429    flushLayers();
430    // Wait for all the layer updates to be executed
431    glFinish();
432}
433
434void OpenGLRenderer::markLayersAsBuildLayers() {
435    for (size_t i = 0; i < mLayerUpdates.size(); i++) {
436        mLayerUpdates[i]->wasBuildLayered = true;
437    }
438}
439
440///////////////////////////////////////////////////////////////////////////////
441// State management
442///////////////////////////////////////////////////////////////////////////////
443
444void OpenGLRenderer::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) {
445    bool restoreViewport = removed.flags & Snapshot::kFlagIsFboLayer;
446    bool restoreClip = removed.flags & Snapshot::kFlagClipSet;
447    bool restoreLayer = removed.flags & Snapshot::kFlagIsLayer;
448
449    if (restoreViewport) {
450        mRenderState.setViewport(getViewportWidth(), getViewportHeight());
451    }
452
453    if (restoreClip) {
454        dirtyClip();
455    }
456
457    if (restoreLayer) {
458        endMark(); // Savelayer
459        ATRACE_END(); // SaveLayer
460        startMark("ComposeLayer");
461        composeLayer(removed, restored);
462        endMark();
463    }
464}
465
466///////////////////////////////////////////////////////////////////////////////
467// Layers
468///////////////////////////////////////////////////////////////////////////////
469
470int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
471        const SkPaint* paint, int flags, const SkPath* convexMask) {
472    // force matrix/clip isolation for layer
473    flags |= SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag;
474
475    const int count = mState.saveSnapshot(flags);
476
477    if (!mState.currentlyIgnored()) {
478        createLayer(left, top, right, bottom, paint, flags, convexMask);
479    }
480
481    return count;
482}
483
484void OpenGLRenderer::calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer) {
485    const Rect untransformedBounds(bounds);
486
487    currentTransform()->mapRect(bounds);
488
489    // Layers only make sense if they are in the framebuffer's bounds
490    if (bounds.intersect(mState.currentClipRect())) {
491        // We cannot work with sub-pixels in this case
492        bounds.snapToPixelBoundaries();
493
494        // When the layer is not an FBO, we may use glCopyTexImage so we
495        // need to make sure the layer does not extend outside the bounds
496        // of the framebuffer
497        const Snapshot& previous = *(currentSnapshot()->previous);
498        Rect previousViewport(0, 0, previous.getViewportWidth(), previous.getViewportHeight());
499        if (!bounds.intersect(previousViewport)) {
500            bounds.setEmpty();
501        } else if (fboLayer) {
502            clip.set(bounds);
503            mat4 inverse;
504            inverse.loadInverse(*currentTransform());
505            inverse.mapRect(clip);
506            clip.snapToPixelBoundaries();
507            if (clip.intersect(untransformedBounds)) {
508                clip.translate(-untransformedBounds.left, -untransformedBounds.top);
509                bounds.set(untransformedBounds);
510            } else {
511                clip.setEmpty();
512            }
513        }
514    } else {
515        bounds.setEmpty();
516    }
517}
518
519void OpenGLRenderer::updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
520        bool fboLayer, int alpha) {
521    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
522            bounds.getHeight() > mCaches.maxTextureSize ||
523            (fboLayer && clip.isEmpty())) {
524        writableSnapshot()->empty = fboLayer;
525    } else {
526        writableSnapshot()->invisible = writableSnapshot()->invisible || (alpha <= 0 && fboLayer);
527    }
528}
529
530int OpenGLRenderer::saveLayerDeferred(float left, float top, float right, float bottom,
531        const SkPaint* paint, int flags) {
532    const int count = mState.saveSnapshot(flags);
533
534    if (!mState.currentlyIgnored() && (flags & SkCanvas::kClipToLayer_SaveFlag)) {
535        // initialize the snapshot as though it almost represents an FBO layer so deferred draw
536        // operations will be able to store and restore the current clip and transform info, and
537        // quick rejection will be correct (for display lists)
538
539        Rect bounds(left, top, right, bottom);
540        Rect clip;
541        calculateLayerBoundsAndClip(bounds, clip, true);
542        updateSnapshotIgnoreForLayer(bounds, clip, true, getAlphaDirect(paint));
543
544        if (!mState.currentlyIgnored()) {
545            writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f);
546            writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom);
547            writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight());
548            writableSnapshot()->roundRectClipState = nullptr;
549        }
550    }
551
552    return count;
553}
554
555/**
556 * Layers are viewed by Skia are slightly different than layers in image editing
557 * programs (for instance.) When a layer is created, previously created layers
558 * and the frame buffer still receive every drawing command. For instance, if a
559 * layer is created and a shape intersecting the bounds of the layers and the
560 * framebuffer is draw, the shape will be drawn on both (unless the layer was
561 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
562 *
563 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
564 * texture. Unfortunately, this is inefficient as it requires every primitive to
565 * be drawn n + 1 times, where n is the number of active layers. In practice this
566 * means, for every primitive:
567 *   - Switch active frame buffer
568 *   - Change viewport, clip and projection matrix
569 *   - Issue the drawing
570 *
571 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
572 * To avoid this, layers are implemented in a different way here, at least in the
573 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
574 * is set. When this flag is set we can redirect all drawing operations into a
575 * single FBO.
576 *
577 * This implementation relies on the frame buffer being at least RGBA 8888. When
578 * a layer is created, only a texture is created, not an FBO. The content of the
579 * frame buffer contained within the layer's bounds is copied into this texture
580 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
581 * buffer and drawing continues as normal. This technique therefore treats the
582 * frame buffer as a scratch buffer for the layers.
583 *
584 * To compose the layers back onto the frame buffer, each layer texture
585 * (containing the original frame buffer data) is drawn as a simple quad over
586 * the frame buffer. The trick is that the quad is set as the composition
587 * destination in the blending equation, and the frame buffer becomes the source
588 * of the composition.
589 *
590 * Drawing layers with an alpha value requires an extra step before composition.
591 * An empty quad is drawn over the layer's region in the frame buffer. This quad
592 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
593 * quad is used to multiply the colors in the frame buffer. This is achieved by
594 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
595 * GL_ZERO, GL_SRC_ALPHA.
596 *
597 * Because glCopyTexImage2D() can be slow, an alternative implementation might
598 * be use to draw a single clipped layer. The implementation described above
599 * is correct in every case.
600 *
601 * (1) The frame buffer is actually not cleared right away. To allow the GPU
602 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
603 *     buffer is left untouched until the first drawing operation. Only when
604 *     something actually gets drawn are the layers regions cleared.
605 */
606bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom,
607        const SkPaint* paint, int flags, const SkPath* convexMask) {
608    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
609    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
610
611    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
612
613    // Window coordinates of the layer
614    Rect clip;
615    Rect bounds(left, top, right, bottom);
616    calculateLayerBoundsAndClip(bounds, clip, fboLayer);
617    updateSnapshotIgnoreForLayer(bounds, clip, fboLayer, getAlphaDirect(paint));
618
619    // Bail out if we won't draw in this snapshot
620    if (mState.currentlyIgnored()) {
621        return false;
622    }
623
624    mCaches.textureState().activateTexture(0);
625    Layer* layer = mCaches.layerCache.get(mRenderState, bounds.getWidth(), bounds.getHeight());
626    if (!layer) {
627        return false;
628    }
629
630    layer->setPaint(paint);
631    layer->layer.set(bounds);
632    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()),
633            bounds.getWidth() / float(layer->getWidth()), 0.0f);
634
635    layer->setBlend(true);
636    layer->setDirty(false);
637    layer->setConvexMask(convexMask); // note: the mask must be cleared before returning to the cache
638
639    // Save the layer in the snapshot
640    writableSnapshot()->flags |= Snapshot::kFlagIsLayer;
641    writableSnapshot()->layer = layer;
642
643    ATRACE_FORMAT_BEGIN("%ssaveLayer %ux%u",
644            fboLayer ? "" : "unclipped ",
645            layer->getWidth(), layer->getHeight());
646    startMark("SaveLayer");
647    if (fboLayer) {
648        return createFboLayer(layer, bounds, clip);
649    } else {
650        // Copy the framebuffer into the layer
651        layer->bindTexture();
652        if (!bounds.isEmpty()) {
653            if (layer->isEmpty()) {
654                // Workaround for some GL drivers. When reading pixels lying outside
655                // of the window we should get undefined values for those pixels.
656                // Unfortunately some drivers will turn the entire target texture black
657                // when reading outside of the window.
658                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->getWidth(), layer->getHeight(),
659                        0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
660                layer->setEmpty(false);
661            }
662
663            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
664                    bounds.left, getViewportHeight() - bounds.bottom,
665                    bounds.getWidth(), bounds.getHeight());
666
667            // Enqueue the buffer coordinates to clear the corresponding region later
668            mLayers.push_back(Rect(bounds));
669        }
670    }
671
672    return true;
673}
674
675bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip) {
676    layer->clipRect.set(clip);
677    layer->setFbo(mCaches.fboCache.get());
678
679    writableSnapshot()->region = &writableSnapshot()->layer->region;
680    writableSnapshot()->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer;
681    writableSnapshot()->fbo = layer->getFbo();
682    writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f);
683    writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom);
684    writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight());
685    writableSnapshot()->roundRectClipState = nullptr;
686
687    debugOverdraw(false, false);
688    // Bind texture to FBO
689    mRenderState.bindFramebuffer(layer->getFbo());
690    layer->bindTexture();
691
692    // Initialize the texture if needed
693    if (layer->isEmpty()) {
694        layer->allocateTexture();
695        layer->setEmpty(false);
696    }
697
698    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
699            layer->getTextureId(), 0);
700
701    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
702    mRenderState.scissor().setEnabled(true);
703    mRenderState.scissor().set(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
704            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
705    glClear(GL_COLOR_BUFFER_BIT);
706
707    dirtyClip();
708
709    // Change the ortho projection
710    mRenderState.setViewport(bounds.getWidth(), bounds.getHeight());
711    return true;
712}
713
714/**
715 * Read the documentation of createLayer() before doing anything in this method.
716 */
717void OpenGLRenderer::composeLayer(const Snapshot& removed, const Snapshot& restored) {
718    if (!removed.layer) {
719        ALOGE("Attempting to compose a layer that does not exist");
720        return;
721    }
722
723    Layer* layer = removed.layer;
724    const Rect& rect = layer->layer;
725    const bool fboLayer = removed.flags & Snapshot::kFlagIsFboLayer;
726
727    bool clipRequired = false;
728    mState.calculateQuickRejectForScissor(rect.left, rect.top, rect.right, rect.bottom,
729            &clipRequired, nullptr, false); // safely ignore return, should never be rejected
730    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
731
732    if (fboLayer) {
733        // Detach the texture from the FBO
734        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
735
736        layer->removeFbo(false);
737
738        // Unbind current FBO and restore previous one
739        mRenderState.bindFramebuffer(restored.fbo);
740        debugOverdraw(true, false);
741    }
742
743    if (!fboLayer && layer->getAlpha() < 255) {
744        SkPaint layerPaint;
745        layerPaint.setAlpha(layer->getAlpha());
746        layerPaint.setXfermodeMode(SkXfermode::kDstIn_Mode);
747        layerPaint.setColorFilter(layer->getColorFilter());
748
749        drawColorRect(rect.left, rect.top, rect.right, rect.bottom, &layerPaint, true);
750        // Required below, composeLayerRect() will divide by 255
751        layer->setAlpha(255);
752    }
753
754    mRenderState.meshState().unbindMeshBuffer();
755
756    mCaches.textureState().activateTexture(0);
757
758    // When the layer is stored in an FBO, we can save a bit of fillrate by
759    // drawing only the dirty region
760    if (fboLayer) {
761        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *restored.transform);
762        composeLayerRegion(layer, rect);
763    } else if (!rect.isEmpty()) {
764        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
765
766        save(0);
767        // the layer contains screen buffer content that shouldn't be alpha modulated
768        // (and any necessary alpha modulation was handled drawing into the layer)
769        writableSnapshot()->alpha = 1.0f;
770        composeLayerRectSwapped(layer, rect);
771        restore();
772    }
773
774    dirtyClip();
775
776    // Failing to add the layer to the cache should happen only if the layer is too large
777    layer->setConvexMask(nullptr);
778    if (!mCaches.layerCache.put(layer)) {
779        LAYER_LOGD("Deleting layer");
780        layer->decStrong(nullptr);
781    }
782}
783
784void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
785    const bool tryToSnap = !layer->getForceFilter()
786            && layer->getWidth() == (uint32_t) rect.getWidth()
787            && layer->getHeight() == (uint32_t) rect.getHeight();
788    Glop glop;
789    GlopBuilder(mRenderState, mCaches, &glop)
790            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
791            .setMeshTexturedUvQuad(nullptr, Rect(0, 1, 1, 0)) // TODO: simplify with VBO
792            .setFillTextureLayer(*layer, getLayerAlpha(layer))
793            .setTransform(*currentSnapshot(), TransformFlags::None)
794            .setModelViewMapUnitToRectOptionalSnap(tryToSnap, rect)
795            .build();
796    renderGlop(glop);
797}
798
799void OpenGLRenderer::composeLayerRectSwapped(Layer* layer, const Rect& rect) {
800    Glop glop;
801    GlopBuilder(mRenderState, mCaches, &glop)
802            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
803            .setMeshTexturedUvQuad(nullptr, layer->texCoords)
804            .setFillLayer(layer->getTexture(), layer->getColorFilter(),
805                    getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::Swap)
806            .setTransform(*currentSnapshot(), TransformFlags::MeshIgnoresCanvasTransform)
807            .setModelViewMapUnitToRect(rect)
808            .build();
809    renderGlop(glop);
810}
811
812void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect) {
813    if (layer->isTextureLayer()) {
814        EVENT_LOGD("composeTextureLayerRect");
815        drawTextureLayer(layer, rect);
816    } else {
817        EVENT_LOGD("composeHardwareLayerRect");
818
819        const bool tryToSnap = layer->getWidth() == static_cast<uint32_t>(rect.getWidth())
820                && layer->getHeight() == static_cast<uint32_t>(rect.getHeight());
821        Glop glop;
822        GlopBuilder(mRenderState, mCaches, &glop)
823                .setRoundRectClipState(currentSnapshot()->roundRectClipState)
824                .setMeshTexturedUvQuad(nullptr, layer->texCoords)
825                .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap)
826                .setTransform(*currentSnapshot(), TransformFlags::None)
827                .setModelViewMapUnitToRectOptionalSnap(tryToSnap, rect)
828                .build();
829        renderGlop(glop);
830    }
831}
832
833/**
834 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated
835 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw
836 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used
837 * by saveLayer's restore
838 */
839#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) { \
840        DRAW_COMMAND; \
841        if (CC_UNLIKELY(Properties::debugOverdraw && getTargetFbo() == 0 && COND)) { \
842            glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); \
843            DRAW_COMMAND; \
844            glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); \
845        } \
846    }
847
848#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND)
849
850// This class is purely for inspection. It inherits from SkShader, but Skia does not know how to
851// use it. The OpenGLRenderer will look at it to find its Layer and whether it is opaque.
852class LayerShader : public SkShader {
853public:
854    LayerShader(Layer* layer, const SkMatrix* localMatrix)
855    : INHERITED(localMatrix)
856    , mLayer(layer) {
857    }
858
859    virtual bool asACustomShader(void** data) const override {
860        if (data) {
861            *data = static_cast<void*>(mLayer);
862        }
863        return true;
864    }
865
866    virtual bool isOpaque() const override {
867        return !mLayer->isBlend();
868    }
869
870protected:
871    virtual void shadeSpan(int x, int y, SkPMColor[], int count) {
872        LOG_ALWAYS_FATAL("LayerShader should never be drawn with raster backend.");
873    }
874
875    virtual void flatten(SkWriteBuffer&) const override {
876        LOG_ALWAYS_FATAL("LayerShader should never be flattened.");
877    }
878
879    virtual Factory getFactory() const override {
880        LOG_ALWAYS_FATAL("LayerShader should never be created from a stream.");
881        return nullptr;
882    }
883private:
884    // Unowned.
885    Layer* mLayer;
886    typedef SkShader INHERITED;
887};
888
889void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
890    if (CC_UNLIKELY(layer->region.isEmpty())) return; // nothing to draw
891
892    if (layer->getConvexMask()) {
893        save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag);
894
895        // clip to the area of the layer the mask can be larger
896        clipRect(rect.left, rect.top, rect.right, rect.bottom, SkRegion::kIntersect_Op);
897
898        SkPaint paint;
899        paint.setAntiAlias(true);
900        paint.setColor(SkColorSetARGB(int(getLayerAlpha(layer) * 255), 0, 0, 0));
901
902        // create LayerShader to map SaveLayer content into subsequent draw
903        SkMatrix shaderMatrix;
904        shaderMatrix.setTranslate(rect.left, rect.bottom);
905        shaderMatrix.preScale(1, -1);
906        LayerShader layerShader(layer, &shaderMatrix);
907        paint.setShader(&layerShader);
908
909        // Since the drawing primitive is defined in local drawing space,
910        // we don't need to modify the draw matrix
911        const SkPath* maskPath = layer->getConvexMask();
912        DRAW_DOUBLE_STENCIL(drawConvexPath(*maskPath, &paint));
913
914        paint.setShader(nullptr);
915        restore();
916
917        return;
918    }
919
920    if (layer->region.isRect()) {
921        layer->setRegionAsRect();
922
923        DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect));
924
925        layer->region.clear();
926        return;
927    }
928
929    EVENT_LOGD("composeLayerRegion");
930    // standard Region based draw
931    size_t count;
932    const android::Rect* rects;
933    Region safeRegion;
934    if (CC_LIKELY(hasRectToRectTransform())) {
935        rects = layer->region.getArray(&count);
936    } else {
937        safeRegion = Region::createTJunctionFreeRegion(layer->region);
938        rects = safeRegion.getArray(&count);
939    }
940
941    const float texX = 1.0f / float(layer->getWidth());
942    const float texY = 1.0f / float(layer->getHeight());
943    const float height = rect.getHeight();
944
945    TextureVertex quadVertices[count * 4];
946    TextureVertex* mesh = &quadVertices[0];
947    for (size_t i = 0; i < count; i++) {
948        const android::Rect* r = &rects[i];
949
950        const float u1 = r->left * texX;
951        const float v1 = (height - r->top) * texY;
952        const float u2 = r->right * texX;
953        const float v2 = (height - r->bottom) * texY;
954
955        // TODO: Reject quads outside of the clip
956        TextureVertex::set(mesh++, r->left, r->top, u1, v1);
957        TextureVertex::set(mesh++, r->right, r->top, u2, v1);
958        TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
959        TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
960    }
961    Rect modelRect = Rect(rect.getWidth(), rect.getHeight());
962    Glop glop;
963    GlopBuilder(mRenderState, mCaches, &glop)
964            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
965            .setMeshTexturedIndexedQuads(&quadVertices[0], count * 6)
966            .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap)
967            .setTransform(*currentSnapshot(),  TransformFlags::None)
968            .setModelViewOffsetRectSnap(rect.left, rect.top, modelRect)
969            .build();
970    DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, renderGlop(glop));
971
972#if DEBUG_LAYERS_AS_REGIONS
973    drawRegionRectsDebug(layer->region);
974#endif
975
976    layer->region.clear();
977}
978
979#if DEBUG_LAYERS_AS_REGIONS
980void OpenGLRenderer::drawRegionRectsDebug(const Region& region) {
981    size_t count;
982    const android::Rect* rects = region.getArray(&count);
983
984    uint32_t colors[] = {
985            0x7fff0000, 0x7f00ff00,
986            0x7f0000ff, 0x7fff00ff,
987    };
988
989    int offset = 0;
990    int32_t top = rects[0].top;
991
992    for (size_t i = 0; i < count; i++) {
993        if (top != rects[i].top) {
994            offset ^= 0x2;
995            top = rects[i].top;
996        }
997
998        SkPaint paint;
999        paint.setColor(colors[offset + (i & 0x1)]);
1000        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1001        drawColorRect(r.left, r.top, r.right, r.bottom, paint);
1002    }
1003}
1004#endif
1005
1006void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) {
1007    Vector<float> rects;
1008
1009    SkRegion::Iterator it(region);
1010    while (!it.done()) {
1011        const SkIRect& r = it.rect();
1012        rects.push(r.fLeft);
1013        rects.push(r.fTop);
1014        rects.push(r.fRight);
1015        rects.push(r.fBottom);
1016        it.next();
1017    }
1018
1019    drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false);
1020}
1021
1022void OpenGLRenderer::dirtyLayer(const float left, const float top,
1023        const float right, const float bottom, const Matrix4& transform) {
1024    if (hasLayer()) {
1025        Rect bounds(left, top, right, bottom);
1026        transform.mapRect(bounds);
1027        dirtyLayerUnchecked(bounds, getRegion());
1028    }
1029}
1030
1031void OpenGLRenderer::dirtyLayer(const float left, const float top,
1032        const float right, const float bottom) {
1033    if (hasLayer()) {
1034        Rect bounds(left, top, right, bottom);
1035        dirtyLayerUnchecked(bounds, getRegion());
1036    }
1037}
1038
1039void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1040    if (CC_LIKELY(!bounds.isEmpty() && bounds.intersect(mState.currentClipRect()))) {
1041        bounds.snapToPixelBoundaries();
1042        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1043        if (!dirty.isEmpty()) {
1044            region->orSelf(dirty);
1045        }
1046    }
1047}
1048
1049void OpenGLRenderer::clearLayerRegions() {
1050    const size_t quadCount = mLayers.size();
1051    if (quadCount == 0) return;
1052
1053    if (!mState.currentlyIgnored()) {
1054        EVENT_LOGD("clearLayerRegions");
1055        // Doing several glScissor/glClear here can negatively impact
1056        // GPUs with a tiler architecture, instead we draw quads with
1057        // the Clear blending mode
1058
1059        // The list contains bounds that have already been clipped
1060        // against their initial clip rect, and the current clip
1061        // is likely different so we need to disable clipping here
1062        bool scissorChanged = mRenderState.scissor().setEnabled(false);
1063
1064        Vertex mesh[quadCount * 4];
1065        Vertex* vertex = mesh;
1066
1067        for (uint32_t i = 0; i < quadCount; i++) {
1068            const Rect& bounds = mLayers[i];
1069
1070            Vertex::set(vertex++, bounds.left, bounds.top);
1071            Vertex::set(vertex++, bounds.right, bounds.top);
1072            Vertex::set(vertex++, bounds.left, bounds.bottom);
1073            Vertex::set(vertex++, bounds.right, bounds.bottom);
1074        }
1075        // We must clear the list of dirty rects before we
1076        // call clearLayerRegions() in renderGlop to prevent
1077        // stencil setup from doing the same thing again
1078        mLayers.clear();
1079
1080        const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform;
1081        Glop glop;
1082        GlopBuilder(mRenderState, mCaches, &glop)
1083                .setRoundRectClipState(nullptr) // clear ignores clip state
1084                .setMeshIndexedQuads(&mesh[0], quadCount)
1085                .setFillClear()
1086                .setTransform(*currentSnapshot(), transformFlags)
1087                .setModelViewOffsetRect(0, 0, Rect(currentSnapshot()->getClipRect()))
1088                .build();
1089        renderGlop(glop, GlopRenderType::LayerClear);
1090
1091        if (scissorChanged) mRenderState.scissor().setEnabled(true);
1092    } else {
1093        mLayers.clear();
1094    }
1095}
1096
1097///////////////////////////////////////////////////////////////////////////////
1098// State Deferral
1099///////////////////////////////////////////////////////////////////////////////
1100
1101bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) {
1102    const Rect& currentClip = mState.currentClipRect();
1103    const mat4* currentMatrix = currentTransform();
1104
1105    if (stateDeferFlags & kStateDeferFlag_Draw) {
1106        // state has bounds initialized in local coordinates
1107        if (!state.mBounds.isEmpty()) {
1108            currentMatrix->mapRect(state.mBounds);
1109            Rect clippedBounds(state.mBounds);
1110            // NOTE: if we ever want to use this clipping info to drive whether the scissor
1111            // is used, it should more closely duplicate the quickReject logic (in how it uses
1112            // snapToPixelBoundaries)
1113
1114            if (!clippedBounds.intersect(currentClip)) {
1115                // quick rejected
1116                return true;
1117            }
1118
1119            state.mClipSideFlags = kClipSide_None;
1120            if (!currentClip.contains(state.mBounds)) {
1121                int& flags = state.mClipSideFlags;
1122                // op partially clipped, so record which sides are clipped for clip-aware merging
1123                if (currentClip.left > state.mBounds.left) flags |= kClipSide_Left;
1124                if (currentClip.top > state.mBounds.top) flags |= kClipSide_Top;
1125                if (currentClip.right < state.mBounds.right) flags |= kClipSide_Right;
1126                if (currentClip.bottom < state.mBounds.bottom) flags |= kClipSide_Bottom;
1127            }
1128            state.mBounds.set(clippedBounds);
1129        } else {
1130            // Empty bounds implies size unknown. Label op as conservatively clipped to disable
1131            // overdraw avoidance (since we don't know what it overlaps)
1132            state.mClipSideFlags = kClipSide_ConservativeFull;
1133            state.mBounds.set(currentClip);
1134        }
1135    }
1136
1137    state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip);
1138    if (state.mClipValid) {
1139        state.mClip.set(currentClip);
1140    }
1141
1142    // Transform and alpha always deferred, since they are used by state operations
1143    // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything)
1144    state.mMatrix = *currentMatrix;
1145    state.mAlpha = currentSnapshot()->alpha;
1146
1147    // always store/restore, since these are just pointers
1148    state.mRoundRectClipState = currentSnapshot()->roundRectClipState;
1149    state.mProjectionPathMask = currentSnapshot()->projectionPathMask;
1150    return false;
1151}
1152
1153void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) {
1154    setGlobalMatrix(state.mMatrix);
1155    writableSnapshot()->alpha = state.mAlpha;
1156    writableSnapshot()->roundRectClipState = state.mRoundRectClipState;
1157    writableSnapshot()->projectionPathMask = state.mProjectionPathMask;
1158
1159    if (state.mClipValid && !skipClipRestore) {
1160        writableSnapshot()->setClip(state.mClip.left, state.mClip.top,
1161                state.mClip.right, state.mClip.bottom);
1162        dirtyClip();
1163    }
1164}
1165
1166/**
1167 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done
1168 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at
1169 * least one op is clipped), or disabled entirely (because no merged op is clipped)
1170 *
1171 * This method should be called when restoreDisplayState() won't be restoring the clip
1172 */
1173void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) {
1174    if (clipRect != nullptr) {
1175        writableSnapshot()->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom);
1176    } else {
1177        writableSnapshot()->setClip(0, 0, mState.getWidth(), mState.getHeight());
1178    }
1179    dirtyClip();
1180    bool enableScissor = (clipRect != nullptr) || mScissorOptimizationDisabled;
1181    mRenderState.scissor().setEnabled(enableScissor);
1182}
1183
1184///////////////////////////////////////////////////////////////////////////////
1185// Clipping
1186///////////////////////////////////////////////////////////////////////////////
1187
1188void OpenGLRenderer::setScissorFromClip() {
1189    Rect clip(mState.currentClipRect());
1190    clip.snapToPixelBoundaries();
1191
1192    if (mRenderState.scissor().set(clip.left, getViewportHeight() - clip.bottom,
1193            clip.getWidth(), clip.getHeight())) {
1194        mState.setDirtyClip(false);
1195    }
1196}
1197
1198void OpenGLRenderer::ensureStencilBuffer() {
1199    // Thanks to the mismatch between EGL and OpenGL ES FBO we
1200    // cannot attach a stencil buffer to fbo0 dynamically. Let's
1201    // just hope we have one when hasLayer() returns false.
1202    if (hasLayer()) {
1203        attachStencilBufferToLayer(currentSnapshot()->layer);
1204    }
1205}
1206
1207void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
1208    // The layer's FBO is already bound when we reach this stage
1209    if (!layer->getStencilRenderBuffer()) {
1210        RenderBuffer* buffer = mCaches.renderBufferCache.get(
1211                Stencil::getLayerStencilFormat(),
1212                layer->getWidth(), layer->getHeight());
1213        layer->setStencilRenderBuffer(buffer);
1214    }
1215}
1216
1217static void handlePoint(std::vector<Vertex>& rectangleVertices, const Matrix4& transform,
1218        float x, float y) {
1219    Vertex v;
1220    v.x = x;
1221    v.y = y;
1222    transform.mapPoint(v.x, v.y);
1223    rectangleVertices.push_back(v);
1224}
1225
1226static void handlePointNoTransform(std::vector<Vertex>& rectangleVertices, float x, float y) {
1227    Vertex v;
1228    v.x = x;
1229    v.y = y;
1230    rectangleVertices.push_back(v);
1231}
1232
1233void OpenGLRenderer::drawRectangleList(const RectangleList& rectangleList) {
1234    int quadCount = rectangleList.getTransformedRectanglesCount();
1235    std::vector<Vertex> rectangleVertices(quadCount * 4);
1236    Rect scissorBox = rectangleList.calculateBounds();
1237    scissorBox.snapToPixelBoundaries();
1238    for (int i = 0; i < quadCount; ++i) {
1239        const TransformedRectangle& tr(rectangleList.getTransformedRectangle(i));
1240        const Matrix4& transform = tr.getTransform();
1241        Rect bounds = tr.getBounds();
1242        if (transform.rectToRect()) {
1243            transform.mapRect(bounds);
1244            if (!bounds.intersect(scissorBox)) {
1245                bounds.setEmpty();
1246            } else {
1247                handlePointNoTransform(rectangleVertices, bounds.left, bounds.top);
1248                handlePointNoTransform(rectangleVertices, bounds.right, bounds.top);
1249                handlePointNoTransform(rectangleVertices, bounds.left, bounds.bottom);
1250                handlePointNoTransform(rectangleVertices, bounds.right, bounds.bottom);
1251            }
1252        } else {
1253            handlePoint(rectangleVertices, transform, bounds.left, bounds.top);
1254            handlePoint(rectangleVertices, transform, bounds.right, bounds.top);
1255            handlePoint(rectangleVertices, transform, bounds.left, bounds.bottom);
1256            handlePoint(rectangleVertices, transform, bounds.right, bounds.bottom);
1257        }
1258    }
1259
1260    mRenderState.scissor().set(scissorBox.left, getViewportHeight() - scissorBox.bottom,
1261            scissorBox.getWidth(), scissorBox.getHeight());
1262    const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform;
1263    Glop glop;
1264    Vertex* vertices = &rectangleVertices[0];
1265    GlopBuilder(mRenderState, mCaches, &glop)
1266            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1267            .setMeshIndexedQuads(vertices, rectangleVertices.size() / 4)
1268            .setFillBlack()
1269            .setTransform(*currentSnapshot(), transformFlags)
1270            .setModelViewOffsetRect(0, 0, scissorBox)
1271            .build();
1272    renderGlop(glop);
1273}
1274
1275void OpenGLRenderer::setStencilFromClip() {
1276    if (!Properties::debugOverdraw) {
1277        if (!currentSnapshot()->clipIsSimple()) {
1278            int incrementThreshold;
1279            EVENT_LOGD("setStencilFromClip - enabling");
1280
1281            // NOTE: The order here is important, we must set dirtyClip to false
1282            //       before any draw call to avoid calling back into this method
1283            mState.setDirtyClip(false);
1284
1285            ensureStencilBuffer();
1286
1287            const ClipArea& clipArea = currentSnapshot()->getClipArea();
1288
1289            bool isRectangleList = clipArea.isRectangleList();
1290            if (isRectangleList) {
1291                incrementThreshold = clipArea.getRectangleList().getTransformedRectanglesCount();
1292            } else {
1293                incrementThreshold = 0;
1294            }
1295
1296            mRenderState.stencil().enableWrite(incrementThreshold);
1297
1298            // Clean and update the stencil, but first make sure we restrict drawing
1299            // to the region's bounds
1300            bool resetScissor = mRenderState.scissor().setEnabled(true);
1301            if (resetScissor) {
1302                // The scissor was not set so we now need to update it
1303                setScissorFromClip();
1304            }
1305
1306            mRenderState.stencil().clear();
1307
1308            // stash and disable the outline clip state, since stencil doesn't account for outline
1309            bool storedSkipOutlineClip = mSkipOutlineClip;
1310            mSkipOutlineClip = true;
1311
1312            SkPaint paint;
1313            paint.setColor(SK_ColorBLACK);
1314            paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1315
1316            if (isRectangleList) {
1317                drawRectangleList(clipArea.getRectangleList());
1318            } else {
1319                // NOTE: We could use the region contour path to generate a smaller mesh
1320                //       Since we are using the stencil we could use the red book path
1321                //       drawing technique. It might increase bandwidth usage though.
1322
1323                // The last parameter is important: we are not drawing in the color buffer
1324                // so we don't want to dirty the current layer, if any
1325                drawRegionRects(clipArea.getClipRegion(), paint, false);
1326            }
1327            if (resetScissor) mRenderState.scissor().setEnabled(false);
1328            mSkipOutlineClip = storedSkipOutlineClip;
1329
1330            mRenderState.stencil().enableTest(incrementThreshold);
1331
1332            // Draw the region used to generate the stencil if the appropriate debug
1333            // mode is enabled
1334            // TODO: Implement for rectangle list clip areas
1335            if (Properties::debugStencilClip == StencilClipDebug::ShowRegion
1336                    && !clipArea.isRectangleList()) {
1337                paint.setColor(0x7f0000ff);
1338                paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
1339                drawRegionRects(currentSnapshot()->getClipRegion(), paint);
1340            }
1341        } else {
1342            EVENT_LOGD("setStencilFromClip - disabling");
1343            mRenderState.stencil().disable();
1344        }
1345    }
1346}
1347
1348/**
1349 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out.
1350 *
1351 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint
1352 *         style, and tessellated AA ramp
1353 */
1354bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom,
1355        const SkPaint* paint) {
1356    bool snapOut = paint && paint->isAntiAlias();
1357
1358    if (paint && paint->getStyle() != SkPaint::kFill_Style) {
1359        float outset = paint->getStrokeWidth() * 0.5f;
1360        left -= outset;
1361        top -= outset;
1362        right += outset;
1363        bottom += outset;
1364    }
1365
1366    bool clipRequired = false;
1367    bool roundRectClipRequired = false;
1368    if (mState.calculateQuickRejectForScissor(left, top, right, bottom,
1369            &clipRequired, &roundRectClipRequired, snapOut)) {
1370        return true;
1371    }
1372
1373    // not quick rejected, so enable the scissor if clipRequired
1374    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
1375    mSkipOutlineClip = !roundRectClipRequired;
1376    return false;
1377}
1378
1379void OpenGLRenderer::debugClip() {
1380#if DEBUG_CLIP_REGIONS
1381    if (!currentSnapshot()->clipRegion->isEmpty()) {
1382        SkPaint paint;
1383        paint.setColor(0x7f00ff00);
1384        drawRegionRects(*(currentSnapshot()->clipRegion, paint);
1385
1386    }
1387#endif
1388}
1389
1390void OpenGLRenderer::renderGlop(const Glop& glop, GlopRenderType type) {
1391    // TODO: It would be best if we could do this before quickRejectSetupScissor()
1392    //       changes the scissor test state
1393    if (type != GlopRenderType::LayerClear) {
1394        // Regular draws need to clear the dirty area on the layer before they start drawing on top
1395        // of it. If this draw *is* a layer clear, it skips the clear step (since it would
1396        // infinitely recurse)
1397        clearLayerRegions();
1398    }
1399
1400    if (mState.getDirtyClip()) {
1401        if (mRenderState.scissor().isEnabled()) {
1402            setScissorFromClip();
1403        }
1404
1405        setStencilFromClip();
1406    }
1407    mRenderState.render(glop);
1408    if (type == GlopRenderType::Standard && !mRenderState.stencil().isWriteEnabled()) {
1409        // TODO: specify more clearly when a draw should dirty the layer.
1410        // is writing to the stencil the only time we should ignore this?
1411        dirtyLayer(glop.bounds.left, glop.bounds.top, glop.bounds.right, glop.bounds.bottom);
1412        mDirty = true;
1413    }
1414}
1415
1416///////////////////////////////////////////////////////////////////////////////
1417// Drawing
1418///////////////////////////////////////////////////////////////////////////////
1419
1420void OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int32_t replayFlags) {
1421    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1422    // will be performed by the display list itself
1423    if (renderNode && renderNode->isRenderable()) {
1424        // compute 3d ordering
1425        renderNode->computeOrdering();
1426        if (CC_UNLIKELY(Properties::drawDeferDisabled)) {
1427            startFrame();
1428            ReplayStateStruct replayStruct(*this, dirty, replayFlags);
1429            renderNode->replay(replayStruct, 0);
1430            return;
1431        }
1432
1433        // Don't avoid overdraw when visualizing, since that makes it harder to
1434        // debug where it's coming from, and when the problem occurs.
1435        bool avoidOverdraw = !Properties::debugOverdraw;
1436        DeferredDisplayList deferredList(mState.currentClipRect(), avoidOverdraw);
1437        DeferStateStruct deferStruct(deferredList, *this, replayFlags);
1438        renderNode->defer(deferStruct, 0);
1439
1440        flushLayers();
1441        startFrame();
1442
1443        deferredList.flush(*this, dirty);
1444    } else {
1445        // Even if there is no drawing command(Ex: invisible),
1446        // it still needs startFrame to clear buffer and start tiling.
1447        startFrame();
1448    }
1449}
1450
1451/**
1452 * Important note: this method is intended to draw batches of bitmaps and
1453 * will not set the scissor enable or dirty the current layer, if any.
1454 * The caller is responsible for properly dirtying the current layer.
1455 */
1456void OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
1457        int bitmapCount, TextureVertex* vertices, bool pureTranslate,
1458        const Rect& bounds, const SkPaint* paint) {
1459    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
1460    if (!texture) return;
1461
1462    const AutoTexture autoCleanup(texture);
1463
1464    // TODO: remove layer dirty in multi-draw callers
1465    // TODO: snap doesn't need to touch transform, only texture filter.
1466    bool snap = pureTranslate;
1467    const float x = floorf(bounds.left + 0.5f);
1468    const float y = floorf(bounds.top + 0.5f);
1469
1470    const int textureFillFlags = (bitmap->colorType() == kAlpha_8_SkColorType)
1471            ? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None;
1472    const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform;
1473    Glop glop;
1474    GlopBuilder(mRenderState, mCaches, &glop)
1475            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1476            .setMeshTexturedMesh(vertices, bitmapCount * 6)
1477            .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1478            .setTransform(*currentSnapshot(), transformFlags)
1479            .setModelViewOffsetRectOptionalSnap(snap, x, y, Rect(0, 0, bounds.getWidth(), bounds.getHeight()))
1480            .build();
1481    renderGlop(glop, GlopRenderType::Multi);
1482}
1483
1484void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) {
1485    if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) {
1486        return;
1487    }
1488
1489    mCaches.textureState().activateTexture(0);
1490    Texture* texture = getTexture(bitmap);
1491    if (!texture) return;
1492    const AutoTexture autoCleanup(texture);
1493
1494    const int textureFillFlags = (bitmap->colorType() == kAlpha_8_SkColorType)
1495            ? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None;
1496    Glop glop;
1497    GlopBuilder(mRenderState, mCaches, &glop)
1498            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1499            .setMeshTexturedUnitQuad(texture->uvMapper)
1500            .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1501            .setTransform(*currentSnapshot(),  TransformFlags::None)
1502            .setModelViewMapUnitToRectSnap(Rect(0, 0, texture->width, texture->height))
1503            .build();
1504    renderGlop(glop);
1505}
1506
1507void OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
1508        const float* vertices, const int* colors, const SkPaint* paint) {
1509    if (!vertices || mState.currentlyIgnored()) {
1510        return;
1511    }
1512
1513    float left = FLT_MAX;
1514    float top = FLT_MAX;
1515    float right = FLT_MIN;
1516    float bottom = FLT_MIN;
1517
1518    const uint32_t elementCount = meshWidth * meshHeight * 6;
1519
1520    std::unique_ptr<ColorTextureVertex[]> mesh(new ColorTextureVertex[elementCount]);
1521    ColorTextureVertex* vertex = &mesh[0];
1522
1523    std::unique_ptr<int[]> tempColors;
1524    if (!colors) {
1525        uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
1526        tempColors.reset(new int[colorsCount]);
1527        memset(tempColors.get(), 0xff, colorsCount * sizeof(int));
1528        colors = tempColors.get();
1529    }
1530
1531    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
1532    const UvMapper& mapper(getMapper(texture));
1533
1534    for (int32_t y = 0; y < meshHeight; y++) {
1535        for (int32_t x = 0; x < meshWidth; x++) {
1536            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1537
1538            float u1 = float(x) / meshWidth;
1539            float u2 = float(x + 1) / meshWidth;
1540            float v1 = float(y) / meshHeight;
1541            float v2 = float(y + 1) / meshHeight;
1542
1543            mapper.map(u1, v1, u2, v2);
1544
1545            int ax = i + (meshWidth + 1) * 2;
1546            int ay = ax + 1;
1547            int bx = i;
1548            int by = bx + 1;
1549            int cx = i + 2;
1550            int cy = cx + 1;
1551            int dx = i + (meshWidth + 1) * 2 + 2;
1552            int dy = dx + 1;
1553
1554            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
1555            ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
1556            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
1557
1558            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
1559            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
1560            ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
1561
1562            left = std::min(left, std::min(vertices[ax], std::min(vertices[bx], vertices[cx])));
1563            top = std::min(top, std::min(vertices[ay], std::min(vertices[by], vertices[cy])));
1564            right = std::max(right, std::max(vertices[ax], std::max(vertices[bx], vertices[cx])));
1565            bottom = std::max(bottom, std::max(vertices[ay], std::max(vertices[by], vertices[cy])));
1566        }
1567    }
1568
1569    if (quickRejectSetupScissor(left, top, right, bottom)) {
1570        return;
1571    }
1572
1573    if (!texture) {
1574        texture = mCaches.textureCache.get(bitmap);
1575        if (!texture) {
1576            return;
1577        }
1578    }
1579    const AutoTexture autoCleanup(texture);
1580
1581    /*
1582     * TODO: handle alpha_8 textures correctly by applying paint color, but *not*
1583     * shader in that case to mimic the behavior in SkiaCanvas::drawBitmapMesh.
1584     */
1585    const int textureFillFlags = TextureFillFlags::None;
1586    Glop glop;
1587    GlopBuilder(mRenderState, mCaches, &glop)
1588            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1589            .setMeshColoredTexturedMesh(mesh.get(), elementCount)
1590            .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1591            .setTransform(*currentSnapshot(),  TransformFlags::None)
1592            .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom))
1593            .build();
1594    renderGlop(glop);
1595}
1596
1597void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, Rect src, Rect dst, const SkPaint* paint) {
1598    if (quickRejectSetupScissor(dst)) {
1599        return;
1600    }
1601
1602    Texture* texture = getTexture(bitmap);
1603    if (!texture) return;
1604    const AutoTexture autoCleanup(texture);
1605
1606    Rect uv(std::max(0.0f, src.left / texture->width),
1607            std::max(0.0f, src.top / texture->height),
1608            std::min(1.0f, src.right / texture->width),
1609            std::min(1.0f, src.bottom / texture->height));
1610
1611    const int textureFillFlags = (bitmap->colorType() == kAlpha_8_SkColorType)
1612            ? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None;
1613    const bool tryToSnap = MathUtils::areEqual(src.getWidth(), dst.getWidth())
1614            && MathUtils::areEqual(src.getHeight(), dst.getHeight());
1615    Glop glop;
1616    GlopBuilder(mRenderState, mCaches, &glop)
1617            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1618            .setMeshTexturedUvQuad(texture->uvMapper, uv)
1619            .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1620            .setTransform(*currentSnapshot(),  TransformFlags::None)
1621            .setModelViewMapUnitToRectOptionalSnap(tryToSnap, dst)
1622            .build();
1623    renderGlop(glop);
1624}
1625
1626void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh,
1627        AssetAtlas::Entry* entry, float left, float top, float right, float bottom,
1628        const SkPaint* paint) {
1629    if (!mesh || !mesh->verticesCount || quickRejectSetupScissor(left, top, right, bottom)) {
1630        return;
1631    }
1632
1633    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
1634    if (!texture) return;
1635
1636    // 9 patches are built for stretching - always filter
1637    int textureFillFlags = TextureFillFlags::ForceFilter;
1638    if (bitmap->colorType() == kAlpha_8_SkColorType) {
1639        textureFillFlags |= TextureFillFlags::IsAlphaMaskTexture;
1640    }
1641    Glop glop;
1642    GlopBuilder(mRenderState, mCaches, &glop)
1643            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1644            .setMeshPatchQuads(*mesh)
1645            .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1646            .setTransform(*currentSnapshot(),  TransformFlags::None)
1647            .setModelViewOffsetRectSnap(left, top, Rect(0, 0, right - left, bottom - top)) // TODO: get minimal bounds from patch
1648            .build();
1649    renderGlop(glop);
1650}
1651
1652/**
1653 * Important note: this method is intended to draw batches of 9-patch objects and
1654 * will not set the scissor enable or dirty the current layer, if any.
1655 * The caller is responsible for properly dirtying the current layer.
1656 */
1657void OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
1658        TextureVertex* vertices, uint32_t elementCount, const SkPaint* paint) {
1659    mCaches.textureState().activateTexture(0);
1660    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
1661    if (!texture) return;
1662    const AutoTexture autoCleanup(texture);
1663
1664    // TODO: get correct bounds from caller
1665    const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform;
1666    // 9 patches are built for stretching - always filter
1667    int textureFillFlags = TextureFillFlags::ForceFilter;
1668    if (bitmap->colorType() == kAlpha_8_SkColorType) {
1669        textureFillFlags |= TextureFillFlags::IsAlphaMaskTexture;
1670    }
1671    Glop glop;
1672    GlopBuilder(mRenderState, mCaches, &glop)
1673            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1674            .setMeshTexturedIndexedQuads(vertices, elementCount)
1675            .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1676            .setTransform(*currentSnapshot(), transformFlags)
1677            .setModelViewOffsetRect(0, 0, Rect(0, 0, 0, 0))
1678            .build();
1679    renderGlop(glop, GlopRenderType::Multi);
1680}
1681
1682void OpenGLRenderer::drawVertexBuffer(float translateX, float translateY,
1683        const VertexBuffer& vertexBuffer, const SkPaint* paint, int displayFlags) {
1684    // not missing call to quickReject/dirtyLayer, always done at a higher level
1685    if (!vertexBuffer.getVertexCount()) {
1686        // no vertices to draw
1687        return;
1688    }
1689
1690    bool shadowInterp = displayFlags & kVertexBuffer_ShadowInterp;
1691    const int transformFlags = TransformFlags::OffsetByFudgeFactor;
1692    Glop glop;
1693    GlopBuilder(mRenderState, mCaches, &glop)
1694            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1695            .setMeshVertexBuffer(vertexBuffer, shadowInterp)
1696            .setFillPaint(*paint, currentSnapshot()->alpha)
1697            .setTransform(*currentSnapshot(), transformFlags)
1698            .setModelViewOffsetRect(translateX, translateY, vertexBuffer.getBounds())
1699            .build();
1700    renderGlop(glop);
1701}
1702
1703/**
1704 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
1705 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
1706 * screen space in all directions. However, instead of using a fragment shader to compute the
1707 * translucency of the color from its position, we simply use a varying parameter to define how far
1708 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
1709 *
1710 * Doesn't yet support joins, caps, or path effects.
1711 */
1712void OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) {
1713    VertexBuffer vertexBuffer;
1714    // TODO: try clipping large paths to viewport
1715
1716    PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer);
1717    drawVertexBuffer(vertexBuffer, paint);
1718}
1719
1720/**
1721 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
1722 * and additional geometry for defining an alpha slope perimeter.
1723 *
1724 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
1725 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
1726 * in-shader alpha region, but found it to be taxing on some GPUs.
1727 *
1728 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
1729 * memory transfer by removing need for degenerate vertices.
1730 */
1731void OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) {
1732    if (mState.currentlyIgnored() || count < 4) return;
1733
1734    count &= ~0x3; // round down to nearest four
1735
1736    VertexBuffer buffer;
1737    PathTessellator::tessellateLines(points, count, paint, *currentTransform(), buffer);
1738    const Rect& bounds = buffer.getBounds();
1739
1740    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
1741        return;
1742    }
1743
1744    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
1745    drawVertexBuffer(buffer, paint, displayFlags);
1746}
1747
1748void OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) {
1749    if (mState.currentlyIgnored() || count < 2) return;
1750
1751    count &= ~0x1; // round down to nearest two
1752
1753    VertexBuffer buffer;
1754    PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), buffer);
1755
1756    const Rect& bounds = buffer.getBounds();
1757    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
1758        return;
1759    }
1760
1761    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
1762    drawVertexBuffer(buffer, paint, displayFlags);
1763
1764    mDirty = true;
1765}
1766
1767void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1768    // No need to check against the clip, we fill the clip region
1769    if (mState.currentlyIgnored()) return;
1770
1771    Rect clip(mState.currentClipRect());
1772    clip.snapToPixelBoundaries();
1773
1774    SkPaint paint;
1775    paint.setColor(color);
1776    paint.setXfermodeMode(mode);
1777
1778    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true);
1779
1780    mDirty = true;
1781}
1782
1783void OpenGLRenderer::drawShape(float left, float top, PathTexture* texture,
1784        const SkPaint* paint) {
1785    if (!texture) return;
1786    const AutoTexture autoCleanup(texture);
1787
1788    const float x = left + texture->left - texture->offset;
1789    const float y = top + texture->top - texture->offset;
1790
1791    drawPathTexture(texture, x, y, paint);
1792
1793    mDirty = true;
1794}
1795
1796void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1797        float rx, float ry, const SkPaint* p) {
1798    if (mState.currentlyIgnored()
1799            || quickRejectSetupScissor(left, top, right, bottom, p)
1800            || PaintUtils::paintWillNotDraw(*p)) {
1801        return;
1802    }
1803
1804    if (p->getPathEffect() != nullptr) {
1805        mCaches.textureState().activateTexture(0);
1806        PathTexture* texture = mCaches.pathCache.getRoundRect(
1807                right - left, bottom - top, rx, ry, p);
1808        drawShape(left, top, texture, p);
1809    } else {
1810        const VertexBuffer* vertexBuffer = mCaches.tessellationCache.getRoundRect(
1811                *currentTransform(), *p, right - left, bottom - top, rx, ry);
1812        drawVertexBuffer(left, top, *vertexBuffer, p);
1813    }
1814}
1815
1816void OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) {
1817    if (mState.currentlyIgnored()
1818            || quickRejectSetupScissor(x - radius, y - radius, x + radius, y + radius, p)
1819            || PaintUtils::paintWillNotDraw(*p)) {
1820        return;
1821    }
1822
1823    if (p->getPathEffect() != nullptr) {
1824        mCaches.textureState().activateTexture(0);
1825        PathTexture* texture = mCaches.pathCache.getCircle(radius, p);
1826        drawShape(x - radius, y - radius, texture, p);
1827        return;
1828    }
1829
1830    SkPath path;
1831    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
1832        path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
1833    } else {
1834        path.addCircle(x, y, radius);
1835    }
1836
1837    if (CC_UNLIKELY(currentSnapshot()->projectionPathMask != nullptr)) {
1838        // mask ripples with projection mask
1839        SkPath maskPath = *(currentSnapshot()->projectionPathMask->projectionMask);
1840
1841        Matrix4 screenSpaceTransform;
1842        currentSnapshot()->buildScreenSpaceTransform(&screenSpaceTransform);
1843
1844        Matrix4 totalTransform;
1845        totalTransform.loadInverse(screenSpaceTransform);
1846        totalTransform.multiply(currentSnapshot()->projectionPathMask->projectionMaskTransform);
1847
1848        SkMatrix skTotalTransform;
1849        totalTransform.copyTo(skTotalTransform);
1850        maskPath.transform(skTotalTransform);
1851
1852        // Mask the ripple path by the projection mask, now that it's
1853        // in local space. Note that this can create CCW paths.
1854        Op(path, maskPath, kIntersect_SkPathOp, &path);
1855    }
1856    drawConvexPath(path, p);
1857}
1858
1859void OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
1860        const SkPaint* p) {
1861    if (mState.currentlyIgnored()
1862            || quickRejectSetupScissor(left, top, right, bottom, p)
1863            || PaintUtils::paintWillNotDraw(*p)) {
1864        return;
1865    }
1866
1867    if (p->getPathEffect() != nullptr) {
1868        mCaches.textureState().activateTexture(0);
1869        PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p);
1870        drawShape(left, top, texture, p);
1871    } else {
1872        SkPath path;
1873        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
1874        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
1875            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
1876        }
1877        path.addOval(rect);
1878        drawConvexPath(path, p);
1879    }
1880}
1881
1882void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
1883        float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) {
1884    if (mState.currentlyIgnored()
1885            || quickRejectSetupScissor(left, top, right, bottom, p)
1886            || PaintUtils::paintWillNotDraw(*p)) {
1887        return;
1888    }
1889
1890    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
1891    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != nullptr || useCenter) {
1892        mCaches.textureState().activateTexture(0);
1893        PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top,
1894                startAngle, sweepAngle, useCenter, p);
1895        drawShape(left, top, texture, p);
1896        return;
1897    }
1898    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
1899    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
1900        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
1901    }
1902
1903    SkPath path;
1904    if (useCenter) {
1905        path.moveTo(rect.centerX(), rect.centerY());
1906    }
1907    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
1908    if (useCenter) {
1909        path.close();
1910    }
1911    drawConvexPath(path, p);
1912}
1913
1914// See SkPaintDefaults.h
1915#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
1916
1917void OpenGLRenderer::drawRect(float left, float top, float right, float bottom,
1918        const SkPaint* p) {
1919    if (mState.currentlyIgnored()
1920            || quickRejectSetupScissor(left, top, right, bottom, p)
1921            || PaintUtils::paintWillNotDraw(*p)) {
1922        return;
1923    }
1924
1925    if (p->getStyle() != SkPaint::kFill_Style) {
1926        // only fill style is supported by drawConvexPath, since others have to handle joins
1927        if (p->getPathEffect() != nullptr || p->getStrokeJoin() != SkPaint::kMiter_Join ||
1928                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
1929            mCaches.textureState().activateTexture(0);
1930            PathTexture* texture =
1931                    mCaches.pathCache.getRect(right - left, bottom - top, p);
1932            drawShape(left, top, texture, p);
1933        } else {
1934            SkPath path;
1935            SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
1936            if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
1937                rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
1938            }
1939            path.addRect(rect);
1940            drawConvexPath(path, p);
1941        }
1942    } else {
1943        if (p->isAntiAlias() && !currentTransform()->isSimple()) {
1944            SkPath path;
1945            path.addRect(left, top, right, bottom);
1946            drawConvexPath(path, p);
1947        } else {
1948            drawColorRect(left, top, right, bottom, p);
1949
1950            mDirty = true;
1951        }
1952    }
1953}
1954
1955void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text,
1956        int bytesCount, int count, const float* positions,
1957        FontRenderer& fontRenderer, int alpha, float x, float y) {
1958    mCaches.textureState().activateTexture(0);
1959
1960    TextShadow textShadow;
1961    if (!getTextShadow(paint, &textShadow)) {
1962        LOG_ALWAYS_FATAL("failed to query shadow attributes");
1963    }
1964
1965    // NOTE: The drop shadow will not perform gamma correction
1966    //       if shader-based correction is enabled
1967    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
1968    ShadowTexture* texture = mCaches.dropShadowCache.get(
1969            paint, text, bytesCount, count, textShadow.radius, positions);
1970    // If the drop shadow exceeds the max texture size or couldn't be
1971    // allocated, skip drawing
1972    if (!texture) return;
1973    const AutoTexture autoCleanup(texture);
1974
1975    const float sx = x - texture->left + textShadow.dx;
1976    const float sy = y - texture->top + textShadow.dy;
1977
1978    Glop glop;
1979    GlopBuilder(mRenderState, mCaches, &glop)
1980            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1981            .setMeshTexturedUnitQuad(nullptr)
1982            .setFillShadowTexturePaint(*texture, textShadow.color, *paint, currentSnapshot()->alpha)
1983            .setTransform(*currentSnapshot(),  TransformFlags::None)
1984            .setModelViewMapUnitToRect(Rect(sx, sy, sx + texture->width, sy + texture->height))
1985            .build();
1986    renderGlop(glop);
1987}
1988
1989bool OpenGLRenderer::canSkipText(const SkPaint* paint) const {
1990    float alpha = (hasTextShadow(paint) ? 1.0f : paint->getAlpha()) * currentSnapshot()->alpha;
1991    return MathUtils::isZero(alpha)
1992            && PaintUtils::getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode;
1993}
1994
1995void OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
1996        const float* positions, const SkPaint* paint) {
1997    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
1998        return;
1999    }
2000
2001    // NOTE: Skia does not support perspective transform on drawPosText yet
2002    if (!currentTransform()->isSimple()) {
2003        return;
2004    }
2005
2006    mRenderState.scissor().setEnabled(true);
2007
2008    float x = 0.0f;
2009    float y = 0.0f;
2010    const bool pureTranslate = currentTransform()->isPureTranslate();
2011    if (pureTranslate) {
2012        x = floorf(x + currentTransform()->getTranslateX() + 0.5f);
2013        y = floorf(y + currentTransform()->getTranslateY() + 0.5f);
2014    }
2015
2016    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2017    fontRenderer.setFont(paint, SkMatrix::I());
2018
2019    int alpha;
2020    SkXfermode::Mode mode;
2021    getAlphaAndMode(paint, &alpha, &mode);
2022
2023    if (CC_UNLIKELY(hasTextShadow(paint))) {
2024        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2025                alpha, 0.0f, 0.0f);
2026    }
2027
2028    // Pick the appropriate texture filtering
2029    bool linearFilter = currentTransform()->changesBounds();
2030    if (pureTranslate && !linearFilter) {
2031        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2032    }
2033    fontRenderer.setTextureFiltering(linearFilter);
2034
2035    const Rect& clip(pureTranslate ? writableSnapshot()->getClipRect() : writableSnapshot()->getLocalClip());
2036    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2037
2038    TextDrawFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2039    if (fontRenderer.renderPosText(paint, &clip, text, 0, bytesCount, count, x, y,
2040            positions, hasLayer() ? &bounds : nullptr, &functor)) {
2041        dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform());
2042        mDirty = true;
2043    }
2044
2045}
2046
2047bool OpenGLRenderer::findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const {
2048    if (CC_LIKELY(transform.isPureTranslate())) {
2049        outMatrix->setIdentity();
2050        return false;
2051    } else if (CC_UNLIKELY(transform.isPerspective())) {
2052        outMatrix->setIdentity();
2053        return true;
2054    }
2055
2056    /**
2057     * Input is a non-perspective, scaling transform. Generate a scale-only transform,
2058     * with values rounded to the nearest int.
2059     */
2060    float sx, sy;
2061    transform.decomposeScale(sx, sy);
2062    outMatrix->setScale(
2063            roundf(std::max(1.0f, sx)),
2064            roundf(std::max(1.0f, sy)));
2065    return true;
2066}
2067
2068int OpenGLRenderer::getSaveCount() const {
2069    return mState.getSaveCount();
2070}
2071
2072int OpenGLRenderer::save(int flags) {
2073    return mState.save(flags);
2074}
2075
2076void OpenGLRenderer::restore() {
2077    mState.restore();
2078}
2079
2080void OpenGLRenderer::restoreToCount(int saveCount) {
2081    mState.restoreToCount(saveCount);
2082}
2083
2084
2085void OpenGLRenderer::translate(float dx, float dy, float dz) {
2086    mState.translate(dx, dy, dz);
2087}
2088
2089void OpenGLRenderer::rotate(float degrees) {
2090    mState.rotate(degrees);
2091}
2092
2093void OpenGLRenderer::scale(float sx, float sy) {
2094    mState.scale(sx, sy);
2095}
2096
2097void OpenGLRenderer::skew(float sx, float sy) {
2098    mState.skew(sx, sy);
2099}
2100
2101void OpenGLRenderer::setLocalMatrix(const Matrix4& matrix) {
2102    mState.setMatrix(mBaseTransform);
2103    mState.concatMatrix(matrix);
2104}
2105
2106void OpenGLRenderer::setLocalMatrix(const SkMatrix& matrix) {
2107    mState.setMatrix(mBaseTransform);
2108    mState.concatMatrix(matrix);
2109}
2110
2111void OpenGLRenderer::concatMatrix(const Matrix4& matrix) {
2112    mState.concatMatrix(matrix);
2113}
2114
2115bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
2116    return mState.clipRect(left, top, right, bottom, op);
2117}
2118
2119bool OpenGLRenderer::clipPath(const SkPath* path, SkRegion::Op op) {
2120    return mState.clipPath(path, op);
2121}
2122
2123bool OpenGLRenderer::clipRegion(const SkRegion* region, SkRegion::Op op) {
2124    return mState.clipRegion(region, op);
2125}
2126
2127void OpenGLRenderer::setClippingOutline(LinearAllocator& allocator, const Outline* outline) {
2128    mState.setClippingOutline(allocator, outline);
2129}
2130
2131void OpenGLRenderer::setClippingRoundRect(LinearAllocator& allocator,
2132        const Rect& rect, float radius, bool highPriority) {
2133    mState.setClippingRoundRect(allocator, rect, radius, highPriority);
2134}
2135
2136void OpenGLRenderer::setProjectionPathMask(LinearAllocator& allocator, const SkPath* path) {
2137    mState.setProjectionPathMask(allocator, path);
2138}
2139
2140void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y,
2141        const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
2142        DrawOpMode drawOpMode) {
2143
2144    if (drawOpMode == DrawOpMode::kImmediate) {
2145        // The checks for corner-case ignorable text and quick rejection is only done for immediate
2146        // drawing as ops from DeferredDisplayList are already filtered for these
2147        if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint) ||
2148                quickRejectSetupScissor(bounds)) {
2149            return;
2150        }
2151    }
2152
2153    const float oldX = x;
2154    const float oldY = y;
2155
2156    const mat4& transform = *currentTransform();
2157    const bool pureTranslate = transform.isPureTranslate();
2158
2159    if (CC_LIKELY(pureTranslate)) {
2160        x = floorf(x + transform.getTranslateX() + 0.5f);
2161        y = floorf(y + transform.getTranslateY() + 0.5f);
2162    }
2163
2164    int alpha;
2165    SkXfermode::Mode mode;
2166    getAlphaAndMode(paint, &alpha, &mode);
2167
2168    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2169
2170    if (CC_UNLIKELY(hasTextShadow(paint))) {
2171        fontRenderer.setFont(paint, SkMatrix::I());
2172        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2173                alpha, oldX, oldY);
2174    }
2175
2176    const bool hasActiveLayer = hasLayer();
2177
2178    // We only pass a partial transform to the font renderer. That partial
2179    // matrix defines how glyphs are rasterized. Typically we want glyphs
2180    // to be rasterized at their final size on screen, which means the partial
2181    // matrix needs to take the scale factor into account.
2182    // When a partial matrix is used to transform glyphs during rasterization,
2183    // the mesh is generated with the inverse transform (in the case of scale,
2184    // the mesh is generated at 1.0 / scale for instance.) This allows us to
2185    // apply the full transform matrix at draw time in the vertex shader.
2186    // Applying the full matrix in the shader is the easiest way to handle
2187    // rotation and perspective and allows us to always generated quads in the
2188    // font renderer which greatly simplifies the code, clipping in particular.
2189    SkMatrix fontTransform;
2190    bool linearFilter = findBestFontTransform(transform, &fontTransform)
2191            || fabs(y - (int) y) > 0.0f
2192            || fabs(x - (int) x) > 0.0f;
2193    fontRenderer.setFont(paint, fontTransform);
2194    fontRenderer.setTextureFiltering(linearFilter);
2195
2196    // TODO: Implement better clipping for scaled/rotated text
2197    const Rect* clip = !pureTranslate ? nullptr : &mState.currentClipRect();
2198    Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2199
2200    bool status;
2201    TextDrawFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2202
2203    // don't call issuedrawcommand, do it at end of batch
2204    bool forceFinish = (drawOpMode != DrawOpMode::kDefer);
2205    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2206        SkPaint paintCopy(*paint);
2207        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2208        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2209                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2210    } else {
2211        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2212                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2213    }
2214
2215    if ((status || drawOpMode != DrawOpMode::kImmediate) && hasActiveLayer) {
2216        if (!pureTranslate) {
2217            transform.mapRect(layerBounds);
2218        }
2219        dirtyLayerUnchecked(layerBounds, getRegion());
2220    }
2221
2222    drawTextDecorations(totalAdvance, oldX, oldY, paint);
2223
2224    mDirty = true;
2225}
2226
2227void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count,
2228        const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) {
2229    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2230        return;
2231    }
2232
2233    // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics
2234    mRenderState.scissor().setEnabled(true);
2235
2236    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2237    fontRenderer.setFont(paint, SkMatrix::I());
2238    fontRenderer.setTextureFiltering(true);
2239
2240    int alpha;
2241    SkXfermode::Mode mode;
2242    getAlphaAndMode(paint, &alpha, &mode);
2243    TextDrawFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint);
2244
2245    const Rect* clip = &writableSnapshot()->getLocalClip();
2246    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2247
2248    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2249            hOffset, vOffset, hasLayer() ? &bounds : nullptr, &functor)) {
2250        dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform());
2251        mDirty = true;
2252    }
2253}
2254
2255void OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) {
2256    if (mState.currentlyIgnored()) return;
2257
2258    mCaches.textureState().activateTexture(0);
2259
2260    PathTexture* texture = mCaches.pathCache.get(path, paint);
2261    if (!texture) return;
2262    const AutoTexture autoCleanup(texture);
2263
2264    const float x = texture->left - texture->offset;
2265    const float y = texture->top - texture->offset;
2266
2267    drawPathTexture(texture, x, y, paint);
2268    mDirty = true;
2269}
2270
2271void OpenGLRenderer::drawLayer(Layer* layer, float x, float y) {
2272    if (!layer) {
2273        return;
2274    }
2275
2276    mat4* transform = nullptr;
2277    if (layer->isTextureLayer()) {
2278        transform = &layer->getTransform();
2279        if (!transform->isIdentity()) {
2280            save(SkCanvas::kMatrix_SaveFlag);
2281            concatMatrix(*transform);
2282        }
2283    }
2284
2285    bool clipRequired = false;
2286    const bool rejected = mState.calculateQuickRejectForScissor(
2287            x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
2288            &clipRequired, nullptr, false);
2289
2290    if (rejected) {
2291        if (transform && !transform->isIdentity()) {
2292            restore();
2293        }
2294        return;
2295    }
2296
2297    EVENT_LOGD("drawLayer," RECT_STRING ", clipRequired %d", x, y,
2298            x + layer->layer.getWidth(), y + layer->layer.getHeight(), clipRequired);
2299
2300    updateLayer(layer, true);
2301
2302    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
2303    mCaches.textureState().activateTexture(0);
2304
2305    if (CC_LIKELY(!layer->region.isEmpty())) {
2306        if (layer->region.isRect()) {
2307            DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
2308                    composeLayerRect(layer, layer->regionRect));
2309        } else if (layer->mesh) {
2310            Glop glop;
2311            GlopBuilder(mRenderState, mCaches, &glop)
2312                    .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2313                    .setMeshTexturedIndexedQuads(layer->mesh, layer->meshElementCount)
2314                    .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap)
2315                    .setTransform(*currentSnapshot(),  TransformFlags::None)
2316                    .setModelViewOffsetRectSnap(x, y, Rect(0, 0, layer->layer.getWidth(), layer->layer.getHeight()))
2317                    .build();
2318            DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, renderGlop(glop));
2319#if DEBUG_LAYERS_AS_REGIONS
2320            drawRegionRectsDebug(layer->region);
2321#endif
2322        }
2323
2324        if (layer->debugDrawUpdate) {
2325            layer->debugDrawUpdate = false;
2326
2327            SkPaint paint;
2328            paint.setColor(0x7f00ff00);
2329            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint);
2330        }
2331    }
2332    layer->hasDrawnSinceUpdate = true;
2333
2334    if (transform && !transform->isIdentity()) {
2335        restore();
2336    }
2337
2338    mDirty = true;
2339}
2340
2341///////////////////////////////////////////////////////////////////////////////
2342// Draw filters
2343///////////////////////////////////////////////////////////////////////////////
2344void OpenGLRenderer::setDrawFilter(SkDrawFilter* filter) {
2345    // We should never get here since we apply the draw filter when stashing
2346    // the paints in the DisplayList.
2347    LOG_ALWAYS_FATAL("OpenGLRenderer does not directly support DrawFilters");
2348}
2349
2350///////////////////////////////////////////////////////////////////////////////
2351// Drawing implementation
2352///////////////////////////////////////////////////////////////////////////////
2353
2354Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) {
2355    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
2356    if (!texture) {
2357        return mCaches.textureCache.get(bitmap);
2358    }
2359    return texture;
2360}
2361
2362void OpenGLRenderer::drawPathTexture(PathTexture* texture, float x, float y,
2363        const SkPaint* paint) {
2364    if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) {
2365        return;
2366    }
2367
2368    Glop glop;
2369    GlopBuilder(mRenderState, mCaches, &glop)
2370            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2371            .setMeshTexturedUnitQuad(nullptr)
2372            .setFillPathTexturePaint(*texture, *paint, currentSnapshot()->alpha)
2373            .setTransform(*currentSnapshot(),  TransformFlags::None)
2374            .setModelViewMapUnitToRect(Rect(x, y, x + texture->width, y + texture->height))
2375            .build();
2376    renderGlop(glop);
2377}
2378
2379// Same values used by Skia
2380#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2381#define kStdUnderline_Offset    (1.0f / 9.0f)
2382#define kStdUnderline_Thickness (1.0f / 18.0f)
2383
2384void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y,
2385        const SkPaint* paint) {
2386    // Handle underline and strike-through
2387    uint32_t flags = paint->getFlags();
2388    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2389        SkPaint paintCopy(*paint);
2390
2391        if (CC_LIKELY(underlineWidth > 0.0f)) {
2392            const float textSize = paintCopy.getTextSize();
2393            const float strokeWidth = std::max(textSize * kStdUnderline_Thickness, 1.0f);
2394
2395            const float left = x;
2396            float top = 0.0f;
2397
2398            int linesCount = 0;
2399            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2400            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2401
2402            const int pointsCount = 4 * linesCount;
2403            float points[pointsCount];
2404            int currentPoint = 0;
2405
2406            if (flags & SkPaint::kUnderlineText_Flag) {
2407                top = y + textSize * kStdUnderline_Offset;
2408                points[currentPoint++] = left;
2409                points[currentPoint++] = top;
2410                points[currentPoint++] = left + underlineWidth;
2411                points[currentPoint++] = top;
2412            }
2413
2414            if (flags & SkPaint::kStrikeThruText_Flag) {
2415                top = y + textSize * kStdStrikeThru_Offset;
2416                points[currentPoint++] = left;
2417                points[currentPoint++] = top;
2418                points[currentPoint++] = left + underlineWidth;
2419                points[currentPoint++] = top;
2420            }
2421
2422            paintCopy.setStrokeWidth(strokeWidth);
2423
2424            drawLines(&points[0], pointsCount, &paintCopy);
2425        }
2426    }
2427}
2428
2429void OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) {
2430    if (mState.currentlyIgnored()) {
2431        return;
2432    }
2433
2434    drawColorRects(rects, count, paint, false, true, true);
2435}
2436
2437void OpenGLRenderer::drawShadow(float casterAlpha,
2438        const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) {
2439    if (mState.currentlyIgnored()) return;
2440
2441    // TODO: use quickRejectWithScissor. For now, always force enable scissor.
2442    mRenderState.scissor().setEnabled(true);
2443
2444    SkPaint paint;
2445    paint.setAntiAlias(true); // want to use AlphaVertex
2446
2447    // The caller has made sure casterAlpha > 0.
2448    float ambientShadowAlpha = mAmbientShadowAlpha;
2449    if (CC_UNLIKELY(Properties::overrideAmbientShadowStrength >= 0)) {
2450        ambientShadowAlpha = Properties::overrideAmbientShadowStrength;
2451    }
2452    if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) {
2453        paint.setARGB(casterAlpha * ambientShadowAlpha, 0, 0, 0);
2454        drawVertexBuffer(*ambientShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
2455    }
2456
2457    float spotShadowAlpha = mSpotShadowAlpha;
2458    if (CC_UNLIKELY(Properties::overrideSpotShadowStrength >= 0)) {
2459        spotShadowAlpha = Properties::overrideSpotShadowStrength;
2460    }
2461    if (spotShadowVertexBuffer && spotShadowAlpha > 0) {
2462        paint.setARGB(casterAlpha * spotShadowAlpha, 0, 0, 0);
2463        drawVertexBuffer(*spotShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
2464    }
2465
2466    mDirty=true;
2467}
2468
2469void OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint,
2470        bool ignoreTransform, bool dirty, bool clip) {
2471    if (count == 0) {
2472        return;
2473    }
2474
2475    float left = FLT_MAX;
2476    float top = FLT_MAX;
2477    float right = FLT_MIN;
2478    float bottom = FLT_MIN;
2479
2480    Vertex mesh[count];
2481    Vertex* vertex = mesh;
2482
2483    for (int index = 0; index < count; index += 4) {
2484        float l = rects[index + 0];
2485        float t = rects[index + 1];
2486        float r = rects[index + 2];
2487        float b = rects[index + 3];
2488
2489        Vertex::set(vertex++, l, t);
2490        Vertex::set(vertex++, r, t);
2491        Vertex::set(vertex++, l, b);
2492        Vertex::set(vertex++, r, b);
2493
2494        left = std::min(left, l);
2495        top = std::min(top, t);
2496        right = std::max(right, r);
2497        bottom = std::max(bottom, b);
2498    }
2499
2500    if (clip && quickRejectSetupScissor(left, top, right, bottom)) {
2501        return;
2502    }
2503
2504    const int transformFlags = ignoreTransform
2505            ? TransformFlags::MeshIgnoresCanvasTransform : TransformFlags::None;
2506    Glop glop;
2507    GlopBuilder(mRenderState, mCaches, &glop)
2508            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2509            .setMeshIndexedQuads(&mesh[0], count / 4)
2510            .setFillPaint(*paint, currentSnapshot()->alpha)
2511            .setTransform(*currentSnapshot(), transformFlags)
2512            .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom))
2513            .build();
2514    renderGlop(glop);
2515}
2516
2517void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
2518        const SkPaint* paint, bool ignoreTransform) {
2519    const int transformFlags = ignoreTransform
2520            ? TransformFlags::MeshIgnoresCanvasTransform : TransformFlags::None;
2521    Glop glop;
2522    GlopBuilder(mRenderState, mCaches, &glop)
2523            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2524            .setMeshUnitQuad()
2525            .setFillPaint(*paint, currentSnapshot()->alpha)
2526            .setTransform(*currentSnapshot(), transformFlags)
2527            .setModelViewMapUnitToRect(Rect(left, top, right, bottom))
2528            .build();
2529    renderGlop(glop);
2530}
2531
2532void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha,
2533        SkXfermode::Mode* mode) const {
2534    getAlphaAndModeDirect(paint, alpha,  mode);
2535    *alpha *= currentSnapshot()->alpha;
2536}
2537
2538float OpenGLRenderer::getLayerAlpha(const Layer* layer) const {
2539    return (layer->getAlpha() / 255.0f) * currentSnapshot()->alpha;
2540}
2541
2542}; // namespace uirenderer
2543}; // namespace android
2544