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