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