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