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