OpenGLRenderer.cpp revision d71dd367af604571c7d00ca473184a1b9240eca2
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
1241    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1242            gMeshStride, vertices);
1243    if (mTexCoordsSlot >= 0) {
1244        glVertexAttribPointer(mTexCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1245    }
1246}
1247
1248void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1249    mCaches.unbindMeshBuffer();
1250    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1251            gVertexStride, vertices);
1252}
1253
1254/**
1255 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an
1256 * outer boundary that fades out to 0. The variables set in the shader define the proportion of
1257 * the width and length of the primitive occupied by the AA region. The vtxWidth and vtxLength
1258 * attributes (one per vertex) are values from zero to one that tells the fragment
1259 * shader where the fragment is in relation to the line width/length overall; these values are
1260 * then used to compute the proper color, based on whether the fragment lies in the fading AA
1261 * region of the line.
1262 * Note that we only pass down the width values in this setup function. The length coordinates
1263 * are set up for each individual segment.
1264 */
1265void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* widthCoords,
1266        GLvoid* lengthCoords, float boundaryWidthProportion) {
1267    mCaches.unbindMeshBuffer();
1268
1269    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1270            gAAVertexStride, vertices);
1271
1272    int widthSlot = mCaches.currentProgram->getAttrib("vtxWidth");
1273    glEnableVertexAttribArray(widthSlot);
1274    glVertexAttribPointer(widthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, widthCoords);
1275
1276    int lengthSlot = mCaches.currentProgram->getAttrib("vtxLength");
1277    glEnableVertexAttribArray(lengthSlot);
1278    glVertexAttribPointer(lengthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, lengthCoords);
1279
1280    int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth");
1281    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1282
1283    // Setting the inverse value saves computations per-fragment in the shader
1284    int inverseBoundaryWidthSlot = mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1285    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1286}
1287
1288void OpenGLRenderer::finishDrawTexture() {
1289    glDisableVertexAttribArray(mTexCoordsSlot);
1290}
1291
1292///////////////////////////////////////////////////////////////////////////////
1293// Drawing
1294///////////////////////////////////////////////////////////////////////////////
1295
1296bool OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t width, uint32_t height,
1297        Rect& dirty, uint32_t level) {
1298    if (quickReject(0.0f, 0.0f, width, height)) {
1299        return false;
1300    }
1301
1302    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1303    // will be performed by the display list itself
1304    if (displayList && displayList->isRenderable()) {
1305        return displayList->replay(*this, dirty, level);
1306    }
1307
1308    return false;
1309}
1310
1311void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) {
1312    if (displayList) {
1313        displayList->output(*this, level);
1314    }
1315}
1316
1317void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1318    int alpha;
1319    SkXfermode::Mode mode;
1320    getAlphaAndMode(paint, &alpha, &mode);
1321
1322    float x = left;
1323    float y = top;
1324
1325    GLenum filter = GL_LINEAR;
1326    bool ignoreTransform = false;
1327    if (mSnapshot->transform->isPureTranslate()) {
1328        x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1329        y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1330        ignoreTransform = true;
1331        filter = GL_NEAREST;
1332    } else {
1333        filter = FILTER(paint);
1334    }
1335
1336    setupDraw();
1337    setupDrawWithTexture(true);
1338    if (paint) {
1339        setupDrawAlpha8Color(paint->getColor(), alpha);
1340    }
1341    setupDrawColorFilter();
1342    setupDrawShader();
1343    setupDrawBlending(true, mode);
1344    setupDrawProgram();
1345    setupDrawModelView(x, y, x + texture->width, y + texture->height, ignoreTransform);
1346
1347    setupDrawTexture(texture->id);
1348    texture->setWrap(GL_CLAMP_TO_EDGE);
1349    texture->setFilter(filter);
1350
1351    setupDrawPureColorUniforms();
1352    setupDrawColorFilterUniforms();
1353    setupDrawShaderUniforms();
1354    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1355
1356    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1357
1358    finishDrawTexture();
1359}
1360
1361void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1362    const float right = left + bitmap->width();
1363    const float bottom = top + bitmap->height();
1364
1365    if (quickReject(left, top, right, bottom)) {
1366        return;
1367    }
1368
1369    glActiveTexture(gTextureUnits[0]);
1370    Texture* texture = mCaches.textureCache.get(bitmap);
1371    if (!texture) return;
1372    const AutoTexture autoCleanup(texture);
1373
1374    if (bitmap->getConfig() == SkBitmap::kA8_Config) {
1375        drawAlphaBitmap(texture, left, top, paint);
1376    } else {
1377        drawTextureRect(left, top, right, bottom, texture, paint);
1378    }
1379}
1380
1381void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1382    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1383    const mat4 transform(*matrix);
1384    transform.mapRect(r);
1385
1386    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1387        return;
1388    }
1389
1390    glActiveTexture(gTextureUnits[0]);
1391    Texture* texture = mCaches.textureCache.get(bitmap);
1392    if (!texture) return;
1393    const AutoTexture autoCleanup(texture);
1394
1395    // This could be done in a cheaper way, all we need is pass the matrix
1396    // to the vertex shader. The save/restore is a bit overkill.
1397    save(SkCanvas::kMatrix_SaveFlag);
1398    concatMatrix(matrix);
1399    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1400    restore();
1401}
1402
1403void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1404        float* vertices, int* colors, SkPaint* paint) {
1405    // TODO: Do a quickReject
1406    if (!vertices || mSnapshot->isIgnored()) {
1407        return;
1408    }
1409
1410    glActiveTexture(gTextureUnits[0]);
1411    Texture* texture = mCaches.textureCache.get(bitmap);
1412    if (!texture) return;
1413    const AutoTexture autoCleanup(texture);
1414
1415    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1416    texture->setFilter(FILTER(paint), true);
1417
1418    int alpha;
1419    SkXfermode::Mode mode;
1420    getAlphaAndMode(paint, &alpha, &mode);
1421
1422    const uint32_t count = meshWidth * meshHeight * 6;
1423
1424    float left = FLT_MAX;
1425    float top = FLT_MAX;
1426    float right = FLT_MIN;
1427    float bottom = FLT_MIN;
1428
1429#if RENDER_LAYERS_AS_REGIONS
1430    bool hasActiveLayer = hasLayer();
1431#else
1432    bool hasActiveLayer = false;
1433#endif
1434
1435    // TODO: Support the colors array
1436    TextureVertex mesh[count];
1437    TextureVertex* vertex = mesh;
1438    for (int32_t y = 0; y < meshHeight; y++) {
1439        for (int32_t x = 0; x < meshWidth; x++) {
1440            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1441
1442            float u1 = float(x) / meshWidth;
1443            float u2 = float(x + 1) / meshWidth;
1444            float v1 = float(y) / meshHeight;
1445            float v2 = float(y + 1) / meshHeight;
1446
1447            int ax = i + (meshWidth + 1) * 2;
1448            int ay = ax + 1;
1449            int bx = i;
1450            int by = bx + 1;
1451            int cx = i + 2;
1452            int cy = cx + 1;
1453            int dx = i + (meshWidth + 1) * 2 + 2;
1454            int dy = dx + 1;
1455
1456            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1457            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1458            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1459
1460            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1461            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1462            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1463
1464#if RENDER_LAYERS_AS_REGIONS
1465            if (hasActiveLayer) {
1466                // TODO: This could be optimized to avoid unnecessary ops
1467                left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1468                top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1469                right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1470                bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1471            }
1472#endif
1473        }
1474    }
1475
1476#if RENDER_LAYERS_AS_REGIONS
1477    if (hasActiveLayer) {
1478        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1479    }
1480#endif
1481
1482    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1483            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1484            GL_TRIANGLES, count, false, false, 0, false, false);
1485}
1486
1487void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1488         float srcLeft, float srcTop, float srcRight, float srcBottom,
1489         float dstLeft, float dstTop, float dstRight, float dstBottom,
1490         SkPaint* paint) {
1491    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1492        return;
1493    }
1494
1495    glActiveTexture(gTextureUnits[0]);
1496    Texture* texture = mCaches.textureCache.get(bitmap);
1497    if (!texture) return;
1498    const AutoTexture autoCleanup(texture);
1499
1500    const float width = texture->width;
1501    const float height = texture->height;
1502
1503    const float u1 = fmax(0.0f, srcLeft / width);
1504    const float v1 = fmax(0.0f, srcTop / height);
1505    const float u2 = fmin(1.0f, srcRight / width);
1506    const float v2 = fmin(1.0f, srcBottom / height);
1507
1508    mCaches.unbindMeshBuffer();
1509    resetDrawTextureTexCoords(u1, v1, u2, v2);
1510
1511    int alpha;
1512    SkXfermode::Mode mode;
1513    getAlphaAndMode(paint, &alpha, &mode);
1514
1515    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1516
1517    if (mSnapshot->transform->isPureTranslate()) {
1518        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1519        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1520
1521        GLenum filter = GL_NEAREST;
1522        // Enable linear filtering if the source rectangle is scaled
1523        if (srcRight - srcLeft != dstRight - dstLeft || srcBottom - srcTop != dstBottom - dstTop) {
1524            filter = FILTER(paint);
1525        }
1526
1527        texture->setFilter(filter, true);
1528        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1529                texture->id, alpha / 255.0f, mode, texture->blend,
1530                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1531                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1532    } else {
1533        texture->setFilter(FILTER(paint), true);
1534        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1535                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1536                GL_TRIANGLE_STRIP, gMeshCount);
1537    }
1538
1539    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1540}
1541
1542void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1543        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1544        float left, float top, float right, float bottom, SkPaint* paint) {
1545    if (quickReject(left, top, right, bottom)) {
1546        return;
1547    }
1548
1549    glActiveTexture(gTextureUnits[0]);
1550    Texture* texture = mCaches.textureCache.get(bitmap);
1551    if (!texture) return;
1552    const AutoTexture autoCleanup(texture);
1553    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1554    texture->setFilter(GL_LINEAR, true);
1555
1556    int alpha;
1557    SkXfermode::Mode mode;
1558    getAlphaAndMode(paint, &alpha, &mode);
1559
1560    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1561            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1562
1563    if (mesh && mesh->verticesCount > 0) {
1564        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1565#if RENDER_LAYERS_AS_REGIONS
1566        // Mark the current layer dirty where we are going to draw the patch
1567        if (hasLayer() && mesh->hasEmptyQuads) {
1568            const float offsetX = left + mSnapshot->transform->getTranslateX();
1569            const float offsetY = top + mSnapshot->transform->getTranslateY();
1570            const size_t count = mesh->quads.size();
1571            for (size_t i = 0; i < count; i++) {
1572                const Rect& bounds = mesh->quads.itemAt(i);
1573                if (pureTranslate) {
1574                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
1575                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
1576                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
1577                } else {
1578                    dirtyLayer(left + bounds.left, top + bounds.top,
1579                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
1580                }
1581            }
1582        }
1583#endif
1584
1585        if (pureTranslate) {
1586            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1587            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1588
1589            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1590                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1591                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1592                    true, !mesh->hasEmptyQuads);
1593        } else {
1594            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1595                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1596                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1597                    true, !mesh->hasEmptyQuads);
1598        }
1599    }
1600}
1601
1602/**
1603 * This function uses a similar approach to that of AA lines in the drawLines() function.
1604 * We expand the rectangle by a half pixel in screen space on all sides, and use a fragment
1605 * shader to compute the translucency of the color, determined by whether a given pixel is
1606 * within that boundary region and how far into the region it is.
1607 */
1608void OpenGLRenderer::drawAARect(float left, float top, float right, float bottom,
1609        int color, SkXfermode::Mode mode) {
1610    float inverseScaleX = 1.0f;
1611    float inverseScaleY = 1.0f;
1612    // The quad that we use needs to account for scaling.
1613    if (!mSnapshot->transform->isPureTranslate()) {
1614        Matrix4 *mat = mSnapshot->transform;
1615        float m00 = mat->data[Matrix4::kScaleX];
1616        float m01 = mat->data[Matrix4::kSkewY];
1617        float m02 = mat->data[2];
1618        float m10 = mat->data[Matrix4::kSkewX];
1619        float m11 = mat->data[Matrix4::kScaleX];
1620        float m12 = mat->data[6];
1621        float scaleX = sqrt(m00 * m00 + m01 * m01);
1622        float scaleY = sqrt(m10 * m10 + m11 * m11);
1623        inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1624        inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1625    }
1626
1627    setupDraw();
1628    setupDrawAALine();
1629    setupDrawColor(color);
1630    setupDrawColorFilter();
1631    setupDrawShader();
1632    setupDrawBlending(true, mode);
1633    setupDrawProgram();
1634    setupDrawModelViewIdentity(true);
1635    setupDrawColorUniforms();
1636    setupDrawColorFilterUniforms();
1637    setupDrawShaderIdentityUniforms();
1638
1639    AAVertex rects[4];
1640    AAVertex* aaVertices = &rects[0];
1641    void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1642    void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1643
1644    float boundarySizeX = .5 * inverseScaleX;
1645    float boundarySizeY = .5 * inverseScaleY;
1646
1647    // Adjust the rect by the AA boundary padding
1648    left -= boundarySizeX;
1649    right += boundarySizeX;
1650    top -= boundarySizeY;
1651    bottom += boundarySizeY;
1652
1653    float width = right - left;
1654    float height = bottom - top;
1655
1656    float boundaryWidthProportion = (width != 0) ? (2 * boundarySizeX) / width : 0;
1657    float boundaryHeightProportion = (height != 0) ? (2 * boundarySizeY) / height : 0;
1658    setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1659    int boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1660    int inverseBoundaryLengthSlot = mCaches.currentProgram->getUniform("inverseBoundaryLength");
1661    glUniform1f(boundaryLengthSlot, boundaryHeightProportion);
1662    glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryHeightProportion));
1663
1664    if (!quickReject(left, top, right, bottom)) {
1665        AAVertex::set(aaVertices++, left, bottom, 1, 1);
1666        AAVertex::set(aaVertices++, left, top, 1, 0);
1667        AAVertex::set(aaVertices++, right, bottom, 0, 1);
1668        AAVertex::set(aaVertices++, right, top, 0, 0);
1669        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1670        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1671    }
1672}
1673
1674/**
1675 * We draw lines as quads (tristrips). Using GL_LINES can be difficult because the rasterization
1676 * rules for those lines produces some unexpected results, and may vary between hardware devices.
1677 * The basics of lines-as-quads is easy; we simply find the normal to the line and position the
1678 * corners of the quads on either side of each line endpoint, separated by the strokeWidth
1679 * of the line. Hairlines are more involved because we need to account for transform scaling
1680 * to end up with a one-pixel-wide line in screen space..
1681 * Anti-aliased lines add another factor to the approach. We use a specialized fragment shader
1682 * in combination with values that we calculate and pass down in this method. The basic approach
1683 * is that the quad we create contains both the core line area plus a bounding area in which
1684 * the translucent/AA pixels are drawn. The values we calculate tell the shader what
1685 * proportion of the width and the length of a given segment is represented by the boundary
1686 * region. The quad ends up being exactly .5 pixel larger in all directions than the non-AA quad.
1687 * The bounding region is actually 1 pixel wide on all sides (half pixel on the outside, half pixel
1688 * on the inside). This ends up giving the result we want, with pixels that are completely
1689 * 'inside' the line area being filled opaquely and the other pixels being filled according to
1690 * how far into the boundary region they are, which is determined by shader interpolation.
1691 */
1692void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
1693    if (mSnapshot->isIgnored()) return;
1694
1695    const bool isAA = paint->isAntiAlias();
1696    // We use half the stroke width here because we're going to position the quad
1697    // corner vertices half of the width away from the line endpoints
1698    float halfStrokeWidth = paint->getStrokeWidth() * 0.5f;
1699    // A stroke width of 0 has a special meaning in Skia:
1700    // it draws a line 1 px wide regardless of current transform
1701    bool isHairLine = paint->getStrokeWidth() == 0.0f;
1702    float inverseScaleX = 1.0f;
1703    float inverseScaleY = 1.0f;
1704    bool scaled = false;
1705    int alpha;
1706    SkXfermode::Mode mode;
1707    int generatedVerticesCount = 0;
1708    int verticesCount = count;
1709    if (count > 4) {
1710        // Polyline: account for extra vertices needed for continuous tri-strip
1711        verticesCount += (count - 4);
1712    }
1713
1714    if (isHairLine || isAA) {
1715        // The quad that we use for AA and hairlines needs to account for scaling. For hairlines
1716        // the line on the screen should always be one pixel wide regardless of scale. For
1717        // AA lines, we only want one pixel of translucent boundary around the quad.
1718        if (!mSnapshot->transform->isPureTranslate()) {
1719            Matrix4 *mat = mSnapshot->transform;
1720            float m00 = mat->data[Matrix4::kScaleX];
1721            float m01 = mat->data[Matrix4::kSkewY];
1722            float m02 = mat->data[2];
1723            float m10 = mat->data[Matrix4::kSkewX];
1724            float m11 = mat->data[Matrix4::kScaleX];
1725            float m12 = mat->data[6];
1726            float scaleX = sqrt(m00*m00 + m01*m01);
1727            float scaleY = sqrt(m10*m10 + m11*m11);
1728            inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1729            inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1730            if (inverseScaleX != 1.0f || inverseScaleY != 1.0f) {
1731                scaled = true;
1732            }
1733        }
1734    }
1735
1736    getAlphaAndMode(paint, &alpha, &mode);
1737    setupDraw();
1738    if (isAA) {
1739        setupDrawAALine();
1740    }
1741    setupDrawColor(paint->getColor(), alpha);
1742    setupDrawColorFilter();
1743    setupDrawShader();
1744    if (isAA) {
1745        setupDrawBlending(true, mode);
1746    } else {
1747        setupDrawBlending(mode);
1748    }
1749    setupDrawProgram();
1750    setupDrawModelViewIdentity(true);
1751    setupDrawColorUniforms();
1752    setupDrawColorFilterUniforms();
1753    setupDrawShaderIdentityUniforms();
1754
1755    if (isHairLine) {
1756        // Set a real stroke width to be used in quad construction
1757        halfStrokeWidth = isAA? 1 : .5;
1758    } else if (isAA && !scaled) {
1759        // Expand boundary to enable AA calculations on the quad border
1760        halfStrokeWidth += .5f;
1761    }
1762    Vertex lines[verticesCount];
1763    Vertex* vertices = &lines[0];
1764    AAVertex wLines[verticesCount];
1765    AAVertex* aaVertices = &wLines[0];
1766    if (!isAA) {
1767        setupDrawVertices(vertices);
1768    } else {
1769        void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1770        void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1771        // innerProportion is the ratio of the inner (non-AA) part of the line to the total
1772        // AA stroke width (the base stroke width expanded by a half pixel on either side).
1773        // This value is used in the fragment shader to determine how to fill fragments.
1774        // We will need to calculate the actual width proportion on each segment for
1775        // scaled non-hairlines, since the boundary proportion may differ per-axis when scaled.
1776        float boundaryWidthProportion = 1 / (2 * halfStrokeWidth);
1777        setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1778    }
1779
1780    AAVertex* prevAAVertex = NULL;
1781    Vertex* prevVertex = NULL;
1782
1783    int boundaryLengthSlot = -1;
1784    int inverseBoundaryLengthSlot = -1;
1785    int boundaryWidthSlot = -1;
1786    int inverseBoundaryWidthSlot = -1;
1787    for (int i = 0; i < count; i += 4) {
1788        // a = start point, b = end point
1789        vec2 a(points[i], points[i + 1]);
1790        vec2 b(points[i + 2], points[i + 3]);
1791        float length = 0;
1792        float boundaryLengthProportion = 0;
1793        float boundaryWidthProportion = 0;
1794
1795        // Find the normal to the line
1796        vec2 n = (b - a).copyNormalized() * halfStrokeWidth;
1797        if (isHairLine) {
1798            if (isAA) {
1799                float wideningFactor;
1800                if (fabs(n.x) >= fabs(n.y)) {
1801                    wideningFactor = fabs(1.0f / n.x);
1802                } else {
1803                    wideningFactor = fabs(1.0f / n.y);
1804                }
1805                n *= wideningFactor;
1806            }
1807            if (scaled) {
1808                n.x *= inverseScaleX;
1809                n.y *= inverseScaleY;
1810            }
1811        } else if (scaled) {
1812            // Extend n by .5 pixel on each side, post-transform
1813            vec2 extendedN = n.copyNormalized();
1814            extendedN /= 2;
1815            extendedN.x *= inverseScaleX;
1816            extendedN.y *= inverseScaleY;
1817            float extendedNLength = extendedN.length();
1818            // We need to set this value on the shader prior to drawing
1819            boundaryWidthProportion = extendedNLength / (halfStrokeWidth + extendedNLength);
1820            n += extendedN;
1821        }
1822        float x = n.x;
1823        n.x = -n.y;
1824        n.y = x;
1825
1826        // aa lines expand the endpoint vertices to encompass the AA boundary
1827        if (isAA) {
1828            vec2 abVector = (b - a);
1829            length = abVector.length();
1830            abVector.normalize();
1831            if (scaled) {
1832                abVector.x *= inverseScaleX;
1833                abVector.y *= inverseScaleY;
1834                float abLength = abVector.length();
1835                boundaryLengthProportion = abLength / (length + abLength);
1836            } else {
1837                boundaryLengthProportion = .5 / (length + 1);
1838            }
1839            abVector /= 2;
1840            a -= abVector;
1841            b += abVector;
1842        }
1843
1844        // Four corners of the rectangle defining a thick line
1845        vec2 p1 = a - n;
1846        vec2 p2 = a + n;
1847        vec2 p3 = b + n;
1848        vec2 p4 = b - n;
1849
1850
1851        const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
1852        const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
1853        const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
1854        const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
1855
1856        if (!quickReject(left, top, right, bottom)) {
1857            if (!isAA) {
1858                if (prevVertex != NULL) {
1859                    // Issue two repeat vertices to create degenerate triangles to bridge
1860                    // between the previous line and the new one. This is necessary because
1861                    // we are creating a single triangle_strip which will contain
1862                    // potentially discontinuous line segments.
1863                    Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]);
1864                    Vertex::set(vertices++, p1.x, p1.y);
1865                    generatedVerticesCount += 2;
1866                }
1867                Vertex::set(vertices++, p1.x, p1.y);
1868                Vertex::set(vertices++, p2.x, p2.y);
1869                Vertex::set(vertices++, p4.x, p4.y);
1870                Vertex::set(vertices++, p3.x, p3.y);
1871                prevVertex = vertices - 1;
1872                generatedVerticesCount += 4;
1873            } else {
1874                if (!isHairLine && scaled) {
1875                    // Must set width proportions per-segment for scaled non-hairlines to use the
1876                    // correct AA boundary dimensions
1877                    if (boundaryWidthSlot < 0) {
1878                        boundaryWidthSlot =
1879                                mCaches.currentProgram->getUniform("boundaryWidth");
1880                        inverseBoundaryWidthSlot =
1881                                mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1882                    }
1883                    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1884                    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1885                }
1886                if (boundaryLengthSlot < 0) {
1887                    boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1888                    inverseBoundaryLengthSlot =
1889                            mCaches.currentProgram->getUniform("inverseBoundaryLength");
1890                }
1891                glUniform1f(boundaryLengthSlot, boundaryLengthProportion);
1892                glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryLengthProportion));
1893
1894                if (prevAAVertex != NULL) {
1895                    // Issue two repeat vertices to create degenerate triangles to bridge
1896                    // between the previous line and the new one. This is necessary because
1897                    // we are creating a single triangle_strip which will contain
1898                    // potentially discontinuous line segments.
1899                    AAVertex::set(aaVertices++,prevAAVertex->position[0],
1900                            prevAAVertex->position[1], prevAAVertex->width, prevAAVertex->length);
1901                    AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1902                    generatedVerticesCount += 2;
1903                }
1904                AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1905                AAVertex::set(aaVertices++, p1.x, p1.y, 1, 0);
1906                AAVertex::set(aaVertices++, p3.x, p3.y, 0, 1);
1907                AAVertex::set(aaVertices++, p2.x, p2.y, 0, 0);
1908                prevAAVertex = aaVertices - 1;
1909                generatedVerticesCount += 4;
1910            }
1911            dirtyLayer(a.x == b.x ? left - 1 : left, a.y == b.y ? top - 1 : top,
1912                    a.x == b.x ? right: right, a.y == b.y ? bottom: bottom,
1913                    *mSnapshot->transform);
1914        }
1915    }
1916    if (generatedVerticesCount > 0) {
1917       glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount);
1918    }
1919}
1920
1921void OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
1922    if (mSnapshot->isIgnored()) return;
1923
1924    // TODO: The paint's cap style defines whether the points are square or circular
1925    // TODO: Handle AA for round points
1926
1927    // A stroke width of 0 has a special meaning in Skia:
1928    // it draws an unscaled 1px point
1929    float strokeWidth = paint->getStrokeWidth();
1930    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1931    if (isHairLine) {
1932        // Now that we know it's hairline, we can set the effective width, to be used later
1933        strokeWidth = 1.0f;
1934    }
1935    const float halfWidth = strokeWidth / 2;
1936    int alpha;
1937    SkXfermode::Mode mode;
1938    getAlphaAndMode(paint, &alpha, &mode);
1939
1940    int verticesCount = count >> 1;
1941    int generatedVerticesCount = 0;
1942
1943    TextureVertex pointsData[verticesCount];
1944    TextureVertex* vertex = &pointsData[0];
1945
1946    setupDraw();
1947    setupDrawPoint(strokeWidth);
1948    setupDrawColor(paint->getColor(), alpha);
1949    setupDrawColorFilter();
1950    setupDrawShader();
1951    setupDrawBlending(mode);
1952    setupDrawProgram();
1953    setupDrawModelViewIdentity(true);
1954    setupDrawColorUniforms();
1955    setupDrawColorFilterUniforms();
1956    setupDrawPointUniforms();
1957    setupDrawShaderIdentityUniforms();
1958    setupDrawMesh(vertex);
1959
1960    for (int i = 0; i < count; i += 2) {
1961        TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
1962        generatedVerticesCount++;
1963        float left = points[i] - halfWidth;
1964        float right = points[i] + halfWidth;
1965        float top = points[i + 1] - halfWidth;
1966        float bottom = points [i + 1] + halfWidth;
1967        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1968    }
1969
1970    glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
1971}
1972
1973void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1974    // No need to check against the clip, we fill the clip region
1975    if (mSnapshot->isIgnored()) return;
1976
1977    Rect& clip(*mSnapshot->clipRect);
1978    clip.snapToPixelBoundaries();
1979
1980    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1981}
1982
1983void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) {
1984    if (!texture) return;
1985    const AutoTexture autoCleanup(texture);
1986
1987    const float x = left + texture->left - texture->offset;
1988    const float y = top + texture->top - texture->offset;
1989
1990    drawPathTexture(texture, x, y, paint);
1991}
1992
1993void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1994        float rx, float ry, SkPaint* paint) {
1995    if (mSnapshot->isIgnored()) return;
1996
1997    glActiveTexture(gTextureUnits[0]);
1998    const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
1999            right - left, bottom - top, rx, ry, paint);
2000    drawShape(left, top, texture, paint);
2001}
2002
2003void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) {
2004    if (mSnapshot->isIgnored()) return;
2005
2006    glActiveTexture(gTextureUnits[0]);
2007    const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint);
2008    drawShape(x - radius, y - radius, texture, paint);
2009}
2010
2011void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) {
2012    if (mSnapshot->isIgnored()) return;
2013
2014    glActiveTexture(gTextureUnits[0]);
2015    const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint);
2016    drawShape(left, top, texture, paint);
2017}
2018
2019void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2020        float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) {
2021    if (mSnapshot->isIgnored()) return;
2022
2023    if (fabs(sweepAngle) >= 360.0f) {
2024        drawOval(left, top, right, bottom, paint);
2025        return;
2026    }
2027
2028    glActiveTexture(gTextureUnits[0]);
2029    const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
2030            startAngle, sweepAngle, useCenter, paint);
2031    drawShape(left, top, texture, paint);
2032}
2033
2034void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom,
2035        SkPaint* paint) {
2036    if (mSnapshot->isIgnored()) return;
2037
2038    glActiveTexture(gTextureUnits[0]);
2039    const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint);
2040    drawShape(left, top, texture, paint);
2041}
2042
2043void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
2044    if (p->getStyle() != SkPaint::kFill_Style) {
2045        drawRectAsShape(left, top, right, bottom, p);
2046        return;
2047    }
2048
2049    if (quickReject(left, top, right, bottom)) {
2050        return;
2051    }
2052
2053    SkXfermode::Mode mode;
2054    if (!mCaches.extensions.hasFramebufferFetch()) {
2055        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
2056        if (!isMode) {
2057            // Assume SRC_OVER
2058            mode = SkXfermode::kSrcOver_Mode;
2059        }
2060    } else {
2061        mode = getXfermode(p->getXfermode());
2062    }
2063
2064    int color = p->getColor();
2065    if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) {
2066        drawAARect(left, top, right, bottom, color, mode);
2067    } else {
2068        drawColorRect(left, top, right, bottom, color, mode);
2069    }
2070}
2071
2072void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
2073        float x, float y, SkPaint* paint, float length) {
2074    if (text == NULL || count == 0) {
2075        return;
2076    }
2077    if (mSnapshot->isIgnored()) return;
2078
2079    // NOTE: AA and glyph id encoding are set in DisplayListRenderer.cpp
2080
2081    switch (paint->getTextAlign()) {
2082        case SkPaint::kCenter_Align:
2083            if (length < 0.0f) length = paint->measureText(text, bytesCount);
2084            x -= length / 2.0f;
2085            break;
2086        case SkPaint::kRight_Align:
2087            if (length < 0.0f) length = paint->measureText(text, bytesCount);
2088            x -= length;
2089            break;
2090        default:
2091            break;
2092    }
2093
2094    SkPaint::FontMetrics metrics;
2095    paint->getFontMetrics(&metrics, 0.0f);
2096    // If no length was specified, just perform the hit test on the Y axis
2097    if (quickReject(x, y + metrics.fTop,
2098            x + (length >= 0.0f ? length : INT_MAX / 2), y + metrics.fBottom)) {
2099        return;
2100    }
2101
2102    const float oldX = x;
2103    const float oldY = y;
2104    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2105    if (pureTranslate) {
2106        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2107        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2108    }
2109
2110    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
2111#if DEBUG_GLYPHS
2112    LOGD("OpenGLRenderer drawText() with FontID=%d", SkTypeface::UniqueID(paint->getTypeface()));
2113#endif
2114    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2115            paint->getTextSize());
2116
2117    int alpha;
2118    SkXfermode::Mode mode;
2119    getAlphaAndMode(paint, &alpha, &mode);
2120
2121    if (mHasShadow) {
2122        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2123        const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2124                paint, text, bytesCount, count, mShadowRadius);
2125        const AutoTexture autoCleanup(shadow);
2126
2127        const float sx = oldX - shadow->left + mShadowDx;
2128        const float sy = oldY - shadow->top + mShadowDy;
2129
2130        const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
2131        int shadowColor = mShadowColor;
2132        if (mShader) {
2133            shadowColor = 0xffffffff;
2134        }
2135
2136        glActiveTexture(gTextureUnits[0]);
2137        setupDraw();
2138        setupDrawWithTexture(true);
2139        setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2140        setupDrawColorFilter();
2141        setupDrawShader();
2142        setupDrawBlending(true, mode);
2143        setupDrawProgram();
2144        setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2145        setupDrawTexture(shadow->id);
2146        setupDrawPureColorUniforms();
2147        setupDrawColorFilterUniforms();
2148        setupDrawShaderUniforms();
2149        setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2150
2151        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2152
2153        finishDrawTexture();
2154    }
2155
2156    if (paint->getAlpha() == 0 && paint->getXfermode() == NULL) {
2157        return;
2158    }
2159
2160    // Pick the appropriate texture filtering
2161    bool linearFilter = mSnapshot->transform->changesBounds();
2162    if (pureTranslate && !linearFilter) {
2163        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2164    }
2165
2166    glActiveTexture(gTextureUnits[0]);
2167    setupDraw();
2168    setupDrawDirtyRegionsDisabled();
2169    setupDrawWithTexture(true);
2170    setupDrawAlpha8Color(paint->getColor(), alpha);
2171    setupDrawColorFilter();
2172    setupDrawShader();
2173    setupDrawBlending(true, mode);
2174    setupDrawProgram();
2175    setupDrawModelView(x, y, x, y, pureTranslate, true);
2176    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2177    setupDrawPureColorUniforms();
2178    setupDrawColorFilterUniforms();
2179    setupDrawShaderUniforms(pureTranslate);
2180
2181    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2182    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2183
2184#if RENDER_LAYERS_AS_REGIONS
2185    bool hasActiveLayer = hasLayer();
2186#else
2187    bool hasActiveLayer = false;
2188#endif
2189    mCaches.unbindMeshBuffer();
2190
2191    // Tell font renderer the locations of position and texture coord
2192    // attributes so it can bind its data properly
2193    int positionSlot = mCaches.currentProgram->position;
2194    fontRenderer.setAttributeBindingSlots(positionSlot, mTexCoordsSlot);
2195    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
2196            hasActiveLayer ? &bounds : NULL)) {
2197#if RENDER_LAYERS_AS_REGIONS
2198        if (hasActiveLayer) {
2199            if (!pureTranslate) {
2200                mSnapshot->transform->mapRect(bounds);
2201            }
2202            dirtyLayerUnchecked(bounds, getRegion());
2203        }
2204#endif
2205    }
2206
2207    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2208    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
2209
2210    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2211}
2212
2213void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
2214    if (mSnapshot->isIgnored()) return;
2215
2216    glActiveTexture(gTextureUnits[0]);
2217
2218    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2219    if (!texture) return;
2220    const AutoTexture autoCleanup(texture);
2221
2222    const float x = texture->left - texture->offset;
2223    const float y = texture->top - texture->offset;
2224
2225    drawPathTexture(texture, x, y, paint);
2226}
2227
2228void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
2229    if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) {
2230        return;
2231    }
2232
2233    glActiveTexture(gTextureUnits[0]);
2234
2235    int alpha;
2236    SkXfermode::Mode mode;
2237    getAlphaAndMode(paint, &alpha, &mode);
2238
2239    layer->setAlpha(alpha, mode);
2240
2241#if RENDER_LAYERS_AS_REGIONS
2242    if (!layer->region.isEmpty()) {
2243        if (layer->region.isRect()) {
2244            composeLayerRect(layer, layer->regionRect);
2245        } else if (layer->mesh) {
2246            const float a = alpha / 255.0f;
2247            const Rect& rect = layer->layer;
2248
2249            setupDraw();
2250            setupDrawWithTexture();
2251            setupDrawColor(a, a, a, a);
2252            setupDrawColorFilter();
2253            setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false);
2254            setupDrawProgram();
2255            setupDrawPureColorUniforms();
2256            setupDrawColorFilterUniforms();
2257            setupDrawTexture(layer->getTexture());
2258            if (mSnapshot->transform->isPureTranslate()) {
2259                x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2260                y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2261
2262                layer->setFilter(GL_NEAREST);
2263                setupDrawModelViewTranslate(x, y,
2264                        x + layer->layer.getWidth(), y + layer->layer.getHeight(), true);
2265            } else {
2266                layer->setFilter(GL_LINEAR);
2267                setupDrawModelViewTranslate(x, y,
2268                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
2269            }
2270            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
2271
2272            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
2273                    GL_UNSIGNED_SHORT, layer->meshIndices);
2274
2275            finishDrawTexture();
2276
2277#if DEBUG_LAYERS_AS_REGIONS
2278            drawRegionRects(layer->region);
2279#endif
2280        }
2281    }
2282#else
2283    const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
2284    composeLayerRect(layer, r);
2285#endif
2286}
2287
2288///////////////////////////////////////////////////////////////////////////////
2289// Shaders
2290///////////////////////////////////////////////////////////////////////////////
2291
2292void OpenGLRenderer::resetShader() {
2293    mShader = NULL;
2294}
2295
2296void OpenGLRenderer::setupShader(SkiaShader* shader) {
2297    mShader = shader;
2298    if (mShader) {
2299        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
2300    }
2301}
2302
2303///////////////////////////////////////////////////////////////////////////////
2304// Color filters
2305///////////////////////////////////////////////////////////////////////////////
2306
2307void OpenGLRenderer::resetColorFilter() {
2308    mColorFilter = NULL;
2309}
2310
2311void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
2312    mColorFilter = filter;
2313}
2314
2315///////////////////////////////////////////////////////////////////////////////
2316// Drop shadow
2317///////////////////////////////////////////////////////////////////////////////
2318
2319void OpenGLRenderer::resetShadow() {
2320    mHasShadow = false;
2321}
2322
2323void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
2324    mHasShadow = true;
2325    mShadowRadius = radius;
2326    mShadowDx = dx;
2327    mShadowDy = dy;
2328    mShadowColor = color;
2329}
2330
2331///////////////////////////////////////////////////////////////////////////////
2332// Drawing implementation
2333///////////////////////////////////////////////////////////////////////////////
2334
2335void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
2336        float x, float y, SkPaint* paint) {
2337    if (quickReject(x, y, x + texture->width, y + texture->height)) {
2338        return;
2339    }
2340
2341    int alpha;
2342    SkXfermode::Mode mode;
2343    getAlphaAndMode(paint, &alpha, &mode);
2344
2345    setupDraw();
2346    setupDrawWithTexture(true);
2347    setupDrawAlpha8Color(paint->getColor(), alpha);
2348    setupDrawColorFilter();
2349    setupDrawShader();
2350    setupDrawBlending(true, mode);
2351    setupDrawProgram();
2352    setupDrawModelView(x, y, x + texture->width, y + texture->height);
2353    setupDrawTexture(texture->id);
2354    setupDrawPureColorUniforms();
2355    setupDrawColorFilterUniforms();
2356    setupDrawShaderUniforms();
2357    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2358
2359    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2360
2361    finishDrawTexture();
2362}
2363
2364// Same values used by Skia
2365#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2366#define kStdUnderline_Offset    (1.0f / 9.0f)
2367#define kStdUnderline_Thickness (1.0f / 18.0f)
2368
2369void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
2370        float x, float y, SkPaint* paint) {
2371    // Handle underline and strike-through
2372    uint32_t flags = paint->getFlags();
2373    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2374        SkPaint paintCopy(*paint);
2375        float underlineWidth = length;
2376        // If length is > 0.0f, we already measured the text for the text alignment
2377        if (length <= 0.0f) {
2378            underlineWidth = paintCopy.measureText(text, bytesCount);
2379        }
2380
2381        float offsetX = 0;
2382        switch (paintCopy.getTextAlign()) {
2383            case SkPaint::kCenter_Align:
2384                offsetX = underlineWidth * 0.5f;
2385                break;
2386            case SkPaint::kRight_Align:
2387                offsetX = underlineWidth;
2388                break;
2389            default:
2390                break;
2391        }
2392
2393        if (underlineWidth > 0.0f) {
2394            const float textSize = paintCopy.getTextSize();
2395            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
2396
2397            const float left = x - offsetX;
2398            float top = 0.0f;
2399
2400            int linesCount = 0;
2401            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2402            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2403
2404            const int pointsCount = 4 * linesCount;
2405            float points[pointsCount];
2406            int currentPoint = 0;
2407
2408            if (flags & SkPaint::kUnderlineText_Flag) {
2409                top = y + textSize * kStdUnderline_Offset;
2410                points[currentPoint++] = left;
2411                points[currentPoint++] = top;
2412                points[currentPoint++] = left + underlineWidth;
2413                points[currentPoint++] = top;
2414            }
2415
2416            if (flags & SkPaint::kStrikeThruText_Flag) {
2417                top = y + textSize * kStdStrikeThru_Offset;
2418                points[currentPoint++] = left;
2419                points[currentPoint++] = top;
2420                points[currentPoint++] = left + underlineWidth;
2421                points[currentPoint++] = top;
2422            }
2423
2424            paintCopy.setStrokeWidth(strokeWidth);
2425
2426            drawLines(&points[0], pointsCount, &paintCopy);
2427        }
2428    }
2429}
2430
2431void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
2432        int color, SkXfermode::Mode mode, bool ignoreTransform) {
2433    // If a shader is set, preserve only the alpha
2434    if (mShader) {
2435        color |= 0x00ffffff;
2436    }
2437
2438    setupDraw();
2439    setupDrawColor(color);
2440    setupDrawShader();
2441    setupDrawColorFilter();
2442    setupDrawBlending(mode);
2443    setupDrawProgram();
2444    setupDrawModelView(left, top, right, bottom, ignoreTransform);
2445    setupDrawColorUniforms();
2446    setupDrawShaderUniforms(ignoreTransform);
2447    setupDrawColorFilterUniforms();
2448    setupDrawSimpleMesh();
2449
2450    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2451}
2452
2453void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2454        Texture* texture, SkPaint* paint) {
2455    int alpha;
2456    SkXfermode::Mode mode;
2457    getAlphaAndMode(paint, &alpha, &mode);
2458
2459    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2460
2461    if (mSnapshot->transform->isPureTranslate()) {
2462        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
2463        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
2464
2465        texture->setFilter(GL_NEAREST, true);
2466        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
2467                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
2468                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
2469    } else {
2470        texture->setFilter(FILTER(paint), true);
2471        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
2472                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
2473                GL_TRIANGLE_STRIP, gMeshCount);
2474    }
2475}
2476
2477void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2478        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
2479    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
2480            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
2481}
2482
2483void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
2484        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
2485        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
2486        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
2487
2488    setupDraw();
2489    setupDrawWithTexture();
2490    setupDrawColor(alpha, alpha, alpha, alpha);
2491    setupDrawColorFilter();
2492    setupDrawBlending(blend, mode, swapSrcDst);
2493    setupDrawProgram();
2494    if (!dirty) {
2495        setupDrawDirtyRegionsDisabled();
2496    }
2497    if (!ignoreScale) {
2498        setupDrawModelView(left, top, right, bottom, ignoreTransform);
2499    } else {
2500        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
2501    }
2502    setupDrawPureColorUniforms();
2503    setupDrawColorFilterUniforms();
2504    setupDrawTexture(texture);
2505    setupDrawMesh(vertices, texCoords, vbo);
2506
2507    glDrawArrays(drawMode, 0, elementsCount);
2508
2509    finishDrawTexture();
2510}
2511
2512void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
2513        ProgramDescription& description, bool swapSrcDst) {
2514    blend = blend || mode != SkXfermode::kSrcOver_Mode;
2515    if (blend) {
2516        if (mode <= SkXfermode::kScreen_Mode) {
2517            if (!mCaches.blend) {
2518                glEnable(GL_BLEND);
2519            }
2520
2521            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
2522            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
2523
2524            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
2525                glBlendFunc(sourceMode, destMode);
2526                mCaches.lastSrcMode = sourceMode;
2527                mCaches.lastDstMode = destMode;
2528            }
2529        } else {
2530            // These blend modes are not supported by OpenGL directly and have
2531            // to be implemented using shaders. Since the shader will perform
2532            // the blending, turn blending off here
2533            if (mCaches.extensions.hasFramebufferFetch()) {
2534                description.framebufferMode = mode;
2535                description.swapSrcDst = swapSrcDst;
2536            }
2537
2538            if (mCaches.blend) {
2539                glDisable(GL_BLEND);
2540            }
2541            blend = false;
2542        }
2543    } else if (mCaches.blend) {
2544        glDisable(GL_BLEND);
2545    }
2546    mCaches.blend = blend;
2547}
2548
2549bool OpenGLRenderer::useProgram(Program* program) {
2550    if (!program->isInUse()) {
2551        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
2552        program->use();
2553        mCaches.currentProgram = program;
2554        return false;
2555    }
2556    return true;
2557}
2558
2559void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
2560    TextureVertex* v = &mMeshVertices[0];
2561    TextureVertex::setUV(v++, u1, v1);
2562    TextureVertex::setUV(v++, u2, v1);
2563    TextureVertex::setUV(v++, u1, v2);
2564    TextureVertex::setUV(v++, u2, v2);
2565}
2566
2567void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
2568    if (paint) {
2569        *mode = getXfermode(paint->getXfermode());
2570
2571        // Skia draws using the color's alpha channel if < 255
2572        // Otherwise, it uses the paint's alpha
2573        int color = paint->getColor();
2574        *alpha = (color >> 24) & 0xFF;
2575        if (*alpha == 255) {
2576            *alpha = paint->getAlpha();
2577        }
2578    } else {
2579        *mode = SkXfermode::kSrcOver_Mode;
2580        *alpha = 255;
2581    }
2582}
2583
2584SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
2585    SkXfermode::Mode resultMode;
2586    if (!SkXfermode::AsMode(mode, &resultMode)) {
2587        resultMode = SkXfermode::kSrcOver_Mode;
2588    }
2589    return resultMode;
2590}
2591
2592}; // namespace uirenderer
2593}; // namespace android
2594