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