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