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