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