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