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