OpenGLRenderer.cpp revision 171c592f0b7066acf279863c8a52ddabea49d3db
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 <ui/Rect.h>
30
31#include "OpenGLRenderer.h"
32#include "DisplayListRenderer.h"
33#include "Vector.h"
34
35namespace android {
36namespace uirenderer {
37
38///////////////////////////////////////////////////////////////////////////////
39// Defines
40///////////////////////////////////////////////////////////////////////////////
41
42#define RAD_TO_DEG (180.0f / 3.14159265f)
43#define MIN_ANGLE 0.001f
44
45// TODO: This should be set in properties
46#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
47
48///////////////////////////////////////////////////////////////////////////////
49// Globals
50///////////////////////////////////////////////////////////////////////////////
51
52/**
53 * Structure mapping Skia xfermodes to OpenGL blending factors.
54 */
55struct Blender {
56    SkXfermode::Mode mode;
57    GLenum src;
58    GLenum dst;
59}; // struct Blender
60
61// In this array, the index of each Blender equals the value of the first
62// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
63static const Blender gBlends[] = {
64    { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
65    { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
66    { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
67    { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
68    { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
69    { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
70    { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
71    { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
72    { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
73    { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
74    { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
75    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
76};
77
78// This array contains the swapped version of each SkXfermode. For instance
79// this array's SrcOver blending mode is actually DstOver. You can refer to
80// createLayer() for more information on the purpose of this array.
81static const Blender gBlendsSwap[] = {
82    { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
83    { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
84    { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
85    { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
86    { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
87    { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
88    { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
89    { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
90    { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
91    { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
92    { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
93    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
94};
95
96static const GLenum gTextureUnits[] = {
97    GL_TEXTURE0,
98    GL_TEXTURE1,
99    GL_TEXTURE2
100};
101
102///////////////////////////////////////////////////////////////////////////////
103// Constructors/destructor
104///////////////////////////////////////////////////////////////////////////////
105
106OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
107    mShader = NULL;
108    mColorFilter = NULL;
109    mHasShadow = false;
110
111    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
112
113    mFirstSnapshot = new Snapshot;
114}
115
116OpenGLRenderer::~OpenGLRenderer() {
117    // The context has already been destroyed at this point, do not call
118    // GL APIs. All GL state should be kept in Caches.h
119}
120
121///////////////////////////////////////////////////////////////////////////////
122// Setup
123///////////////////////////////////////////////////////////////////////////////
124
125void OpenGLRenderer::setViewport(int width, int height) {
126    glViewport(0, 0, width, height);
127    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
128
129    mWidth = width;
130    mHeight = height;
131
132    mFirstSnapshot->height = height;
133    mFirstSnapshot->viewport.set(0, 0, width, height);
134
135    mDirtyClip = false;
136}
137
138void OpenGLRenderer::prepare(bool opaque) {
139    mCaches.clearGarbage();
140
141    mSnapshot = new Snapshot(mFirstSnapshot,
142            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
143    mSaveCount = 1;
144
145    glViewport(0, 0, mWidth, mHeight);
146
147    glDisable(GL_DITHER);
148
149    if (!opaque) {
150        glDisable(GL_SCISSOR_TEST);
151        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
152        glClear(GL_COLOR_BUFFER_BIT);
153    }
154
155    glEnable(GL_SCISSOR_TEST);
156    glScissor(0, 0, mWidth, mHeight);
157    mSnapshot->setClip(0.0f, 0.0f, mWidth, mHeight);
158}
159
160void OpenGLRenderer::finish() {
161#if DEBUG_OPENGL
162    GLenum status = GL_NO_ERROR;
163    while ((status = glGetError()) != GL_NO_ERROR) {
164        LOGD("GL error from OpenGLRenderer: 0x%x", status);
165    }
166#endif
167#if DEBUG_MEMORY_USAGE
168    mCaches.dumpMemoryUsage();
169#else
170    if (mCaches.getDebugLevel() & kDebugMemory) {
171        mCaches.dumpMemoryUsage();
172    }
173#endif
174}
175
176void OpenGLRenderer::acquireContext() {
177    if (mCaches.currentProgram) {
178        if (mCaches.currentProgram->isInUse()) {
179            mCaches.currentProgram->remove();
180            mCaches.currentProgram = NULL;
181        }
182    }
183    mCaches.unbindMeshBuffer();
184}
185
186void OpenGLRenderer::releaseContext() {
187    glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight());
188
189    glEnable(GL_SCISSOR_TEST);
190    dirtyClip();
191
192    glDisable(GL_DITHER);
193
194    glBindFramebuffer(GL_FRAMEBUFFER, 0);
195    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
196
197    mCaches.blend = true;
198    glEnable(GL_BLEND);
199    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
200    glBlendEquation(GL_FUNC_ADD);
201}
202
203///////////////////////////////////////////////////////////////////////////////
204// State management
205///////////////////////////////////////////////////////////////////////////////
206
207int OpenGLRenderer::getSaveCount() const {
208    return mSaveCount;
209}
210
211int OpenGLRenderer::save(int flags) {
212    return saveSnapshot(flags);
213}
214
215void OpenGLRenderer::restore() {
216    if (mSaveCount > 1) {
217        restoreSnapshot();
218    }
219}
220
221void OpenGLRenderer::restoreToCount(int saveCount) {
222    if (saveCount < 1) saveCount = 1;
223
224    while (mSaveCount > saveCount) {
225        restoreSnapshot();
226    }
227}
228
229int OpenGLRenderer::saveSnapshot(int flags) {
230    mSnapshot = new Snapshot(mSnapshot, flags);
231    return mSaveCount++;
232}
233
234bool OpenGLRenderer::restoreSnapshot() {
235    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
236    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
237    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
238
239    sp<Snapshot> current = mSnapshot;
240    sp<Snapshot> previous = mSnapshot->previous;
241
242    if (restoreOrtho) {
243        Rect& r = previous->viewport;
244        glViewport(r.left, r.top, r.right, r.bottom);
245        mOrthoMatrix.load(current->orthoMatrix);
246    }
247
248    mSaveCount--;
249    mSnapshot = previous;
250
251    if (restoreClip) {
252        dirtyClip();
253    }
254
255    if (restoreLayer) {
256        composeLayer(current, previous);
257    }
258
259    return restoreClip;
260}
261
262///////////////////////////////////////////////////////////////////////////////
263// Layers
264///////////////////////////////////////////////////////////////////////////////
265
266int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
267        SkPaint* p, int flags) {
268    const GLuint previousFbo = mSnapshot->fbo;
269    const int count = saveSnapshot(flags);
270
271    if (!mSnapshot->isIgnored()) {
272        int alpha = 255;
273        SkXfermode::Mode mode;
274
275        if (p) {
276            alpha = p->getAlpha();
277            if (!mCaches.extensions.hasFramebufferFetch()) {
278                const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
279                if (!isMode) {
280                    // Assume SRC_OVER
281                    mode = SkXfermode::kSrcOver_Mode;
282                }
283            } else {
284                mode = getXfermode(p->getXfermode());
285            }
286        } else {
287            mode = SkXfermode::kSrcOver_Mode;
288        }
289
290        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
291    }
292
293    return count;
294}
295
296int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
297        int alpha, int flags) {
298    if (alpha >= 255 - ALPHA_THRESHOLD) {
299        return saveLayer(left, top, right, bottom, NULL, flags);
300    } else {
301        SkPaint paint;
302        paint.setAlpha(alpha);
303        return saveLayer(left, top, right, bottom, &paint, flags);
304    }
305}
306
307/**
308 * Layers are viewed by Skia are slightly different than layers in image editing
309 * programs (for instance.) When a layer is created, previously created layers
310 * and the frame buffer still receive every drawing command. For instance, if a
311 * layer is created and a shape intersecting the bounds of the layers and the
312 * framebuffer is draw, the shape will be drawn on both (unless the layer was
313 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
314 *
315 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
316 * texture. Unfortunately, this is inefficient as it requires every primitive to
317 * be drawn n + 1 times, where n is the number of active layers. In practice this
318 * means, for every primitive:
319 *   - Switch active frame buffer
320 *   - Change viewport, clip and projection matrix
321 *   - Issue the drawing
322 *
323 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
324 * To avoid this, layers are implemented in a different way here, at least in the
325 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
326 * is set. When this flag is set we can redirect all drawing operations into a
327 * single FBO.
328 *
329 * This implementation relies on the frame buffer being at least RGBA 8888. When
330 * a layer is created, only a texture is created, not an FBO. The content of the
331 * frame buffer contained within the layer's bounds is copied into this texture
332 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
333 * buffer and drawing continues as normal. This technique therefore treats the
334 * frame buffer as a scratch buffer for the layers.
335 *
336 * To compose the layers back onto the frame buffer, each layer texture
337 * (containing the original frame buffer data) is drawn as a simple quad over
338 * the frame buffer. The trick is that the quad is set as the composition
339 * destination in the blending equation, and the frame buffer becomes the source
340 * of the composition.
341 *
342 * Drawing layers with an alpha value requires an extra step before composition.
343 * An empty quad is drawn over the layer's region in the frame buffer. This quad
344 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
345 * quad is used to multiply the colors in the frame buffer. This is achieved by
346 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
347 * GL_ZERO, GL_SRC_ALPHA.
348 *
349 * Because glCopyTexImage2D() can be slow, an alternative implementation might
350 * be use to draw a single clipped layer. The implementation described above
351 * is correct in every case.
352 *
353 * (1) The frame buffer is actually not cleared right away. To allow the GPU
354 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
355 *     buffer is left untouched until the first drawing operation. Only when
356 *     something actually gets drawn are the layers regions cleared.
357 */
358bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
359        float right, float bottom, int alpha, SkXfermode::Mode mode,
360        int flags, GLuint previousFbo) {
361    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
362    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
363
364    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
365
366    // Window coordinates of the layer
367    Rect bounds(left, top, right, bottom);
368    if (fboLayer) {
369        // Clear the previous layer regions before we change the viewport
370        clearLayerRegions();
371    } else {
372        mSnapshot->transform->mapRect(bounds);
373
374        // Layers only make sense if they are in the framebuffer's bounds
375        bounds.intersect(*snapshot->clipRect);
376
377        // We cannot work with sub-pixels in this case
378        bounds.snapToPixelBoundaries();
379
380        // When the layer is not an FBO, we may use glCopyTexImage so we
381        // need to make sure the layer does not extend outside the bounds
382        // of the framebuffer
383        bounds.intersect(snapshot->previous->viewport);
384    }
385
386    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
387            bounds.getHeight() > mCaches.maxTextureSize) {
388        snapshot->empty = fboLayer;
389    } else {
390        snapshot->invisible = snapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
391    }
392
393    // Bail out if we won't draw in this snapshot
394    if (snapshot->invisible || snapshot->empty) {
395        return false;
396    }
397
398    glActiveTexture(gTextureUnits[0]);
399    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
400    if (!layer) {
401        return false;
402    }
403
404    layer->mode = mode;
405    layer->alpha = alpha;
406    layer->layer.set(bounds);
407    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
408            bounds.getWidth() / float(layer->width), 0.0f);
409    layer->colorFilter = mColorFilter;
410
411    // Save the layer in the snapshot
412    snapshot->flags |= Snapshot::kFlagIsLayer;
413    snapshot->layer = layer;
414
415    if (fboLayer) {
416        return createFboLayer(layer, bounds, snapshot, previousFbo);
417    } else {
418        // Copy the framebuffer into the layer
419        glBindTexture(GL_TEXTURE_2D, layer->texture);
420
421        if (layer->empty) {
422            glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left,
423                    snapshot->height - bounds.bottom, layer->width, layer->height, 0);
424            layer->empty = false;
425        } else {
426            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
427                    snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
428        }
429
430        // Enqueue the buffer coordinates to clear the corresponding region later
431        mLayers.push(new Rect(bounds));
432    }
433
434    return true;
435}
436
437bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
438        GLuint previousFbo) {
439    layer->fbo = mCaches.fboCache.get();
440
441#if RENDER_LAYERS_AS_REGIONS
442    snapshot->region = &snapshot->layer->region;
443    snapshot->flags |= Snapshot::kFlagFboTarget;
444#endif
445
446    Rect clip(bounds);
447    snapshot->transform->mapRect(clip);
448    clip.intersect(*snapshot->clipRect);
449    clip.snapToPixelBoundaries();
450    clip.intersect(snapshot->previous->viewport);
451
452    mat4 inverse;
453    inverse.loadInverse(*mSnapshot->transform);
454
455    inverse.mapRect(clip);
456    clip.snapToPixelBoundaries();
457    clip.intersect(bounds);
458    clip.translate(-bounds.left, -bounds.top);
459
460    snapshot->flags |= Snapshot::kFlagIsFboLayer;
461    snapshot->fbo = layer->fbo;
462    snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
463    snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
464    snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
465    snapshot->height = bounds.getHeight();
466    snapshot->flags |= Snapshot::kFlagDirtyOrtho;
467    snapshot->orthoMatrix.load(mOrthoMatrix);
468
469    // Bind texture to FBO
470    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
471    glBindTexture(GL_TEXTURE_2D, layer->texture);
472
473    // Initialize the texture if needed
474    if (layer->empty) {
475        layer->empty = false;
476        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
477                GL_RGBA, GL_UNSIGNED_BYTE, NULL);
478    }
479
480    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
481            layer->texture, 0);
482
483#if DEBUG_LAYERS_AS_REGIONS
484    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
485    if (status != GL_FRAMEBUFFER_COMPLETE) {
486        LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
487
488        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
489        glDeleteTextures(1, &layer->texture);
490        mCaches.fboCache.put(layer->fbo);
491
492        delete layer;
493
494        return false;
495    }
496#endif
497
498    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
499    glScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
500            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
501    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
502    glClear(GL_COLOR_BUFFER_BIT);
503
504    dirtyClip();
505
506    // Change the ortho projection
507    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
508    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
509
510    return true;
511}
512
513/**
514 * Read the documentation of createLayer() before doing anything in this method.
515 */
516void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
517    if (!current->layer) {
518        LOGE("Attempting to compose a layer that does not exist");
519        return;
520    }
521
522    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
523
524    if (fboLayer) {
525        // Unbind current FBO and restore previous one
526        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
527    }
528
529    Layer* layer = current->layer;
530    const Rect& rect = layer->layer;
531
532    if (!fboLayer && layer->alpha < 255) {
533        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
534                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
535        // Required below, composeLayerRect() will divide by 255
536        layer->alpha = 255;
537    }
538
539    mCaches.unbindMeshBuffer();
540
541    glActiveTexture(gTextureUnits[0]);
542
543    // When the layer is stored in an FBO, we can save a bit of fillrate by
544    // drawing only the dirty region
545    if (fboLayer) {
546        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
547        if (layer->colorFilter) {
548            setupColorFilter(layer->colorFilter);
549        }
550        composeLayerRegion(layer, rect);
551        if (layer->colorFilter) {
552            resetColorFilter();
553        }
554    } else {
555        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
556        composeLayerRect(layer, rect, true);
557    }
558
559    if (fboLayer) {
560        // Detach the texture from the FBO
561        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
562        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
563        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
564
565        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
566        mCaches.fboCache.put(current->fbo);
567    }
568
569    dirtyClip();
570
571    // Failing to add the layer to the cache should happen only if the layer is too large
572    if (!mCaches.layerCache.put(layer)) {
573        LAYER_LOGD("Deleting layer");
574        glDeleteTextures(1, &layer->texture);
575        delete layer;
576    }
577}
578
579void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
580    const Rect& texCoords = layer->texCoords;
581    resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom);
582
583    drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
584            layer->alpha / 255.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
585            &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, swap, swap);
586
587    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
588}
589
590void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
591#if RENDER_LAYERS_AS_REGIONS
592    if (layer->region.isRect()) {
593        composeLayerRect(layer, rect);
594        layer->region.clear();
595        return;
596    }
597
598    if (!layer->region.isEmpty()) {
599        size_t count;
600        const android::Rect* rects = layer->region.getArray(&count);
601
602        setupDraw();
603
604        ProgramDescription description;
605        description.hasTexture = true;
606
607        const float alpha = layer->alpha / 255.0f;
608        const bool setColor = description.setColor(alpha, alpha, alpha, alpha);
609        chooseBlending(layer->blend || layer->alpha < 255, layer->mode, description, false);
610
611        useProgram(mCaches.programCache.get(description));
612
613        // Texture
614        bindTexture(layer->texture);
615        glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
616
617        // Always premultiplied
618        if (setColor) {
619            mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha);
620        }
621
622        // Mesh
623        int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
624        glEnableVertexAttribArray(texCoordsSlot);
625
626        mModelView.loadIdentity();
627        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
628
629        const float texX = 1.0f / float(layer->width);
630        const float texY = 1.0f / float(layer->height);
631
632        TextureVertex* mesh = mCaches.getRegionMesh();
633        GLsizei numQuads = 0;
634
635        glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
636                gMeshStride, &mesh[0].position[0]);
637        glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE,
638                gMeshStride, &mesh[0].texture[0]);
639
640        for (size_t i = 0; i < count; i++) {
641            const android::Rect* r = &rects[i];
642
643            const float u1 = r->left * texX;
644            const float v1 = (rect.getHeight() - r->top) * texY;
645            const float u2 = r->right * texX;
646            const float v2 = (rect.getHeight() - r->bottom) * texY;
647
648            // TODO: Reject quads outside of the clip
649            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
650            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
651            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
652            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
653
654            numQuads++;
655
656            if (numQuads >= REGION_MESH_QUAD_COUNT) {
657                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
658                numQuads = 0;
659                mesh = mCaches.getRegionMesh();
660            }
661        }
662
663        if (numQuads > 0) {
664            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
665        }
666
667        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
668        glDisableVertexAttribArray(texCoordsSlot);
669
670#if DEBUG_LAYERS_AS_REGIONS
671        uint32_t colors[] = {
672                0x7fff0000, 0x7f00ff00,
673                0x7f0000ff, 0x7fff00ff,
674        };
675
676        int offset = 0;
677        int32_t top = rects[0].top;
678        int i = 0;
679
680        for (size_t i = 0; i < count; i++) {
681            if (top != rects[i].top) {
682                offset ^= 0x2;
683                top = rects[i].top;
684            }
685
686            Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
687            drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
688                    SkXfermode::kSrcOver_Mode);
689        }
690#endif
691
692        layer->region.clear();
693    }
694#else
695    composeLayerRect(layer, rect);
696#endif
697}
698
699void OpenGLRenderer::dirtyLayer(const float left, const float top,
700        const float right, const float bottom, const mat4 transform) {
701#if RENDER_LAYERS_AS_REGIONS
702    if ((mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region) {
703        Rect bounds(left, top, right, bottom);
704        transform.mapRect(bounds);
705        bounds.intersect(*mSnapshot->clipRect);
706        bounds.snapToPixelBoundaries();
707
708        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
709        if (!dirty.isEmpty()) {
710            mSnapshot->region->orSelf(dirty);
711        }
712    }
713#endif
714}
715
716void OpenGLRenderer::dirtyLayer(const float left, const float top,
717        const float right, const float bottom) {
718#if RENDER_LAYERS_AS_REGIONS
719    if ((mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region) {
720        Rect bounds(left, top, right, bottom);
721        bounds.intersect(*mSnapshot->clipRect);
722        bounds.snapToPixelBoundaries();
723
724        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
725        if (!dirty.isEmpty()) {
726            mSnapshot->region->orSelf(dirty);
727        }
728    }
729#endif
730}
731
732void OpenGLRenderer::clearLayerRegions() {
733    if (mLayers.size() == 0 || mSnapshot->isIgnored()) return;
734
735    Rect clipRect(*mSnapshot->clipRect);
736    clipRect.snapToPixelBoundaries();
737
738    for (uint32_t i = 0; i < mLayers.size(); i++) {
739        Rect* bounds = mLayers.itemAt(i);
740        if (clipRect.intersects(*bounds)) {
741            // Clear the framebuffer where the layer will draw
742            glScissor(bounds->left, mSnapshot->height - bounds->bottom,
743                    bounds->getWidth(), bounds->getHeight());
744            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
745            glClear(GL_COLOR_BUFFER_BIT);
746
747            // Restore the clip
748            dirtyClip();
749        }
750
751        delete bounds;
752    }
753
754    mLayers.clear();
755}
756
757///////////////////////////////////////////////////////////////////////////////
758// Transforms
759///////////////////////////////////////////////////////////////////////////////
760
761void OpenGLRenderer::translate(float dx, float dy) {
762    mSnapshot->transform->translate(dx, dy, 0.0f);
763}
764
765void OpenGLRenderer::rotate(float degrees) {
766    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
767}
768
769void OpenGLRenderer::scale(float sx, float sy) {
770    mSnapshot->transform->scale(sx, sy, 1.0f);
771}
772
773void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
774    mSnapshot->transform->load(*matrix);
775}
776
777const float* OpenGLRenderer::getMatrix() const {
778    if (mSnapshot->fbo != 0) {
779        return &mSnapshot->transform->data[0];
780    }
781    return &mIdentity.data[0];
782}
783
784void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
785    mSnapshot->transform->copyTo(*matrix);
786}
787
788void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
789    SkMatrix transform;
790    mSnapshot->transform->copyTo(transform);
791    transform.preConcat(*matrix);
792    mSnapshot->transform->load(transform);
793}
794
795///////////////////////////////////////////////////////////////////////////////
796// Clipping
797///////////////////////////////////////////////////////////////////////////////
798
799void OpenGLRenderer::setScissorFromClip() {
800    Rect clip(*mSnapshot->clipRect);
801    clip.snapToPixelBoundaries();
802    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
803    mDirtyClip = false;
804}
805
806const Rect& OpenGLRenderer::getClipBounds() {
807    return mSnapshot->getLocalClip();
808}
809
810bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
811    if (mSnapshot->isIgnored()) {
812        return true;
813    }
814
815    Rect r(left, top, right, bottom);
816    mSnapshot->transform->mapRect(r);
817    r.snapToPixelBoundaries();
818
819    Rect clipRect(*mSnapshot->clipRect);
820    clipRect.snapToPixelBoundaries();
821
822    return !clipRect.intersects(r);
823}
824
825bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
826    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
827    if (clipped) {
828        dirtyClip();
829    }
830    return !mSnapshot->clipRect->isEmpty();
831}
832
833///////////////////////////////////////////////////////////////////////////////
834// Drawing commands
835///////////////////////////////////////////////////////////////////////////////
836
837void OpenGLRenderer::setupDraw() {
838    clearLayerRegions();
839    if (mDirtyClip) {
840        setScissorFromClip();
841    }
842    mDescription.reset();
843    mSetShaderColor = false;
844    mColorSet = false;
845    mColorA = mColorR = mColorG = mColorB = 0.0f;
846    mTextureUnit = 0;
847    mTrackDirtyRegions = true;
848    mTexCoordsSlot = -1;
849}
850
851void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
852    mDescription.hasTexture = true;
853    mDescription.hasAlpha8Texture = isAlpha8;
854}
855
856void OpenGLRenderer::setupDrawColor(int color) {
857    setupDrawColor(color, (color >> 24) & 0xFF);
858}
859
860void OpenGLRenderer::setupDrawColor(int color, int alpha) {
861    mColorA = alpha / 255.0f;
862    const float a = mColorA / 255.0f;
863    mColorR = a * ((color >> 16) & 0xFF);
864    mColorG = a * ((color >>  8) & 0xFF);
865    mColorB = a * ((color      ) & 0xFF);
866    mColorSet = true;
867    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
868}
869
870void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
871    mColorA = alpha / 255.0f;
872    const float a = mColorA / 255.0f;
873    mColorR = a * ((color >> 16) & 0xFF);
874    mColorG = a * ((color >>  8) & 0xFF);
875    mColorB = a * ((color      ) & 0xFF);
876    mColorSet = true;
877    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
878}
879
880void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
881    mColorA = a;
882    mColorR = r;
883    mColorG = g;
884    mColorB = b;
885    mColorSet = true;
886    mSetShaderColor = mDescription.setColor(r, g, b, a);
887}
888
889void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) {
890    mColorA = a;
891    mColorR = r;
892    mColorG = g;
893    mColorB = b;
894    mColorSet = true;
895    mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a);
896}
897
898void OpenGLRenderer::setupDrawShader() {
899    if (mShader) {
900        mShader->describe(mDescription, mCaches.extensions);
901    }
902}
903
904void OpenGLRenderer::setupDrawColorFilter() {
905    if (mColorFilter) {
906        mColorFilter->describe(mDescription, mCaches.extensions);
907    }
908}
909
910void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
911    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
912            mDescription, swapSrcDst);
913}
914
915void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
916    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
917            mDescription, swapSrcDst);
918}
919
920void OpenGLRenderer::setupDrawProgram() {
921    useProgram(mCaches.programCache.get(mDescription));
922}
923
924void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
925    mTrackDirtyRegions = false;
926}
927
928void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
929        bool ignoreTransform) {
930    mModelView.loadTranslate(left, top, 0.0f);
931    if (!ignoreTransform) {
932        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
933        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
934    } else {
935        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
936        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
937    }
938}
939
940void OpenGLRenderer::setupDrawModelViewIdentity() {
941    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform);
942}
943
944void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
945        bool ignoreTransform, bool ignoreModelView) {
946    if (!ignoreModelView) {
947        mModelView.loadTranslate(left, top, 0.0f);
948        mModelView.scale(right - left, bottom - top, 1.0f);
949    } else {
950        mModelView.loadIdentity();
951    }
952    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
953    if (!ignoreTransform) {
954        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
955        if (mTrackDirtyRegions && dirty) {
956            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
957        }
958    } else {
959        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
960        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
961    }
962}
963
964void OpenGLRenderer::setupDrawColorUniforms() {
965    if (mColorSet || (mShader && mSetShaderColor)) {
966        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
967    }
968}
969
970void OpenGLRenderer::setupDrawPureColorUniforms() {
971    if (mSetShaderColor) {
972        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
973    }
974}
975
976void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
977    if (mShader) {
978        if (ignoreTransform) {
979            mModelView.loadInverse(*mSnapshot->transform);
980        }
981        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
982    }
983}
984
985void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
986    if (mShader) {
987        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
988    }
989}
990
991void OpenGLRenderer::setupDrawColorFilterUniforms() {
992    if (mColorFilter) {
993        mColorFilter->setupProgram(mCaches.currentProgram);
994    }
995}
996
997void OpenGLRenderer::setupDrawSimpleMesh() {
998    mCaches.bindMeshBuffer();
999    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1000            gMeshStride, 0);
1001}
1002
1003void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1004    bindTexture(texture);
1005    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1006
1007    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1008    glEnableVertexAttribArray(mTexCoordsSlot);
1009}
1010
1011void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1012    if (!vertices) {
1013        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1014    } else {
1015        mCaches.unbindMeshBuffer();
1016    }
1017    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1018            gMeshStride, vertices);
1019    if (mTexCoordsSlot > 0) {
1020        glVertexAttribPointer(mTexCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1021    }
1022}
1023
1024void OpenGLRenderer::finishDrawTexture() {
1025    glDisableVertexAttribArray(mTexCoordsSlot);
1026}
1027
1028///////////////////////////////////////////////////////////////////////////////
1029// Drawing
1030///////////////////////////////////////////////////////////////////////////////
1031
1032void OpenGLRenderer::drawDisplayList(DisplayList* displayList) {
1033    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1034    // will be performed by the display list itself
1035    if (displayList) {
1036        displayList->replay(*this);
1037    }
1038}
1039
1040void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1041    const float right = left + bitmap->width();
1042    const float bottom = top + bitmap->height();
1043
1044    if (quickReject(left, top, right, bottom)) {
1045        return;
1046    }
1047
1048    glActiveTexture(gTextureUnits[0]);
1049    Texture* texture = mCaches.textureCache.get(bitmap);
1050    if (!texture) return;
1051    const AutoTexture autoCleanup(texture);
1052
1053    drawTextureRect(left, top, right, bottom, texture, paint);
1054}
1055
1056void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1057    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1058    const mat4 transform(*matrix);
1059    transform.mapRect(r);
1060
1061    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1062        return;
1063    }
1064
1065    glActiveTexture(gTextureUnits[0]);
1066    Texture* texture = mCaches.textureCache.get(bitmap);
1067    if (!texture) return;
1068    const AutoTexture autoCleanup(texture);
1069
1070    // This could be done in a cheaper way, all we need is pass the matrix
1071    // to the vertex shader. The save/restore is a bit overkill.
1072    save(SkCanvas::kMatrix_SaveFlag);
1073    concatMatrix(matrix);
1074    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1075    restore();
1076}
1077
1078void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1079         float srcLeft, float srcTop, float srcRight, float srcBottom,
1080         float dstLeft, float dstTop, float dstRight, float dstBottom,
1081         SkPaint* paint) {
1082    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1083        return;
1084    }
1085
1086    glActiveTexture(gTextureUnits[0]);
1087    Texture* texture = mCaches.textureCache.get(bitmap);
1088    if (!texture) return;
1089    const AutoTexture autoCleanup(texture);
1090    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1091
1092    const float width = texture->width;
1093    const float height = texture->height;
1094
1095    const float u1 = srcLeft / width;
1096    const float v1 = srcTop / height;
1097    const float u2 = srcRight / width;
1098    const float v2 = srcBottom / height;
1099
1100    mCaches.unbindMeshBuffer();
1101    resetDrawTextureTexCoords(u1, v1, u2, v2);
1102
1103    int alpha;
1104    SkXfermode::Mode mode;
1105    getAlphaAndMode(paint, &alpha, &mode);
1106
1107    if (mSnapshot->transform->isPureTranslate()) {
1108        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1109        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1110
1111        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1112                texture->id, alpha / 255.0f, mode, texture->blend,
1113                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1114                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1115    } else {
1116        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1117                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1118                GL_TRIANGLE_STRIP, gMeshCount);
1119    }
1120
1121    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1122}
1123
1124void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1125        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1126        float left, float top, float right, float bottom, SkPaint* paint) {
1127    if (quickReject(left, top, right, bottom)) {
1128        return;
1129    }
1130
1131    glActiveTexture(gTextureUnits[0]);
1132    Texture* texture = mCaches.textureCache.get(bitmap);
1133    if (!texture) return;
1134    const AutoTexture autoCleanup(texture);
1135    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1136
1137    int alpha;
1138    SkXfermode::Mode mode;
1139    getAlphaAndMode(paint, &alpha, &mode);
1140
1141    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1142            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1143
1144    if (mesh && mesh->verticesCount > 0) {
1145        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1146#if RENDER_LAYERS_AS_REGIONS
1147        // Mark the current layer dirty where we are going to draw the patch
1148        if ((mSnapshot->flags & Snapshot::kFlagFboTarget) &&
1149                mSnapshot->region && mesh->hasEmptyQuads) {
1150            const size_t count = mesh->quads.size();
1151            for (size_t i = 0; i < count; i++) {
1152                const Rect& bounds = mesh->quads.itemAt(i);
1153                if (pureTranslate) {
1154                    const float x = (int) floorf(bounds.left + 0.5f);
1155                    const float y = (int) floorf(bounds.top + 0.5f);
1156                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
1157                            *mSnapshot->transform);
1158                } else {
1159                    dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom,
1160                            *mSnapshot->transform);
1161                }
1162            }
1163        }
1164#endif
1165
1166        if (pureTranslate) {
1167            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1168            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1169
1170            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1171                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1172                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1173                    true, !mesh->hasEmptyQuads);
1174        } else {
1175            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1176                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1177                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1178                    true, !mesh->hasEmptyQuads);
1179        }
1180    }
1181}
1182
1183void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
1184    // TODO: Should do quickReject for each line
1185    if (mSnapshot->isIgnored()) return;
1186
1187    const bool isAA = paint->isAntiAlias();
1188    const float strokeWidth = paint->getStrokeWidth() * 0.5f;
1189    // A stroke width of 0 has a special meaningin Skia:
1190    // it draws an unscaled 1px wide line
1191    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1192
1193    int alpha;
1194    SkXfermode::Mode mode;
1195    getAlphaAndMode(paint, &alpha, &mode);
1196
1197    int verticesCount = count >> 2;
1198    if (!isHairLine) {
1199        // TODO: AA needs more vertices
1200        verticesCount *= 6;
1201    } else {
1202        // TODO: AA will be different
1203        verticesCount *= 2;
1204    }
1205
1206    TextureVertex lines[verticesCount];
1207    TextureVertex* vertex = &lines[0];
1208
1209    setupDraw();
1210    setupDrawColor(paint->getColor(), alpha);
1211    setupDrawColorFilter();
1212    setupDrawShader();
1213    setupDrawBlending(mode);
1214    setupDrawProgram();
1215    setupDrawModelViewIdentity();
1216    setupDrawColorUniforms();
1217    setupDrawColorFilterUniforms();
1218    setupDrawShaderIdentityUniforms();
1219    setupDrawMesh(vertex);
1220
1221    if (!isHairLine) {
1222        // TODO: Handle the AA case
1223        for (int i = 0; i < count; i += 4) {
1224            // a = start point, b = end point
1225            vec2 a(points[i], points[i + 1]);
1226            vec2 b(points[i + 2], points[i + 3]);
1227
1228            // Bias to snap to the same pixels as Skia
1229            a += 0.375;
1230            b += 0.375;
1231
1232            // Find the normal to the line
1233            vec2 n = (b - a).copyNormalized() * strokeWidth;
1234            float x = n.x;
1235            n.x = -n.y;
1236            n.y = x;
1237
1238            // Four corners of the rectangle defining a thick line
1239            vec2 p1 = a - n;
1240            vec2 p2 = a + n;
1241            vec2 p3 = b + n;
1242            vec2 p4 = b - n;
1243
1244            // Draw the line as 2 triangles, could be optimized
1245            // by using only 4 vertices and the correct indices
1246            // Also we should probably used non textured vertices
1247            // when line AA is disabled to save on bandwidth
1248            TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
1249            TextureVertex::set(vertex++, p2.x, p2.y, 0.0f, 0.0f);
1250            TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
1251            TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
1252            TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
1253            TextureVertex::set(vertex++, p4.x, p4.y, 0.0f, 0.0f);
1254
1255            // TODO: Mark the dirty regions when RENDER_LAYERS_AS_REGIONS is set
1256        }
1257
1258        // GL_LINE does not give the result we want to match Skia
1259        glDrawArrays(GL_TRIANGLES, 0, verticesCount);
1260    } else {
1261        // TODO: Handle the AA case
1262        for (int i = 0; i < count; i += 4) {
1263            TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
1264            TextureVertex::set(vertex++, points[i + 2], points[i + 3], 0.0f, 0.0f);
1265        }
1266
1267        glLineWidth(1.0f);
1268        glDrawArrays(GL_LINES, 0, verticesCount);
1269    }
1270}
1271
1272void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1273    // No need to check against the clip, we fill the clip region
1274    if (mSnapshot->isIgnored()) return;
1275
1276    Rect& clip(*mSnapshot->clipRect);
1277    clip.snapToPixelBoundaries();
1278
1279    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1280}
1281
1282void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
1283    if (quickReject(left, top, right, bottom)) {
1284        return;
1285    }
1286
1287    SkXfermode::Mode mode;
1288    if (!mCaches.extensions.hasFramebufferFetch()) {
1289        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
1290        if (!isMode) {
1291            // Assume SRC_OVER
1292            mode = SkXfermode::kSrcOver_Mode;
1293        }
1294    } else {
1295        mode = getXfermode(p->getXfermode());
1296    }
1297
1298    // Skia draws using the color's alpha channel if < 255
1299    // Otherwise, it uses the paint's alpha
1300    int color = p->getColor();
1301    if (((color >> 24) & 0xff) == 255) {
1302        color |= p->getAlpha() << 24;
1303    }
1304
1305    drawColorRect(left, top, right, bottom, color, mode);
1306}
1307
1308void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
1309        float x, float y, SkPaint* paint) {
1310    if (text == NULL || count == 0) {
1311        return;
1312    }
1313    if (mSnapshot->isIgnored()) return;
1314
1315    paint->setAntiAlias(true);
1316
1317    float length = -1.0f;
1318    switch (paint->getTextAlign()) {
1319        case SkPaint::kCenter_Align:
1320            length = paint->measureText(text, bytesCount);
1321            x -= length / 2.0f;
1322            break;
1323        case SkPaint::kRight_Align:
1324            length = paint->measureText(text, bytesCount);
1325            x -= length;
1326            break;
1327        default:
1328            break;
1329    }
1330
1331    // TODO: Handle paint->getTextScaleX()
1332    const float oldX = x;
1333    const float oldY = y;
1334    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1335    if (pureTranslate) {
1336        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
1337        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
1338    }
1339
1340    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
1341    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
1342            paint->getTextSize());
1343
1344    int alpha;
1345    SkXfermode::Mode mode;
1346    getAlphaAndMode(paint, &alpha, &mode);
1347
1348    if (mHasShadow) {
1349        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
1350        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
1351                count, mShadowRadius);
1352        const AutoTexture autoCleanup(shadow);
1353
1354        const float sx = x - shadow->left + mShadowDx;
1355        const float sy = y - shadow->top + mShadowDy;
1356
1357        const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
1358
1359        glActiveTexture(gTextureUnits[0]);
1360        setupDraw();
1361        setupDrawWithTexture(true);
1362        setupDrawAlpha8Color(mShadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
1363        setupDrawBlending(true, mode);
1364        setupDrawProgram();
1365        setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height, pureTranslate);
1366        setupDrawTexture(shadow->id);
1367        setupDrawPureColorUniforms();
1368        setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1369
1370        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1371        finishDrawTexture();
1372    }
1373
1374    if (paint->getAlpha() == 0 && paint->getXfermode() == NULL) {
1375        return;
1376    }
1377
1378    // Pick the appropriate texture filtering
1379    bool linearFilter = mSnapshot->transform->changesBounds();
1380    if (pureTranslate && !linearFilter) {
1381        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
1382    }
1383
1384    glActiveTexture(gTextureUnits[0]);
1385    setupDraw();
1386    setupDrawDirtyRegionsDisabled();
1387    setupDrawWithTexture(true);
1388    setupDrawAlpha8Color(paint->getColor(), alpha);
1389    setupDrawColorFilter();
1390    setupDrawShader();
1391    setupDrawBlending(true, mode);
1392    setupDrawProgram();
1393    setupDrawModelView(x, y, x, y, pureTranslate, true);
1394    setupDrawTexture(fontRenderer.getTexture(linearFilter));
1395    setupDrawPureColorUniforms();
1396    setupDrawColorFilterUniforms();
1397    setupDrawShaderUniforms(pureTranslate);
1398
1399    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
1400    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
1401
1402#if RENDER_LAYERS_AS_REGIONS
1403    bool hasLayer = (mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region;
1404#else
1405    bool hasLayer = false;
1406#endif
1407
1408    mCaches.unbindMeshBuffer();
1409    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
1410            hasLayer ? &bounds : NULL)) {
1411#if RENDER_LAYERS_AS_REGIONS
1412        if (hasLayer) {
1413            if (!pureTranslate) {
1414                mSnapshot->transform->mapRect(bounds);
1415            }
1416            bounds.intersect(*mSnapshot->clipRect);
1417            bounds.snapToPixelBoundaries();
1418
1419            android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1420            mSnapshot->region->orSelf(dirty);
1421        }
1422#endif
1423    }
1424
1425    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1426    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1427
1428    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
1429}
1430
1431void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
1432    if (mSnapshot->isIgnored()) return;
1433
1434    GLuint textureUnit = 0;
1435    glActiveTexture(gTextureUnits[textureUnit]);
1436
1437    const PathTexture* texture = mCaches.pathCache.get(path, paint);
1438    if (!texture) return;
1439    const AutoTexture autoCleanup(texture);
1440
1441    const float x = texture->left - texture->offset;
1442    const float y = texture->top - texture->offset;
1443
1444    if (quickReject(x, y, x + texture->width, y + texture->height)) {
1445        return;
1446    }
1447
1448    int alpha;
1449    SkXfermode::Mode mode;
1450    getAlphaAndMode(paint, &alpha, &mode);
1451
1452    setupDraw();
1453    setupDrawWithTexture(true);
1454    setupDrawAlpha8Color(paint->getColor(), alpha);
1455    setupDrawColorFilter();
1456    setupDrawShader();
1457    setupDrawBlending(true, mode);
1458    setupDrawProgram();
1459    setupDrawModelView(x, y, x + texture->width, y + texture->height);
1460    setupDrawTexture(texture->id);
1461    setupDrawPureColorUniforms();
1462    setupDrawColorFilterUniforms();
1463    setupDrawShaderUniforms();
1464    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1465
1466    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1467
1468    finishDrawTexture();
1469}
1470
1471///////////////////////////////////////////////////////////////////////////////
1472// Shaders
1473///////////////////////////////////////////////////////////////////////////////
1474
1475void OpenGLRenderer::resetShader() {
1476    mShader = NULL;
1477}
1478
1479void OpenGLRenderer::setupShader(SkiaShader* shader) {
1480    mShader = shader;
1481    if (mShader) {
1482        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
1483    }
1484}
1485
1486///////////////////////////////////////////////////////////////////////////////
1487// Color filters
1488///////////////////////////////////////////////////////////////////////////////
1489
1490void OpenGLRenderer::resetColorFilter() {
1491    mColorFilter = NULL;
1492}
1493
1494void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
1495    mColorFilter = filter;
1496}
1497
1498///////////////////////////////////////////////////////////////////////////////
1499// Drop shadow
1500///////////////////////////////////////////////////////////////////////////////
1501
1502void OpenGLRenderer::resetShadow() {
1503    mHasShadow = false;
1504}
1505
1506void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
1507    mHasShadow = true;
1508    mShadowRadius = radius;
1509    mShadowDx = dx;
1510    mShadowDy = dy;
1511    mShadowColor = color;
1512}
1513
1514///////////////////////////////////////////////////////////////////////////////
1515// Drawing implementation
1516///////////////////////////////////////////////////////////////////////////////
1517
1518// Same values used by Skia
1519#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
1520#define kStdUnderline_Offset    (1.0f / 9.0f)
1521#define kStdUnderline_Thickness (1.0f / 18.0f)
1522
1523void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
1524        float x, float y, SkPaint* paint) {
1525    // Handle underline and strike-through
1526    uint32_t flags = paint->getFlags();
1527    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
1528        float underlineWidth = length;
1529        // If length is > 0.0f, we already measured the text for the text alignment
1530        if (length <= 0.0f) {
1531            underlineWidth = paint->measureText(text, bytesCount);
1532        }
1533
1534        float offsetX = 0;
1535        switch (paint->getTextAlign()) {
1536            case SkPaint::kCenter_Align:
1537                offsetX = underlineWidth * 0.5f;
1538                break;
1539            case SkPaint::kRight_Align:
1540                offsetX = underlineWidth;
1541                break;
1542            default:
1543                break;
1544        }
1545
1546        if (underlineWidth > 0.0f) {
1547            const float textSize = paint->getTextSize();
1548            const float strokeWidth = textSize * kStdUnderline_Thickness;
1549
1550            const float left = x - offsetX;
1551            float top = 0.0f;
1552
1553            const int pointsCount = 4 * (flags & SkPaint::kStrikeThruText_Flag ? 2 : 1);
1554            float points[pointsCount];
1555            int currentPoint = 0;
1556
1557            if (flags & SkPaint::kUnderlineText_Flag) {
1558                top = y + textSize * kStdUnderline_Offset;
1559                points[currentPoint++] = left;
1560                points[currentPoint++] = top;
1561                points[currentPoint++] = left + underlineWidth;
1562                points[currentPoint++] = top;
1563            }
1564
1565            if (flags & SkPaint::kStrikeThruText_Flag) {
1566                top = y + textSize * kStdStrikeThru_Offset;
1567                points[currentPoint++] = left;
1568                points[currentPoint++] = top;
1569                points[currentPoint++] = left + underlineWidth;
1570                points[currentPoint++] = top;
1571            }
1572
1573            SkPaint linesPaint(*paint);
1574            linesPaint.setStrokeWidth(strokeWidth);
1575
1576            drawLines(&points[0], pointsCount, &linesPaint);
1577        }
1578    }
1579}
1580
1581void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
1582        int color, SkXfermode::Mode mode, bool ignoreTransform) {
1583    // If a shader is set, preserve only the alpha
1584    if (mShader) {
1585        color |= 0x00ffffff;
1586    }
1587
1588    setupDraw();
1589    setupDrawColor(color);
1590    setupDrawShader();
1591    setupDrawColorFilter();
1592    setupDrawBlending(mode);
1593    setupDrawProgram();
1594    setupDrawModelView(left, top, right, bottom, ignoreTransform);
1595    setupDrawColorUniforms();
1596    setupDrawShaderUniforms(ignoreTransform);
1597    setupDrawColorFilterUniforms();
1598    setupDrawSimpleMesh();
1599
1600    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1601}
1602
1603void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1604        Texture* texture, SkPaint* paint) {
1605    int alpha;
1606    SkXfermode::Mode mode;
1607    getAlphaAndMode(paint, &alpha, &mode);
1608
1609    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1610
1611    if (mSnapshot->transform->isPureTranslate()) {
1612        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1613        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1614
1615        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1616                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
1617                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
1618    } else {
1619        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
1620                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
1621                GL_TRIANGLE_STRIP, gMeshCount);
1622    }
1623}
1624
1625void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1626        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
1627    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
1628            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
1629}
1630
1631void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
1632        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
1633        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
1634        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
1635
1636    setupDraw();
1637    setupDrawWithTexture();
1638    setupDrawColor(alpha, alpha, alpha, alpha);
1639    setupDrawColorFilter();
1640    setupDrawBlending(blend, mode, swapSrcDst);
1641    setupDrawProgram();
1642    if (!dirty) {
1643        setupDrawDirtyRegionsDisabled();
1644    }
1645    if (!ignoreScale) {
1646        setupDrawModelView(left, top, right, bottom, ignoreTransform);
1647    } else {
1648        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
1649    }
1650    setupDrawPureColorUniforms();
1651    setupDrawColorFilterUniforms();
1652    setupDrawTexture(texture);
1653    setupDrawMesh(vertices, texCoords, vbo);
1654
1655    glDrawArrays(drawMode, 0, elementsCount);
1656
1657    finishDrawTexture();
1658}
1659
1660void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
1661        ProgramDescription& description, bool swapSrcDst) {
1662    blend = blend || mode != SkXfermode::kSrcOver_Mode;
1663    if (blend) {
1664        if (mode < SkXfermode::kPlus_Mode) {
1665            if (!mCaches.blend) {
1666                glEnable(GL_BLEND);
1667            }
1668
1669            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
1670            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
1671
1672            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
1673                glBlendFunc(sourceMode, destMode);
1674                mCaches.lastSrcMode = sourceMode;
1675                mCaches.lastDstMode = destMode;
1676            }
1677        } else {
1678            // These blend modes are not supported by OpenGL directly and have
1679            // to be implemented using shaders. Since the shader will perform
1680            // the blending, turn blending off here
1681            if (mCaches.extensions.hasFramebufferFetch()) {
1682                description.framebufferMode = mode;
1683                description.swapSrcDst = swapSrcDst;
1684            }
1685
1686            if (mCaches.blend) {
1687                glDisable(GL_BLEND);
1688            }
1689            blend = false;
1690        }
1691    } else if (mCaches.blend) {
1692        glDisable(GL_BLEND);
1693    }
1694    mCaches.blend = blend;
1695}
1696
1697bool OpenGLRenderer::useProgram(Program* program) {
1698    if (!program->isInUse()) {
1699        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1700        program->use();
1701        mCaches.currentProgram = program;
1702        return false;
1703    }
1704    return true;
1705}
1706
1707void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1708    TextureVertex* v = &mMeshVertices[0];
1709    TextureVertex::setUV(v++, u1, v1);
1710    TextureVertex::setUV(v++, u2, v1);
1711    TextureVertex::setUV(v++, u1, v2);
1712    TextureVertex::setUV(v++, u2, v2);
1713}
1714
1715void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1716    if (paint) {
1717        if (!mCaches.extensions.hasFramebufferFetch()) {
1718            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1719            if (!isMode) {
1720                // Assume SRC_OVER
1721                *mode = SkXfermode::kSrcOver_Mode;
1722            }
1723        } else {
1724            *mode = getXfermode(paint->getXfermode());
1725        }
1726
1727        // Skia draws using the color's alpha channel if < 255
1728        // Otherwise, it uses the paint's alpha
1729        int color = paint->getColor();
1730        *alpha = (color >> 24) & 0xFF;
1731        if (*alpha == 255) {
1732            *alpha = paint->getAlpha();
1733        }
1734    } else {
1735        *mode = SkXfermode::kSrcOver_Mode;
1736        *alpha = 255;
1737    }
1738}
1739
1740SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1741    if (mode == NULL) {
1742        return SkXfermode::kSrcOver_Mode;
1743    }
1744    return mode->fMode;
1745}
1746
1747void OpenGLRenderer::setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT) {
1748    bool bound = false;
1749    if (wrapS != texture->wrapS) {
1750        glBindTexture(GL_TEXTURE_2D, texture->id);
1751        bound = true;
1752        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1753        texture->wrapS = wrapS;
1754    }
1755    if (wrapT != texture->wrapT) {
1756        if (!bound) {
1757            glBindTexture(GL_TEXTURE_2D, texture->id);
1758        }
1759        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1760        texture->wrapT = wrapT;
1761    }
1762}
1763
1764}; // namespace uirenderer
1765}; // namespace android
1766