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