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