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