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