OpenGLRenderer.cpp revision b2e2f2470693e78baed20617f989d9a166864ed4
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 <SkPathMeasure.h>
25#include <SkTypeface.h>
26
27#include <utils/Log.h>
28#include <utils/StopWatch.h>
29
30#include <private/hwui/DrawGlInfo.h>
31
32#include <ui/Rect.h>
33
34#include "OpenGLRenderer.h"
35#include "DisplayListRenderer.h"
36#include "PathRenderer.h"
37#include "Properties.h"
38#include "Vector.h"
39
40namespace android {
41namespace uirenderer {
42
43///////////////////////////////////////////////////////////////////////////////
44// Defines
45///////////////////////////////////////////////////////////////////////////////
46
47#define RAD_TO_DEG (180.0f / 3.14159265f)
48#define MIN_ANGLE 0.001f
49
50#define ALPHA_THRESHOLD 0
51
52#define FILTER(paint) (!paint || paint->isFilterBitmap() ? GL_LINEAR : GL_NEAREST)
53
54///////////////////////////////////////////////////////////////////////////////
55// Globals
56///////////////////////////////////////////////////////////////////////////////
57
58/**
59 * Structure mapping Skia xfermodes to OpenGL blending factors.
60 */
61struct Blender {
62    SkXfermode::Mode mode;
63    GLenum src;
64    GLenum dst;
65}; // struct Blender
66
67// In this array, the index of each Blender equals the value of the first
68// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
69static const Blender gBlends[] = {
70    { SkXfermode::kClear_Mode,    GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
71    { SkXfermode::kSrc_Mode,      GL_ONE,                 GL_ZERO },
72    { SkXfermode::kDst_Mode,      GL_ZERO,                GL_ONE },
73    { SkXfermode::kSrcOver_Mode,  GL_ONE,                 GL_ONE_MINUS_SRC_ALPHA },
74    { SkXfermode::kDstOver_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_ONE },
75    { SkXfermode::kSrcIn_Mode,    GL_DST_ALPHA,           GL_ZERO },
76    { SkXfermode::kDstIn_Mode,    GL_ZERO,                GL_SRC_ALPHA },
77    { SkXfermode::kSrcOut_Mode,   GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
78    { SkXfermode::kDstOut_Mode,   GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
79    { SkXfermode::kSrcATop_Mode,  GL_DST_ALPHA,           GL_ONE_MINUS_SRC_ALPHA },
80    { SkXfermode::kDstATop_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA },
81    { SkXfermode::kXor_Mode,      GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
82    { SkXfermode::kPlus_Mode,     GL_ONE,                 GL_ONE },
83    { SkXfermode::kMultiply_Mode, GL_ZERO,                GL_SRC_COLOR },
84    { SkXfermode::kScreen_Mode,   GL_ONE,                 GL_ONE_MINUS_SRC_COLOR }
85};
86
87// This array contains the swapped version of each SkXfermode. For instance
88// this array's SrcOver blending mode is actually DstOver. You can refer to
89// createLayer() for more information on the purpose of this array.
90static const Blender gBlendsSwap[] = {
91    { SkXfermode::kClear_Mode,    GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
92    { SkXfermode::kSrc_Mode,      GL_ZERO,                GL_ONE },
93    { SkXfermode::kDst_Mode,      GL_ONE,                 GL_ZERO },
94    { SkXfermode::kSrcOver_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_ONE },
95    { SkXfermode::kDstOver_Mode,  GL_ONE,                 GL_ONE_MINUS_SRC_ALPHA },
96    { SkXfermode::kSrcIn_Mode,    GL_ZERO,                GL_SRC_ALPHA },
97    { SkXfermode::kDstIn_Mode,    GL_DST_ALPHA,           GL_ZERO },
98    { SkXfermode::kSrcOut_Mode,   GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
99    { SkXfermode::kDstOut_Mode,   GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
100    { SkXfermode::kSrcATop_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA },
101    { SkXfermode::kDstATop_Mode,  GL_DST_ALPHA,           GL_ONE_MINUS_SRC_ALPHA },
102    { SkXfermode::kXor_Mode,      GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
103    { SkXfermode::kPlus_Mode,     GL_ONE,                 GL_ONE },
104    { SkXfermode::kMultiply_Mode, GL_DST_COLOR,           GL_ZERO },
105    { SkXfermode::kScreen_Mode,   GL_ONE_MINUS_DST_COLOR, GL_ONE }
106};
107
108///////////////////////////////////////////////////////////////////////////////
109// Constructors/destructor
110///////////////////////////////////////////////////////////////////////////////
111
112OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
113    mShader = NULL;
114    mColorFilter = NULL;
115    mHasShadow = false;
116    mHasDrawFilter = false;
117
118    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
119
120    mFirstSnapshot = new Snapshot;
121
122    mScissorOptimizationDisabled = false;
123}
124
125OpenGLRenderer::~OpenGLRenderer() {
126    // The context has already been destroyed at this point, do not call
127    // GL APIs. All GL state should be kept in Caches.h
128}
129
130void OpenGLRenderer::initProperties() {
131    char property[PROPERTY_VALUE_MAX];
132    if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) {
133        mScissorOptimizationDisabled = !strcasecmp(property, "true");
134        INIT_LOGD("  Scissor optimization %s",
135                mScissorOptimizationDisabled ? "disabled" : "enabled");
136    } else {
137        INIT_LOGD("  Scissor optimization enabled");
138    }
139}
140
141///////////////////////////////////////////////////////////////////////////////
142// Setup
143///////////////////////////////////////////////////////////////////////////////
144
145bool OpenGLRenderer::isDeferred() {
146    return false;
147}
148
149void OpenGLRenderer::setViewport(int width, int height) {
150    initViewport(width, height);
151
152    glDisable(GL_DITHER);
153    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
154
155    glEnableVertexAttribArray(Program::kBindingPosition);
156}
157
158void OpenGLRenderer::initViewport(int width, int height) {
159    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
160
161    mWidth = width;
162    mHeight = height;
163
164    mFirstSnapshot->height = height;
165    mFirstSnapshot->viewport.set(0, 0, width, height);
166}
167
168int OpenGLRenderer::prepare(bool opaque) {
169    return prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
170}
171
172int OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom, bool opaque) {
173    mCaches.clearGarbage();
174
175    mSnapshot = new Snapshot(mFirstSnapshot,
176            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
177    mSnapshot->fbo = getTargetFbo();
178    mSaveCount = 1;
179
180    mSnapshot->setClip(left, top, right, bottom);
181    mDirtyClip = opaque;
182
183    updateLayers();
184
185    // If we know that we are going to redraw the entire framebuffer,
186    // perform a discard to let the driver know we don't need to preserve
187    // the back buffer for this frame.
188    if (mCaches.extensions.hasDiscardFramebuffer() &&
189            left <= 0.0f && top <= 0.0f && right >= mWidth && bottom >= mHeight) {
190        const GLenum attachments[] = { getTargetFbo() == 0 ? GL_COLOR_EXT : GL_COLOR_ATTACHMENT0 };
191        glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
192    }
193
194    syncState();
195
196    // Functors break the tiling extension in pretty spectacular ways
197    // This ensures we don't use tiling when a functor is going to be
198    // invoked during the frame
199    mSuppressTiling = mCaches.hasRegisteredFunctors();
200
201    mTilingSnapshot = mSnapshot;
202    startTiling(mTilingSnapshot, true);
203
204    debugOverdraw(true, true);
205
206    if (!opaque) {
207        mCaches.enableScissor();
208        mCaches.setScissor(left, mSnapshot->height - bottom, right - left, bottom - top);
209        glClear(GL_COLOR_BUFFER_BIT);
210        return DrawGlInfo::kStatusDrew;
211    } else {
212        mCaches.resetScissor();
213    }
214
215    return DrawGlInfo::kStatusDone;
216}
217
218void OpenGLRenderer::syncState() {
219    glViewport(0, 0, mWidth, mHeight);
220
221    if (mCaches.blend) {
222        glEnable(GL_BLEND);
223    } else {
224        glDisable(GL_BLEND);
225    }
226}
227
228void OpenGLRenderer::startTiling(const sp<Snapshot>& s, bool opaque) {
229    if (!mSuppressTiling) {
230        Rect* clip = mTilingSnapshot->clipRect;
231        if (s->flags & Snapshot::kFlagIsFboLayer) {
232            clip = s->clipRect;
233        }
234
235        mCaches.startTiling(clip->left, s->height - clip->bottom,
236                clip->right - clip->left, clip->bottom - clip->top, opaque);
237    }
238}
239
240void OpenGLRenderer::endTiling() {
241    if (!mSuppressTiling) mCaches.endTiling();
242}
243
244void OpenGLRenderer::finish() {
245    renderOverdraw();
246    endTiling();
247
248    if (!suppressErrorChecks()) {
249#if DEBUG_OPENGL
250        GLenum status = GL_NO_ERROR;
251        while ((status = glGetError()) != GL_NO_ERROR) {
252            ALOGD("GL error from OpenGLRenderer: 0x%x", status);
253            switch (status) {
254                case GL_INVALID_ENUM:
255                    ALOGE("  GL_INVALID_ENUM");
256                    break;
257                case GL_INVALID_VALUE:
258                    ALOGE("  GL_INVALID_VALUE");
259                    break;
260                case GL_INVALID_OPERATION:
261                    ALOGE("  GL_INVALID_OPERATION");
262                    break;
263                case GL_OUT_OF_MEMORY:
264                    ALOGE("  Out of memory!");
265                    break;
266            }
267        }
268#endif
269
270#if DEBUG_MEMORY_USAGE
271        mCaches.dumpMemoryUsage();
272#else
273        if (mCaches.getDebugLevel() & kDebugMemory) {
274            mCaches.dumpMemoryUsage();
275        }
276#endif
277    }
278}
279
280void OpenGLRenderer::interrupt() {
281    if (mCaches.currentProgram) {
282        if (mCaches.currentProgram->isInUse()) {
283            mCaches.currentProgram->remove();
284            mCaches.currentProgram = NULL;
285        }
286    }
287    mCaches.unbindMeshBuffer();
288    mCaches.unbindIndicesBuffer();
289    mCaches.resetVertexPointers();
290    mCaches.disbaleTexCoordsVertexArray();
291    debugOverdraw(false, false);
292}
293
294void OpenGLRenderer::resume() {
295    sp<Snapshot> snapshot = (mSnapshot != NULL) ? mSnapshot : mFirstSnapshot;
296    glViewport(0, 0, snapshot->viewport.getWidth(), snapshot->viewport.getHeight());
297    glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo);
298    debugOverdraw(true, false);
299
300    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
301
302    mCaches.scissorEnabled = glIsEnabled(GL_SCISSOR_TEST);
303    mCaches.enableScissor();
304    mCaches.resetScissor();
305    dirtyClip();
306
307    mCaches.activeTexture(0);
308
309    mCaches.blend = true;
310    glEnable(GL_BLEND);
311    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
312    glBlendEquation(GL_FUNC_ADD);
313}
314
315void OpenGLRenderer::resumeAfterLayer() {
316    sp<Snapshot> snapshot = (mSnapshot != NULL) ? mSnapshot : mFirstSnapshot;
317    glViewport(0, 0, snapshot->viewport.getWidth(), snapshot->viewport.getHeight());
318    glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo);
319    debugOverdraw(true, false);
320
321    mCaches.resetScissor();
322    dirtyClip();
323}
324
325void OpenGLRenderer::detachFunctor(Functor* functor) {
326    mFunctors.remove(functor);
327}
328
329void OpenGLRenderer::attachFunctor(Functor* functor) {
330    mFunctors.add(functor);
331}
332
333status_t OpenGLRenderer::invokeFunctors(Rect& dirty) {
334    status_t result = DrawGlInfo::kStatusDone;
335    size_t count = mFunctors.size();
336
337    if (count > 0) {
338        SortedVector<Functor*> functors(mFunctors);
339        mFunctors.clear();
340
341        DrawGlInfo info;
342        info.clipLeft = 0;
343        info.clipTop = 0;
344        info.clipRight = 0;
345        info.clipBottom = 0;
346        info.isLayer = false;
347        info.width = 0;
348        info.height = 0;
349        memset(info.transform, 0, sizeof(float) * 16);
350
351        for (size_t i = 0; i < count; i++) {
352            Functor* f = functors.itemAt(i);
353            result |= (*f)(DrawGlInfo::kModeProcess, &info);
354
355            if (result & DrawGlInfo::kStatusDraw) {
356                Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
357                dirty.unionWith(localDirty);
358            }
359
360            if (result & DrawGlInfo::kStatusInvoke) {
361                mFunctors.add(f);
362            }
363        }
364        // protect against functors binding to other buffers
365        mCaches.unbindMeshBuffer();
366        mCaches.unbindIndicesBuffer();
367        mCaches.activeTexture(0);
368    }
369
370    return result;
371}
372
373status_t OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) {
374    interrupt();
375    detachFunctor(functor);
376
377    mCaches.enableScissor();
378    if (mDirtyClip) {
379        setScissorFromClip();
380    }
381
382    Rect clip(*mSnapshot->clipRect);
383    clip.snapToPixelBoundaries();
384
385    // Since we don't know what the functor will draw, let's dirty
386    // tne entire clip region
387    if (hasLayer()) {
388        dirtyLayerUnchecked(clip, getRegion());
389    }
390
391    DrawGlInfo info;
392    info.clipLeft = clip.left;
393    info.clipTop = clip.top;
394    info.clipRight = clip.right;
395    info.clipBottom = clip.bottom;
396    info.isLayer = hasLayer();
397    info.width = getSnapshot()->viewport.getWidth();
398    info.height = getSnapshot()->height;
399    getSnapshot()->transform->copyTo(&info.transform[0]);
400
401    status_t result = (*functor)(DrawGlInfo::kModeDraw, &info) | DrawGlInfo::kStatusDrew;
402
403    if (result != DrawGlInfo::kStatusDone) {
404        Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
405        dirty.unionWith(localDirty);
406
407        if (result & DrawGlInfo::kStatusInvoke) {
408            mFunctors.add(functor);
409        }
410    }
411
412    resume();
413    return result;
414}
415
416///////////////////////////////////////////////////////////////////////////////
417// Debug
418///////////////////////////////////////////////////////////////////////////////
419
420void OpenGLRenderer::startMark(const char* name) const {
421    mCaches.startMark(0, name);
422}
423
424void OpenGLRenderer::endMark() const {
425    mCaches.endMark();
426}
427
428void OpenGLRenderer::debugOverdraw(bool enable, bool clear) {
429    if (mCaches.debugOverdraw && getTargetFbo() == 0) {
430        if (clear) {
431            mCaches.disableScissor();
432            mCaches.stencil.clear();
433        }
434        if (enable) {
435            mCaches.stencil.enableDebugWrite();
436        } else {
437            mCaches.stencil.disable();
438        }
439    }
440}
441
442void OpenGLRenderer::renderOverdraw() {
443    if (mCaches.debugOverdraw && getTargetFbo() == 0) {
444        const Rect* clip = mTilingSnapshot->clipRect;
445
446        mCaches.enableScissor();
447        mCaches.setScissor(clip->left, mTilingSnapshot->height - clip->bottom,
448                clip->right - clip->left, clip->bottom - clip->top);
449
450        mCaches.stencil.enableDebugTest(2);
451        drawColor(0x2f0000ff, SkXfermode::kSrcOver_Mode);
452        mCaches.stencil.enableDebugTest(3);
453        drawColor(0x2f00ff00, SkXfermode::kSrcOver_Mode);
454        mCaches.stencil.enableDebugTest(4);
455        drawColor(0x3fff0000, SkXfermode::kSrcOver_Mode);
456        mCaches.stencil.enableDebugTest(4, true);
457        drawColor(0x7fff0000, SkXfermode::kSrcOver_Mode);
458        mCaches.stencil.disable();
459    }
460}
461
462///////////////////////////////////////////////////////////////////////////////
463// Layers
464///////////////////////////////////////////////////////////////////////////////
465
466bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) {
467    if (layer->deferredUpdateScheduled && layer->renderer && layer->displayList) {
468        OpenGLRenderer* renderer = layer->renderer;
469        Rect& dirty = layer->dirtyRect;
470
471        if (inFrame) {
472            endTiling();
473            debugOverdraw(false, false);
474        }
475
476        renderer->setViewport(layer->layer.getWidth(), layer->layer.getHeight());
477        renderer->prepareDirty(dirty.left, dirty.top, dirty.right, dirty.bottom, !layer->isBlend());
478        renderer->drawDisplayList(layer->displayList, dirty, DisplayList::kReplayFlag_ClipChildren);
479        renderer->finish();
480
481        if (inFrame) {
482            resumeAfterLayer();
483            startTiling(mSnapshot);
484        }
485
486        dirty.setEmpty();
487        layer->deferredUpdateScheduled = false;
488        layer->renderer = NULL;
489        layer->displayList = NULL;
490
491        return true;
492    }
493
494    return false;
495}
496
497void OpenGLRenderer::updateLayers() {
498    int count = mLayerUpdates.size();
499    if (count > 0) {
500        startMark("Layer Updates");
501
502        // Note: it is very important to update the layers in reverse order
503        for (int i = count - 1; i >= 0; i--) {
504            Layer* layer = mLayerUpdates.itemAt(i);
505            updateLayer(layer, false);
506            mCaches.resourceCache.decrementRefcount(layer);
507        }
508        mLayerUpdates.clear();
509
510        glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo());
511        endMark();
512    }
513}
514
515void OpenGLRenderer::pushLayerUpdate(Layer* layer) {
516    if (layer) {
517        mLayerUpdates.push_back(layer);
518        mCaches.resourceCache.incrementRefcount(layer);
519    }
520}
521
522void OpenGLRenderer::clearLayerUpdates() {
523    size_t count = mLayerUpdates.size();
524    if (count > 0) {
525        mCaches.resourceCache.lock();
526        for (size_t i = 0; i < count; i++) {
527            mCaches.resourceCache.decrementRefcountLocked(mLayerUpdates.itemAt(i));
528        }
529        mCaches.resourceCache.unlock();
530        mLayerUpdates.clear();
531    }
532}
533
534///////////////////////////////////////////////////////////////////////////////
535// State management
536///////////////////////////////////////////////////////////////////////////////
537
538int OpenGLRenderer::getSaveCount() const {
539    return mSaveCount;
540}
541
542int OpenGLRenderer::save(int flags) {
543    return saveSnapshot(flags);
544}
545
546void OpenGLRenderer::restore() {
547    if (mSaveCount > 1) {
548        restoreSnapshot();
549    }
550}
551
552void OpenGLRenderer::restoreToCount(int saveCount) {
553    if (saveCount < 1) saveCount = 1;
554
555    while (mSaveCount > saveCount) {
556        restoreSnapshot();
557    }
558}
559
560int OpenGLRenderer::saveSnapshot(int flags) {
561    mSnapshot = new Snapshot(mSnapshot, flags);
562    return mSaveCount++;
563}
564
565bool OpenGLRenderer::restoreSnapshot() {
566    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
567    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
568    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
569
570    sp<Snapshot> current = mSnapshot;
571    sp<Snapshot> previous = mSnapshot->previous;
572
573    if (restoreOrtho) {
574        Rect& r = previous->viewport;
575        glViewport(r.left, r.top, r.right, r.bottom);
576        mOrthoMatrix.load(current->orthoMatrix);
577    }
578
579    mSaveCount--;
580    mSnapshot = previous;
581
582    if (restoreClip) {
583        dirtyClip();
584    }
585
586    if (restoreLayer) {
587        composeLayer(current, previous);
588    }
589
590    return restoreClip;
591}
592
593///////////////////////////////////////////////////////////////////////////////
594// Layers
595///////////////////////////////////////////////////////////////////////////////
596
597int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
598        SkPaint* p, int flags) {
599    const GLuint previousFbo = mSnapshot->fbo;
600    const int count = saveSnapshot(flags);
601
602    if (!mSnapshot->isIgnored()) {
603        int alpha = 255;
604        SkXfermode::Mode mode;
605
606        if (p) {
607            alpha = p->getAlpha();
608            mode = getXfermode(p->getXfermode());
609        } else {
610            mode = SkXfermode::kSrcOver_Mode;
611        }
612
613        createLayer(left, top, right, bottom, alpha, mode, flags, previousFbo);
614    }
615
616    return count;
617}
618
619int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
620        int alpha, int flags) {
621    if (alpha >= 255) {
622        return saveLayer(left, top, right, bottom, NULL, flags);
623    } else {
624        SkPaint paint;
625        paint.setAlpha(alpha);
626        return saveLayer(left, top, right, bottom, &paint, flags);
627    }
628}
629
630/**
631 * Layers are viewed by Skia are slightly different than layers in image editing
632 * programs (for instance.) When a layer is created, previously created layers
633 * and the frame buffer still receive every drawing command. For instance, if a
634 * layer is created and a shape intersecting the bounds of the layers and the
635 * framebuffer is draw, the shape will be drawn on both (unless the layer was
636 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
637 *
638 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
639 * texture. Unfortunately, this is inefficient as it requires every primitive to
640 * be drawn n + 1 times, where n is the number of active layers. In practice this
641 * means, for every primitive:
642 *   - Switch active frame buffer
643 *   - Change viewport, clip and projection matrix
644 *   - Issue the drawing
645 *
646 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
647 * To avoid this, layers are implemented in a different way here, at least in the
648 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
649 * is set. When this flag is set we can redirect all drawing operations into a
650 * single FBO.
651 *
652 * This implementation relies on the frame buffer being at least RGBA 8888. When
653 * a layer is created, only a texture is created, not an FBO. The content of the
654 * frame buffer contained within the layer's bounds is copied into this texture
655 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
656 * buffer and drawing continues as normal. This technique therefore treats the
657 * frame buffer as a scratch buffer for the layers.
658 *
659 * To compose the layers back onto the frame buffer, each layer texture
660 * (containing the original frame buffer data) is drawn as a simple quad over
661 * the frame buffer. The trick is that the quad is set as the composition
662 * destination in the blending equation, and the frame buffer becomes the source
663 * of the composition.
664 *
665 * Drawing layers with an alpha value requires an extra step before composition.
666 * An empty quad is drawn over the layer's region in the frame buffer. This quad
667 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
668 * quad is used to multiply the colors in the frame buffer. This is achieved by
669 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
670 * GL_ZERO, GL_SRC_ALPHA.
671 *
672 * Because glCopyTexImage2D() can be slow, an alternative implementation might
673 * be use to draw a single clipped layer. The implementation described above
674 * is correct in every case.
675 *
676 * (1) The frame buffer is actually not cleared right away. To allow the GPU
677 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
678 *     buffer is left untouched until the first drawing operation. Only when
679 *     something actually gets drawn are the layers regions cleared.
680 */
681bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom,
682        int alpha, SkXfermode::Mode mode, int flags, GLuint previousFbo) {
683    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
684    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
685
686    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
687
688    // Window coordinates of the layer
689    Rect clip;
690    Rect bounds(left, top, right, bottom);
691    Rect untransformedBounds(bounds);
692    mSnapshot->transform->mapRect(bounds);
693
694    // Layers only make sense if they are in the framebuffer's bounds
695    if (bounds.intersect(*mSnapshot->clipRect)) {
696        // We cannot work with sub-pixels in this case
697        bounds.snapToPixelBoundaries();
698
699        // When the layer is not an FBO, we may use glCopyTexImage so we
700        // need to make sure the layer does not extend outside the bounds
701        // of the framebuffer
702        if (!bounds.intersect(mSnapshot->previous->viewport)) {
703            bounds.setEmpty();
704        } else if (fboLayer) {
705            clip.set(bounds);
706            mat4 inverse;
707            inverse.loadInverse(*mSnapshot->transform);
708            inverse.mapRect(clip);
709            clip.snapToPixelBoundaries();
710            if (clip.intersect(untransformedBounds)) {
711                clip.translate(-left, -top);
712                bounds.set(untransformedBounds);
713            } else {
714                clip.setEmpty();
715            }
716        }
717    } else {
718        bounds.setEmpty();
719    }
720
721    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
722            bounds.getHeight() > mCaches.maxTextureSize ||
723            (fboLayer && clip.isEmpty())) {
724        mSnapshot->empty = fboLayer;
725    } else {
726        mSnapshot->invisible = mSnapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
727    }
728
729    // Bail out if we won't draw in this snapshot
730    if (mSnapshot->invisible || mSnapshot->empty) {
731        return false;
732    }
733
734    mCaches.activeTexture(0);
735    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
736    if (!layer) {
737        return false;
738    }
739
740    layer->setAlpha(alpha, mode);
741    layer->layer.set(bounds);
742    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()),
743            bounds.getWidth() / float(layer->getWidth()), 0.0f);
744    layer->setColorFilter(mColorFilter);
745    layer->setBlend(true);
746
747    // Save the layer in the snapshot
748    mSnapshot->flags |= Snapshot::kFlagIsLayer;
749    mSnapshot->layer = layer;
750
751    if (fboLayer) {
752        return createFboLayer(layer, bounds, clip, previousFbo);
753    } else {
754        // Copy the framebuffer into the layer
755        layer->bindTexture();
756        if (!bounds.isEmpty()) {
757            if (layer->isEmpty()) {
758                glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
759                        bounds.left, mSnapshot->height - bounds.bottom,
760                        layer->getWidth(), layer->getHeight(), 0);
761                layer->setEmpty(false);
762            } else {
763                glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
764                        mSnapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
765            }
766
767            // Enqueue the buffer coordinates to clear the corresponding region later
768            mLayers.push(new Rect(bounds));
769        }
770    }
771
772    return true;
773}
774
775bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip, GLuint previousFbo) {
776    layer->setFbo(mCaches.fboCache.get());
777
778    mSnapshot->region = &mSnapshot->layer->region;
779    mSnapshot->flags |= Snapshot::kFlagFboTarget;
780
781    mSnapshot->flags |= Snapshot::kFlagIsFboLayer;
782    mSnapshot->fbo = layer->getFbo();
783    mSnapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
784    mSnapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
785    mSnapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
786    mSnapshot->height = bounds.getHeight();
787    mSnapshot->flags |= Snapshot::kFlagDirtyOrtho;
788    mSnapshot->orthoMatrix.load(mOrthoMatrix);
789
790    endTiling();
791    debugOverdraw(false, false);
792    // Bind texture to FBO
793    glBindFramebuffer(GL_FRAMEBUFFER, layer->getFbo());
794    layer->bindTexture();
795
796    // Initialize the texture if needed
797    if (layer->isEmpty()) {
798        layer->allocateTexture(GL_RGBA, GL_UNSIGNED_BYTE);
799        layer->setEmpty(false);
800    }
801
802    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
803            layer->getTexture(), 0);
804
805    startTiling(mSnapshot);
806
807    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
808    mCaches.enableScissor();
809    mCaches.setScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
810            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
811    glClear(GL_COLOR_BUFFER_BIT);
812
813    dirtyClip();
814
815    // Change the ortho projection
816    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
817    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
818
819    return true;
820}
821
822/**
823 * Read the documentation of createLayer() before doing anything in this method.
824 */
825void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
826    if (!current->layer) {
827        ALOGE("Attempting to compose a layer that does not exist");
828        return;
829    }
830
831    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
832
833    if (fboLayer) {
834        endTiling();
835
836        // Detach the texture from the FBO
837        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
838        // Unbind current FBO and restore previous one
839        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
840        debugOverdraw(true, false);
841
842        startTiling(previous);
843    }
844
845    Layer* layer = current->layer;
846    const Rect& rect = layer->layer;
847
848    if (!fboLayer && layer->getAlpha() < 255) {
849        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
850                layer->getAlpha() << 24, SkXfermode::kDstIn_Mode, true);
851        // Required below, composeLayerRect() will divide by 255
852        layer->setAlpha(255);
853    }
854
855    mCaches.unbindMeshBuffer();
856
857    mCaches.activeTexture(0);
858
859    // When the layer is stored in an FBO, we can save a bit of fillrate by
860    // drawing only the dirty region
861    if (fboLayer) {
862        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
863        if (layer->getColorFilter()) {
864            setupColorFilter(layer->getColorFilter());
865        }
866        composeLayerRegion(layer, rect);
867        if (layer->getColorFilter()) {
868            resetColorFilter();
869        }
870    } else if (!rect.isEmpty()) {
871        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
872        composeLayerRect(layer, rect, true);
873    }
874
875    if (fboLayer) {
876        // Note: No need to use glDiscardFramebufferEXT() since we never
877        //       create/compose layers that are not on screen with this
878        //       code path
879        // See LayerRenderer::destroyLayer(Layer*)
880
881        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
882        mCaches.fboCache.put(current->fbo);
883        layer->setFbo(0);
884    }
885
886    dirtyClip();
887
888    // Failing to add the layer to the cache should happen only if the layer is too large
889    if (!mCaches.layerCache.put(layer)) {
890        LAYER_LOGD("Deleting layer");
891        Caches::getInstance().resourceCache.decrementRefcount(layer);
892    }
893}
894
895void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
896    float alpha = layer->getAlpha() / 255.0f;
897
898    setupDraw();
899    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
900        setupDrawWithTexture();
901    } else {
902        setupDrawWithExternalTexture();
903    }
904    setupDrawTextureTransform();
905    setupDrawColor(alpha, alpha, alpha, alpha);
906    setupDrawColorFilter();
907    setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode());
908    setupDrawProgram();
909    setupDrawPureColorUniforms();
910    setupDrawColorFilterUniforms();
911    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
912        setupDrawTexture(layer->getTexture());
913    } else {
914        setupDrawExternalTexture(layer->getTexture());
915    }
916    if (mSnapshot->transform->isPureTranslate() &&
917            layer->getWidth() == (uint32_t) rect.getWidth() &&
918            layer->getHeight() == (uint32_t) rect.getHeight()) {
919        const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
920        const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
921
922        layer->setFilter(GL_NEAREST);
923        setupDrawModelView(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
924    } else {
925        layer->setFilter(GL_LINEAR);
926        setupDrawModelView(rect.left, rect.top, rect.right, rect.bottom);
927    }
928    setupDrawTextureTransformUniforms(layer->getTexTransform());
929    setupDrawMesh(&mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
930
931    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
932
933    finishDrawTexture();
934}
935
936void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
937    if (!layer->isTextureLayer()) {
938        const Rect& texCoords = layer->texCoords;
939        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
940                texCoords.right, texCoords.bottom);
941
942        float x = rect.left;
943        float y = rect.top;
944        bool simpleTransform = mSnapshot->transform->isPureTranslate() &&
945                layer->getWidth() == (uint32_t) rect.getWidth() &&
946                layer->getHeight() == (uint32_t) rect.getHeight();
947
948        if (simpleTransform) {
949            // When we're swapping, the layer is already in screen coordinates
950            if (!swap) {
951                x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
952                y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
953            }
954
955            layer->setFilter(GL_NEAREST, true);
956        } else {
957            layer->setFilter(GL_LINEAR, true);
958        }
959
960        drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(),
961                layer->getTexture(), layer->getAlpha() / 255.0f,
962                layer->getMode(), layer->isBlend(),
963                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
964                GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform);
965
966        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
967    } else {
968        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
969        drawTextureLayer(layer, rect);
970        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
971    }
972}
973
974void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
975    if (layer->region.isRect()) {
976        layer->setRegionAsRect();
977
978        composeLayerRect(layer, layer->regionRect);
979
980        layer->region.clear();
981        return;
982    }
983
984    // TODO: See LayerRenderer.cpp::generateMesh() for important
985    //       information about this implementation
986    if (CC_LIKELY(!layer->region.isEmpty())) {
987        size_t count;
988        const android::Rect* rects = layer->region.getArray(&count);
989
990        const float alpha = layer->getAlpha() / 255.0f;
991        const float texX = 1.0f / float(layer->getWidth());
992        const float texY = 1.0f / float(layer->getHeight());
993        const float height = rect.getHeight();
994
995        TextureVertex* mesh = mCaches.getRegionMesh();
996        GLsizei numQuads = 0;
997
998        setupDraw();
999        setupDrawWithTexture();
1000        setupDrawColor(alpha, alpha, alpha, alpha);
1001        setupDrawColorFilter();
1002        setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode(), false);
1003        setupDrawProgram();
1004        setupDrawDirtyRegionsDisabled();
1005        setupDrawPureColorUniforms();
1006        setupDrawColorFilterUniforms();
1007        setupDrawTexture(layer->getTexture());
1008        if (mSnapshot->transform->isPureTranslate()) {
1009            const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
1010            const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
1011
1012            layer->setFilter(GL_NEAREST);
1013            setupDrawModelViewTranslate(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1014        } else {
1015            layer->setFilter(GL_LINEAR);
1016            setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
1017        }
1018        setupDrawMeshIndices(&mesh[0].position[0], &mesh[0].texture[0]);
1019
1020        for (size_t i = 0; i < count; i++) {
1021            const android::Rect* r = &rects[i];
1022
1023            const float u1 = r->left * texX;
1024            const float v1 = (height - r->top) * texY;
1025            const float u2 = r->right * texX;
1026            const float v2 = (height - r->bottom) * texY;
1027
1028            // TODO: Reject quads outside of the clip
1029            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
1030            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
1031            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
1032            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
1033
1034            numQuads++;
1035
1036            if (numQuads >= REGION_MESH_QUAD_COUNT) {
1037                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
1038                numQuads = 0;
1039                mesh = mCaches.getRegionMesh();
1040            }
1041        }
1042
1043        if (numQuads > 0) {
1044            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
1045        }
1046
1047        finishDrawTexture();
1048
1049#if DEBUG_LAYERS_AS_REGIONS
1050        drawRegionRects(layer->region);
1051#endif
1052
1053        layer->region.clear();
1054    }
1055}
1056
1057void OpenGLRenderer::drawRegionRects(const Region& region) {
1058#if DEBUG_LAYERS_AS_REGIONS
1059    size_t count;
1060    const android::Rect* rects = region.getArray(&count);
1061
1062    uint32_t colors[] = {
1063            0x7fff0000, 0x7f00ff00,
1064            0x7f0000ff, 0x7fff00ff,
1065    };
1066
1067    int offset = 0;
1068    int32_t top = rects[0].top;
1069
1070    for (size_t i = 0; i < count; i++) {
1071        if (top != rects[i].top) {
1072            offset ^= 0x2;
1073            top = rects[i].top;
1074        }
1075
1076        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1077        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
1078                SkXfermode::kSrcOver_Mode);
1079    }
1080#endif
1081}
1082
1083void OpenGLRenderer::dirtyLayer(const float left, const float top,
1084        const float right, const float bottom, const mat4 transform) {
1085    if (hasLayer()) {
1086        Rect bounds(left, top, right, bottom);
1087        transform.mapRect(bounds);
1088        dirtyLayerUnchecked(bounds, getRegion());
1089    }
1090}
1091
1092void OpenGLRenderer::dirtyLayer(const float left, const float top,
1093        const float right, const float bottom) {
1094    if (hasLayer()) {
1095        Rect bounds(left, top, right, bottom);
1096        dirtyLayerUnchecked(bounds, getRegion());
1097    }
1098}
1099
1100void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1101    if (bounds.intersect(*mSnapshot->clipRect)) {
1102        bounds.snapToPixelBoundaries();
1103        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1104        if (!dirty.isEmpty()) {
1105            region->orSelf(dirty);
1106        }
1107    }
1108}
1109
1110void OpenGLRenderer::clearLayerRegions() {
1111    const size_t count = mLayers.size();
1112    if (count == 0) return;
1113
1114    if (!mSnapshot->isIgnored()) {
1115        // Doing several glScissor/glClear here can negatively impact
1116        // GPUs with a tiler architecture, instead we draw quads with
1117        // the Clear blending mode
1118
1119        // The list contains bounds that have already been clipped
1120        // against their initial clip rect, and the current clip
1121        // is likely different so we need to disable clipping here
1122        bool scissorChanged = mCaches.disableScissor();
1123
1124        Vertex mesh[count * 6];
1125        Vertex* vertex = mesh;
1126
1127        for (uint32_t i = 0; i < count; i++) {
1128            Rect* bounds = mLayers.itemAt(i);
1129
1130            Vertex::set(vertex++, bounds->left, bounds->bottom);
1131            Vertex::set(vertex++, bounds->left, bounds->top);
1132            Vertex::set(vertex++, bounds->right, bounds->top);
1133            Vertex::set(vertex++, bounds->left, bounds->bottom);
1134            Vertex::set(vertex++, bounds->right, bounds->top);
1135            Vertex::set(vertex++, bounds->right, bounds->bottom);
1136
1137            delete bounds;
1138        }
1139
1140        setupDraw(false);
1141        setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
1142        setupDrawBlending(true, SkXfermode::kClear_Mode);
1143        setupDrawProgram();
1144        setupDrawPureColorUniforms();
1145        setupDrawModelViewTranslate(0.0f, 0.0f, 0.0f, 0.0f, true);
1146        setupDrawVertices(&mesh[0].position[0]);
1147
1148        glDrawArrays(GL_TRIANGLES, 0, count * 6);
1149
1150        if (scissorChanged) mCaches.enableScissor();
1151    } else {
1152        for (uint32_t i = 0; i < count; i++) {
1153            delete mLayers.itemAt(i);
1154        }
1155    }
1156
1157    mLayers.clear();
1158}
1159
1160///////////////////////////////////////////////////////////////////////////////
1161// Transforms
1162///////////////////////////////////////////////////////////////////////////////
1163
1164void OpenGLRenderer::translate(float dx, float dy) {
1165    mSnapshot->transform->translate(dx, dy, 0.0f);
1166}
1167
1168void OpenGLRenderer::rotate(float degrees) {
1169    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
1170}
1171
1172void OpenGLRenderer::scale(float sx, float sy) {
1173    mSnapshot->transform->scale(sx, sy, 1.0f);
1174}
1175
1176void OpenGLRenderer::skew(float sx, float sy) {
1177    mSnapshot->transform->skew(sx, sy);
1178}
1179
1180void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
1181    if (matrix) {
1182        mSnapshot->transform->load(*matrix);
1183    } else {
1184        mSnapshot->transform->loadIdentity();
1185    }
1186}
1187
1188void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
1189    mSnapshot->transform->copyTo(*matrix);
1190}
1191
1192void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
1193    SkMatrix transform;
1194    mSnapshot->transform->copyTo(transform);
1195    transform.preConcat(*matrix);
1196    mSnapshot->transform->load(transform);
1197}
1198
1199///////////////////////////////////////////////////////////////////////////////
1200// Clipping
1201///////////////////////////////////////////////////////////////////////////////
1202
1203void OpenGLRenderer::setScissorFromClip() {
1204    Rect clip(*mSnapshot->clipRect);
1205    clip.snapToPixelBoundaries();
1206
1207    if (mCaches.setScissor(clip.left, mSnapshot->height - clip.bottom,
1208            clip.getWidth(), clip.getHeight())) {
1209        mDirtyClip = false;
1210    }
1211}
1212
1213const Rect& OpenGLRenderer::getClipBounds() {
1214    return mSnapshot->getLocalClip();
1215}
1216
1217bool OpenGLRenderer::quickRejectNoScissor(float left, float top, float right, float bottom) {
1218    if (mSnapshot->isIgnored()) {
1219        return true;
1220    }
1221
1222    Rect r(left, top, right, bottom);
1223    mSnapshot->transform->mapRect(r);
1224    r.snapToPixelBoundaries();
1225
1226    Rect clipRect(*mSnapshot->clipRect);
1227    clipRect.snapToPixelBoundaries();
1228
1229    return !clipRect.intersects(r);
1230}
1231
1232bool OpenGLRenderer::quickRejectNoScissor(float left, float top, float right, float bottom,
1233        Rect& transformed, Rect& clip) {
1234    if (mSnapshot->isIgnored()) {
1235        return true;
1236    }
1237
1238    transformed.set(left, top, right, bottom);
1239    mSnapshot->transform->mapRect(transformed);
1240    transformed.snapToPixelBoundaries();
1241
1242    clip.set(*mSnapshot->clipRect);
1243    clip.snapToPixelBoundaries();
1244
1245    return !clip.intersects(transformed);
1246}
1247
1248bool OpenGLRenderer::quickRejectPreStroke(float left, float top, float right, float bottom, SkPaint* paint) {
1249    if (paint->getStyle() != SkPaint::kFill_Style) {
1250        float outset = paint->getStrokeWidth() * 0.5f;
1251        return quickReject(left - outset, top - outset, right + outset, bottom + outset);
1252    } else {
1253        return quickReject(left, top, right, bottom);
1254    }
1255}
1256
1257bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
1258    if (mSnapshot->isIgnored() || bottom <= top || right <= left) {
1259        return true;
1260    }
1261
1262    Rect r(left, top, right, bottom);
1263    mSnapshot->transform->mapRect(r);
1264    r.snapToPixelBoundaries();
1265
1266    Rect clipRect(*mSnapshot->clipRect);
1267    clipRect.snapToPixelBoundaries();
1268
1269    bool rejected = !clipRect.intersects(r);
1270    if (!isDeferred() && !rejected) {
1271        mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clipRect.contains(r));
1272    }
1273
1274    return rejected;
1275}
1276
1277bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
1278    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
1279    if (clipped) {
1280        dirtyClip();
1281    }
1282    return !mSnapshot->clipRect->isEmpty();
1283}
1284
1285Rect* OpenGLRenderer::getClipRect() {
1286    return mSnapshot->clipRect;
1287}
1288
1289///////////////////////////////////////////////////////////////////////////////
1290// Drawing commands
1291///////////////////////////////////////////////////////////////////////////////
1292
1293void OpenGLRenderer::setupDraw(bool clear) {
1294    // TODO: It would be best if we could do this before quickReject()
1295    //       changes the scissor test state
1296    if (clear) clearLayerRegions();
1297    if (mDirtyClip) {
1298        setScissorFromClip();
1299    }
1300    mDescription.reset();
1301    mSetShaderColor = false;
1302    mColorSet = false;
1303    mColorA = mColorR = mColorG = mColorB = 0.0f;
1304    mTextureUnit = 0;
1305    mTrackDirtyRegions = true;
1306}
1307
1308void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1309    mDescription.hasTexture = true;
1310    mDescription.hasAlpha8Texture = isAlpha8;
1311}
1312
1313void OpenGLRenderer::setupDrawWithExternalTexture() {
1314    mDescription.hasExternalTexture = true;
1315}
1316
1317void OpenGLRenderer::setupDrawNoTexture() {
1318    mCaches.disbaleTexCoordsVertexArray();
1319}
1320
1321void OpenGLRenderer::setupDrawAA() {
1322    mDescription.isAA = true;
1323}
1324
1325void OpenGLRenderer::setupDrawVertexShape() {
1326    mDescription.isVertexShape = true;
1327}
1328
1329void OpenGLRenderer::setupDrawPoint(float pointSize) {
1330    mDescription.isPoint = true;
1331    mDescription.pointSize = pointSize;
1332}
1333
1334void OpenGLRenderer::setupDrawColor(int color) {
1335    setupDrawColor(color, (color >> 24) & 0xFF);
1336}
1337
1338void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1339    mColorA = alpha / 255.0f;
1340    // Second divide of a by 255 is an optimization, allowing us to simply multiply
1341    // the rgb values by a instead of also dividing by 255
1342    const float a = mColorA / 255.0f;
1343    mColorR = a * ((color >> 16) & 0xFF);
1344    mColorG = a * ((color >>  8) & 0xFF);
1345    mColorB = a * ((color      ) & 0xFF);
1346    mColorSet = true;
1347    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
1348}
1349
1350void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1351    mColorA = alpha / 255.0f;
1352    // Double-divide of a by 255 is an optimization, allowing us to simply multiply
1353    // the rgb values by a instead of also dividing by 255
1354    const float a = mColorA / 255.0f;
1355    mColorR = a * ((color >> 16) & 0xFF);
1356    mColorG = a * ((color >>  8) & 0xFF);
1357    mColorB = a * ((color      ) & 0xFF);
1358    mColorSet = true;
1359    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
1360}
1361
1362void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) {
1363    mCaches.fontRenderer->describe(mDescription, paint);
1364}
1365
1366void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1367    mColorA = a;
1368    mColorR = r;
1369    mColorG = g;
1370    mColorB = b;
1371    mColorSet = true;
1372    mSetShaderColor = mDescription.setColor(r, g, b, a);
1373}
1374
1375void OpenGLRenderer::setupDrawShader() {
1376    if (mShader) {
1377        mShader->describe(mDescription, mCaches.extensions);
1378    }
1379}
1380
1381void OpenGLRenderer::setupDrawColorFilter() {
1382    if (mColorFilter) {
1383        mColorFilter->describe(mDescription, mCaches.extensions);
1384    }
1385}
1386
1387void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1388    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1389        mColorA = 1.0f;
1390        mColorR = mColorG = mColorB = 0.0f;
1391        mSetShaderColor = mDescription.modulate = true;
1392    }
1393}
1394
1395void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
1396    // When the blending mode is kClear_Mode, we need to use a modulate color
1397    // argb=1,0,0,0
1398    accountForClear(mode);
1399    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1400            mDescription, swapSrcDst);
1401}
1402
1403void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
1404    // When the blending mode is kClear_Mode, we need to use a modulate color
1405    // argb=1,0,0,0
1406    accountForClear(mode);
1407    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()) ||
1408            (mColorFilter && mColorFilter->blend()), mode, mDescription, swapSrcDst);
1409}
1410
1411void OpenGLRenderer::setupDrawProgram() {
1412    useProgram(mCaches.programCache.get(mDescription));
1413}
1414
1415void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1416    mTrackDirtyRegions = false;
1417}
1418
1419void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
1420        bool ignoreTransform) {
1421    mModelView.loadTranslate(left, top, 0.0f);
1422    if (!ignoreTransform) {
1423        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1424        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1425    } else {
1426        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1427        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1428    }
1429}
1430
1431void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) {
1432    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset);
1433}
1434
1435void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
1436        bool ignoreTransform, bool ignoreModelView) {
1437    if (!ignoreModelView) {
1438        mModelView.loadTranslate(left, top, 0.0f);
1439        mModelView.scale(right - left, bottom - top, 1.0f);
1440    } else {
1441        mModelView.loadIdentity();
1442    }
1443    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1444    if (!ignoreTransform) {
1445        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1446        if (mTrackDirtyRegions && dirty) {
1447            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1448        }
1449    } else {
1450        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1451        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1452    }
1453}
1454
1455void OpenGLRenderer::setupDrawPointUniforms() {
1456    int slot = mCaches.currentProgram->getUniform("pointSize");
1457    glUniform1f(slot, mDescription.pointSize);
1458}
1459
1460void OpenGLRenderer::setupDrawColorUniforms() {
1461    if ((mColorSet && !mShader) || (mShader && mSetShaderColor)) {
1462        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1463    }
1464}
1465
1466void OpenGLRenderer::setupDrawPureColorUniforms() {
1467    if (mSetShaderColor) {
1468        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1469    }
1470}
1471
1472void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1473    if (mShader) {
1474        if (ignoreTransform) {
1475            mModelView.loadInverse(*mSnapshot->transform);
1476        }
1477        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
1478    }
1479}
1480
1481void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1482    if (mShader) {
1483        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1484    }
1485}
1486
1487void OpenGLRenderer::setupDrawColorFilterUniforms() {
1488    if (mColorFilter) {
1489        mColorFilter->setupProgram(mCaches.currentProgram);
1490    }
1491}
1492
1493void OpenGLRenderer::setupDrawTextGammaUniforms() {
1494    mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram);
1495}
1496
1497void OpenGLRenderer::setupDrawSimpleMesh() {
1498    bool force = mCaches.bindMeshBuffer();
1499    mCaches.bindPositionVertexPointer(force, 0);
1500    mCaches.unbindIndicesBuffer();
1501}
1502
1503void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1504    bindTexture(texture);
1505    mTextureUnit++;
1506    mCaches.enableTexCoordsVertexArray();
1507}
1508
1509void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1510    bindExternalTexture(texture);
1511    mTextureUnit++;
1512    mCaches.enableTexCoordsVertexArray();
1513}
1514
1515void OpenGLRenderer::setupDrawTextureTransform() {
1516    mDescription.hasTextureTransform = true;
1517}
1518
1519void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1520    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1521            GL_FALSE, &transform.data[0]);
1522}
1523
1524void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1525    bool force = false;
1526    if (!vertices) {
1527        force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1528    } else {
1529        force = mCaches.unbindMeshBuffer();
1530    }
1531
1532    mCaches.bindPositionVertexPointer(force, vertices);
1533    if (mCaches.currentProgram->texCoords >= 0) {
1534        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1535    }
1536
1537    mCaches.unbindIndicesBuffer();
1538}
1539
1540void OpenGLRenderer::setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords) {
1541    bool force = mCaches.unbindMeshBuffer();
1542    mCaches.bindPositionVertexPointer(force, vertices);
1543    if (mCaches.currentProgram->texCoords >= 0) {
1544        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1545    }
1546}
1547
1548void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1549    bool force = mCaches.unbindMeshBuffer();
1550    mCaches.bindPositionVertexPointer(force, vertices, gVertexStride);
1551    mCaches.unbindIndicesBuffer();
1552}
1553
1554/**
1555 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an
1556 * outer boundary that fades out to 0. The variables set in the shader define the proportion of
1557 * the width and length of the primitive occupied by the AA region. The vtxWidth and vtxLength
1558 * attributes (one per vertex) are values from zero to one that tells the fragment
1559 * shader where the fragment is in relation to the line width/length overall; these values are
1560 * then used to compute the proper color, based on whether the fragment lies in the fading AA
1561 * region of the line.
1562 * Note that we only pass down the width values in this setup function. The length coordinates
1563 * are set up for each individual segment.
1564 */
1565void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* widthCoords,
1566        GLvoid* lengthCoords, float boundaryWidthProportion, int& widthSlot, int& lengthSlot) {
1567    bool force = mCaches.unbindMeshBuffer();
1568    mCaches.bindPositionVertexPointer(force, vertices, gAAVertexStride);
1569    mCaches.resetTexCoordsVertexPointer();
1570    mCaches.unbindIndicesBuffer();
1571
1572    widthSlot = mCaches.currentProgram->getAttrib("vtxWidth");
1573    glEnableVertexAttribArray(widthSlot);
1574    glVertexAttribPointer(widthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, widthCoords);
1575
1576    lengthSlot = mCaches.currentProgram->getAttrib("vtxLength");
1577    glEnableVertexAttribArray(lengthSlot);
1578    glVertexAttribPointer(lengthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, lengthCoords);
1579
1580    int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth");
1581    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1582}
1583
1584void OpenGLRenderer::finishDrawAALine(const int widthSlot, const int lengthSlot) {
1585    glDisableVertexAttribArray(widthSlot);
1586    glDisableVertexAttribArray(lengthSlot);
1587}
1588
1589void OpenGLRenderer::finishDrawTexture() {
1590}
1591
1592///////////////////////////////////////////////////////////////////////////////
1593// Drawing
1594///////////////////////////////////////////////////////////////////////////////
1595
1596status_t OpenGLRenderer::drawDisplayList(DisplayList* displayList,
1597        Rect& dirty, int32_t flags, uint32_t level) {
1598
1599    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1600    // will be performed by the display list itself
1601    if (displayList && displayList->isRenderable()) {
1602        return displayList->replay(*this, dirty, flags, level);
1603    }
1604
1605    return DrawGlInfo::kStatusDone;
1606}
1607
1608void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) {
1609    if (displayList) {
1610        displayList->output(*this, level);
1611    }
1612}
1613
1614void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1615    int alpha;
1616    SkXfermode::Mode mode;
1617    getAlphaAndMode(paint, &alpha, &mode);
1618
1619    float x = left;
1620    float y = top;
1621
1622    GLenum filter = GL_LINEAR;
1623    bool ignoreTransform = false;
1624    if (mSnapshot->transform->isPureTranslate()) {
1625        x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1626        y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1627        ignoreTransform = true;
1628        filter = GL_NEAREST;
1629    } else {
1630        filter = FILTER(paint);
1631    }
1632
1633    setupDraw();
1634    setupDrawWithTexture(true);
1635    if (paint) {
1636        setupDrawAlpha8Color(paint->getColor(), alpha);
1637    }
1638    setupDrawColorFilter();
1639    setupDrawShader();
1640    setupDrawBlending(true, mode);
1641    setupDrawProgram();
1642    setupDrawModelView(x, y, x + texture->width, y + texture->height, ignoreTransform);
1643
1644    setupDrawTexture(texture->id);
1645    texture->setWrap(GL_CLAMP_TO_EDGE);
1646    texture->setFilter(filter);
1647
1648    setupDrawPureColorUniforms();
1649    setupDrawColorFilterUniforms();
1650    setupDrawShaderUniforms();
1651    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1652
1653    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1654
1655    finishDrawTexture();
1656}
1657
1658status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1659    const float right = left + bitmap->width();
1660    const float bottom = top + bitmap->height();
1661
1662    if (quickReject(left, top, right, bottom)) {
1663        return DrawGlInfo::kStatusDone;
1664    }
1665
1666    mCaches.activeTexture(0);
1667    Texture* texture = mCaches.textureCache.get(bitmap);
1668    if (!texture) return DrawGlInfo::kStatusDone;
1669    const AutoTexture autoCleanup(texture);
1670
1671    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1672        drawAlphaBitmap(texture, left, top, paint);
1673    } else {
1674        drawTextureRect(left, top, right, bottom, texture, paint);
1675    }
1676
1677    return DrawGlInfo::kStatusDrew;
1678}
1679
1680status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1681    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1682    const mat4 transform(*matrix);
1683    transform.mapRect(r);
1684
1685    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1686        return DrawGlInfo::kStatusDone;
1687    }
1688
1689    mCaches.activeTexture(0);
1690    Texture* texture = mCaches.textureCache.get(bitmap);
1691    if (!texture) return DrawGlInfo::kStatusDone;
1692    const AutoTexture autoCleanup(texture);
1693
1694    // This could be done in a cheaper way, all we need is pass the matrix
1695    // to the vertex shader. The save/restore is a bit overkill.
1696    save(SkCanvas::kMatrix_SaveFlag);
1697    concatMatrix(matrix);
1698    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1699    restore();
1700
1701    return DrawGlInfo::kStatusDrew;
1702}
1703
1704status_t OpenGLRenderer::drawBitmapData(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1705    const float right = left + bitmap->width();
1706    const float bottom = top + bitmap->height();
1707
1708    if (quickReject(left, top, right, bottom)) {
1709        return DrawGlInfo::kStatusDone;
1710    }
1711
1712    mCaches.activeTexture(0);
1713    Texture* texture = mCaches.textureCache.getTransient(bitmap);
1714    const AutoTexture autoCleanup(texture);
1715
1716    drawTextureRect(left, top, right, bottom, texture, paint);
1717
1718    return DrawGlInfo::kStatusDrew;
1719}
1720
1721status_t OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1722        float* vertices, int* colors, SkPaint* paint) {
1723    if (!vertices || mSnapshot->isIgnored()) {
1724        return DrawGlInfo::kStatusDone;
1725    }
1726
1727    // TODO: We should compute the bounding box when recording the display list
1728    float left = FLT_MAX;
1729    float top = FLT_MAX;
1730    float right = FLT_MIN;
1731    float bottom = FLT_MIN;
1732
1733    const uint32_t count = meshWidth * meshHeight * 6;
1734
1735    // TODO: Support the colors array
1736    TextureVertex mesh[count];
1737    TextureVertex* vertex = mesh;
1738
1739    for (int32_t y = 0; y < meshHeight; y++) {
1740        for (int32_t x = 0; x < meshWidth; x++) {
1741            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1742
1743            float u1 = float(x) / meshWidth;
1744            float u2 = float(x + 1) / meshWidth;
1745            float v1 = float(y) / meshHeight;
1746            float v2 = float(y + 1) / meshHeight;
1747
1748            int ax = i + (meshWidth + 1) * 2;
1749            int ay = ax + 1;
1750            int bx = i;
1751            int by = bx + 1;
1752            int cx = i + 2;
1753            int cy = cx + 1;
1754            int dx = i + (meshWidth + 1) * 2 + 2;
1755            int dy = dx + 1;
1756
1757            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1758            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1759            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1760
1761            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1762            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1763            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1764
1765            // TODO: This could be optimized to avoid unnecessary ops
1766            left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1767            top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1768            right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1769            bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1770        }
1771    }
1772
1773    if (quickReject(left, top, right, bottom)) {
1774        return DrawGlInfo::kStatusDone;
1775    }
1776
1777    mCaches.activeTexture(0);
1778    Texture* texture = mCaches.textureCache.get(bitmap);
1779    if (!texture) return DrawGlInfo::kStatusDone;
1780    const AutoTexture autoCleanup(texture);
1781
1782    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1783    texture->setFilter(FILTER(paint), true);
1784
1785    int alpha;
1786    SkXfermode::Mode mode;
1787    getAlphaAndMode(paint, &alpha, &mode);
1788
1789    if (hasLayer()) {
1790        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1791    }
1792
1793    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1794            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1795            GL_TRIANGLES, count, false, false, 0, false, false);
1796
1797    return DrawGlInfo::kStatusDrew;
1798}
1799
1800status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1801         float srcLeft, float srcTop, float srcRight, float srcBottom,
1802         float dstLeft, float dstTop, float dstRight, float dstBottom,
1803         SkPaint* paint) {
1804    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1805        return DrawGlInfo::kStatusDone;
1806    }
1807
1808    mCaches.activeTexture(0);
1809    Texture* texture = mCaches.textureCache.get(bitmap);
1810    if (!texture) return DrawGlInfo::kStatusDone;
1811    const AutoTexture autoCleanup(texture);
1812
1813    const float width = texture->width;
1814    const float height = texture->height;
1815
1816    const float u1 = fmax(0.0f, srcLeft / width);
1817    const float v1 = fmax(0.0f, srcTop / height);
1818    const float u2 = fmin(1.0f, srcRight / width);
1819    const float v2 = fmin(1.0f, srcBottom / height);
1820
1821    mCaches.unbindMeshBuffer();
1822    resetDrawTextureTexCoords(u1, v1, u2, v2);
1823
1824    int alpha;
1825    SkXfermode::Mode mode;
1826    getAlphaAndMode(paint, &alpha, &mode);
1827
1828    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1829
1830    if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
1831        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1832        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1833
1834        GLenum filter = GL_NEAREST;
1835        // Enable linear filtering if the source rectangle is scaled
1836        if (srcRight - srcLeft != dstRight - dstLeft || srcBottom - srcTop != dstBottom - dstTop) {
1837            filter = FILTER(paint);
1838        }
1839
1840        texture->setFilter(filter, true);
1841        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1842                texture->id, alpha / 255.0f, mode, texture->blend,
1843                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1844                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1845    } else {
1846        texture->setFilter(FILTER(paint), true);
1847        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1848                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1849                GL_TRIANGLE_STRIP, gMeshCount);
1850    }
1851
1852    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1853
1854    return DrawGlInfo::kStatusDrew;
1855}
1856
1857status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1858        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1859        float left, float top, float right, float bottom, SkPaint* paint) {
1860    int alpha;
1861    SkXfermode::Mode mode;
1862    getAlphaAndModeDirect(paint, &alpha, &mode);
1863
1864    return drawPatch(bitmap, xDivs, yDivs, colors, width, height, numColors,
1865            left, top, right, bottom, alpha, mode);
1866}
1867
1868status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1869        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1870        float left, float top, float right, float bottom, int alpha, SkXfermode::Mode mode) {
1871    if (quickReject(left, top, right, bottom)) {
1872        return DrawGlInfo::kStatusDone;
1873    }
1874
1875    alpha *= mSnapshot->alpha;
1876
1877    mCaches.activeTexture(0);
1878    Texture* texture = mCaches.textureCache.get(bitmap);
1879    if (!texture) return DrawGlInfo::kStatusDone;
1880    const AutoTexture autoCleanup(texture);
1881    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1882    texture->setFilter(GL_LINEAR, true);
1883
1884    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1885            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1886
1887    if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
1888        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1889        // Mark the current layer dirty where we are going to draw the patch
1890        if (hasLayer() && mesh->hasEmptyQuads) {
1891            const float offsetX = left + mSnapshot->transform->getTranslateX();
1892            const float offsetY = top + mSnapshot->transform->getTranslateY();
1893            const size_t count = mesh->quads.size();
1894            for (size_t i = 0; i < count; i++) {
1895                const Rect& bounds = mesh->quads.itemAt(i);
1896                if (CC_LIKELY(pureTranslate)) {
1897                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
1898                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
1899                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
1900                } else {
1901                    dirtyLayer(left + bounds.left, top + bounds.top,
1902                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
1903                }
1904            }
1905        }
1906
1907        if (CC_LIKELY(pureTranslate)) {
1908            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1909            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1910
1911            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1912                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1913                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1914                    true, !mesh->hasEmptyQuads);
1915        } else {
1916            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1917                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1918                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1919                    true, !mesh->hasEmptyQuads);
1920        }
1921    }
1922
1923    return DrawGlInfo::kStatusDrew;
1924}
1925
1926/**
1927 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
1928 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
1929 * screen space in all directions. However, instead of using a fragment shader to compute the
1930 * translucency of the color from its position, we simply use a varying parameter to define how far
1931 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
1932 *
1933 * Doesn't yet support joins, caps, or path effects.
1934 */
1935void OpenGLRenderer::drawConvexPath(const SkPath& path, SkPaint* paint) {
1936    int color = paint->getColor();
1937    SkPaint::Style style = paint->getStyle();
1938    SkXfermode::Mode mode = getXfermode(paint->getXfermode());
1939    bool isAA = paint->isAntiAlias();
1940
1941    VertexBuffer vertexBuffer;
1942    // TODO: try clipping large paths to viewport
1943    PathRenderer::convexPathVertices(path, paint, mSnapshot->transform, vertexBuffer);
1944
1945    if (!vertexBuffer.getSize()) {
1946        // no vertices to draw
1947        return;
1948    }
1949
1950    setupDraw();
1951    setupDrawNoTexture();
1952    if (isAA) setupDrawAA();
1953    setupDrawVertexShape();
1954    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
1955    setupDrawColorFilter();
1956    setupDrawShader();
1957    setupDrawBlending(isAA, mode);
1958    setupDrawProgram();
1959    setupDrawModelViewIdentity();
1960    setupDrawColorUniforms();
1961    setupDrawColorFilterUniforms();
1962    setupDrawShaderIdentityUniforms();
1963
1964    void* vertices = vertexBuffer.getBuffer();
1965    bool force = mCaches.unbindMeshBuffer();
1966    mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride);
1967    mCaches.resetTexCoordsVertexPointer();
1968    mCaches.unbindIndicesBuffer();
1969
1970    int alphaSlot = -1;
1971    if (isAA) {
1972        void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset;
1973        alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha");
1974
1975        // TODO: avoid enable/disable in back to back uses of the alpha attribute
1976        glEnableVertexAttribArray(alphaSlot);
1977        glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords);
1978    }
1979
1980    SkRect bounds = PathRenderer::computePathBounds(path, paint);
1981    dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *mSnapshot->transform);
1982
1983    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getSize());
1984
1985    if (isAA) {
1986        glDisableVertexAttribArray(alphaSlot);
1987    }
1988}
1989
1990/**
1991 * We draw lines as quads (tristrips). Using GL_LINES can be difficult because the rasterization
1992 * rules for those lines produces some unexpected results, and may vary between hardware devices.
1993 * The basics of lines-as-quads is easy; we simply find the normal to the line and position the
1994 * corners of the quads on either side of each line endpoint, separated by the strokeWidth
1995 * of the line. Hairlines are more involved because we need to account for transform scaling
1996 * to end up with a one-pixel-wide line in screen space..
1997 * Anti-aliased lines add another factor to the approach. We use a specialized fragment shader
1998 * in combination with values that we calculate and pass down in this method. The basic approach
1999 * is that the quad we create contains both the core line area plus a bounding area in which
2000 * the translucent/AA pixels are drawn. The values we calculate tell the shader what
2001 * proportion of the width and the length of a given segment is represented by the boundary
2002 * region. The quad ends up being exactly .5 pixel larger in all directions than the non-AA quad.
2003 * The bounding region is actually 1 pixel wide on all sides (half pixel on the outside, half pixel
2004 * on the inside). This ends up giving the result we want, with pixels that are completely
2005 * 'inside' the line area being filled opaquely and the other pixels being filled according to
2006 * how far into the boundary region they are, which is determined by shader interpolation.
2007 */
2008status_t OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
2009    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2010
2011    const bool isAA = paint->isAntiAlias();
2012    // We use half the stroke width here because we're going to position the quad
2013    // corner vertices half of the width away from the line endpoints
2014    float halfStrokeWidth = paint->getStrokeWidth() * 0.5f;
2015    // A stroke width of 0 has a special meaning in Skia:
2016    // it draws a line 1 px wide regardless of current transform
2017    bool isHairLine = paint->getStrokeWidth() == 0.0f;
2018
2019    float inverseScaleX = 1.0f;
2020    float inverseScaleY = 1.0f;
2021    bool scaled = false;
2022
2023    int alpha;
2024    SkXfermode::Mode mode;
2025
2026    int generatedVerticesCount = 0;
2027    int verticesCount = count;
2028    if (count > 4) {
2029        // Polyline: account for extra vertices needed for continuous tri-strip
2030        verticesCount += (count - 4);
2031    }
2032
2033    if (isHairLine || isAA) {
2034        // The quad that we use for AA and hairlines needs to account for scaling. For hairlines
2035        // the line on the screen should always be one pixel wide regardless of scale. For
2036        // AA lines, we only want one pixel of translucent boundary around the quad.
2037        if (CC_UNLIKELY(!mSnapshot->transform->isPureTranslate())) {
2038            Matrix4 *mat = mSnapshot->transform;
2039            float m00 = mat->data[Matrix4::kScaleX];
2040            float m01 = mat->data[Matrix4::kSkewY];
2041            float m10 = mat->data[Matrix4::kSkewX];
2042            float m11 = mat->data[Matrix4::kScaleY];
2043
2044            float scaleX = sqrtf(m00 * m00 + m01 * m01);
2045            float scaleY = sqrtf(m10 * m10 + m11 * m11);
2046
2047            inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
2048            inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
2049
2050            if (inverseScaleX != 1.0f || inverseScaleY != 1.0f) {
2051                scaled = true;
2052            }
2053        }
2054    }
2055
2056    getAlphaAndMode(paint, &alpha, &mode);
2057
2058    mCaches.enableScissor();
2059
2060    setupDraw();
2061    setupDrawNoTexture();
2062    if (isAA) {
2063        setupDrawAA();
2064    }
2065    setupDrawColor(paint->getColor(), alpha);
2066    setupDrawColorFilter();
2067    setupDrawShader();
2068    setupDrawBlending(isAA, mode);
2069    setupDrawProgram();
2070    setupDrawModelViewIdentity(true);
2071    setupDrawColorUniforms();
2072    setupDrawColorFilterUniforms();
2073    setupDrawShaderIdentityUniforms();
2074
2075    if (isHairLine) {
2076        // Set a real stroke width to be used in quad construction
2077        halfStrokeWidth = isAA? 1 : .5;
2078    } else if (isAA && !scaled) {
2079        // Expand boundary to enable AA calculations on the quad border
2080        halfStrokeWidth += .5f;
2081    }
2082
2083    int widthSlot;
2084    int lengthSlot;
2085
2086    Vertex lines[verticesCount];
2087    Vertex* vertices = &lines[0];
2088
2089    AAVertex wLines[verticesCount];
2090    AAVertex* aaVertices = &wLines[0];
2091
2092    if (CC_UNLIKELY(!isAA)) {
2093        setupDrawVertices(vertices);
2094    } else {
2095        void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
2096        void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
2097        // innerProportion is the ratio of the inner (non-AA) part of the line to the total
2098        // AA stroke width (the base stroke width expanded by a half pixel on either side).
2099        // This value is used in the fragment shader to determine how to fill fragments.
2100        // We will need to calculate the actual width proportion on each segment for
2101        // scaled non-hairlines, since the boundary proportion may differ per-axis when scaled.
2102        float boundaryWidthProportion = .5 - 1 / (2 * halfStrokeWidth);
2103        setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords,
2104                boundaryWidthProportion, widthSlot, lengthSlot);
2105    }
2106
2107    AAVertex* prevAAVertex = NULL;
2108    Vertex* prevVertex = NULL;
2109
2110    int boundaryLengthSlot = -1;
2111    int boundaryWidthSlot = -1;
2112
2113    for (int i = 0; i < count; i += 4) {
2114        // a = start point, b = end point
2115        vec2 a(points[i], points[i + 1]);
2116        vec2 b(points[i + 2], points[i + 3]);
2117
2118        float length = 0;
2119        float boundaryLengthProportion = 0;
2120        float boundaryWidthProportion = 0;
2121
2122        // Find the normal to the line
2123        vec2 n = (b - a).copyNormalized() * halfStrokeWidth;
2124        float x = n.x;
2125        n.x = -n.y;
2126        n.y = x;
2127
2128        if (isHairLine) {
2129            if (isAA) {
2130                float wideningFactor;
2131                if (fabs(n.x) >= fabs(n.y)) {
2132                    wideningFactor = fabs(1.0f / n.x);
2133                } else {
2134                    wideningFactor = fabs(1.0f / n.y);
2135                }
2136                n *= wideningFactor;
2137            }
2138
2139            if (scaled) {
2140                n.x *= inverseScaleX;
2141                n.y *= inverseScaleY;
2142            }
2143        } else if (scaled) {
2144            // Extend n by .5 pixel on each side, post-transform
2145            vec2 extendedN = n.copyNormalized();
2146            extendedN /= 2;
2147            extendedN.x *= inverseScaleX;
2148            extendedN.y *= inverseScaleY;
2149
2150            float extendedNLength = extendedN.length();
2151            // We need to set this value on the shader prior to drawing
2152            boundaryWidthProportion = .5 - extendedNLength / (halfStrokeWidth + extendedNLength);
2153            n += extendedN;
2154        }
2155
2156        // aa lines expand the endpoint vertices to encompass the AA boundary
2157        if (isAA) {
2158            vec2 abVector = (b - a);
2159            length = abVector.length();
2160            abVector.normalize();
2161
2162            if (scaled) {
2163                abVector.x *= inverseScaleX;
2164                abVector.y *= inverseScaleY;
2165                float abLength = abVector.length();
2166                boundaryLengthProportion = .5 - abLength / (length + abLength);
2167            } else {
2168                boundaryLengthProportion = .5 - .5 / (length + 1);
2169            }
2170
2171            abVector /= 2;
2172            a -= abVector;
2173            b += abVector;
2174        }
2175
2176        // Four corners of the rectangle defining a thick line
2177        vec2 p1 = a - n;
2178        vec2 p2 = a + n;
2179        vec2 p3 = b + n;
2180        vec2 p4 = b - n;
2181
2182
2183        const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
2184        const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
2185        const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
2186        const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
2187
2188        if (!quickRejectNoScissor(left, top, right, bottom)) {
2189            if (!isAA) {
2190                if (prevVertex != NULL) {
2191                    // Issue two repeat vertices to create degenerate triangles to bridge
2192                    // between the previous line and the new one. This is necessary because
2193                    // we are creating a single triangle_strip which will contain
2194                    // potentially discontinuous line segments.
2195                    Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]);
2196                    Vertex::set(vertices++, p1.x, p1.y);
2197                    generatedVerticesCount += 2;
2198                }
2199
2200                Vertex::set(vertices++, p1.x, p1.y);
2201                Vertex::set(vertices++, p2.x, p2.y);
2202                Vertex::set(vertices++, p4.x, p4.y);
2203                Vertex::set(vertices++, p3.x, p3.y);
2204
2205                prevVertex = vertices - 1;
2206                generatedVerticesCount += 4;
2207            } else {
2208                if (!isHairLine && scaled) {
2209                    // Must set width proportions per-segment for scaled non-hairlines to use the
2210                    // correct AA boundary dimensions
2211                    if (boundaryWidthSlot < 0) {
2212                        boundaryWidthSlot =
2213                                mCaches.currentProgram->getUniform("boundaryWidth");
2214                    }
2215
2216                    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
2217                }
2218
2219                if (boundaryLengthSlot < 0) {
2220                    boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
2221                }
2222
2223                glUniform1f(boundaryLengthSlot, boundaryLengthProportion);
2224
2225                if (prevAAVertex != NULL) {
2226                    // Issue two repeat vertices to create degenerate triangles to bridge
2227                    // between the previous line and the new one. This is necessary because
2228                    // we are creating a single triangle_strip which will contain
2229                    // potentially discontinuous line segments.
2230                    AAVertex::set(aaVertices++,prevAAVertex->position[0],
2231                            prevAAVertex->position[1], prevAAVertex->width, prevAAVertex->length);
2232                    AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
2233                    generatedVerticesCount += 2;
2234                }
2235
2236                AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
2237                AAVertex::set(aaVertices++, p1.x, p1.y, 1, 0);
2238                AAVertex::set(aaVertices++, p3.x, p3.y, 0, 1);
2239                AAVertex::set(aaVertices++, p2.x, p2.y, 0, 0);
2240
2241                prevAAVertex = aaVertices - 1;
2242                generatedVerticesCount += 4;
2243            }
2244
2245            dirtyLayer(a.x == b.x ? left - 1 : left, a.y == b.y ? top - 1 : top,
2246                    a.x == b.x ? right: right, a.y == b.y ? bottom: bottom,
2247                    *mSnapshot->transform);
2248        }
2249    }
2250
2251    if (generatedVerticesCount > 0) {
2252       glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount);
2253    }
2254
2255    if (isAA) {
2256        finishDrawAALine(widthSlot, lengthSlot);
2257    }
2258
2259    return DrawGlInfo::kStatusDrew;
2260}
2261
2262status_t OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
2263    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2264
2265    // TODO: The paint's cap style defines whether the points are square or circular
2266    // TODO: Handle AA for round points
2267
2268    // A stroke width of 0 has a special meaning in Skia:
2269    // it draws an unscaled 1px point
2270    float strokeWidth = paint->getStrokeWidth();
2271    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
2272    if (isHairLine) {
2273        // Now that we know it's hairline, we can set the effective width, to be used later
2274        strokeWidth = 1.0f;
2275    }
2276    const float halfWidth = strokeWidth / 2;
2277    int alpha;
2278    SkXfermode::Mode mode;
2279    getAlphaAndMode(paint, &alpha, &mode);
2280
2281    int verticesCount = count >> 1;
2282    int generatedVerticesCount = 0;
2283
2284    TextureVertex pointsData[verticesCount];
2285    TextureVertex* vertex = &pointsData[0];
2286
2287    // TODO: We should optimize this method to not generate vertices for points
2288    // that lie outside of the clip.
2289    mCaches.enableScissor();
2290
2291    setupDraw();
2292    setupDrawNoTexture();
2293    setupDrawPoint(strokeWidth);
2294    setupDrawColor(paint->getColor(), alpha);
2295    setupDrawColorFilter();
2296    setupDrawShader();
2297    setupDrawBlending(mode);
2298    setupDrawProgram();
2299    setupDrawModelViewIdentity(true);
2300    setupDrawColorUniforms();
2301    setupDrawColorFilterUniforms();
2302    setupDrawPointUniforms();
2303    setupDrawShaderIdentityUniforms();
2304    setupDrawMesh(vertex);
2305
2306    for (int i = 0; i < count; i += 2) {
2307        TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
2308        generatedVerticesCount++;
2309
2310        float left = points[i] - halfWidth;
2311        float right = points[i] + halfWidth;
2312        float top = points[i + 1] - halfWidth;
2313        float bottom = points [i + 1] + halfWidth;
2314
2315        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
2316    }
2317
2318    glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
2319
2320    return DrawGlInfo::kStatusDrew;
2321}
2322
2323status_t OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2324    // No need to check against the clip, we fill the clip region
2325    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2326
2327    Rect& clip(*mSnapshot->clipRect);
2328    clip.snapToPixelBoundaries();
2329
2330    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
2331
2332    return DrawGlInfo::kStatusDrew;
2333}
2334
2335status_t OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture,
2336        SkPaint* paint) {
2337    if (!texture) return DrawGlInfo::kStatusDone;
2338    const AutoTexture autoCleanup(texture);
2339
2340    const float x = left + texture->left - texture->offset;
2341    const float y = top + texture->top - texture->offset;
2342
2343    drawPathTexture(texture, x, y, paint);
2344
2345    return DrawGlInfo::kStatusDrew;
2346}
2347
2348status_t OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2349        float rx, float ry, SkPaint* p) {
2350    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2351        return DrawGlInfo::kStatusDone;
2352    }
2353
2354    if (p->getPathEffect() != 0) {
2355        mCaches.activeTexture(0);
2356        const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
2357                right - left, bottom - top, rx, ry, p);
2358        return drawShape(left, top, texture, p);
2359    }
2360
2361    SkPath path;
2362    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2363    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2364        float outset = p->getStrokeWidth() / 2;
2365        rect.outset(outset, outset);
2366        rx += outset;
2367        ry += outset;
2368    }
2369    path.addRoundRect(rect, rx, ry);
2370    drawConvexPath(path, p);
2371
2372    return DrawGlInfo::kStatusDrew;
2373}
2374
2375status_t OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* p) {
2376    if (mSnapshot->isIgnored() || quickRejectPreStroke(x - radius, y - radius,
2377            x + radius, y + radius, p)) {
2378        return DrawGlInfo::kStatusDone;
2379    }
2380    if (p->getPathEffect() != 0) {
2381        mCaches.activeTexture(0);
2382        const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, p);
2383        return drawShape(x - radius, y - radius, texture, p);
2384    }
2385
2386    SkPath path;
2387    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2388        path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2389    } else {
2390        path.addCircle(x, y, radius);
2391    }
2392    drawConvexPath(path, p);
2393
2394    return DrawGlInfo::kStatusDrew;
2395}
2396
2397status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2398        SkPaint* p) {
2399    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2400        return DrawGlInfo::kStatusDone;
2401    }
2402
2403    if (p->getPathEffect() != 0) {
2404        mCaches.activeTexture(0);
2405        const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, p);
2406        return drawShape(left, top, texture, p);
2407    }
2408
2409    SkPath path;
2410    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2411    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2412        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2413    }
2414    path.addOval(rect);
2415    drawConvexPath(path, p);
2416
2417    return DrawGlInfo::kStatusDrew;
2418}
2419
2420status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2421        float startAngle, float sweepAngle, bool useCenter, SkPaint* p) {
2422    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2423        return DrawGlInfo::kStatusDone;
2424    }
2425
2426    if (fabs(sweepAngle) >= 360.0f) {
2427        return drawOval(left, top, right, bottom, p);
2428    }
2429
2430    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2431    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || p->getStrokeCap() != SkPaint::kButt_Cap) {
2432        mCaches.activeTexture(0);
2433        const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
2434                startAngle, sweepAngle, useCenter, p);
2435        return drawShape(left, top, texture, p);
2436    }
2437
2438    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2439    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2440        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2441    }
2442
2443    SkPath path;
2444    if (useCenter) {
2445        path.moveTo(rect.centerX(), rect.centerY());
2446    }
2447    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2448    if (useCenter) {
2449        path.close();
2450    }
2451    drawConvexPath(path, p);
2452
2453    return DrawGlInfo::kStatusDrew;
2454}
2455
2456// See SkPaintDefaults.h
2457#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2458
2459status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
2460    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2461        return DrawGlInfo::kStatusDone;
2462    }
2463
2464    if (p->getStyle() != SkPaint::kFill_Style) {
2465        // only fill style is supported by drawConvexPath, since others have to handle joins
2466        if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2467                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2468            mCaches.activeTexture(0);
2469            const PathTexture* texture =
2470                    mCaches.rectShapeCache.getRect(right - left, bottom - top, p);
2471            return drawShape(left, top, texture, p);
2472        }
2473
2474        SkPath path;
2475        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2476        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2477            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2478        }
2479        path.addRect(rect);
2480        drawConvexPath(path, p);
2481
2482        return DrawGlInfo::kStatusDrew;
2483    }
2484
2485    if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) {
2486        SkPath path;
2487        path.addRect(left, top, right, bottom);
2488        drawConvexPath(path, p);
2489    } else {
2490        drawColorRect(left, top, right, bottom, p->getColor(), getXfermode(p->getXfermode()));
2491    }
2492
2493    return DrawGlInfo::kStatusDrew;
2494}
2495
2496void OpenGLRenderer::drawTextShadow(SkPaint* paint, const char* text, int bytesCount, int count,
2497        const float* positions, FontRenderer& fontRenderer, int alpha, SkXfermode::Mode mode,
2498        float x, float y) {
2499    mCaches.activeTexture(0);
2500
2501    // NOTE: The drop shadow will not perform gamma correction
2502    //       if shader-based correction is enabled
2503    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2504    const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2505            paint, text, bytesCount, count, mShadowRadius, positions);
2506    const AutoTexture autoCleanup(shadow);
2507
2508    const float sx = x - shadow->left + mShadowDx;
2509    const float sy = y - shadow->top + mShadowDy;
2510
2511    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF) * mSnapshot->alpha;
2512    int shadowColor = mShadowColor;
2513    if (mShader) {
2514        shadowColor = 0xffffffff;
2515    }
2516
2517    setupDraw();
2518    setupDrawWithTexture(true);
2519    setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2520    setupDrawColorFilter();
2521    setupDrawShader();
2522    setupDrawBlending(true, mode);
2523    setupDrawProgram();
2524    setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2525    setupDrawTexture(shadow->id);
2526    setupDrawPureColorUniforms();
2527    setupDrawColorFilterUniforms();
2528    setupDrawShaderUniforms();
2529    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2530
2531    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2532}
2533
2534status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2535        const float* positions, SkPaint* paint) {
2536    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2537            (paint->getAlpha() * mSnapshot->alpha == 0 && paint->getXfermode() == NULL)) {
2538        return DrawGlInfo::kStatusDone;
2539    }
2540
2541    // NOTE: Skia does not support perspective transform on drawPosText yet
2542    if (!mSnapshot->transform->isSimple()) {
2543        return DrawGlInfo::kStatusDone;
2544    }
2545
2546    float x = 0.0f;
2547    float y = 0.0f;
2548    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2549    if (pureTranslate) {
2550        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2551        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2552    }
2553
2554    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2555    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2556            paint->getTextSize());
2557
2558    int alpha;
2559    SkXfermode::Mode mode;
2560    getAlphaAndMode(paint, &alpha, &mode);
2561
2562    if (CC_UNLIKELY(mHasShadow)) {
2563        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, alpha, mode,
2564                0.0f, 0.0f);
2565    }
2566
2567    // Pick the appropriate texture filtering
2568    bool linearFilter = mSnapshot->transform->changesBounds();
2569    if (pureTranslate && !linearFilter) {
2570        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2571    }
2572
2573    mCaches.activeTexture(0);
2574    setupDraw();
2575    setupDrawTextGamma(paint);
2576    setupDrawDirtyRegionsDisabled();
2577    setupDrawWithTexture(true);
2578    setupDrawAlpha8Color(paint->getColor(), alpha);
2579    setupDrawColorFilter();
2580    setupDrawShader();
2581    setupDrawBlending(true, mode);
2582    setupDrawProgram();
2583    setupDrawModelView(x, y, x, y, pureTranslate, true);
2584    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2585    setupDrawPureColorUniforms();
2586    setupDrawColorFilterUniforms();
2587    setupDrawShaderUniforms(pureTranslate);
2588    setupDrawTextGammaUniforms();
2589
2590    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2591    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2592
2593    const bool hasActiveLayer = hasLayer();
2594
2595    if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2596            positions, hasActiveLayer ? &bounds : NULL)) {
2597        if (hasActiveLayer) {
2598            if (!pureTranslate) {
2599                mSnapshot->transform->mapRect(bounds);
2600            }
2601            dirtyLayerUnchecked(bounds, getRegion());
2602        }
2603    }
2604
2605    return DrawGlInfo::kStatusDrew;
2606}
2607
2608status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
2609        float x, float y, const float* positions, SkPaint* paint, float length) {
2610    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2611            (paint->getAlpha() * mSnapshot->alpha == 0 && paint->getXfermode() == NULL)) {
2612        return DrawGlInfo::kStatusDone;
2613    }
2614
2615    if (length < 0.0f) length = paint->measureText(text, bytesCount);
2616    switch (paint->getTextAlign()) {
2617        case SkPaint::kCenter_Align:
2618            x -= length / 2.0f;
2619            break;
2620        case SkPaint::kRight_Align:
2621            x -= length;
2622            break;
2623        default:
2624            break;
2625    }
2626
2627    SkPaint::FontMetrics metrics;
2628    paint->getFontMetrics(&metrics, 0.0f);
2629    if (quickReject(x, y + metrics.fTop, x + length, y + metrics.fBottom)) {
2630        return DrawGlInfo::kStatusDone;
2631    }
2632
2633    const float oldX = x;
2634    const float oldY = y;
2635    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2636    if (CC_LIKELY(pureTranslate)) {
2637        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2638        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2639    }
2640
2641#if DEBUG_GLYPHS
2642    ALOGD("OpenGLRenderer drawText() with FontID=%d",
2643            SkTypeface::UniqueID(paint->getTypeface()));
2644#endif
2645
2646    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2647    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2648            paint->getTextSize());
2649
2650    int alpha;
2651    SkXfermode::Mode mode;
2652    getAlphaAndMode(paint, &alpha, &mode);
2653
2654    if (CC_UNLIKELY(mHasShadow)) {
2655        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, alpha, mode,
2656                oldX, oldY);
2657    }
2658
2659    // Pick the appropriate texture filtering
2660    bool linearFilter = mSnapshot->transform->changesBounds();
2661    if (pureTranslate && !linearFilter) {
2662        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2663    }
2664
2665    // The font renderer will always use texture unit 0
2666    mCaches.activeTexture(0);
2667    setupDraw();
2668    setupDrawTextGamma(paint);
2669    setupDrawDirtyRegionsDisabled();
2670    setupDrawWithTexture(true);
2671    setupDrawAlpha8Color(paint->getColor(), alpha);
2672    setupDrawColorFilter();
2673    setupDrawShader();
2674    setupDrawBlending(true, mode);
2675    setupDrawProgram();
2676    setupDrawModelView(x, y, x, y, pureTranslate, true);
2677    // See comment above; the font renderer must use texture unit 0
2678    // assert(mTextureUnit == 0)
2679    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2680    setupDrawPureColorUniforms();
2681    setupDrawColorFilterUniforms();
2682    setupDrawShaderUniforms(pureTranslate);
2683    setupDrawTextGammaUniforms();
2684
2685    const Rect* clip = pureTranslate ? mSnapshot->clipRect :
2686            (mSnapshot->hasPerspectiveTransform() ? NULL : &mSnapshot->getLocalClip());
2687    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2688
2689    const bool hasActiveLayer = hasLayer();
2690
2691    bool status;
2692    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2693        SkPaint paintCopy(*paint);
2694        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2695        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2696                positions, hasActiveLayer ? &bounds : NULL);
2697    } else {
2698        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2699                positions, hasActiveLayer ? &bounds : NULL);
2700    }
2701
2702    if (status && hasActiveLayer) {
2703        if (!pureTranslate) {
2704            mSnapshot->transform->mapRect(bounds);
2705        }
2706        dirtyLayerUnchecked(bounds, getRegion());
2707    }
2708
2709    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2710
2711    return DrawGlInfo::kStatusDrew;
2712}
2713
2714status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, SkPath* path,
2715        float hOffset, float vOffset, SkPaint* paint) {
2716    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2717            (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
2718        return DrawGlInfo::kStatusDone;
2719    }
2720
2721    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2722    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2723            paint->getTextSize());
2724
2725    int alpha;
2726    SkXfermode::Mode mode;
2727    getAlphaAndMode(paint, &alpha, &mode);
2728
2729    mCaches.activeTexture(0);
2730    setupDraw();
2731    setupDrawTextGamma(paint);
2732    setupDrawDirtyRegionsDisabled();
2733    setupDrawWithTexture(true);
2734    setupDrawAlpha8Color(paint->getColor(), alpha);
2735    setupDrawColorFilter();
2736    setupDrawShader();
2737    setupDrawBlending(true, mode);
2738    setupDrawProgram();
2739    setupDrawModelView(0.0f, 0.0f, 0.0f, 0.0f, false, true);
2740    setupDrawTexture(fontRenderer.getTexture(true));
2741    setupDrawPureColorUniforms();
2742    setupDrawColorFilterUniforms();
2743    setupDrawShaderUniforms(false);
2744    setupDrawTextGammaUniforms();
2745
2746    const Rect* clip = &mSnapshot->getLocalClip();
2747    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2748
2749    const bool hasActiveLayer = hasLayer();
2750
2751    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2752            hOffset, vOffset, hasActiveLayer ? &bounds : NULL)) {
2753        if (hasActiveLayer) {
2754            mSnapshot->transform->mapRect(bounds);
2755            dirtyLayerUnchecked(bounds, getRegion());
2756        }
2757    }
2758
2759    return DrawGlInfo::kStatusDrew;
2760}
2761
2762status_t OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
2763    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2764
2765    mCaches.activeTexture(0);
2766
2767    // TODO: Perform early clip test before we rasterize the path
2768    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2769    if (!texture) return DrawGlInfo::kStatusDone;
2770    const AutoTexture autoCleanup(texture);
2771
2772    const float x = texture->left - texture->offset;
2773    const float y = texture->top - texture->offset;
2774
2775    drawPathTexture(texture, x, y, paint);
2776
2777    return DrawGlInfo::kStatusDrew;
2778}
2779
2780status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
2781    if (!layer) {
2782        return DrawGlInfo::kStatusDone;
2783    }
2784
2785    mat4* transform = NULL;
2786    if (layer->isTextureLayer()) {
2787        transform = &layer->getTransform();
2788        if (!transform->isIdentity()) {
2789            save(0);
2790            mSnapshot->transform->multiply(*transform);
2791        }
2792    }
2793
2794    Rect transformed;
2795    Rect clip;
2796    const bool rejected = quickRejectNoScissor(x, y,
2797            x + layer->layer.getWidth(), y + layer->layer.getHeight(), transformed, clip);
2798
2799    if (rejected) {
2800        if (transform && !transform->isIdentity()) {
2801            restore();
2802        }
2803        return DrawGlInfo::kStatusDone;
2804    }
2805
2806    bool debugLayerUpdate = false;
2807    if (updateLayer(layer, true)) {
2808        debugLayerUpdate = mCaches.debugLayersUpdates;
2809    }
2810
2811    mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clip.contains(transformed));
2812    mCaches.activeTexture(0);
2813
2814    if (CC_LIKELY(!layer->region.isEmpty())) {
2815        SkiaColorFilter* oldFilter = mColorFilter;
2816        mColorFilter = layer->getColorFilter();
2817
2818        if (layer->region.isRect()) {
2819            composeLayerRect(layer, layer->regionRect);
2820        } else if (layer->mesh) {
2821            const float a = layer->getAlpha() / 255.0f;
2822            setupDraw();
2823            setupDrawWithTexture();
2824            setupDrawColor(a, a, a, a);
2825            setupDrawColorFilter();
2826            setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false);
2827            setupDrawProgram();
2828            setupDrawPureColorUniforms();
2829            setupDrawColorFilterUniforms();
2830            setupDrawTexture(layer->getTexture());
2831            if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
2832                int tx = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2833                int ty = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2834
2835                layer->setFilter(GL_NEAREST);
2836                setupDrawModelViewTranslate(tx, ty,
2837                        tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
2838            } else {
2839                layer->setFilter(GL_LINEAR);
2840                setupDrawModelViewTranslate(x, y,
2841                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
2842            }
2843            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
2844
2845            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
2846                    GL_UNSIGNED_SHORT, layer->meshIndices);
2847
2848            finishDrawTexture();
2849
2850#if DEBUG_LAYERS_AS_REGIONS
2851            drawRegionRects(layer->region);
2852#endif
2853        }
2854
2855        mColorFilter = oldFilter;
2856
2857        if (debugLayerUpdate) {
2858            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
2859                    0x7f00ff00, SkXfermode::kSrcOver_Mode);
2860        }
2861    }
2862
2863    if (transform && !transform->isIdentity()) {
2864        restore();
2865    }
2866
2867    return DrawGlInfo::kStatusDrew;
2868}
2869
2870///////////////////////////////////////////////////////////////////////////////
2871// Shaders
2872///////////////////////////////////////////////////////////////////////////////
2873
2874void OpenGLRenderer::resetShader() {
2875    mShader = NULL;
2876}
2877
2878void OpenGLRenderer::setupShader(SkiaShader* shader) {
2879    mShader = shader;
2880    if (mShader) {
2881        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
2882    }
2883}
2884
2885///////////////////////////////////////////////////////////////////////////////
2886// Color filters
2887///////////////////////////////////////////////////////////////////////////////
2888
2889void OpenGLRenderer::resetColorFilter() {
2890    mColorFilter = NULL;
2891}
2892
2893void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
2894    mColorFilter = filter;
2895}
2896
2897///////////////////////////////////////////////////////////////////////////////
2898// Drop shadow
2899///////////////////////////////////////////////////////////////////////////////
2900
2901void OpenGLRenderer::resetShadow() {
2902    mHasShadow = false;
2903}
2904
2905void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
2906    mHasShadow = true;
2907    mShadowRadius = radius;
2908    mShadowDx = dx;
2909    mShadowDy = dy;
2910    mShadowColor = color;
2911}
2912
2913///////////////////////////////////////////////////////////////////////////////
2914// Draw filters
2915///////////////////////////////////////////////////////////////////////////////
2916
2917void OpenGLRenderer::resetPaintFilter() {
2918    mHasDrawFilter = false;
2919}
2920
2921void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) {
2922    mHasDrawFilter = true;
2923    mPaintFilterClearBits = clearBits & SkPaint::kAllFlags;
2924    mPaintFilterSetBits = setBits & SkPaint::kAllFlags;
2925}
2926
2927SkPaint* OpenGLRenderer::filterPaint(SkPaint* paint) {
2928    if (CC_LIKELY(!mHasDrawFilter || !paint)) return paint;
2929
2930    uint32_t flags = paint->getFlags();
2931
2932    mFilteredPaint = *paint;
2933    mFilteredPaint.setFlags((flags & ~mPaintFilterClearBits) | mPaintFilterSetBits);
2934
2935    return &mFilteredPaint;
2936}
2937
2938///////////////////////////////////////////////////////////////////////////////
2939// Drawing implementation
2940///////////////////////////////////////////////////////////////////////////////
2941
2942void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
2943        float x, float y, SkPaint* paint) {
2944    if (quickReject(x, y, x + texture->width, y + texture->height)) {
2945        return;
2946    }
2947
2948    int alpha;
2949    SkXfermode::Mode mode;
2950    getAlphaAndMode(paint, &alpha, &mode);
2951
2952    setupDraw();
2953    setupDrawWithTexture(true);
2954    setupDrawAlpha8Color(paint->getColor(), alpha);
2955    setupDrawColorFilter();
2956    setupDrawShader();
2957    setupDrawBlending(true, mode);
2958    setupDrawProgram();
2959    setupDrawModelView(x, y, x + texture->width, y + texture->height);
2960    setupDrawTexture(texture->id);
2961    setupDrawPureColorUniforms();
2962    setupDrawColorFilterUniforms();
2963    setupDrawShaderUniforms();
2964    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2965
2966    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2967
2968    finishDrawTexture();
2969}
2970
2971// Same values used by Skia
2972#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2973#define kStdUnderline_Offset    (1.0f / 9.0f)
2974#define kStdUnderline_Thickness (1.0f / 18.0f)
2975
2976void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
2977        float x, float y, SkPaint* paint) {
2978    // Handle underline and strike-through
2979    uint32_t flags = paint->getFlags();
2980    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2981        SkPaint paintCopy(*paint);
2982        float underlineWidth = length;
2983        // If length is > 0.0f, we already measured the text for the text alignment
2984        if (length <= 0.0f) {
2985            underlineWidth = paintCopy.measureText(text, bytesCount);
2986        }
2987
2988        if (CC_LIKELY(underlineWidth > 0.0f)) {
2989            const float textSize = paintCopy.getTextSize();
2990            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
2991
2992            const float left = x;
2993            float top = 0.0f;
2994
2995            int linesCount = 0;
2996            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2997            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2998
2999            const int pointsCount = 4 * linesCount;
3000            float points[pointsCount];
3001            int currentPoint = 0;
3002
3003            if (flags & SkPaint::kUnderlineText_Flag) {
3004                top = y + textSize * kStdUnderline_Offset;
3005                points[currentPoint++] = left;
3006                points[currentPoint++] = top;
3007                points[currentPoint++] = left + underlineWidth;
3008                points[currentPoint++] = top;
3009            }
3010
3011            if (flags & SkPaint::kStrikeThruText_Flag) {
3012                top = y + textSize * kStdStrikeThru_Offset;
3013                points[currentPoint++] = left;
3014                points[currentPoint++] = top;
3015                points[currentPoint++] = left + underlineWidth;
3016                points[currentPoint++] = top;
3017            }
3018
3019            paintCopy.setStrokeWidth(strokeWidth);
3020
3021            drawLines(&points[0], pointsCount, &paintCopy);
3022        }
3023    }
3024}
3025
3026void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
3027        int color, SkXfermode::Mode mode, bool ignoreTransform) {
3028    // If a shader is set, preserve only the alpha
3029    if (mShader) {
3030        color |= 0x00ffffff;
3031    }
3032
3033    setupDraw();
3034    setupDrawNoTexture();
3035    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
3036    setupDrawShader();
3037    setupDrawColorFilter();
3038    setupDrawBlending(mode);
3039    setupDrawProgram();
3040    setupDrawModelView(left, top, right, bottom, ignoreTransform);
3041    setupDrawColorUniforms();
3042    setupDrawShaderUniforms(ignoreTransform);
3043    setupDrawColorFilterUniforms();
3044    setupDrawSimpleMesh();
3045
3046    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3047}
3048
3049void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3050        Texture* texture, SkPaint* paint) {
3051    int alpha;
3052    SkXfermode::Mode mode;
3053    getAlphaAndMode(paint, &alpha, &mode);
3054
3055    texture->setWrap(GL_CLAMP_TO_EDGE, true);
3056
3057    if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
3058        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
3059        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
3060
3061        texture->setFilter(GL_NEAREST, true);
3062        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3063                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
3064                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
3065    } else {
3066        texture->setFilter(FILTER(paint), true);
3067        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
3068                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
3069                GL_TRIANGLE_STRIP, gMeshCount);
3070    }
3071}
3072
3073void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3074        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
3075    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
3076            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
3077}
3078
3079void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3080        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
3081        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3082        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
3083
3084    setupDraw();
3085    setupDrawWithTexture();
3086    setupDrawColor(alpha, alpha, alpha, alpha);
3087    setupDrawColorFilter();
3088    setupDrawBlending(blend, mode, swapSrcDst);
3089    setupDrawProgram();
3090    if (!dirty) {
3091        setupDrawDirtyRegionsDisabled();
3092    }
3093    if (!ignoreScale) {
3094        setupDrawModelView(left, top, right, bottom, ignoreTransform);
3095    } else {
3096        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
3097    }
3098    setupDrawPureColorUniforms();
3099    setupDrawColorFilterUniforms();
3100    setupDrawTexture(texture);
3101    setupDrawMesh(vertices, texCoords, vbo);
3102
3103    glDrawArrays(drawMode, 0, elementsCount);
3104
3105    finishDrawTexture();
3106}
3107
3108void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3109        ProgramDescription& description, bool swapSrcDst) {
3110    blend = blend || mode != SkXfermode::kSrcOver_Mode;
3111
3112    if (blend) {
3113        // These blend modes are not supported by OpenGL directly and have
3114        // to be implemented using shaders. Since the shader will perform
3115        // the blending, turn blending off here
3116        // If the blend mode cannot be implemented using shaders, fall
3117        // back to the default SrcOver blend mode instead
3118        if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3119            if (CC_UNLIKELY(mCaches.extensions.hasFramebufferFetch())) {
3120                description.framebufferMode = mode;
3121                description.swapSrcDst = swapSrcDst;
3122
3123                if (mCaches.blend) {
3124                    glDisable(GL_BLEND);
3125                    mCaches.blend = false;
3126                }
3127
3128                return;
3129            } else {
3130                mode = SkXfermode::kSrcOver_Mode;
3131            }
3132        }
3133
3134        if (!mCaches.blend) {
3135            glEnable(GL_BLEND);
3136        }
3137
3138        GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
3139        GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
3140
3141        if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
3142            glBlendFunc(sourceMode, destMode);
3143            mCaches.lastSrcMode = sourceMode;
3144            mCaches.lastDstMode = destMode;
3145        }
3146    } else if (mCaches.blend) {
3147        glDisable(GL_BLEND);
3148    }
3149    mCaches.blend = blend;
3150}
3151
3152bool OpenGLRenderer::useProgram(Program* program) {
3153    if (!program->isInUse()) {
3154        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
3155        program->use();
3156        mCaches.currentProgram = program;
3157        return false;
3158    }
3159    return true;
3160}
3161
3162void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3163    TextureVertex* v = &mMeshVertices[0];
3164    TextureVertex::setUV(v++, u1, v1);
3165    TextureVertex::setUV(v++, u2, v1);
3166    TextureVertex::setUV(v++, u1, v2);
3167    TextureVertex::setUV(v++, u2, v2);
3168}
3169
3170void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
3171    getAlphaAndModeDirect(paint, alpha,  mode);
3172    *alpha *= mSnapshot->alpha;
3173}
3174
3175}; // namespace uirenderer
3176}; // namespace android
3177