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