OpenGLRenderer.cpp revision 117bdbcfa3e8306dad21e7e01fa71b00cdfa7265
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 "DisplayListRenderer.h"
21#include "Fence.h"
22#include "GammaFontRenderer.h"
23#include "Glop.h"
24#include "GlopBuilder.h"
25#include "Patch.h"
26#include "PathTessellator.h"
27#include "Properties.h"
28#include "RenderNode.h"
29#include "renderstate/MeshState.h"
30#include "renderstate/RenderState.h"
31#include "ShadowTessellator.h"
32#include "SkiaShader.h"
33#include "Vector.h"
34#include "VertexBuffer.h"
35#include "utils/GLUtils.h"
36#include "utils/PaintUtils.h"
37#include "utils/TraceUtils.h"
38
39#include <stdlib.h>
40#include <stdint.h>
41#include <sys/types.h>
42
43#include <SkCanvas.h>
44#include <SkColor.h>
45#include <SkShader.h>
46#include <SkTypeface.h>
47
48#include <utils/Log.h>
49#include <utils/StopWatch.h>
50
51#include <private/hwui/DrawGlInfo.h>
52
53#include <ui/Rect.h>
54
55#if DEBUG_DETAILED_EVENTS
56    #define EVENT_LOGD(...) eventMarkDEBUG(__VA_ARGS__)
57#else
58    #define EVENT_LOGD(...)
59#endif
60
61namespace android {
62namespace uirenderer {
63
64static GLenum getFilter(const SkPaint* paint) {
65    if (!paint || paint->getFilterLevel() != SkPaint::kNone_FilterLevel) {
66        return GL_LINEAR;
67    }
68    return GL_NEAREST;
69}
70
71///////////////////////////////////////////////////////////////////////////////
72// Globals
73///////////////////////////////////////////////////////////////////////////////
74
75
76///////////////////////////////////////////////////////////////////////////////
77// Functions
78///////////////////////////////////////////////////////////////////////////////
79
80template<typename T>
81static inline T min(T a, T b) {
82    return a < b ? a : b;
83}
84
85///////////////////////////////////////////////////////////////////////////////
86// Constructors/destructor
87///////////////////////////////////////////////////////////////////////////////
88
89OpenGLRenderer::OpenGLRenderer(RenderState& renderState)
90        : mState(*this)
91        , mCaches(Caches::getInstance())
92        , mRenderState(renderState)
93        , mFrameStarted(false)
94        , mScissorOptimizationDisabled(false)
95        , mSuppressTiling(false)
96        , mFirstFrameAfterResize(true)
97        , mDirty(false)
98        , mLightCenter((Vector3){FLT_MIN, FLT_MIN, FLT_MIN})
99        , mLightRadius(FLT_MIN)
100        , mAmbientShadowAlpha(0)
101        , mSpotShadowAlpha(0) {
102    // *set* draw modifiers to be 0
103    memset(&mDrawModifiers, 0, sizeof(mDrawModifiers));
104    mDrawModifiers.mOverrideLayerAlpha = 1.0f;
105
106    memcpy(mMeshVertices, kUnitQuadVertices, sizeof(kUnitQuadVertices));
107}
108
109OpenGLRenderer::~OpenGLRenderer() {
110    // The context has already been destroyed at this point, do not call
111    // GL APIs. All GL state should be kept in Caches.h
112}
113
114void OpenGLRenderer::initProperties() {
115    char property[PROPERTY_VALUE_MAX];
116    if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) {
117        mScissorOptimizationDisabled = !strcasecmp(property, "true");
118        INIT_LOGD("  Scissor optimization %s",
119                mScissorOptimizationDisabled ? "disabled" : "enabled");
120    } else {
121        INIT_LOGD("  Scissor optimization enabled");
122    }
123}
124
125void OpenGLRenderer::initLight(const Vector3& lightCenter, float lightRadius,
126        uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
127    mLightCenter = lightCenter;
128    mLightRadius = lightRadius;
129    mAmbientShadowAlpha = ambientShadowAlpha;
130    mSpotShadowAlpha = spotShadowAlpha;
131}
132
133///////////////////////////////////////////////////////////////////////////////
134// Setup
135///////////////////////////////////////////////////////////////////////////////
136
137void OpenGLRenderer::onViewportInitialized() {
138    glDisable(GL_DITHER);
139    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
140    mFirstFrameAfterResize = true;
141}
142
143void OpenGLRenderer::setupFrameState(float left, float top,
144        float right, float bottom, bool opaque) {
145    mCaches.clearGarbage();
146    mState.initializeSaveStack(left, top, right, bottom, mLightCenter);
147    mOpaque = opaque;
148    mTilingClip.set(left, top, right, bottom);
149}
150
151void OpenGLRenderer::startFrame() {
152    if (mFrameStarted) return;
153    mFrameStarted = true;
154
155    mState.setDirtyClip(true);
156
157    discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom);
158
159    mRenderState.setViewport(mState.getWidth(), mState.getHeight());
160
161    // Functors break the tiling extension in pretty spectacular ways
162    // This ensures we don't use tiling when a functor is going to be
163    // invoked during the frame
164    mSuppressTiling = mCaches.hasRegisteredFunctors()
165            || mFirstFrameAfterResize;
166    mFirstFrameAfterResize = false;
167
168    startTilingCurrentClip(true);
169
170    debugOverdraw(true, true);
171
172    clear(mTilingClip.left, mTilingClip.top,
173            mTilingClip.right, mTilingClip.bottom, mOpaque);
174}
175
176void OpenGLRenderer::prepareDirty(float left, float top,
177        float right, float bottom, bool opaque) {
178
179    setupFrameState(left, top, right, bottom, opaque);
180
181    // Layer renderers will start the frame immediately
182    // The framebuffer renderer will first defer the display list
183    // for each layer and wait until the first drawing command
184    // to start the frame
185    if (currentSnapshot()->fbo == 0) {
186        mRenderState.blend().syncEnabled();
187        updateLayers();
188    } else {
189        startFrame();
190    }
191}
192
193void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) {
194    // If we know that we are going to redraw the entire framebuffer,
195    // perform a discard to let the driver know we don't need to preserve
196    // the back buffer for this frame.
197    if (mCaches.extensions().hasDiscardFramebuffer() &&
198            left <= 0.0f && top <= 0.0f && right >= mState.getWidth() && bottom >= mState.getHeight()) {
199        const bool isFbo = onGetTargetFbo() == 0;
200        const GLenum attachments[] = {
201                isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0,
202                isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT };
203        glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
204    }
205}
206
207void OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
208    if (!opaque) {
209        mRenderState.scissor().setEnabled(true);
210        mRenderState.scissor().set(left, getViewportHeight() - bottom, right - left, bottom - top);
211        glClear(GL_COLOR_BUFFER_BIT);
212        mDirty = true;
213        return;
214    }
215
216    mRenderState.scissor().reset();
217}
218
219void OpenGLRenderer::startTilingCurrentClip(bool opaque, bool expand) {
220    if (!mSuppressTiling) {
221        const Snapshot* snapshot = currentSnapshot();
222
223        const Rect* clip = &mTilingClip;
224        if (snapshot->flags & Snapshot::kFlagFboTarget) {
225            clip = &(snapshot->layer->clipRect);
226        }
227
228        startTiling(*clip, getViewportHeight(), opaque, expand);
229    }
230}
231
232void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque, bool expand) {
233    if (!mSuppressTiling) {
234        if(expand) {
235            // Expand the startTiling region by 1
236            int leftNotZero = (clip.left > 0) ? 1 : 0;
237            int topNotZero = (windowHeight - clip.bottom > 0) ? 1 : 0;
238
239            mCaches.startTiling(
240                clip.left - leftNotZero,
241                windowHeight - clip.bottom - topNotZero,
242                clip.right - clip.left + leftNotZero + 1,
243                clip.bottom - clip.top + topNotZero + 1,
244                opaque);
245        } else {
246            mCaches.startTiling(clip.left, windowHeight - clip.bottom,
247                clip.right - clip.left, clip.bottom - clip.top, opaque);
248        }
249    }
250}
251
252void OpenGLRenderer::endTiling() {
253    if (!mSuppressTiling) mCaches.endTiling();
254}
255
256bool OpenGLRenderer::finish() {
257    renderOverdraw();
258    endTiling();
259    mTempPaths.clear();
260
261    // When finish() is invoked on FBO 0 we've reached the end
262    // of the current frame
263    if (onGetTargetFbo() == 0) {
264        mCaches.pathCache.trim();
265        mCaches.tessellationCache.trim();
266    }
267
268    if (!suppressErrorChecks()) {
269#if DEBUG_OPENGL
270        GLUtils::dumpGLErrors();
271#endif
272
273#if DEBUG_MEMORY_USAGE
274        mCaches.dumpMemoryUsage();
275#else
276        if (mCaches.getDebugLevel() & kDebugMemory) {
277            mCaches.dumpMemoryUsage();
278        }
279#endif
280    }
281
282    mFrameStarted = false;
283
284    return reportAndClearDirty();
285}
286
287void OpenGLRenderer::resumeAfterLayer() {
288    mRenderState.setViewport(getViewportWidth(), getViewportHeight());
289    mRenderState.bindFramebuffer(currentSnapshot()->fbo);
290    debugOverdraw(true, false);
291
292    mRenderState.scissor().reset();
293    dirtyClip();
294}
295
296void OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) {
297    if (mState.currentlyIgnored()) return;
298
299    Rect clip(mState.currentClipRect());
300    clip.snapToPixelBoundaries();
301
302    // Since we don't know what the functor will draw, let's dirty
303    // the entire clip region
304    if (hasLayer()) {
305        dirtyLayerUnchecked(clip, getRegion());
306    }
307
308    DrawGlInfo info;
309    info.clipLeft = clip.left;
310    info.clipTop = clip.top;
311    info.clipRight = clip.right;
312    info.clipBottom = clip.bottom;
313    info.isLayer = hasLayer();
314    info.width = getViewportWidth();
315    info.height = getViewportHeight();
316    currentTransform()->copyTo(&info.transform[0]);
317
318    bool prevDirtyClip = mState.getDirtyClip();
319    // setup GL state for functor
320    if (mState.getDirtyClip()) {
321        setStencilFromClip(); // can issue draws, so must precede enableScissor()/interrupt()
322    }
323    if (mRenderState.scissor().setEnabled(true) || prevDirtyClip) {
324        setScissorFromClip();
325    }
326
327    mRenderState.invokeFunctor(functor, DrawGlInfo::kModeDraw, &info);
328    // Scissor may have been modified, reset dirty clip
329    dirtyClip();
330
331    mDirty = true;
332}
333
334///////////////////////////////////////////////////////////////////////////////
335// Debug
336///////////////////////////////////////////////////////////////////////////////
337
338void OpenGLRenderer::eventMarkDEBUG(const char* fmt, ...) const {
339#if DEBUG_DETAILED_EVENTS
340    const int BUFFER_SIZE = 256;
341    va_list ap;
342    char buf[BUFFER_SIZE];
343
344    va_start(ap, fmt);
345    vsnprintf(buf, BUFFER_SIZE, fmt, ap);
346    va_end(ap);
347
348    eventMark(buf);
349#endif
350}
351
352
353void OpenGLRenderer::eventMark(const char* name) const {
354    mCaches.eventMark(0, name);
355}
356
357void OpenGLRenderer::startMark(const char* name) const {
358    mCaches.startMark(0, name);
359}
360
361void OpenGLRenderer::endMark() const {
362    mCaches.endMark();
363}
364
365void OpenGLRenderer::debugOverdraw(bool enable, bool clear) {
366    mRenderState.debugOverdraw(enable, clear);
367}
368
369void OpenGLRenderer::renderOverdraw() {
370    if (mCaches.debugOverdraw && onGetTargetFbo() == 0) {
371        const Rect* clip = &mTilingClip;
372
373        mRenderState.scissor().setEnabled(true);
374        mRenderState.scissor().set(clip->left,
375                mState.firstSnapshot()->getViewportHeight() - clip->bottom,
376                clip->right - clip->left,
377                clip->bottom - clip->top);
378
379        // 1x overdraw
380        mRenderState.stencil().enableDebugTest(2);
381        drawColor(mCaches.getOverdrawColor(1), SkXfermode::kSrcOver_Mode);
382
383        // 2x overdraw
384        mRenderState.stencil().enableDebugTest(3);
385        drawColor(mCaches.getOverdrawColor(2), SkXfermode::kSrcOver_Mode);
386
387        // 3x overdraw
388        mRenderState.stencil().enableDebugTest(4);
389        drawColor(mCaches.getOverdrawColor(3), SkXfermode::kSrcOver_Mode);
390
391        // 4x overdraw and higher
392        mRenderState.stencil().enableDebugTest(4, true);
393        drawColor(mCaches.getOverdrawColor(4), SkXfermode::kSrcOver_Mode);
394
395        mRenderState.stencil().disable();
396    }
397}
398
399///////////////////////////////////////////////////////////////////////////////
400// Layers
401///////////////////////////////////////////////////////////////////////////////
402
403bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) {
404    if (layer->deferredUpdateScheduled && layer->renderer
405            && layer->renderNode.get() && layer->renderNode->isRenderable()) {
406
407        if (inFrame) {
408            endTiling();
409            debugOverdraw(false, false);
410        }
411
412        if (CC_UNLIKELY(inFrame || mCaches.drawDeferDisabled)) {
413            layer->render(*this);
414        } else {
415            layer->defer(*this);
416        }
417
418        if (inFrame) {
419            resumeAfterLayer();
420            startTilingCurrentClip();
421        }
422
423        layer->debugDrawUpdate = mCaches.debugLayersUpdates;
424        layer->hasDrawnSinceUpdate = false;
425
426        return true;
427    }
428
429    return false;
430}
431
432void OpenGLRenderer::updateLayers() {
433    // If draw deferring is enabled this method will simply defer
434    // the display list of each individual layer. The layers remain
435    // in the layer updates list which will be cleared by flushLayers().
436    int count = mLayerUpdates.size();
437    if (count > 0) {
438        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
439            startMark("Layer Updates");
440        } else {
441            startMark("Defer Layer Updates");
442        }
443
444        // Note: it is very important to update the layers in order
445        for (int i = 0; i < count; i++) {
446            Layer* layer = mLayerUpdates.itemAt(i).get();
447            updateLayer(layer, false);
448        }
449
450        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
451            mLayerUpdates.clear();
452            mRenderState.bindFramebuffer(onGetTargetFbo());
453        }
454        endMark();
455    }
456}
457
458void OpenGLRenderer::flushLayers() {
459    int count = mLayerUpdates.size();
460    if (count > 0) {
461        startMark("Apply Layer Updates");
462
463        // Note: it is very important to update the layers in order
464        for (int i = 0; i < count; i++) {
465            mLayerUpdates.itemAt(i)->flush();
466        }
467
468        mLayerUpdates.clear();
469        mRenderState.bindFramebuffer(onGetTargetFbo());
470
471        endMark();
472    }
473}
474
475void OpenGLRenderer::pushLayerUpdate(Layer* layer) {
476    if (layer) {
477        // Make sure we don't introduce duplicates.
478        // SortedVector would do this automatically but we need to respect
479        // the insertion order. The linear search is not an issue since
480        // this list is usually very short (typically one item, at most a few)
481        for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
482            if (mLayerUpdates.itemAt(i) == layer) {
483                return;
484            }
485        }
486        mLayerUpdates.push_back(layer);
487    }
488}
489
490void OpenGLRenderer::cancelLayerUpdate(Layer* layer) {
491    if (layer) {
492        for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
493            if (mLayerUpdates.itemAt(i) == layer) {
494                mLayerUpdates.removeAt(i);
495                break;
496            }
497        }
498    }
499}
500
501void OpenGLRenderer::flushLayerUpdates() {
502    ATRACE_NAME("Update HW Layers");
503    mRenderState.blend().syncEnabled();
504    updateLayers();
505    flushLayers();
506    // Wait for all the layer updates to be executed
507    AutoFence fence;
508}
509
510void OpenGLRenderer::markLayersAsBuildLayers() {
511    for (size_t i = 0; i < mLayerUpdates.size(); i++) {
512        mLayerUpdates[i]->wasBuildLayered = true;
513    }
514}
515
516///////////////////////////////////////////////////////////////////////////////
517// State management
518///////////////////////////////////////////////////////////////////////////////
519
520void OpenGLRenderer::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) {
521    bool restoreViewport = removed.flags & Snapshot::kFlagIsFboLayer;
522    bool restoreClip = removed.flags & Snapshot::kFlagClipSet;
523    bool restoreLayer = removed.flags & Snapshot::kFlagIsLayer;
524
525    if (restoreViewport) {
526        mRenderState.setViewport(getViewportWidth(), getViewportHeight());
527    }
528
529    if (restoreClip) {
530        dirtyClip();
531    }
532
533    if (restoreLayer) {
534        endMark(); // Savelayer
535        ATRACE_END(); // SaveLayer
536        startMark("ComposeLayer");
537        composeLayer(removed, restored);
538        endMark();
539    }
540}
541
542///////////////////////////////////////////////////////////////////////////////
543// Layers
544///////////////////////////////////////////////////////////////////////////////
545
546int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
547        const SkPaint* paint, int flags, const SkPath* convexMask) {
548    // force matrix/clip isolation for layer
549    flags |= SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag;
550
551    const int count = mState.saveSnapshot(flags);
552
553    if (!mState.currentlyIgnored()) {
554        createLayer(left, top, right, bottom, paint, flags, convexMask);
555    }
556
557    return count;
558}
559
560void OpenGLRenderer::calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer) {
561    const Rect untransformedBounds(bounds);
562
563    currentTransform()->mapRect(bounds);
564
565    // Layers only make sense if they are in the framebuffer's bounds
566    if (bounds.intersect(mState.currentClipRect())) {
567        // We cannot work with sub-pixels in this case
568        bounds.snapToPixelBoundaries();
569
570        // When the layer is not an FBO, we may use glCopyTexImage so we
571        // need to make sure the layer does not extend outside the bounds
572        // of the framebuffer
573        const Snapshot& previous = *(currentSnapshot()->previous);
574        Rect previousViewport(0, 0, previous.getViewportWidth(), previous.getViewportHeight());
575        if (!bounds.intersect(previousViewport)) {
576            bounds.setEmpty();
577        } else if (fboLayer) {
578            clip.set(bounds);
579            mat4 inverse;
580            inverse.loadInverse(*currentTransform());
581            inverse.mapRect(clip);
582            clip.snapToPixelBoundaries();
583            if (clip.intersect(untransformedBounds)) {
584                clip.translate(-untransformedBounds.left, -untransformedBounds.top);
585                bounds.set(untransformedBounds);
586            } else {
587                clip.setEmpty();
588            }
589        }
590    } else {
591        bounds.setEmpty();
592    }
593}
594
595void OpenGLRenderer::updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
596        bool fboLayer, int alpha) {
597    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
598            bounds.getHeight() > mCaches.maxTextureSize ||
599            (fboLayer && clip.isEmpty())) {
600        writableSnapshot()->empty = fboLayer;
601    } else {
602        writableSnapshot()->invisible = writableSnapshot()->invisible || (alpha <= 0 && fboLayer);
603    }
604}
605
606int OpenGLRenderer::saveLayerDeferred(float left, float top, float right, float bottom,
607        const SkPaint* paint, int flags) {
608    const int count = mState.saveSnapshot(flags);
609
610    if (!mState.currentlyIgnored() && (flags & SkCanvas::kClipToLayer_SaveFlag)) {
611        // initialize the snapshot as though it almost represents an FBO layer so deferred draw
612        // operations will be able to store and restore the current clip and transform info, and
613        // quick rejection will be correct (for display lists)
614
615        Rect bounds(left, top, right, bottom);
616        Rect clip;
617        calculateLayerBoundsAndClip(bounds, clip, true);
618        updateSnapshotIgnoreForLayer(bounds, clip, true, getAlphaDirect(paint));
619
620        if (!mState.currentlyIgnored()) {
621            writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f);
622            writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom);
623            writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight());
624            writableSnapshot()->roundRectClipState = nullptr;
625        }
626    }
627
628    return count;
629}
630
631/**
632 * Layers are viewed by Skia are slightly different than layers in image editing
633 * programs (for instance.) When a layer is created, previously created layers
634 * and the frame buffer still receive every drawing command. For instance, if a
635 * layer is created and a shape intersecting the bounds of the layers and the
636 * framebuffer is draw, the shape will be drawn on both (unless the layer was
637 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
638 *
639 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
640 * texture. Unfortunately, this is inefficient as it requires every primitive to
641 * be drawn n + 1 times, where n is the number of active layers. In practice this
642 * means, for every primitive:
643 *   - Switch active frame buffer
644 *   - Change viewport, clip and projection matrix
645 *   - Issue the drawing
646 *
647 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
648 * To avoid this, layers are implemented in a different way here, at least in the
649 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
650 * is set. When this flag is set we can redirect all drawing operations into a
651 * single FBO.
652 *
653 * This implementation relies on the frame buffer being at least RGBA 8888. When
654 * a layer is created, only a texture is created, not an FBO. The content of the
655 * frame buffer contained within the layer's bounds is copied into this texture
656 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
657 * buffer and drawing continues as normal. This technique therefore treats the
658 * frame buffer as a scratch buffer for the layers.
659 *
660 * To compose the layers back onto the frame buffer, each layer texture
661 * (containing the original frame buffer data) is drawn as a simple quad over
662 * the frame buffer. The trick is that the quad is set as the composition
663 * destination in the blending equation, and the frame buffer becomes the source
664 * of the composition.
665 *
666 * Drawing layers with an alpha value requires an extra step before composition.
667 * An empty quad is drawn over the layer's region in the frame buffer. This quad
668 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
669 * quad is used to multiply the colors in the frame buffer. This is achieved by
670 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
671 * GL_ZERO, GL_SRC_ALPHA.
672 *
673 * Because glCopyTexImage2D() can be slow, an alternative implementation might
674 * be use to draw a single clipped layer. The implementation described above
675 * is correct in every case.
676 *
677 * (1) The frame buffer is actually not cleared right away. To allow the GPU
678 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
679 *     buffer is left untouched until the first drawing operation. Only when
680 *     something actually gets drawn are the layers regions cleared.
681 */
682bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom,
683        const SkPaint* paint, int flags, const SkPath* convexMask) {
684    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
685    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
686
687    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
688
689    // Window coordinates of the layer
690    Rect clip;
691    Rect bounds(left, top, right, bottom);
692    calculateLayerBoundsAndClip(bounds, clip, fboLayer);
693    updateSnapshotIgnoreForLayer(bounds, clip, fboLayer, getAlphaDirect(paint));
694
695    // Bail out if we won't draw in this snapshot
696    if (mState.currentlyIgnored()) {
697        return false;
698    }
699
700    mCaches.textureState().activateTexture(0);
701    Layer* layer = mCaches.layerCache.get(mRenderState, bounds.getWidth(), bounds.getHeight());
702    if (!layer) {
703        return false;
704    }
705
706    layer->setPaint(paint);
707    layer->layer.set(bounds);
708    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()),
709            bounds.getWidth() / float(layer->getWidth()), 0.0f);
710
711    layer->setBlend(true);
712    layer->setDirty(false);
713    layer->setConvexMask(convexMask); // note: the mask must be cleared before returning to the cache
714
715    // Save the layer in the snapshot
716    writableSnapshot()->flags |= Snapshot::kFlagIsLayer;
717    writableSnapshot()->layer = layer;
718
719    ATRACE_FORMAT_BEGIN("%ssaveLayer %ux%u",
720            fboLayer ? "" : "unclipped ",
721            layer->getWidth(), layer->getHeight());
722    startMark("SaveLayer");
723    if (fboLayer) {
724        return createFboLayer(layer, bounds, clip);
725    } else {
726        // Copy the framebuffer into the layer
727        layer->bindTexture();
728        if (!bounds.isEmpty()) {
729            if (layer->isEmpty()) {
730                // Workaround for some GL drivers. When reading pixels lying outside
731                // of the window we should get undefined values for those pixels.
732                // Unfortunately some drivers will turn the entire target texture black
733                // when reading outside of the window.
734                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->getWidth(), layer->getHeight(),
735                        0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
736                layer->setEmpty(false);
737            }
738
739            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
740                    bounds.left, getViewportHeight() - bounds.bottom,
741                    bounds.getWidth(), bounds.getHeight());
742
743            // Enqueue the buffer coordinates to clear the corresponding region later
744            mLayers.push_back(Rect(bounds));
745        }
746    }
747
748    return true;
749}
750
751bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip) {
752    layer->clipRect.set(clip);
753    layer->setFbo(mCaches.fboCache.get());
754
755    writableSnapshot()->region = &writableSnapshot()->layer->region;
756    writableSnapshot()->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer;
757    writableSnapshot()->fbo = layer->getFbo();
758    writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f);
759    writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom);
760    writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight());
761    writableSnapshot()->roundRectClipState = nullptr;
762
763    endTiling();
764    debugOverdraw(false, false);
765    // Bind texture to FBO
766    mRenderState.bindFramebuffer(layer->getFbo());
767    layer->bindTexture();
768
769    // Initialize the texture if needed
770    if (layer->isEmpty()) {
771        layer->allocateTexture();
772        layer->setEmpty(false);
773    }
774
775    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
776            layer->getTexture(), 0);
777
778    // Expand the startTiling region by 1
779    startTilingCurrentClip(true, true);
780
781    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
782    mRenderState.scissor().setEnabled(true);
783    mRenderState.scissor().set(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
784            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
785    glClear(GL_COLOR_BUFFER_BIT);
786
787    dirtyClip();
788
789    // Change the ortho projection
790    mRenderState.setViewport(bounds.getWidth(), bounds.getHeight());
791    return true;
792}
793
794/**
795 * Read the documentation of createLayer() before doing anything in this method.
796 */
797void OpenGLRenderer::composeLayer(const Snapshot& removed, const Snapshot& restored) {
798    if (!removed.layer) {
799        ALOGE("Attempting to compose a layer that does not exist");
800        return;
801    }
802
803    Layer* layer = removed.layer;
804    const Rect& rect = layer->layer;
805    const bool fboLayer = removed.flags & Snapshot::kFlagIsFboLayer;
806
807    bool clipRequired = false;
808    mState.calculateQuickRejectForScissor(rect.left, rect.top, rect.right, rect.bottom,
809            &clipRequired, nullptr, false); // safely ignore return, should never be rejected
810    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
811
812    if (fboLayer) {
813        endTiling();
814
815        // Detach the texture from the FBO
816        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
817
818        layer->removeFbo(false);
819
820        // Unbind current FBO and restore previous one
821        mRenderState.bindFramebuffer(restored.fbo);
822        debugOverdraw(true, false);
823
824        startTilingCurrentClip();
825    }
826
827    if (!fboLayer && layer->getAlpha() < 255) {
828        SkPaint layerPaint;
829        layerPaint.setAlpha(layer->getAlpha());
830        layerPaint.setXfermodeMode(SkXfermode::kDstIn_Mode);
831        layerPaint.setColorFilter(layer->getColorFilter());
832
833        drawColorRect(rect.left, rect.top, rect.right, rect.bottom, &layerPaint, true);
834        // Required below, composeLayerRect() will divide by 255
835        layer->setAlpha(255);
836    }
837
838    mRenderState.meshState().unbindMeshBuffer();
839
840    mCaches.textureState().activateTexture(0);
841
842    // When the layer is stored in an FBO, we can save a bit of fillrate by
843    // drawing only the dirty region
844    if (fboLayer) {
845        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *restored.transform);
846        composeLayerRegion(layer, rect);
847    } else if (!rect.isEmpty()) {
848        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
849
850        save(0);
851        // the layer contains screen buffer content that shouldn't be alpha modulated
852        // (and any necessary alpha modulation was handled drawing into the layer)
853        writableSnapshot()->alpha = 1.0f;
854        composeLayerRect(layer, rect, true);
855        restore();
856    }
857
858    dirtyClip();
859
860    // Failing to add the layer to the cache should happen only if the layer is too large
861    layer->setConvexMask(nullptr);
862    if (!mCaches.layerCache.put(layer)) {
863        LAYER_LOGD("Deleting layer");
864        layer->decStrong(nullptr);
865    }
866}
867
868void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
869    float alpha = getLayerAlpha(layer);
870
871    setupDraw();
872    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
873        setupDrawWithTexture();
874    } else {
875        setupDrawWithExternalTexture();
876    }
877    setupDrawTextureTransform();
878    setupDrawColor(alpha, alpha, alpha, alpha);
879    setupDrawColorFilter(layer->getColorFilter());
880    setupDrawBlending(layer);
881    setupDrawProgram();
882    setupDrawPureColorUniforms();
883    setupDrawColorFilterUniforms(layer->getColorFilter());
884    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
885        setupDrawTexture(layer->getTexture());
886    } else {
887        setupDrawExternalTexture(layer->getTexture());
888    }
889    if (currentTransform()->isPureTranslate() &&
890            !layer->getForceFilter() &&
891            layer->getWidth() == (uint32_t) rect.getWidth() &&
892            layer->getHeight() == (uint32_t) rect.getHeight()) {
893        const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
894        const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
895
896        layer->setFilter(GL_NEAREST);
897        setupDrawModelView(kModelViewMode_TranslateAndScale, false,
898                x, y, x + rect.getWidth(), y + rect.getHeight(), true);
899    } else {
900        layer->setFilter(GL_LINEAR);
901        setupDrawModelView(kModelViewMode_TranslateAndScale, false,
902                rect.left, rect.top, rect.right, rect.bottom);
903    }
904    setupDrawTextureTransformUniforms(layer->getTexTransform());
905    setupDrawMesh(&mMeshVertices[0].x, &mMeshVertices[0].u);
906
907    glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount);
908}
909
910void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
911    if (layer->isTextureLayer()) {
912        EVENT_LOGD("composeTextureLayerRect");
913        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
914        drawTextureLayer(layer, rect);
915        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
916    } else {
917        EVENT_LOGD("composeHardwareLayerRect");
918        const Rect& texCoords = layer->texCoords;
919        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
920                texCoords.right, texCoords.bottom);
921
922        float x = rect.left;
923        float y = rect.top;
924        bool simpleTransform = currentTransform()->isPureTranslate() &&
925                layer->getWidth() == (uint32_t) rect.getWidth() &&
926                layer->getHeight() == (uint32_t) rect.getHeight();
927
928        if (simpleTransform) {
929            // When we're swapping, the layer is already in screen coordinates
930            if (!swap) {
931                x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
932                y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
933            }
934
935            layer->setFilter(GL_NEAREST, true);
936        } else {
937            layer->setFilter(GL_LINEAR, true);
938        }
939
940        SkPaint layerPaint;
941        layerPaint.setAlpha(getLayerAlpha(layer) * 255);
942        layerPaint.setXfermodeMode(layer->getMode());
943        layerPaint.setColorFilter(layer->getColorFilter());
944
945        bool blend = layer->isBlend() || getLayerAlpha(layer) < 1.0f;
946        drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(),
947                layer->getTexture(), &layerPaint, blend,
948                &mMeshVertices[0].x, &mMeshVertices[0].u,
949                GL_TRIANGLE_STRIP, kUnitQuadCount, swap, swap || simpleTransform);
950
951        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
952    }
953}
954
955/**
956 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated
957 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw
958 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used
959 * by saveLayer's restore
960 */
961#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) {                               \
962        DRAW_COMMAND;                                                              \
963        if (CC_UNLIKELY(mCaches.debugOverdraw && onGetTargetFbo() == 0 && COND)) { \
964            glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);                   \
965            DRAW_COMMAND;                                                          \
966            glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);                       \
967        }                                                                          \
968    }
969
970#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND)
971
972// This class is purely for inspection. It inherits from SkShader, but Skia does not know how to
973// use it. The OpenGLRenderer will look at it to find its Layer and whether it is opaque.
974class LayerShader : public SkShader {
975public:
976    LayerShader(Layer* layer, const SkMatrix* localMatrix)
977    : INHERITED(localMatrix)
978    , mLayer(layer) {
979    }
980
981    virtual bool asACustomShader(void** data) const override {
982        if (data) {
983            *data = static_cast<void*>(mLayer);
984        }
985        return true;
986    }
987
988    virtual bool isOpaque() const override {
989        return !mLayer->isBlend();
990    }
991
992protected:
993    virtual void shadeSpan(int x, int y, SkPMColor[], int count) {
994        LOG_ALWAYS_FATAL("LayerShader should never be drawn with raster backend.");
995    }
996
997    virtual void flatten(SkWriteBuffer&) const override {
998        LOG_ALWAYS_FATAL("LayerShader should never be flattened.");
999    }
1000
1001    virtual Factory getFactory() const override {
1002        LOG_ALWAYS_FATAL("LayerShader should never be created from a stream.");
1003        return nullptr;
1004    }
1005private:
1006    // Unowned.
1007    Layer* mLayer;
1008    typedef SkShader INHERITED;
1009};
1010
1011void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
1012    if (CC_UNLIKELY(layer->region.isEmpty())) return; // nothing to draw
1013
1014    if (layer->getConvexMask()) {
1015        save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag);
1016
1017        // clip to the area of the layer the mask can be larger
1018        clipRect(rect.left, rect.top, rect.right, rect.bottom, SkRegion::kIntersect_Op);
1019
1020        SkPaint paint;
1021        paint.setAntiAlias(true);
1022        paint.setColor(SkColorSetARGB(int(getLayerAlpha(layer) * 255), 0, 0, 0));
1023
1024        // create LayerShader to map SaveLayer content into subsequent draw
1025        SkMatrix shaderMatrix;
1026        shaderMatrix.setTranslate(rect.left, rect.bottom);
1027        shaderMatrix.preScale(1, -1);
1028        LayerShader layerShader(layer, &shaderMatrix);
1029        paint.setShader(&layerShader);
1030
1031        // Since the drawing primitive is defined in local drawing space,
1032        // we don't need to modify the draw matrix
1033        const SkPath* maskPath = layer->getConvexMask();
1034        DRAW_DOUBLE_STENCIL(drawConvexPath(*maskPath, &paint));
1035
1036        paint.setShader(nullptr);
1037        restore();
1038
1039        return;
1040    }
1041
1042    if (layer->region.isRect()) {
1043        layer->setRegionAsRect();
1044
1045        DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect));
1046
1047        layer->region.clear();
1048        return;
1049    }
1050
1051    EVENT_LOGD("composeLayerRegion");
1052    // standard Region based draw
1053    size_t count;
1054    const android::Rect* rects;
1055    Region safeRegion;
1056    if (CC_LIKELY(hasRectToRectTransform())) {
1057        rects = layer->region.getArray(&count);
1058    } else {
1059        safeRegion = Region::createTJunctionFreeRegion(layer->region);
1060        rects = safeRegion.getArray(&count);
1061    }
1062
1063    const float alpha = getLayerAlpha(layer);
1064    const float texX = 1.0f / float(layer->getWidth());
1065    const float texY = 1.0f / float(layer->getHeight());
1066    const float height = rect.getHeight();
1067
1068    setupDraw();
1069
1070    // We must get (and therefore bind) the region mesh buffer
1071    // after we setup drawing in case we need to mess with the
1072    // stencil buffer in setupDraw()
1073    TextureVertex* mesh = mCaches.getRegionMesh();
1074    uint32_t numQuads = 0;
1075
1076    setupDrawWithTexture();
1077    setupDrawColor(alpha, alpha, alpha, alpha);
1078    setupDrawColorFilter(layer->getColorFilter());
1079    setupDrawBlending(layer);
1080    setupDrawProgram();
1081    setupDrawDirtyRegionsDisabled();
1082    setupDrawPureColorUniforms();
1083    setupDrawColorFilterUniforms(layer->getColorFilter());
1084    setupDrawTexture(layer->getTexture());
1085    if (currentTransform()->isPureTranslate()) {
1086        const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
1087        const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
1088
1089        layer->setFilter(GL_NEAREST);
1090        setupDrawModelView(kModelViewMode_Translate, false,
1091                x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1092    } else {
1093        layer->setFilter(GL_LINEAR);
1094        setupDrawModelView(kModelViewMode_Translate, false,
1095                rect.left, rect.top, rect.right, rect.bottom);
1096    }
1097    setupDrawMeshIndices(&mesh[0].x, &mesh[0].u);
1098
1099    for (size_t i = 0; i < count; i++) {
1100        const android::Rect* r = &rects[i];
1101
1102        const float u1 = r->left * texX;
1103        const float v1 = (height - r->top) * texY;
1104        const float u2 = r->right * texX;
1105        const float v2 = (height - r->bottom) * texY;
1106
1107        // TODO: Reject quads outside of the clip
1108        TextureVertex::set(mesh++, r->left, r->top, u1, v1);
1109        TextureVertex::set(mesh++, r->right, r->top, u2, v1);
1110        TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
1111        TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
1112
1113        numQuads++;
1114
1115        if (numQuads >= kMaxNumberOfQuads) {
1116            DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1117                    GL_UNSIGNED_SHORT, nullptr));
1118            numQuads = 0;
1119            mesh = mCaches.getRegionMesh();
1120        }
1121    }
1122
1123    if (numQuads > 0) {
1124        DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1125                GL_UNSIGNED_SHORT, nullptr));
1126    }
1127
1128#if DEBUG_LAYERS_AS_REGIONS
1129    drawRegionRectsDebug(layer->region);
1130#endif
1131
1132    layer->region.clear();
1133}
1134
1135#if DEBUG_LAYERS_AS_REGIONS
1136void OpenGLRenderer::drawRegionRectsDebug(const Region& region) {
1137    size_t count;
1138    const android::Rect* rects = region.getArray(&count);
1139
1140    uint32_t colors[] = {
1141            0x7fff0000, 0x7f00ff00,
1142            0x7f0000ff, 0x7fff00ff,
1143    };
1144
1145    int offset = 0;
1146    int32_t top = rects[0].top;
1147
1148    for (size_t i = 0; i < count; i++) {
1149        if (top != rects[i].top) {
1150            offset ^= 0x2;
1151            top = rects[i].top;
1152        }
1153
1154        SkPaint paint;
1155        paint.setColor(colors[offset + (i & 0x1)]);
1156        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1157        drawColorRect(r.left, r.top, r.right, r.bottom, paint);
1158    }
1159}
1160#endif
1161
1162void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) {
1163    Vector<float> rects;
1164
1165    SkRegion::Iterator it(region);
1166    while (!it.done()) {
1167        const SkIRect& r = it.rect();
1168        rects.push(r.fLeft);
1169        rects.push(r.fTop);
1170        rects.push(r.fRight);
1171        rects.push(r.fBottom);
1172        it.next();
1173    }
1174
1175    drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false);
1176}
1177
1178void OpenGLRenderer::dirtyLayer(const float left, const float top,
1179        const float right, const float bottom, const mat4 transform) {
1180    if (hasLayer()) {
1181        Rect bounds(left, top, right, bottom);
1182        transform.mapRect(bounds);
1183        dirtyLayerUnchecked(bounds, getRegion());
1184    }
1185}
1186
1187void OpenGLRenderer::dirtyLayer(const float left, const float top,
1188        const float right, const float bottom) {
1189    if (hasLayer()) {
1190        Rect bounds(left, top, right, bottom);
1191        dirtyLayerUnchecked(bounds, getRegion());
1192    }
1193}
1194
1195void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1196    if (bounds.intersect(mState.currentClipRect())) {
1197        bounds.snapToPixelBoundaries();
1198        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1199        if (!dirty.isEmpty()) {
1200            region->orSelf(dirty);
1201        }
1202    }
1203}
1204
1205void OpenGLRenderer::issueIndexedQuadDraw(Vertex* mesh, GLsizei quadsCount) {
1206    GLsizei elementsCount = quadsCount * 6;
1207    while (elementsCount > 0) {
1208        GLsizei drawCount = min(elementsCount, (GLsizei) kMaxNumberOfQuads * 6);
1209
1210        setupDrawIndexedVertices(&mesh[0].x);
1211        glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, nullptr);
1212
1213        elementsCount -= drawCount;
1214        // Though there are 4 vertices in a quad, we use 6 indices per
1215        // quad to draw with GL_TRIANGLES
1216        mesh += (drawCount / 6) * 4;
1217    }
1218}
1219
1220void OpenGLRenderer::clearLayerRegions() {
1221    const size_t count = mLayers.size();
1222    if (count == 0) return;
1223
1224    if (!mState.currentlyIgnored()) {
1225        EVENT_LOGD("clearLayerRegions");
1226        // Doing several glScissor/glClear here can negatively impact
1227        // GPUs with a tiler architecture, instead we draw quads with
1228        // the Clear blending mode
1229
1230        // The list contains bounds that have already been clipped
1231        // against their initial clip rect, and the current clip
1232        // is likely different so we need to disable clipping here
1233        bool scissorChanged = mRenderState.scissor().setEnabled(false);
1234
1235        Vertex mesh[count * 4];
1236        Vertex* vertex = mesh;
1237
1238        for (uint32_t i = 0; i < count; i++) {
1239            const Rect& bounds = mLayers[i];
1240
1241            Vertex::set(vertex++, bounds.left, bounds.top);
1242            Vertex::set(vertex++, bounds.right, bounds.top);
1243            Vertex::set(vertex++, bounds.left, bounds.bottom);
1244            Vertex::set(vertex++, bounds.right, bounds.bottom);
1245        }
1246        // We must clear the list of dirty rects before we
1247        // call setupDraw() to prevent stencil setup to do
1248        // the same thing again
1249        mLayers.clear();
1250
1251        SkPaint clearPaint;
1252        clearPaint.setXfermodeMode(SkXfermode::kClear_Mode);
1253
1254        setupDraw(false);
1255        setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
1256        setupDrawBlending(&clearPaint, true);
1257        setupDrawProgram();
1258        setupDrawPureColorUniforms();
1259        setupDrawModelView(kModelViewMode_Translate, false,
1260                0.0f, 0.0f, 0.0f, 0.0f, true);
1261
1262        issueIndexedQuadDraw(&mesh[0], count);
1263
1264        if (scissorChanged) mRenderState.scissor().setEnabled(true);
1265    } else {
1266        mLayers.clear();
1267    }
1268}
1269
1270///////////////////////////////////////////////////////////////////////////////
1271// State Deferral
1272///////////////////////////////////////////////////////////////////////////////
1273
1274bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) {
1275    const Rect& currentClip = mState.currentClipRect();
1276    const mat4* currentMatrix = currentTransform();
1277
1278    if (stateDeferFlags & kStateDeferFlag_Draw) {
1279        // state has bounds initialized in local coordinates
1280        if (!state.mBounds.isEmpty()) {
1281            currentMatrix->mapRect(state.mBounds);
1282            Rect clippedBounds(state.mBounds);
1283            // NOTE: if we ever want to use this clipping info to drive whether the scissor
1284            // is used, it should more closely duplicate the quickReject logic (in how it uses
1285            // snapToPixelBoundaries)
1286
1287            if (!clippedBounds.intersect(currentClip)) {
1288                // quick rejected
1289                return true;
1290            }
1291
1292            state.mClipSideFlags = kClipSide_None;
1293            if (!currentClip.contains(state.mBounds)) {
1294                int& flags = state.mClipSideFlags;
1295                // op partially clipped, so record which sides are clipped for clip-aware merging
1296                if (currentClip.left > state.mBounds.left) flags |= kClipSide_Left;
1297                if (currentClip.top > state.mBounds.top) flags |= kClipSide_Top;
1298                if (currentClip.right < state.mBounds.right) flags |= kClipSide_Right;
1299                if (currentClip.bottom < state.mBounds.bottom) flags |= kClipSide_Bottom;
1300            }
1301            state.mBounds.set(clippedBounds);
1302        } else {
1303            // Empty bounds implies size unknown. Label op as conservatively clipped to disable
1304            // overdraw avoidance (since we don't know what it overlaps)
1305            state.mClipSideFlags = kClipSide_ConservativeFull;
1306            state.mBounds.set(currentClip);
1307        }
1308    }
1309
1310    state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip);
1311    if (state.mClipValid) {
1312        state.mClip.set(currentClip);
1313    }
1314
1315    // Transform, drawModifiers, and alpha always deferred, since they are used by state operations
1316    // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything)
1317    state.mMatrix.load(*currentMatrix);
1318    state.mDrawModifiers = mDrawModifiers;
1319    state.mAlpha = currentSnapshot()->alpha;
1320
1321    // always store/restore, since it's just a pointer
1322    state.mRoundRectClipState = currentSnapshot()->roundRectClipState;
1323    return false;
1324}
1325
1326void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) {
1327    setMatrix(state.mMatrix);
1328    writableSnapshot()->alpha = state.mAlpha;
1329    mDrawModifiers = state.mDrawModifiers;
1330    writableSnapshot()->roundRectClipState = state.mRoundRectClipState;
1331
1332    if (state.mClipValid && !skipClipRestore) {
1333        writableSnapshot()->setClip(state.mClip.left, state.mClip.top,
1334                state.mClip.right, state.mClip.bottom);
1335        dirtyClip();
1336    }
1337}
1338
1339/**
1340 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done
1341 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at
1342 * least one op is clipped), or disabled entirely (because no merged op is clipped)
1343 *
1344 * This method should be called when restoreDisplayState() won't be restoring the clip
1345 */
1346void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) {
1347    if (clipRect != nullptr) {
1348        writableSnapshot()->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom);
1349    } else {
1350        writableSnapshot()->setClip(0, 0, mState.getWidth(), mState.getHeight());
1351    }
1352    dirtyClip();
1353    bool enableScissor = (clipRect != nullptr) || mScissorOptimizationDisabled;
1354    mRenderState.scissor().setEnabled(enableScissor);
1355}
1356
1357///////////////////////////////////////////////////////////////////////////////
1358// Clipping
1359///////////////////////////////////////////////////////////////////////////////
1360
1361void OpenGLRenderer::setScissorFromClip() {
1362    Rect clip(mState.currentClipRect());
1363    clip.snapToPixelBoundaries();
1364
1365    if (mRenderState.scissor().set(clip.left, getViewportHeight() - clip.bottom,
1366            clip.getWidth(), clip.getHeight())) {
1367        mState.setDirtyClip(false);
1368    }
1369}
1370
1371void OpenGLRenderer::ensureStencilBuffer() {
1372    // Thanks to the mismatch between EGL and OpenGL ES FBO we
1373    // cannot attach a stencil buffer to fbo0 dynamically. Let's
1374    // just hope we have one when hasLayer() returns false.
1375    if (hasLayer()) {
1376        attachStencilBufferToLayer(currentSnapshot()->layer);
1377    }
1378}
1379
1380void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
1381    // The layer's FBO is already bound when we reach this stage
1382    if (!layer->getStencilRenderBuffer()) {
1383        // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer
1384        // is attached after we initiated tiling. We must turn it off,
1385        // attach the new render buffer then turn tiling back on
1386        endTiling();
1387
1388        RenderBuffer* buffer = mCaches.renderBufferCache.get(
1389                Stencil::getSmallestStencilFormat(),
1390                layer->getWidth(), layer->getHeight());
1391        layer->setStencilRenderBuffer(buffer);
1392
1393        startTiling(layer->clipRect, layer->layer.getHeight());
1394    }
1395}
1396
1397static void handlePoint(std::vector<Vertex>& rectangleVertices, const Matrix4& transform,
1398        float x, float y) {
1399    Vertex v;
1400    v.x = x;
1401    v.y = y;
1402    transform.mapPoint(v.x, v.y);
1403    rectangleVertices.push_back(v);
1404}
1405
1406static void handlePointNoTransform(std::vector<Vertex>& rectangleVertices, float x, float y) {
1407    Vertex v;
1408    v.x = x;
1409    v.y = y;
1410    rectangleVertices.push_back(v);
1411}
1412
1413void OpenGLRenderer::drawRectangleList(const RectangleList& rectangleList) {
1414    int count = rectangleList.getTransformedRectanglesCount();
1415    std::vector<Vertex> rectangleVertices(count * 4);
1416    Rect scissorBox = rectangleList.calculateBounds();
1417    scissorBox.snapToPixelBoundaries();
1418    for (int i = 0; i < count; ++i) {
1419        const TransformedRectangle& tr(rectangleList.getTransformedRectangle(i));
1420        const Matrix4& transform = tr.getTransform();
1421        Rect bounds = tr.getBounds();
1422        if (transform.rectToRect()) {
1423            transform.mapRect(bounds);
1424            if (!bounds.intersect(scissorBox)) {
1425                bounds.setEmpty();
1426            } else {
1427                handlePointNoTransform(rectangleVertices, bounds.left, bounds.top);
1428                handlePointNoTransform(rectangleVertices, bounds.right, bounds.top);
1429                handlePointNoTransform(rectangleVertices, bounds.left, bounds.bottom);
1430                handlePointNoTransform(rectangleVertices, bounds.right, bounds.bottom);
1431            }
1432        } else {
1433            handlePoint(rectangleVertices, transform, bounds.left, bounds.top);
1434            handlePoint(rectangleVertices, transform, bounds.right, bounds.top);
1435            handlePoint(rectangleVertices, transform, bounds.left, bounds.bottom);
1436            handlePoint(rectangleVertices, transform, bounds.right, bounds.bottom);
1437        }
1438    }
1439
1440    mRenderState.scissor().set(scissorBox.left, getViewportHeight() - scissorBox.bottom,
1441            scissorBox.getWidth(), scissorBox.getHeight());
1442
1443    const SkPaint* paint = nullptr;
1444    setupDraw();
1445    setupDrawNoTexture();
1446    setupDrawColor(0, 0xff * currentSnapshot()->alpha);
1447    setupDrawShader(getShader(paint));
1448    setupDrawColorFilter(getColorFilter(paint));
1449    setupDrawBlending(paint);
1450    setupDrawProgram();
1451    setupDrawDirtyRegionsDisabled();
1452    setupDrawModelView(kModelViewMode_Translate, false,
1453            0.0f, 0.0f, 0.0f, 0.0f, true);
1454    setupDrawColorUniforms(getShader(paint));
1455    setupDrawShaderUniforms(getShader(paint));
1456    setupDrawColorFilterUniforms(getColorFilter(paint));
1457
1458    issueIndexedQuadDraw(&rectangleVertices[0], rectangleVertices.size() / 4);
1459}
1460
1461void OpenGLRenderer::setStencilFromClip() {
1462    if (!mCaches.debugOverdraw) {
1463        if (!currentSnapshot()->clipIsSimple()) {
1464            int incrementThreshold;
1465            EVENT_LOGD("setStencilFromClip - enabling");
1466
1467            // NOTE: The order here is important, we must set dirtyClip to false
1468            //       before any draw call to avoid calling back into this method
1469            mState.setDirtyClip(false);
1470
1471            ensureStencilBuffer();
1472
1473            const ClipArea& clipArea = currentSnapshot()->getClipArea();
1474
1475            bool isRectangleList = clipArea.isRectangleList();
1476            if (isRectangleList) {
1477                incrementThreshold = clipArea.getRectangleList().getTransformedRectanglesCount();
1478            } else {
1479                incrementThreshold = 0;
1480            }
1481
1482            mRenderState.stencil().enableWrite(incrementThreshold);
1483
1484            // Clean and update the stencil, but first make sure we restrict drawing
1485            // to the region's bounds
1486            bool resetScissor = mRenderState.scissor().setEnabled(true);
1487            if (resetScissor) {
1488                // The scissor was not set so we now need to update it
1489                setScissorFromClip();
1490            }
1491
1492            mRenderState.stencil().clear();
1493
1494            // stash and disable the outline clip state, since stencil doesn't account for outline
1495            bool storedSkipOutlineClip = mSkipOutlineClip;
1496            mSkipOutlineClip = true;
1497
1498            SkPaint paint;
1499            paint.setColor(SK_ColorBLACK);
1500            paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1501
1502            if (isRectangleList) {
1503                drawRectangleList(clipArea.getRectangleList());
1504            } else {
1505                // NOTE: We could use the region contour path to generate a smaller mesh
1506                //       Since we are using the stencil we could use the red book path
1507                //       drawing technique. It might increase bandwidth usage though.
1508
1509                // The last parameter is important: we are not drawing in the color buffer
1510                // so we don't want to dirty the current layer, if any
1511                drawRegionRects(clipArea.getClipRegion(), paint, false);
1512            }
1513            if (resetScissor) mRenderState.scissor().setEnabled(false);
1514            mSkipOutlineClip = storedSkipOutlineClip;
1515
1516            mRenderState.stencil().enableTest(incrementThreshold);
1517
1518            // Draw the region used to generate the stencil if the appropriate debug
1519            // mode is enabled
1520            // TODO: Implement for rectangle list clip areas
1521            if (mCaches.debugStencilClip == Caches::kStencilShowRegion &&
1522                    !clipArea.isRectangleList()) {
1523                paint.setColor(0x7f0000ff);
1524                paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
1525                drawRegionRects(currentSnapshot()->getClipRegion(), paint);
1526            }
1527        } else {
1528            EVENT_LOGD("setStencilFromClip - disabling");
1529            mRenderState.stencil().disable();
1530        }
1531    }
1532}
1533
1534/**
1535 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out.
1536 *
1537 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint
1538 *         style, and tessellated AA ramp
1539 */
1540bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom,
1541        const SkPaint* paint) {
1542    bool snapOut = paint && paint->isAntiAlias();
1543
1544    if (paint && paint->getStyle() != SkPaint::kFill_Style) {
1545        float outset = paint->getStrokeWidth() * 0.5f;
1546        left -= outset;
1547        top -= outset;
1548        right += outset;
1549        bottom += outset;
1550    }
1551
1552    bool clipRequired = false;
1553    bool roundRectClipRequired = false;
1554    if (mState.calculateQuickRejectForScissor(left, top, right, bottom,
1555            &clipRequired, &roundRectClipRequired, snapOut)) {
1556        return true;
1557    }
1558
1559    // not quick rejected, so enable the scissor if clipRequired
1560    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
1561    mSkipOutlineClip = !roundRectClipRequired;
1562    return false;
1563}
1564
1565void OpenGLRenderer::debugClip() {
1566#if DEBUG_CLIP_REGIONS
1567    if (!currentSnapshot()->clipRegion->isEmpty()) {
1568        SkPaint paint;
1569        paint.setColor(0x7f00ff00);
1570        drawRegionRects(*(currentSnapshot()->clipRegion, paint);
1571
1572    }
1573#endif
1574}
1575
1576void OpenGLRenderer::renderGlop(const Glop& glop) {
1577    if (mState.getDirtyClip()) {
1578        if (mRenderState.scissor().isEnabled()) {
1579            setScissorFromClip();
1580        }
1581
1582        setStencilFromClip();
1583    }
1584    mRenderState.render(glop);
1585    dirtyLayer(glop.bounds.left, glop.bounds.top, glop.bounds.right, glop.bounds.bottom);
1586}
1587
1588///////////////////////////////////////////////////////////////////////////////
1589// Drawing commands
1590///////////////////////////////////////////////////////////////////////////////
1591
1592void OpenGLRenderer::setupDraw(bool clearLayer) {
1593    // TODO: It would be best if we could do this before quickRejectSetupScissor()
1594    //       changes the scissor test state
1595    if (clearLayer) clearLayerRegions();
1596    // Make sure setScissor & setStencil happen at the beginning of
1597    // this method
1598    if (mState.getDirtyClip()) {
1599        if (mRenderState.scissor().isEnabled()) {
1600            setScissorFromClip();
1601        }
1602
1603        setStencilFromClip();
1604    }
1605
1606    mDescription.reset();
1607
1608    mSetShaderColor = false;
1609    mColorSet = false;
1610    mColorA = mColorR = mColorG = mColorB = 0.0f;
1611    mTextureUnit = 0;
1612    mTrackDirtyRegions = true;
1613
1614    // Enable debug highlight when what we're about to draw is tested against
1615    // the stencil buffer and if stencil highlight debugging is on
1616    mDescription.hasDebugHighlight = !mCaches.debugOverdraw
1617            && mCaches.debugStencilClip == Caches::kStencilShowHighlight
1618            && mRenderState.stencil().isTestEnabled();
1619}
1620
1621void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1622    mDescription.hasTexture = true;
1623    mDescription.hasAlpha8Texture = isAlpha8;
1624}
1625
1626void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) {
1627    mDescription.hasTexture = true;
1628    mDescription.hasColors = true;
1629    mDescription.hasAlpha8Texture = isAlpha8;
1630}
1631
1632void OpenGLRenderer::setupDrawWithExternalTexture() {
1633    mDescription.hasExternalTexture = true;
1634}
1635
1636void OpenGLRenderer::setupDrawNoTexture() {
1637    mRenderState.meshState().disableTexCoordsVertexArray();
1638}
1639
1640void OpenGLRenderer::setupDrawVertexAlpha(bool useShadowAlphaInterp) {
1641    mDescription.hasVertexAlpha = true;
1642    mDescription.useShadowAlphaInterp = useShadowAlphaInterp;
1643}
1644
1645void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1646    mColorA = alpha / 255.0f;
1647    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1648    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1649    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1650    mColorSet = true;
1651    mSetShaderColor = mDescription.setColorModulate(mColorA);
1652}
1653
1654void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1655    mColorA = alpha / 255.0f;
1656    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1657    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1658    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1659    mColorSet = true;
1660    mSetShaderColor = mDescription.setAlpha8ColorModulate(mColorR, mColorG, mColorB, mColorA);
1661}
1662
1663void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) {
1664    mCaches.fontRenderer->describe(mDescription, paint);
1665}
1666
1667void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1668    mColorA = a;
1669    mColorR = r;
1670    mColorG = g;
1671    mColorB = b;
1672    mColorSet = true;
1673    mSetShaderColor = mDescription.setColorModulate(a);
1674}
1675
1676void OpenGLRenderer::setupDrawShader(const SkShader* shader) {
1677    if (shader != nullptr) {
1678        SkiaShader::describe(&mCaches, mDescription, mCaches.extensions(), *shader);
1679    }
1680}
1681
1682void OpenGLRenderer::setupDrawColorFilter(const SkColorFilter* filter) {
1683    if (filter == nullptr) {
1684        return;
1685    }
1686
1687    SkXfermode::Mode mode;
1688    if (filter->asColorMode(nullptr, &mode)) {
1689        mDescription.colorOp = ProgramDescription::kColorBlend;
1690        mDescription.colorMode = mode;
1691    } else if (filter->asColorMatrix(nullptr)) {
1692        mDescription.colorOp = ProgramDescription::kColorMatrix;
1693    }
1694}
1695
1696void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1697    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1698        mColorA = 1.0f;
1699        mColorR = mColorG = mColorB = 0.0f;
1700        mSetShaderColor = mDescription.modulate = true;
1701    }
1702}
1703
1704void OpenGLRenderer::setupDrawBlending(const Layer* layer, bool swapSrcDst) {
1705    SkXfermode::Mode mode = layer->getMode();
1706    // When the blending mode is kClear_Mode, we need to use a modulate color
1707    // argb=1,0,0,0
1708    accountForClear(mode);
1709    // TODO: check shader blending, once we have shader drawing support for layers.
1710    bool blend = layer->isBlend()
1711            || getLayerAlpha(layer) < 1.0f
1712            || (mColorSet && mColorA < 1.0f)
1713            || PaintUtils::isBlendedColorFilter(layer->getColorFilter());
1714    chooseBlending(blend, mode, mDescription, swapSrcDst);
1715}
1716
1717void OpenGLRenderer::setupDrawBlending(const SkPaint* paint, bool blend, bool swapSrcDst) {
1718    SkXfermode::Mode mode = getXfermodeDirect(paint);
1719    // When the blending mode is kClear_Mode, we need to use a modulate color
1720    // argb=1,0,0,0
1721    accountForClear(mode);
1722    blend |= (mColorSet && mColorA < 1.0f)
1723            || (getShader(paint) && !getShader(paint)->isOpaque())
1724            || PaintUtils::isBlendedColorFilter(getColorFilter(paint));
1725    chooseBlending(blend, mode, mDescription, swapSrcDst);
1726}
1727
1728void OpenGLRenderer::setupDrawProgram() {
1729    mCaches.setProgram(mDescription);
1730    if (mDescription.hasRoundRectClip) {
1731        // TODO: avoid doing this repeatedly, stashing state pointer in program
1732        const RoundRectClipState* state = writableSnapshot()->roundRectClipState;
1733        const Rect& innerRect = state->innerRect;
1734        glUniform4f(mCaches.program().getUniform("roundRectInnerRectLTRB"),
1735                innerRect.left, innerRect.top,
1736                innerRect.right, innerRect.bottom);
1737        glUniformMatrix4fv(mCaches.program().getUniform("roundRectInvTransform"),
1738                1, GL_FALSE, &state->matrix.data[0]);
1739
1740        // add half pixel to round out integer rect space to cover pixel centers
1741        float roundedOutRadius = state->radius + 0.5f;
1742        glUniform1f(mCaches.program().getUniform("roundRectRadius"),
1743                roundedOutRadius);
1744    }
1745}
1746
1747void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1748    mTrackDirtyRegions = false;
1749}
1750
1751void OpenGLRenderer::setupDrawModelView(ModelViewMode mode, bool offset,
1752        float left, float top, float right, float bottom, bool ignoreTransform) {
1753    mModelViewMatrix.loadTranslate(left, top, 0.0f);
1754    if (mode == kModelViewMode_TranslateAndScale) {
1755        mModelViewMatrix.scale(right - left, bottom - top, 1.0f);
1756    }
1757
1758    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1759    const Matrix4& transformMatrix = ignoreTransform ? Matrix4::identity() : *currentTransform();
1760
1761    mCaches.program().set(currentSnapshot()->getOrthoMatrix(),
1762            mModelViewMatrix, transformMatrix, offset);
1763    if (dirty && mTrackDirtyRegions) {
1764        if (!ignoreTransform) {
1765            dirtyLayer(left, top, right, bottom, *currentTransform());
1766        } else {
1767            dirtyLayer(left, top, right, bottom);
1768        }
1769    }
1770}
1771
1772void OpenGLRenderer::setupDrawColorUniforms(bool hasShader) {
1773    if ((mColorSet && !hasShader) || (hasShader && mSetShaderColor)) {
1774        mCaches.program().setColor(mColorR, mColorG, mColorB, mColorA);
1775    }
1776}
1777
1778void OpenGLRenderer::setupDrawPureColorUniforms() {
1779    if (mSetShaderColor) {
1780        mCaches.program().setColor(mColorR, mColorG, mColorB, mColorA);
1781    }
1782}
1783
1784void OpenGLRenderer::setupDrawShaderUniforms(const SkShader* shader, bool ignoreTransform) {
1785    if (shader == nullptr) {
1786        return;
1787    }
1788
1789    if (ignoreTransform) {
1790        // if ignoreTransform=true was passed to setupDrawModelView, undo currentTransform()
1791        // because it was built into modelView / the geometry, and the description needs to
1792        // compensate.
1793        mat4 modelViewWithoutTransform;
1794        modelViewWithoutTransform.loadInverse(*currentTransform());
1795        modelViewWithoutTransform.multiply(mModelViewMatrix);
1796        mModelViewMatrix.load(modelViewWithoutTransform);
1797    }
1798
1799    SkiaShader::setupProgram(&mCaches, mModelViewMatrix, &mTextureUnit,
1800            mCaches.extensions(), *shader);
1801}
1802
1803void OpenGLRenderer::setupDrawColorFilterUniforms(const SkColorFilter* filter) {
1804    if (nullptr == filter) {
1805        return;
1806    }
1807
1808    SkColor color;
1809    SkXfermode::Mode mode;
1810    if (filter->asColorMode(&color, &mode)) {
1811        const int alpha = SkColorGetA(color);
1812        const GLfloat a = alpha / 255.0f;
1813        const GLfloat r = a * SkColorGetR(color) / 255.0f;
1814        const GLfloat g = a * SkColorGetG(color) / 255.0f;
1815        const GLfloat b = a * SkColorGetB(color) / 255.0f;
1816        glUniform4f(mCaches.program().getUniform("colorBlend"), r, g, b, a);
1817        return;
1818    }
1819
1820    SkScalar srcColorMatrix[20];
1821    if (filter->asColorMatrix(srcColorMatrix)) {
1822
1823        float colorMatrix[16];
1824        memcpy(colorMatrix, srcColorMatrix, 4 * sizeof(float));
1825        memcpy(&colorMatrix[4], &srcColorMatrix[5], 4 * sizeof(float));
1826        memcpy(&colorMatrix[8], &srcColorMatrix[10], 4 * sizeof(float));
1827        memcpy(&colorMatrix[12], &srcColorMatrix[15], 4 * sizeof(float));
1828
1829        // Skia uses the range [0..255] for the addition vector, but we need
1830        // the [0..1] range to apply the vector in GLSL
1831        float colorVector[4];
1832        colorVector[0] = srcColorMatrix[4] / 255.0f;
1833        colorVector[1] = srcColorMatrix[9] / 255.0f;
1834        colorVector[2] = srcColorMatrix[14] / 255.0f;
1835        colorVector[3] = srcColorMatrix[19] / 255.0f;
1836
1837        glUniformMatrix4fv(mCaches.program().getUniform("colorMatrix"), 1,
1838                GL_FALSE, colorMatrix);
1839        glUniform4fv(mCaches.program().getUniform("colorMatrixVector"), 1, colorVector);
1840        return;
1841    }
1842
1843    // it is an error if we ever get here
1844}
1845
1846void OpenGLRenderer::setupDrawTextGammaUniforms() {
1847    mCaches.fontRenderer->setupProgram(mDescription, mCaches.program());
1848}
1849
1850void OpenGLRenderer::setupDrawSimpleMesh() {
1851    bool force = mRenderState.meshState().bindMeshBuffer();
1852    mRenderState.meshState().bindPositionVertexPointer(force, nullptr);
1853    mRenderState.meshState().unbindIndicesBuffer();
1854}
1855
1856void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1857    if (texture) mCaches.textureState().bindTexture(texture);
1858    mTextureUnit++;
1859    mRenderState.meshState().enableTexCoordsVertexArray();
1860}
1861
1862void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1863    mCaches.textureState().bindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
1864    mTextureUnit++;
1865    mRenderState.meshState().enableTexCoordsVertexArray();
1866}
1867
1868void OpenGLRenderer::setupDrawTextureTransform() {
1869    mDescription.hasTextureTransform = true;
1870}
1871
1872void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1873    glUniformMatrix4fv(mCaches.program().getUniform("mainTextureTransform"), 1,
1874            GL_FALSE, &transform.data[0]);
1875}
1876
1877void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices,
1878        const GLvoid* texCoords, GLuint vbo) {
1879    bool force = false;
1880    if (!vertices || vbo) {
1881        force = mRenderState.meshState().bindMeshBuffer(vbo);
1882    } else {
1883        force = mRenderState.meshState().unbindMeshBuffer();
1884    }
1885
1886    mRenderState.meshState().bindPositionVertexPointer(force, vertices);
1887    if (mCaches.program().texCoords >= 0) {
1888        mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords);
1889    }
1890
1891    mRenderState.meshState().unbindIndicesBuffer();
1892}
1893
1894void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices,
1895        const GLvoid* texCoords, const GLvoid* colors) {
1896    bool force = mRenderState.meshState().unbindMeshBuffer();
1897    GLsizei stride = sizeof(ColorTextureVertex);
1898
1899    mRenderState.meshState().bindPositionVertexPointer(force, vertices, stride);
1900    if (mCaches.program().texCoords >= 0) {
1901        mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords, stride);
1902    }
1903    int slot = mCaches.program().getAttrib("colors");
1904    if (slot >= 0) {
1905        glEnableVertexAttribArray(slot);
1906        glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors);
1907    }
1908
1909    mRenderState.meshState().unbindIndicesBuffer();
1910}
1911
1912void OpenGLRenderer::setupDrawMeshIndices(const GLvoid* vertices,
1913        const GLvoid* texCoords, GLuint vbo) {
1914    bool force = false;
1915    // If vbo is != 0 we want to treat the vertices parameter as an offset inside
1916    // a VBO. However, if vertices is set to NULL and vbo == 0 then we want to
1917    // use the default VBO found in RenderState
1918    if (!vertices || vbo) {
1919        force = mRenderState.meshState().bindMeshBuffer(vbo);
1920    } else {
1921        force = mRenderState.meshState().unbindMeshBuffer();
1922    }
1923    mRenderState.meshState().bindQuadIndicesBuffer();
1924
1925    mRenderState.meshState().bindPositionVertexPointer(force, vertices);
1926    if (mCaches.program().texCoords >= 0) {
1927        mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords);
1928    }
1929}
1930
1931void OpenGLRenderer::setupDrawIndexedVertices(GLvoid* vertices) {
1932    bool force = mRenderState.meshState().unbindMeshBuffer();
1933    mRenderState.meshState().bindQuadIndicesBuffer();
1934    mRenderState.meshState().bindPositionVertexPointer(force, vertices, kVertexStride);
1935}
1936
1937///////////////////////////////////////////////////////////////////////////////
1938// Drawing
1939///////////////////////////////////////////////////////////////////////////////
1940
1941void OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int32_t replayFlags) {
1942    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1943    // will be performed by the display list itself
1944    if (renderNode && renderNode->isRenderable()) {
1945        // compute 3d ordering
1946        renderNode->computeOrdering();
1947        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
1948            startFrame();
1949            ReplayStateStruct replayStruct(*this, dirty, replayFlags);
1950            renderNode->replay(replayStruct, 0);
1951            return;
1952        }
1953
1954        // Don't avoid overdraw when visualizing, since that makes it harder to
1955        // debug where it's coming from, and when the problem occurs.
1956        bool avoidOverdraw = !mCaches.debugOverdraw;
1957        DeferredDisplayList deferredList(mState.currentClipRect(), avoidOverdraw);
1958        DeferStateStruct deferStruct(deferredList, *this, replayFlags);
1959        renderNode->defer(deferStruct, 0);
1960
1961        flushLayers();
1962        startFrame();
1963
1964        deferredList.flush(*this, dirty);
1965    } else {
1966        // Even if there is no drawing command(Ex: invisible),
1967        // it still needs startFrame to clear buffer and start tiling.
1968        startFrame();
1969    }
1970}
1971
1972void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top,
1973        const SkPaint* paint) {
1974    float x = left;
1975    float y = top;
1976
1977    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1978
1979    bool ignoreTransform = false;
1980    if (currentTransform()->isPureTranslate()) {
1981        x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
1982        y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
1983        ignoreTransform = true;
1984
1985        texture->setFilter(GL_NEAREST, true);
1986    } else {
1987        texture->setFilter(getFilter(paint), true);
1988    }
1989
1990    // No need to check for a UV mapper on the texture object, only ARGB_8888
1991    // bitmaps get packed in the atlas
1992    drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1993            paint, (GLvoid*) nullptr, (GLvoid*) kMeshTextureOffset,
1994            GL_TRIANGLE_STRIP, kUnitQuadCount, ignoreTransform);
1995}
1996
1997/**
1998 * Important note: this method is intended to draw batches of bitmaps and
1999 * will not set the scissor enable or dirty the current layer, if any.
2000 * The caller is responsible for properly dirtying the current layer.
2001 */
2002void OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
2003        int bitmapCount, TextureVertex* vertices, bool pureTranslate,
2004        const Rect& bounds, const SkPaint* paint) {
2005    mCaches.textureState().activateTexture(0);
2006    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2007    if (!texture) return;
2008
2009    const AutoTexture autoCleanup(texture);
2010
2011    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2012    texture->setFilter(pureTranslate ? GL_NEAREST : getFilter(paint), true);
2013
2014    const float x = (int) floorf(bounds.left + 0.5f);
2015    const float y = (int) floorf(bounds.top + 0.5f);
2016    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2017        drawAlpha8TextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2018                texture->id, paint, &vertices[0].x, &vertices[0].u,
2019                GL_TRIANGLES, bitmapCount * 6, true,
2020                kModelViewMode_Translate, false);
2021    } else {
2022        drawTextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2023                texture->id, paint, texture->blend, &vertices[0].x, &vertices[0].u,
2024                GL_TRIANGLES, bitmapCount * 6, false, true, 0,
2025                kModelViewMode_Translate, false);
2026    }
2027
2028    mDirty = true;
2029}
2030
2031void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) {
2032    if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) {
2033        return;
2034    }
2035
2036    mCaches.textureState().activateTexture(0);
2037    Texture* texture = getTexture(bitmap);
2038    if (!texture) return;
2039    const AutoTexture autoCleanup(texture);
2040
2041    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2042        drawAlphaBitmap(texture, 0, 0, paint);
2043    } else {
2044        drawTextureRect(0, 0, bitmap->width(), bitmap->height(), texture, paint);
2045    }
2046
2047    mDirty = true;
2048}
2049
2050void OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
2051        const float* vertices, const int* colors, const SkPaint* paint) {
2052    if (!vertices || mState.currentlyIgnored()) {
2053        return;
2054    }
2055
2056    // TODO: use quickReject on bounds from vertices
2057    mRenderState.scissor().setEnabled(true);
2058
2059    float left = FLT_MAX;
2060    float top = FLT_MAX;
2061    float right = FLT_MIN;
2062    float bottom = FLT_MIN;
2063
2064    const uint32_t count = meshWidth * meshHeight * 6;
2065
2066    std::unique_ptr<ColorTextureVertex[]> mesh(new ColorTextureVertex[count]);
2067    ColorTextureVertex* vertex = &mesh[0];
2068
2069    std::unique_ptr<int[]> tempColors;
2070    if (!colors) {
2071        uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
2072        tempColors.reset(new int[colorsCount]);
2073        memset(tempColors.get(), 0xff, colorsCount * sizeof(int));
2074        colors = tempColors.get();
2075    }
2076
2077    mCaches.textureState().activateTexture(0);
2078    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
2079    const UvMapper& mapper(getMapper(texture));
2080
2081    for (int32_t y = 0; y < meshHeight; y++) {
2082        for (int32_t x = 0; x < meshWidth; x++) {
2083            uint32_t i = (y * (meshWidth + 1) + x) * 2;
2084
2085            float u1 = float(x) / meshWidth;
2086            float u2 = float(x + 1) / meshWidth;
2087            float v1 = float(y) / meshHeight;
2088            float v2 = float(y + 1) / meshHeight;
2089
2090            mapper.map(u1, v1, u2, v2);
2091
2092            int ax = i + (meshWidth + 1) * 2;
2093            int ay = ax + 1;
2094            int bx = i;
2095            int by = bx + 1;
2096            int cx = i + 2;
2097            int cy = cx + 1;
2098            int dx = i + (meshWidth + 1) * 2 + 2;
2099            int dy = dx + 1;
2100
2101            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2102            ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
2103            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2104
2105            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2106            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2107            ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
2108
2109            left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
2110            top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
2111            right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
2112            bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
2113        }
2114    }
2115
2116    if (quickRejectSetupScissor(left, top, right, bottom)) {
2117        return;
2118    }
2119
2120    if (!texture) {
2121        texture = mCaches.textureCache.get(bitmap);
2122        if (!texture) {
2123            return;
2124        }
2125    }
2126    const AutoTexture autoCleanup(texture);
2127
2128    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2129    texture->setFilter(getFilter(paint), true);
2130
2131    int alpha;
2132    SkXfermode::Mode mode;
2133    getAlphaAndMode(paint, &alpha, &mode);
2134
2135    float a = alpha / 255.0f;
2136
2137    if (hasLayer()) {
2138        dirtyLayer(left, top, right, bottom, *currentTransform());
2139    }
2140
2141    setupDraw();
2142    setupDrawWithTextureAndColor();
2143    setupDrawColor(a, a, a, a);
2144    setupDrawColorFilter(getColorFilter(paint));
2145    setupDrawBlending(paint, true);
2146    setupDrawProgram();
2147    setupDrawDirtyRegionsDisabled();
2148    setupDrawModelView(kModelViewMode_Translate, false, 0, 0, 0, 0);
2149    setupDrawTexture(texture->id);
2150    setupDrawPureColorUniforms();
2151    setupDrawColorFilterUniforms(getColorFilter(paint));
2152    setupDrawMesh(&mesh[0].x, &mesh[0].u, &mesh[0].r);
2153
2154    glDrawArrays(GL_TRIANGLES, 0, count);
2155
2156    int slot = mCaches.program().getAttrib("colors");
2157    if (slot >= 0) {
2158        glDisableVertexAttribArray(slot);
2159    }
2160
2161    mDirty = true;
2162}
2163
2164void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap,
2165         float srcLeft, float srcTop, float srcRight, float srcBottom,
2166         float dstLeft, float dstTop, float dstRight, float dstBottom,
2167         const SkPaint* paint) {
2168    if (quickRejectSetupScissor(dstLeft, dstTop, dstRight, dstBottom)) {
2169        return;
2170    }
2171
2172    mCaches.textureState().activateTexture(0);
2173    Texture* texture = getTexture(bitmap);
2174    if (!texture) return;
2175    const AutoTexture autoCleanup(texture);
2176
2177    const float width = texture->width;
2178    const float height = texture->height;
2179
2180    float u1 = fmax(0.0f, srcLeft / width);
2181    float v1 = fmax(0.0f, srcTop / height);
2182    float u2 = fmin(1.0f, srcRight / width);
2183    float v2 = fmin(1.0f, srcBottom / height);
2184
2185    getMapper(texture).map(u1, v1, u2, v2);
2186
2187    mRenderState.meshState().unbindMeshBuffer();
2188    resetDrawTextureTexCoords(u1, v1, u2, v2);
2189
2190    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2191
2192    float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft);
2193    float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop);
2194
2195    bool scaled = scaleX != 1.0f || scaleY != 1.0f;
2196    // Apply a scale transform on the canvas only when a shader is in use
2197    // Skia handles the ratio between the dst and src rects as a scale factor
2198    // when a shader is set
2199    bool useScaleTransform = getShader(paint) && scaled;
2200    bool ignoreTransform = false;
2201
2202    if (CC_LIKELY(currentTransform()->isPureTranslate() && !useScaleTransform)) {
2203        float x = (int) floorf(dstLeft + currentTransform()->getTranslateX() + 0.5f);
2204        float y = (int) floorf(dstTop + currentTransform()->getTranslateY() + 0.5f);
2205
2206        dstRight = x + (dstRight - dstLeft);
2207        dstBottom = y + (dstBottom - dstTop);
2208
2209        dstLeft = x;
2210        dstTop = y;
2211
2212        texture->setFilter(scaled ? getFilter(paint) : GL_NEAREST, true);
2213        ignoreTransform = true;
2214    } else {
2215        texture->setFilter(getFilter(paint), true);
2216    }
2217
2218    if (CC_UNLIKELY(useScaleTransform)) {
2219        save(SkCanvas::kMatrix_SaveFlag);
2220        translate(dstLeft, dstTop);
2221        scale(scaleX, scaleY);
2222
2223        dstLeft = 0.0f;
2224        dstTop = 0.0f;
2225
2226        dstRight = srcRight - srcLeft;
2227        dstBottom = srcBottom - srcTop;
2228    }
2229
2230    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2231        drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2232                texture->id, paint,
2233                &mMeshVertices[0].x, &mMeshVertices[0].u,
2234                GL_TRIANGLE_STRIP, kUnitQuadCount, ignoreTransform);
2235    } else {
2236        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2237                texture->id, paint, texture->blend,
2238                &mMeshVertices[0].x, &mMeshVertices[0].u,
2239                GL_TRIANGLE_STRIP, kUnitQuadCount, false, ignoreTransform);
2240    }
2241
2242    if (CC_UNLIKELY(useScaleTransform)) {
2243        restore();
2244    }
2245
2246    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
2247
2248    mDirty = true;
2249}
2250
2251void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch,
2252        float left, float top, float right, float bottom, const SkPaint* paint) {
2253    if (quickRejectSetupScissor(left, top, right, bottom)) {
2254        return;
2255    }
2256
2257    AssetAtlas::Entry* entry = mRenderState.assetAtlas().getEntry(bitmap);
2258    const Patch* mesh = mCaches.patchCache.get(entry, bitmap->width(), bitmap->height(),
2259            right - left, bottom - top, patch);
2260
2261    drawPatch(bitmap, mesh, entry, left, top, right, bottom, paint);
2262}
2263
2264void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh,
2265        AssetAtlas::Entry* entry, float left, float top, float right, float bottom,
2266        const SkPaint* paint) {
2267    if (quickRejectSetupScissor(left, top, right, bottom)) {
2268        return;
2269    }
2270
2271    if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
2272        mCaches.textureState().activateTexture(0);
2273        Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2274        if (!texture) return;
2275        const AutoTexture autoCleanup(texture);
2276
2277        texture->setWrap(GL_CLAMP_TO_EDGE, true);
2278        texture->setFilter(GL_LINEAR, true);
2279
2280        const bool pureTranslate = currentTransform()->isPureTranslate();
2281        // Mark the current layer dirty where we are going to draw the patch
2282        if (hasLayer() && mesh->hasEmptyQuads) {
2283            const float offsetX = left + currentTransform()->getTranslateX();
2284            const float offsetY = top + currentTransform()->getTranslateY();
2285            const size_t count = mesh->quads.size();
2286            for (size_t i = 0; i < count; i++) {
2287                const Rect& bounds = mesh->quads.itemAt(i);
2288                if (CC_LIKELY(pureTranslate)) {
2289                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
2290                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
2291                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
2292                } else {
2293                    dirtyLayer(left + bounds.left, top + bounds.top,
2294                            left + bounds.right, top + bounds.bottom, *currentTransform());
2295                }
2296            }
2297        }
2298
2299        bool ignoreTransform = false;
2300        if (CC_LIKELY(pureTranslate)) {
2301            const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
2302            const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
2303
2304            right = x + right - left;
2305            bottom = y + bottom - top;
2306            left = x;
2307            top = y;
2308            ignoreTransform = true;
2309        }
2310        drawIndexedTextureMesh(left, top, right, bottom, texture->id, paint,
2311                texture->blend, (GLvoid*) mesh->offset, (GLvoid*) mesh->textureOffset,
2312                GL_TRIANGLES, mesh->indexCount, false, ignoreTransform,
2313                mCaches.patchCache.getMeshBuffer(), kModelViewMode_Translate, !mesh->hasEmptyQuads);
2314    }
2315
2316    mDirty = true;
2317}
2318
2319/**
2320 * Important note: this method is intended to draw batches of 9-patch objects and
2321 * will not set the scissor enable or dirty the current layer, if any.
2322 * The caller is responsible for properly dirtying the current layer.
2323 */
2324void OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
2325        TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint) {
2326    mCaches.textureState().activateTexture(0);
2327    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2328    if (!texture) return;
2329    const AutoTexture autoCleanup(texture);
2330
2331    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2332    texture->setFilter(GL_LINEAR, true);
2333
2334    drawIndexedTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, paint,
2335            texture->blend, &vertices[0].x, &vertices[0].u,
2336            GL_TRIANGLES, indexCount, false, true, 0, kModelViewMode_Translate, false);
2337
2338    mDirty = true;
2339}
2340
2341void OpenGLRenderer::drawVertexBuffer(float translateX, float translateY,
2342        const VertexBuffer& vertexBuffer, const SkPaint* paint, int displayFlags) {
2343    // not missing call to quickReject/dirtyLayer, always done at a higher level
2344    if (!vertexBuffer.getVertexCount()) {
2345        // no vertices to draw
2346        return;
2347    }
2348
2349    if (!paint->getShader() && !currentSnapshot()->roundRectClipState) {
2350        Glop glop;
2351        GlopBuilder aBuilder(mRenderState, mCaches, &glop);
2352        bool fudgeOffset = displayFlags & kVertexBuffer_Offset;
2353        bool shadowInterp = displayFlags & kVertexBuffer_ShadowInterp;
2354        aBuilder.setMeshVertexBuffer(vertexBuffer, shadowInterp)
2355                .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), fudgeOffset)
2356                .setModelViewOffsetRect(translateX, translateY, vertexBuffer.getBounds())
2357                .setPaint(paint, currentSnapshot()->alpha)
2358                .build();
2359        renderGlop(glop);
2360        return;
2361    }
2362
2363
2364    const VertexBuffer::MeshFeatureFlags meshFeatureFlags = vertexBuffer.getMeshFeatureFlags();
2365    Rect bounds(vertexBuffer.getBounds());
2366    bounds.translate(translateX, translateY);
2367    dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform());
2368
2369    int color = paint->getColor();
2370    bool isAA = meshFeatureFlags & VertexBuffer::kAlpha;
2371
2372    setupDraw();
2373    setupDrawNoTexture();
2374    if (isAA) setupDrawVertexAlpha((displayFlags & kVertexBuffer_ShadowInterp));
2375    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
2376    setupDrawColorFilter(getColorFilter(paint));
2377    setupDrawShader(getShader(paint));
2378    setupDrawBlending(paint, isAA);
2379    setupDrawProgram();
2380    setupDrawModelView(kModelViewMode_Translate, (displayFlags & kVertexBuffer_Offset),
2381            translateX, translateY, 0, 0);
2382    setupDrawColorUniforms(getShader(paint));
2383    setupDrawColorFilterUniforms(getColorFilter(paint));
2384    setupDrawShaderUniforms(getShader(paint));
2385
2386    const void* vertices = vertexBuffer.getBuffer();
2387    mRenderState.meshState().unbindMeshBuffer();
2388    mRenderState.meshState().bindPositionVertexPointer(true, vertices,
2389            isAA ? kAlphaVertexStride : kVertexStride);
2390    mRenderState.meshState().resetTexCoordsVertexPointer();
2391
2392    int alphaSlot = -1;
2393    if (isAA) {
2394        void* alphaCoords = ((GLbyte*) vertices) + kVertexAlphaOffset;
2395        alphaSlot = mCaches.program().getAttrib("vtxAlpha");
2396        // TODO: avoid enable/disable in back to back uses of the alpha attribute
2397        glEnableVertexAttribArray(alphaSlot);
2398        glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, kAlphaVertexStride, alphaCoords);
2399    }
2400
2401    if (meshFeatureFlags & VertexBuffer::kIndices) {
2402        mRenderState.meshState().unbindIndicesBuffer();
2403        glDrawElements(GL_TRIANGLE_STRIP, vertexBuffer.getIndexCount(),
2404                GL_UNSIGNED_SHORT, vertexBuffer.getIndices());
2405    } else {
2406        mRenderState.meshState().unbindIndicesBuffer();
2407        glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getVertexCount());
2408    }
2409
2410    if (isAA) {
2411        glDisableVertexAttribArray(alphaSlot);
2412    }
2413
2414    mDirty = true;
2415}
2416
2417/**
2418 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
2419 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
2420 * screen space in all directions. However, instead of using a fragment shader to compute the
2421 * translucency of the color from its position, we simply use a varying parameter to define how far
2422 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
2423 *
2424 * Doesn't yet support joins, caps, or path effects.
2425 */
2426void OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) {
2427    VertexBuffer vertexBuffer;
2428    // TODO: try clipping large paths to viewport
2429    PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer);
2430    drawVertexBuffer(vertexBuffer, paint);
2431}
2432
2433/**
2434 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
2435 * and additional geometry for defining an alpha slope perimeter.
2436 *
2437 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
2438 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
2439 * in-shader alpha region, but found it to be taxing on some GPUs.
2440 *
2441 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
2442 * memory transfer by removing need for degenerate vertices.
2443 */
2444void OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) {
2445    if (mState.currentlyIgnored() || count < 4) return;
2446
2447    count &= ~0x3; // round down to nearest four
2448
2449    VertexBuffer buffer;
2450    PathTessellator::tessellateLines(points, count, paint, *currentTransform(), buffer);
2451    const Rect& bounds = buffer.getBounds();
2452
2453    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
2454        return;
2455    }
2456
2457    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
2458    drawVertexBuffer(buffer, paint, displayFlags);
2459}
2460
2461void OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) {
2462    if (mState.currentlyIgnored() || count < 2) return;
2463
2464    count &= ~0x1; // round down to nearest two
2465
2466    VertexBuffer buffer;
2467    PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), buffer);
2468
2469    const Rect& bounds = buffer.getBounds();
2470    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
2471        return;
2472    }
2473
2474    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
2475    drawVertexBuffer(buffer, paint, displayFlags);
2476
2477    mDirty = true;
2478}
2479
2480void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2481    // No need to check against the clip, we fill the clip region
2482    if (mState.currentlyIgnored()) return;
2483
2484    Rect clip(mState.currentClipRect());
2485    clip.snapToPixelBoundaries();
2486
2487    SkPaint paint;
2488    paint.setColor(color);
2489    paint.setXfermodeMode(mode);
2490
2491    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true);
2492
2493    mDirty = true;
2494}
2495
2496void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture,
2497        const SkPaint* paint) {
2498    if (!texture) return;
2499    const AutoTexture autoCleanup(texture);
2500
2501    const float x = left + texture->left - texture->offset;
2502    const float y = top + texture->top - texture->offset;
2503
2504    drawPathTexture(texture, x, y, paint);
2505
2506    mDirty = true;
2507}
2508
2509void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2510        float rx, float ry, const SkPaint* p) {
2511    if (mState.currentlyIgnored()
2512            || quickRejectSetupScissor(left, top, right, bottom, p)
2513            || PaintUtils::paintWillNotDraw(*p)) {
2514        return;
2515    }
2516
2517    if (p->getPathEffect() != nullptr) {
2518        mCaches.textureState().activateTexture(0);
2519        const PathTexture* texture = mCaches.pathCache.getRoundRect(
2520                right - left, bottom - top, rx, ry, p);
2521        drawShape(left, top, texture, p);
2522    } else {
2523        const VertexBuffer* vertexBuffer = mCaches.tessellationCache.getRoundRect(
2524                *currentTransform(), *p, right - left, bottom - top, rx, ry);
2525        drawVertexBuffer(left, top, *vertexBuffer, p);
2526    }
2527}
2528
2529void OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) {
2530    if (mState.currentlyIgnored()
2531            || quickRejectSetupScissor(x - radius, y - radius, x + radius, y + radius, p)
2532            || PaintUtils::paintWillNotDraw(*p)) {
2533        return;
2534    }
2535    if (p->getPathEffect() != nullptr) {
2536        mCaches.textureState().activateTexture(0);
2537        const PathTexture* texture = mCaches.pathCache.getCircle(radius, p);
2538        drawShape(x - radius, y - radius, texture, p);
2539    } else {
2540        SkPath path;
2541        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2542            path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2543        } else {
2544            path.addCircle(x, y, radius);
2545        }
2546        drawConvexPath(path, p);
2547    }
2548}
2549
2550void OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2551        const SkPaint* p) {
2552    if (mState.currentlyIgnored()
2553            || quickRejectSetupScissor(left, top, right, bottom, p)
2554            || PaintUtils::paintWillNotDraw(*p)) {
2555        return;
2556    }
2557
2558    if (p->getPathEffect() != nullptr) {
2559        mCaches.textureState().activateTexture(0);
2560        const PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p);
2561        drawShape(left, top, texture, p);
2562    } else {
2563        SkPath path;
2564        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2565        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2566            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2567        }
2568        path.addOval(rect);
2569        drawConvexPath(path, p);
2570    }
2571}
2572
2573void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2574        float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) {
2575    if (mState.currentlyIgnored()
2576            || quickRejectSetupScissor(left, top, right, bottom, p)
2577            || PaintUtils::paintWillNotDraw(*p)) {
2578        return;
2579    }
2580
2581    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2582    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != nullptr || useCenter) {
2583        mCaches.textureState().activateTexture(0);
2584        const PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top,
2585                startAngle, sweepAngle, useCenter, p);
2586        drawShape(left, top, texture, p);
2587        return;
2588    }
2589    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2590    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2591        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2592    }
2593
2594    SkPath path;
2595    if (useCenter) {
2596        path.moveTo(rect.centerX(), rect.centerY());
2597    }
2598    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2599    if (useCenter) {
2600        path.close();
2601    }
2602    drawConvexPath(path, p);
2603}
2604
2605// See SkPaintDefaults.h
2606#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2607
2608void OpenGLRenderer::drawRect(float left, float top, float right, float bottom,
2609        const SkPaint* p) {
2610    if (mState.currentlyIgnored()
2611            || quickRejectSetupScissor(left, top, right, bottom, p)
2612            || PaintUtils::paintWillNotDraw(*p)) {
2613        return;
2614    }
2615
2616    if (p->getStyle() != SkPaint::kFill_Style) {
2617        // only fill style is supported by drawConvexPath, since others have to handle joins
2618        if (p->getPathEffect() != nullptr || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2619                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2620            mCaches.textureState().activateTexture(0);
2621            const PathTexture* texture =
2622                    mCaches.pathCache.getRect(right - left, bottom - top, p);
2623            drawShape(left, top, texture, p);
2624        } else {
2625            SkPath path;
2626            SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2627            if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2628                rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2629            }
2630            path.addRect(rect);
2631            drawConvexPath(path, p);
2632        }
2633    } else {
2634        if (p->isAntiAlias() && !currentTransform()->isSimple()) {
2635            SkPath path;
2636            path.addRect(left, top, right, bottom);
2637            drawConvexPath(path, p);
2638        } else {
2639            drawColorRect(left, top, right, bottom, p);
2640
2641            mDirty = true;
2642        }
2643    }
2644}
2645
2646void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text,
2647        int bytesCount, int count, const float* positions,
2648        FontRenderer& fontRenderer, int alpha, float x, float y) {
2649    mCaches.textureState().activateTexture(0);
2650
2651    TextShadow textShadow;
2652    if (!getTextShadow(paint, &textShadow)) {
2653        LOG_ALWAYS_FATAL("failed to query shadow attributes");
2654    }
2655
2656    // NOTE: The drop shadow will not perform gamma correction
2657    //       if shader-based correction is enabled
2658    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2659    const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2660            paint, text, bytesCount, count, textShadow.radius, positions);
2661    // If the drop shadow exceeds the max texture size or couldn't be
2662    // allocated, skip drawing
2663    if (!shadow) return;
2664    const AutoTexture autoCleanup(shadow);
2665
2666    const float sx = x - shadow->left + textShadow.dx;
2667    const float sy = y - shadow->top + textShadow.dy;
2668
2669    const int shadowAlpha = ((textShadow.color >> 24) & 0xFF) * writableSnapshot()->alpha;
2670    if (getShader(paint)) {
2671        textShadow.color = SK_ColorWHITE;
2672    }
2673
2674    setupDraw();
2675    setupDrawWithTexture(true);
2676    setupDrawAlpha8Color(textShadow.color, shadowAlpha < 255 ? shadowAlpha : alpha);
2677    setupDrawColorFilter(getColorFilter(paint));
2678    setupDrawShader(getShader(paint));
2679    setupDrawBlending(paint, true);
2680    setupDrawProgram();
2681    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
2682            sx, sy, sx + shadow->width, sy + shadow->height);
2683    setupDrawTexture(shadow->id);
2684    setupDrawPureColorUniforms();
2685    setupDrawColorFilterUniforms(getColorFilter(paint));
2686    setupDrawShaderUniforms(getShader(paint));
2687    setupDrawMesh(nullptr, (GLvoid*) kMeshTextureOffset);
2688
2689    glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount);
2690}
2691
2692bool OpenGLRenderer::canSkipText(const SkPaint* paint) const {
2693    float alpha = (hasTextShadow(paint) ? 1.0f : paint->getAlpha()) * currentSnapshot()->alpha;
2694    return MathUtils::isZero(alpha)
2695            && PaintUtils::getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode;
2696}
2697
2698void OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2699        const float* positions, const SkPaint* paint) {
2700    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2701        return;
2702    }
2703
2704    // NOTE: Skia does not support perspective transform on drawPosText yet
2705    if (!currentTransform()->isSimple()) {
2706        return;
2707    }
2708
2709    mRenderState.scissor().setEnabled(true);
2710
2711    float x = 0.0f;
2712    float y = 0.0f;
2713    const bool pureTranslate = currentTransform()->isPureTranslate();
2714    if (pureTranslate) {
2715        x = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f);
2716        y = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f);
2717    }
2718
2719    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2720    fontRenderer.setFont(paint, SkMatrix::I());
2721
2722    int alpha;
2723    SkXfermode::Mode mode;
2724    getAlphaAndMode(paint, &alpha, &mode);
2725
2726    if (CC_UNLIKELY(hasTextShadow(paint))) {
2727        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2728                alpha, 0.0f, 0.0f);
2729    }
2730
2731    // Pick the appropriate texture filtering
2732    bool linearFilter = currentTransform()->changesBounds();
2733    if (pureTranslate && !linearFilter) {
2734        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2735    }
2736    fontRenderer.setTextureFiltering(linearFilter);
2737
2738    const Rect& clip(pureTranslate ? writableSnapshot()->getClipRect() : writableSnapshot()->getLocalClip());
2739    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2740
2741    const bool hasActiveLayer = hasLayer();
2742
2743    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2744    if (fontRenderer.renderPosText(paint, &clip, text, 0, bytesCount, count, x, y,
2745            positions, hasActiveLayer ? &bounds : nullptr, &functor)) {
2746        if (hasActiveLayer) {
2747            if (!pureTranslate) {
2748                currentTransform()->mapRect(bounds);
2749            }
2750            dirtyLayerUnchecked(bounds, getRegion());
2751        }
2752    }
2753
2754    mDirty = true;
2755}
2756
2757bool OpenGLRenderer::findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const {
2758    if (CC_LIKELY(transform.isPureTranslate())) {
2759        outMatrix->setIdentity();
2760        return false;
2761    } else if (CC_UNLIKELY(transform.isPerspective())) {
2762        outMatrix->setIdentity();
2763        return true;
2764    }
2765
2766    /**
2767     * Input is a non-perspective, scaling transform. Generate a scale-only transform,
2768     * with values rounded to the nearest int.
2769     */
2770    float sx, sy;
2771    transform.decomposeScale(sx, sy);
2772    outMatrix->setScale(
2773            roundf(fmaxf(1.0f, sx)),
2774            roundf(fmaxf(1.0f, sy)));
2775    return true;
2776}
2777
2778int OpenGLRenderer::getSaveCount() const {
2779    return mState.getSaveCount();
2780}
2781
2782int OpenGLRenderer::save(int flags) {
2783    return mState.save(flags);
2784}
2785
2786void OpenGLRenderer::restore() {
2787    return mState.restore();
2788}
2789
2790void OpenGLRenderer::restoreToCount(int saveCount) {
2791    return mState.restoreToCount(saveCount);
2792}
2793
2794void OpenGLRenderer::translate(float dx, float dy, float dz) {
2795    return mState.translate(dx, dy, dz);
2796}
2797
2798void OpenGLRenderer::rotate(float degrees) {
2799    return mState.rotate(degrees);
2800}
2801
2802void OpenGLRenderer::scale(float sx, float sy) {
2803    return mState.scale(sx, sy);
2804}
2805
2806void OpenGLRenderer::skew(float sx, float sy) {
2807    return mState.skew(sx, sy);
2808}
2809
2810void OpenGLRenderer::setMatrix(const Matrix4& matrix) {
2811    mState.setMatrix(matrix);
2812}
2813
2814void OpenGLRenderer::concatMatrix(const Matrix4& matrix) {
2815    mState.concatMatrix(matrix);
2816}
2817
2818bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
2819    return mState.clipRect(left, top, right, bottom, op);
2820}
2821
2822bool OpenGLRenderer::clipPath(const SkPath* path, SkRegion::Op op) {
2823    return mState.clipPath(path, op);
2824}
2825
2826bool OpenGLRenderer::clipRegion(const SkRegion* region, SkRegion::Op op) {
2827    return mState.clipRegion(region, op);
2828}
2829
2830void OpenGLRenderer::setClippingOutline(LinearAllocator& allocator, const Outline* outline) {
2831    mState.setClippingOutline(allocator, outline);
2832}
2833
2834void OpenGLRenderer::setClippingRoundRect(LinearAllocator& allocator,
2835        const Rect& rect, float radius, bool highPriority) {
2836    mState.setClippingRoundRect(allocator, rect, radius, highPriority);
2837}
2838
2839void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y,
2840        const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
2841        DrawOpMode drawOpMode) {
2842
2843    if (drawOpMode == kDrawOpMode_Immediate) {
2844        // The checks for corner-case ignorable text and quick rejection is only done for immediate
2845        // drawing as ops from DeferredDisplayList are already filtered for these
2846        if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint) ||
2847                quickRejectSetupScissor(bounds)) {
2848            return;
2849        }
2850    }
2851
2852    const float oldX = x;
2853    const float oldY = y;
2854
2855    const mat4& transform = *currentTransform();
2856    const bool pureTranslate = transform.isPureTranslate();
2857
2858    if (CC_LIKELY(pureTranslate)) {
2859        x = (int) floorf(x + transform.getTranslateX() + 0.5f);
2860        y = (int) floorf(y + transform.getTranslateY() + 0.5f);
2861    }
2862
2863    int alpha;
2864    SkXfermode::Mode mode;
2865    getAlphaAndMode(paint, &alpha, &mode);
2866
2867    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2868
2869    if (CC_UNLIKELY(hasTextShadow(paint))) {
2870        fontRenderer.setFont(paint, SkMatrix::I());
2871        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2872                alpha, oldX, oldY);
2873    }
2874
2875    const bool hasActiveLayer = hasLayer();
2876
2877    // We only pass a partial transform to the font renderer. That partial
2878    // matrix defines how glyphs are rasterized. Typically we want glyphs
2879    // to be rasterized at their final size on screen, which means the partial
2880    // matrix needs to take the scale factor into account.
2881    // When a partial matrix is used to transform glyphs during rasterization,
2882    // the mesh is generated with the inverse transform (in the case of scale,
2883    // the mesh is generated at 1.0 / scale for instance.) This allows us to
2884    // apply the full transform matrix at draw time in the vertex shader.
2885    // Applying the full matrix in the shader is the easiest way to handle
2886    // rotation and perspective and allows us to always generated quads in the
2887    // font renderer which greatly simplifies the code, clipping in particular.
2888    SkMatrix fontTransform;
2889    bool linearFilter = findBestFontTransform(transform, &fontTransform)
2890            || fabs(y - (int) y) > 0.0f
2891            || fabs(x - (int) x) > 0.0f;
2892    fontRenderer.setFont(paint, fontTransform);
2893    fontRenderer.setTextureFiltering(linearFilter);
2894
2895    // TODO: Implement better clipping for scaled/rotated text
2896    const Rect* clip = !pureTranslate ? nullptr : &mState.currentClipRect();
2897    Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2898
2899    bool status;
2900    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2901
2902    // don't call issuedrawcommand, do it at end of batch
2903    bool forceFinish = (drawOpMode != kDrawOpMode_Defer);
2904    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2905        SkPaint paintCopy(*paint);
2906        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2907        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2908                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2909    } else {
2910        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2911                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2912    }
2913
2914    if ((status || drawOpMode != kDrawOpMode_Immediate) && hasActiveLayer) {
2915        if (!pureTranslate) {
2916            transform.mapRect(layerBounds);
2917        }
2918        dirtyLayerUnchecked(layerBounds, getRegion());
2919    }
2920
2921    drawTextDecorations(totalAdvance, oldX, oldY, paint);
2922
2923    mDirty = true;
2924}
2925
2926void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count,
2927        const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) {
2928    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2929        return;
2930    }
2931
2932    // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics
2933    mRenderState.scissor().setEnabled(true);
2934
2935    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2936    fontRenderer.setFont(paint, SkMatrix::I());
2937    fontRenderer.setTextureFiltering(true);
2938
2939    int alpha;
2940    SkXfermode::Mode mode;
2941    getAlphaAndMode(paint, &alpha, &mode);
2942    TextSetupFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint);
2943
2944    const Rect* clip = &writableSnapshot()->getLocalClip();
2945    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2946
2947    const bool hasActiveLayer = hasLayer();
2948
2949    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2950            hOffset, vOffset, hasActiveLayer ? &bounds : nullptr, &functor)) {
2951        if (hasActiveLayer) {
2952            currentTransform()->mapRect(bounds);
2953            dirtyLayerUnchecked(bounds, getRegion());
2954        }
2955    }
2956
2957    mDirty = true;
2958}
2959
2960void OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) {
2961    if (mState.currentlyIgnored()) return;
2962
2963    mCaches.textureState().activateTexture(0);
2964
2965    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2966    if (!texture) return;
2967    const AutoTexture autoCleanup(texture);
2968
2969    const float x = texture->left - texture->offset;
2970    const float y = texture->top - texture->offset;
2971
2972    drawPathTexture(texture, x, y, paint);
2973    mDirty = true;
2974}
2975
2976void OpenGLRenderer::drawLayer(Layer* layer, float x, float y) {
2977    if (!layer) {
2978        return;
2979    }
2980
2981    mat4* transform = nullptr;
2982    if (layer->isTextureLayer()) {
2983        transform = &layer->getTransform();
2984        if (!transform->isIdentity()) {
2985            save(SkCanvas::kMatrix_SaveFlag);
2986            concatMatrix(*transform);
2987        }
2988    }
2989
2990    bool clipRequired = false;
2991    const bool rejected = mState.calculateQuickRejectForScissor(
2992            x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
2993            &clipRequired, nullptr, false);
2994
2995    if (rejected) {
2996        if (transform && !transform->isIdentity()) {
2997            restore();
2998        }
2999        return;
3000    }
3001
3002    EVENT_LOGD("drawLayer," RECT_STRING ", clipRequired %d", x, y,
3003            x + layer->layer.getWidth(), y + layer->layer.getHeight(), clipRequired);
3004
3005    updateLayer(layer, true);
3006
3007    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
3008    mCaches.textureState().activateTexture(0);
3009
3010    if (CC_LIKELY(!layer->region.isEmpty())) {
3011        if (layer->region.isRect()) {
3012            DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3013                    composeLayerRect(layer, layer->regionRect));
3014        } else if (layer->mesh) {
3015
3016            const float a = getLayerAlpha(layer);
3017            setupDraw();
3018            setupDrawWithTexture();
3019            setupDrawColor(a, a, a, a);
3020            setupDrawColorFilter(layer->getColorFilter());
3021            setupDrawBlending(layer);
3022            setupDrawProgram();
3023            setupDrawPureColorUniforms();
3024            setupDrawColorFilterUniforms(layer->getColorFilter());
3025            setupDrawTexture(layer->getTexture());
3026            if (CC_LIKELY(currentTransform()->isPureTranslate())) {
3027                int tx = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f);
3028                int ty = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f);
3029
3030                layer->setFilter(GL_NEAREST);
3031                setupDrawModelView(kModelViewMode_Translate, false, tx, ty,
3032                        tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
3033            } else {
3034                layer->setFilter(GL_LINEAR);
3035                setupDrawModelView(kModelViewMode_Translate, false, x, y,
3036                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
3037            }
3038
3039            TextureVertex* mesh = &layer->mesh[0];
3040            GLsizei elementsCount = layer->meshElementCount;
3041
3042            while (elementsCount > 0) {
3043                GLsizei drawCount = min(elementsCount, (GLsizei) kMaxNumberOfQuads * 6);
3044
3045                setupDrawMeshIndices(&mesh[0].x, &mesh[0].u);
3046                DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3047                        glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, nullptr));
3048
3049                elementsCount -= drawCount;
3050                // Though there are 4 vertices in a quad, we use 6 indices per
3051                // quad to draw with GL_TRIANGLES
3052                mesh += (drawCount / 6) * 4;
3053            }
3054
3055#if DEBUG_LAYERS_AS_REGIONS
3056            drawRegionRectsDebug(layer->region);
3057#endif
3058        }
3059
3060        if (layer->debugDrawUpdate) {
3061            layer->debugDrawUpdate = false;
3062
3063            SkPaint paint;
3064            paint.setColor(0x7f00ff00);
3065            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint);
3066        }
3067    }
3068    layer->hasDrawnSinceUpdate = true;
3069
3070    if (transform && !transform->isIdentity()) {
3071        restore();
3072    }
3073
3074    mDirty = true;
3075}
3076
3077///////////////////////////////////////////////////////////////////////////////
3078// Draw filters
3079///////////////////////////////////////////////////////////////////////////////
3080void OpenGLRenderer::setDrawFilter(SkDrawFilter* filter) {
3081    // We should never get here since we apply the draw filter when stashing
3082    // the paints in the DisplayList.
3083    LOG_ALWAYS_FATAL("OpenGLRenderer does not directly support DrawFilters");
3084}
3085
3086///////////////////////////////////////////////////////////////////////////////
3087// Drawing implementation
3088///////////////////////////////////////////////////////////////////////////////
3089
3090Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) {
3091    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
3092    if (!texture) {
3093        return mCaches.textureCache.get(bitmap);
3094    }
3095    return texture;
3096}
3097
3098void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
3099        float x, float y, const SkPaint* paint) {
3100    if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) {
3101        return;
3102    }
3103
3104    int alpha;
3105    SkXfermode::Mode mode;
3106    getAlphaAndMode(paint, &alpha, &mode);
3107
3108    setupDraw();
3109    setupDrawWithTexture(true);
3110    setupDrawAlpha8Color(paint->getColor(), alpha);
3111    setupDrawColorFilter(getColorFilter(paint));
3112    setupDrawShader(getShader(paint));
3113    setupDrawBlending(paint, true);
3114    setupDrawProgram();
3115    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
3116            x, y, x + texture->width, y + texture->height);
3117    setupDrawTexture(texture->id);
3118    setupDrawPureColorUniforms();
3119    setupDrawColorFilterUniforms(getColorFilter(paint));
3120    setupDrawShaderUniforms(getShader(paint));
3121    setupDrawMesh(nullptr, (GLvoid*) kMeshTextureOffset);
3122
3123    glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount);
3124}
3125
3126// Same values used by Skia
3127#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
3128#define kStdUnderline_Offset    (1.0f / 9.0f)
3129#define kStdUnderline_Thickness (1.0f / 18.0f)
3130
3131void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y,
3132        const SkPaint* paint) {
3133    // Handle underline and strike-through
3134    uint32_t flags = paint->getFlags();
3135    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
3136        SkPaint paintCopy(*paint);
3137
3138        if (CC_LIKELY(underlineWidth > 0.0f)) {
3139            const float textSize = paintCopy.getTextSize();
3140            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
3141
3142            const float left = x;
3143            float top = 0.0f;
3144
3145            int linesCount = 0;
3146            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
3147            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
3148
3149            const int pointsCount = 4 * linesCount;
3150            float points[pointsCount];
3151            int currentPoint = 0;
3152
3153            if (flags & SkPaint::kUnderlineText_Flag) {
3154                top = y + textSize * kStdUnderline_Offset;
3155                points[currentPoint++] = left;
3156                points[currentPoint++] = top;
3157                points[currentPoint++] = left + underlineWidth;
3158                points[currentPoint++] = top;
3159            }
3160
3161            if (flags & SkPaint::kStrikeThruText_Flag) {
3162                top = y + textSize * kStdStrikeThru_Offset;
3163                points[currentPoint++] = left;
3164                points[currentPoint++] = top;
3165                points[currentPoint++] = left + underlineWidth;
3166                points[currentPoint++] = top;
3167            }
3168
3169            paintCopy.setStrokeWidth(strokeWidth);
3170
3171            drawLines(&points[0], pointsCount, &paintCopy);
3172        }
3173    }
3174}
3175
3176void OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) {
3177    if (mState.currentlyIgnored()) {
3178        return;
3179    }
3180
3181    drawColorRects(rects, count, paint, false, true, true);
3182}
3183
3184void OpenGLRenderer::drawShadow(float casterAlpha,
3185        const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) {
3186    if (mState.currentlyIgnored()) return;
3187
3188    // TODO: use quickRejectWithScissor. For now, always force enable scissor.
3189    mRenderState.scissor().setEnabled(true);
3190
3191    SkPaint paint;
3192    paint.setAntiAlias(true); // want to use AlphaVertex
3193
3194    // The caller has made sure casterAlpha > 0.
3195    float ambientShadowAlpha = mAmbientShadowAlpha;
3196    if (CC_UNLIKELY(mCaches.propertyAmbientShadowStrength >= 0)) {
3197        ambientShadowAlpha = mCaches.propertyAmbientShadowStrength;
3198    }
3199    if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) {
3200        paint.setARGB(casterAlpha * ambientShadowAlpha, 0, 0, 0);
3201        drawVertexBuffer(*ambientShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
3202    }
3203
3204    float spotShadowAlpha = mSpotShadowAlpha;
3205    if (CC_UNLIKELY(mCaches.propertySpotShadowStrength >= 0)) {
3206        spotShadowAlpha = mCaches.propertySpotShadowStrength;
3207    }
3208    if (spotShadowVertexBuffer && spotShadowAlpha > 0) {
3209        paint.setARGB(casterAlpha * spotShadowAlpha, 0, 0, 0);
3210        drawVertexBuffer(*spotShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
3211    }
3212
3213    mDirty=true;
3214}
3215
3216void OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint,
3217        bool ignoreTransform, bool dirty, bool clip) {
3218    if (count == 0) {
3219        return;
3220    }
3221
3222    int color = paint->getColor();
3223    // If a shader is set, preserve only the alpha
3224    if (getShader(paint)) {
3225        color |= 0x00ffffff;
3226    }
3227
3228    float left = FLT_MAX;
3229    float top = FLT_MAX;
3230    float right = FLT_MIN;
3231    float bottom = FLT_MIN;
3232
3233    Vertex mesh[count];
3234    Vertex* vertex = mesh;
3235
3236    for (int index = 0; index < count; index += 4) {
3237        float l = rects[index + 0];
3238        float t = rects[index + 1];
3239        float r = rects[index + 2];
3240        float b = rects[index + 3];
3241
3242        Vertex::set(vertex++, l, t);
3243        Vertex::set(vertex++, r, t);
3244        Vertex::set(vertex++, l, b);
3245        Vertex::set(vertex++, r, b);
3246
3247        left = fminf(left, l);
3248        top = fminf(top, t);
3249        right = fmaxf(right, r);
3250        bottom = fmaxf(bottom, b);
3251    }
3252
3253    if (clip && quickRejectSetupScissor(left, top, right, bottom)) {
3254        return;
3255    }
3256
3257    setupDraw();
3258    setupDrawNoTexture();
3259    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
3260    setupDrawShader(getShader(paint));
3261    setupDrawColorFilter(getColorFilter(paint));
3262    setupDrawBlending(paint);
3263    setupDrawProgram();
3264    setupDrawDirtyRegionsDisabled();
3265    setupDrawModelView(kModelViewMode_Translate, false,
3266            0.0f, 0.0f, 0.0f, 0.0f, ignoreTransform);
3267    setupDrawColorUniforms(getShader(paint));
3268    setupDrawShaderUniforms(getShader(paint));
3269    setupDrawColorFilterUniforms(getColorFilter(paint));
3270
3271    if (dirty && hasLayer()) {
3272        dirtyLayer(left, top, right, bottom, *currentTransform());
3273    }
3274
3275    issueIndexedQuadDraw(&mesh[0], count / 4);
3276
3277    mDirty = true;
3278}
3279
3280void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
3281        const SkPaint* paint, bool ignoreTransform) {
3282
3283    if (!paint->getShader() && !currentSnapshot()->roundRectClipState) {
3284        const Matrix4& transform = ignoreTransform ? Matrix4::identity() : *currentTransform();
3285        Glop glop;
3286        GlopBuilder aBuilder(mRenderState, mCaches, &glop);
3287        aBuilder.setMeshUnitQuad()
3288                .setTransform(currentSnapshot()->getOrthoMatrix(), transform, false)
3289                .setModelViewMapUnitToRect(Rect(left, top, right, bottom))
3290                .setPaint(paint, currentSnapshot()->alpha)
3291                .build();
3292        renderGlop(glop);
3293        return;
3294    }
3295
3296    int color = paint->getColor();
3297    // If a shader is set, preserve only the alpha
3298    if (getShader(paint)) {
3299        color |= 0x00ffffff;
3300    }
3301
3302    setupDraw();
3303    setupDrawNoTexture();
3304    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
3305    setupDrawShader(getShader(paint));
3306    setupDrawColorFilter(getColorFilter(paint));
3307    setupDrawBlending(paint);
3308    setupDrawProgram();
3309    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
3310            left, top, right, bottom, ignoreTransform);
3311    setupDrawColorUniforms(getShader(paint));
3312    setupDrawShaderUniforms(getShader(paint), ignoreTransform);
3313    setupDrawColorFilterUniforms(getColorFilter(paint));
3314    setupDrawSimpleMesh();
3315
3316    glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount);
3317}
3318
3319void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3320        Texture* texture, const SkPaint* paint) {
3321    texture->setWrap(GL_CLAMP_TO_EDGE, true);
3322
3323    GLvoid* vertices = (GLvoid*) nullptr;
3324    GLvoid* texCoords = (GLvoid*) kMeshTextureOffset;
3325
3326    if (texture->uvMapper) {
3327        vertices = &mMeshVertices[0].x;
3328        texCoords = &mMeshVertices[0].u;
3329
3330        Rect uvs(0.0f, 0.0f, 1.0f, 1.0f);
3331        texture->uvMapper->map(uvs);
3332
3333        resetDrawTextureTexCoords(uvs.left, uvs.top, uvs.right, uvs.bottom);
3334    }
3335
3336    if (CC_LIKELY(currentTransform()->isPureTranslate())) {
3337        const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
3338        const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
3339
3340        texture->setFilter(GL_NEAREST, true);
3341        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3342                paint, texture->blend, vertices, texCoords,
3343                GL_TRIANGLE_STRIP, kUnitQuadCount, false, true);
3344    } else {
3345        texture->setFilter(getFilter(paint), true);
3346        drawTextureMesh(left, top, right, bottom, texture->id, paint,
3347                texture->blend, vertices, texCoords, GL_TRIANGLE_STRIP, kUnitQuadCount);
3348    }
3349
3350    if (texture->uvMapper) {
3351        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
3352    }
3353}
3354
3355void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3356        GLuint texture, const SkPaint* paint, bool blend,
3357        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3358        bool swapSrcDst, bool ignoreTransform, GLuint vbo,
3359        ModelViewMode modelViewMode, bool dirty) {
3360
3361    int a;
3362    SkXfermode::Mode mode;
3363    getAlphaAndMode(paint, &a, &mode);
3364    const float alpha = a / 255.0f;
3365
3366    setupDraw();
3367    setupDrawWithTexture();
3368    setupDrawColor(alpha, alpha, alpha, alpha);
3369    setupDrawColorFilter(getColorFilter(paint));
3370    setupDrawBlending(paint, blend, swapSrcDst);
3371    setupDrawProgram();
3372    if (!dirty) setupDrawDirtyRegionsDisabled();
3373    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3374    setupDrawTexture(texture);
3375    setupDrawPureColorUniforms();
3376    setupDrawColorFilterUniforms(getColorFilter(paint));
3377    setupDrawMesh(vertices, texCoords, vbo);
3378
3379    glDrawArrays(drawMode, 0, elementsCount);
3380}
3381
3382void OpenGLRenderer::drawIndexedTextureMesh(float left, float top, float right, float bottom,
3383        GLuint texture, const SkPaint* paint, bool blend,
3384        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3385        bool swapSrcDst, bool ignoreTransform, GLuint vbo,
3386        ModelViewMode modelViewMode, bool dirty) {
3387
3388    int a;
3389    SkXfermode::Mode mode;
3390    getAlphaAndMode(paint, &a, &mode);
3391    const float alpha = a / 255.0f;
3392
3393    setupDraw();
3394    setupDrawWithTexture();
3395    setupDrawColor(alpha, alpha, alpha, alpha);
3396    setupDrawColorFilter(getColorFilter(paint));
3397    setupDrawBlending(paint, blend, swapSrcDst);
3398    setupDrawProgram();
3399    if (!dirty) setupDrawDirtyRegionsDisabled();
3400    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3401    setupDrawTexture(texture);
3402    setupDrawPureColorUniforms();
3403    setupDrawColorFilterUniforms(getColorFilter(paint));
3404    setupDrawMeshIndices(vertices, texCoords, vbo);
3405
3406    glDrawElements(drawMode, elementsCount, GL_UNSIGNED_SHORT, nullptr);
3407}
3408
3409void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom,
3410        GLuint texture, const SkPaint* paint,
3411        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3412        bool ignoreTransform, ModelViewMode modelViewMode, bool dirty) {
3413
3414    int color = paint != nullptr ? paint->getColor() : 0;
3415    int alpha;
3416    SkXfermode::Mode mode;
3417    getAlphaAndMode(paint, &alpha, &mode);
3418
3419    setupDraw();
3420    setupDrawWithTexture(true);
3421    if (paint != nullptr) {
3422        setupDrawAlpha8Color(color, alpha);
3423    }
3424    setupDrawColorFilter(getColorFilter(paint));
3425    setupDrawShader(getShader(paint));
3426    setupDrawBlending(paint, true);
3427    setupDrawProgram();
3428    if (!dirty) setupDrawDirtyRegionsDisabled();
3429    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3430    setupDrawTexture(texture);
3431    setupDrawPureColorUniforms();
3432    setupDrawColorFilterUniforms(getColorFilter(paint));
3433    setupDrawShaderUniforms(getShader(paint), ignoreTransform);
3434    setupDrawMesh(vertices, texCoords);
3435
3436    glDrawArrays(drawMode, 0, elementsCount);
3437}
3438
3439void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3440        ProgramDescription& description, bool swapSrcDst) {
3441
3442    if (currentSnapshot()->roundRectClipState != nullptr /*&& !mSkipOutlineClip*/) {
3443        blend = true;
3444        mDescription.hasRoundRectClip = true;
3445    }
3446    mSkipOutlineClip = true;
3447
3448    blend = blend || mode != SkXfermode::kSrcOver_Mode;
3449
3450    if (blend) {
3451        // These blend modes are not supported by OpenGL directly and have
3452        // to be implemented using shaders. Since the shader will perform
3453        // the blending, turn blending off here
3454        // If the blend mode cannot be implemented using shaders, fall
3455        // back to the default SrcOver blend mode instead
3456        if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3457            if (CC_UNLIKELY(mCaches.extensions().hasFramebufferFetch())) {
3458                description.framebufferMode = mode;
3459                description.swapSrcDst = swapSrcDst;
3460
3461                mRenderState.blend().disable();
3462                return;
3463            } else {
3464                mode = SkXfermode::kSrcOver_Mode;
3465            }
3466        }
3467        mRenderState.blend().enable(mode, swapSrcDst);
3468    } else {
3469        mRenderState.blend().disable();
3470    }
3471}
3472
3473void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3474    TextureVertex* v = &mMeshVertices[0];
3475    TextureVertex::setUV(v++, u1, v1);
3476    TextureVertex::setUV(v++, u2, v1);
3477    TextureVertex::setUV(v++, u1, v2);
3478    TextureVertex::setUV(v++, u2, v2);
3479}
3480
3481void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha,
3482        SkXfermode::Mode* mode) const {
3483    getAlphaAndModeDirect(paint, alpha,  mode);
3484    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3485        // if drawing a layer, ignore the paint's alpha
3486        *alpha = mDrawModifiers.mOverrideLayerAlpha * 255;
3487    }
3488    *alpha *= currentSnapshot()->alpha;
3489}
3490
3491float OpenGLRenderer::getLayerAlpha(const Layer* layer) const {
3492    float alpha;
3493    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3494        alpha = mDrawModifiers.mOverrideLayerAlpha;
3495    } else {
3496        alpha = layer->getAlpha() / 255.0f;
3497    }
3498    return alpha * currentSnapshot()->alpha;
3499}
3500
3501}; // namespace uirenderer
3502}; // namespace android
3503