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