OpenGLRenderer.cpp revision bf434114cbf55b216fdc76fc8d65a75e84c9dab5
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 28#include "OpenGLRenderer.h" 29 30namespace android { 31namespace uirenderer { 32 33/////////////////////////////////////////////////////////////////////////////// 34// Defines 35/////////////////////////////////////////////////////////////////////////////// 36 37#define REQUIRED_TEXTURE_UNITS_COUNT 3 38 39// Generates simple and textured vertices 40#define FV(x, y, u, v) { { x, y }, { u, v } } 41 42/////////////////////////////////////////////////////////////////////////////// 43// Globals 44/////////////////////////////////////////////////////////////////////////////// 45 46// This array is never used directly but used as a memcpy source in the 47// OpenGLRenderer constructor 48static const TextureVertex gMeshVertices[] = { 49 FV(0.0f, 0.0f, 0.0f, 0.0f), 50 FV(1.0f, 0.0f, 1.0f, 0.0f), 51 FV(0.0f, 1.0f, 0.0f, 1.0f), 52 FV(1.0f, 1.0f, 1.0f, 1.0f) 53}; 54static const GLsizei gMeshStride = sizeof(TextureVertex); 55static const GLsizei gMeshCount = 4; 56 57/** 58 * Structure mapping Skia xfermodes to OpenGL blending factors. 59 */ 60struct Blender { 61 SkXfermode::Mode mode; 62 GLenum src; 63 GLenum dst; 64}; // struct Blender 65 66// In this array, the index of each Blender equals the value of the first 67// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode] 68static const Blender gBlends[] = { 69 { SkXfermode::kClear_Mode, GL_ZERO, GL_ZERO }, 70 { SkXfermode::kSrc_Mode, GL_ONE, GL_ZERO }, 71 { SkXfermode::kDst_Mode, GL_ZERO, GL_ONE }, 72 { SkXfermode::kSrcOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA }, 73 { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE }, 74 { SkXfermode::kSrcIn_Mode, GL_DST_ALPHA, GL_ZERO }, 75 { SkXfermode::kDstIn_Mode, GL_ZERO, GL_SRC_ALPHA }, 76 { SkXfermode::kSrcOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 77 { SkXfermode::kDstOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 78 { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 79 { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA }, 80 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA } 81}; 82 83// This array contains the swapped version of each SkXfermode. For instance 84// this array's SrcOver blending mode is actually DstOver. You can refer to 85// createLayer() for more information on the purpose of this array. 86static const Blender gBlendsSwap[] = { 87 { SkXfermode::kClear_Mode, GL_ZERO, GL_ZERO }, 88 { SkXfermode::kSrc_Mode, GL_ZERO, GL_ONE }, 89 { SkXfermode::kDst_Mode, GL_ONE, GL_ZERO }, 90 { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE }, 91 { SkXfermode::kDstOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA }, 92 { SkXfermode::kSrcIn_Mode, GL_ZERO, GL_SRC_ALPHA }, 93 { SkXfermode::kDstIn_Mode, GL_DST_ALPHA, GL_ZERO }, 94 { SkXfermode::kSrcOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 95 { SkXfermode::kDstOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 96 { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA }, 97 { SkXfermode::kDstATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 98 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA } 99}; 100 101static const GLenum gTextureUnits[] = { 102 GL_TEXTURE0, 103 GL_TEXTURE1, 104 GL_TEXTURE2 105}; 106 107/////////////////////////////////////////////////////////////////////////////// 108// Constructors/destructor 109/////////////////////////////////////////////////////////////////////////////// 110 111OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) { 112 LOGD("Create OpenGLRenderer"); 113 114 mShader = NULL; 115 mColorFilter = NULL; 116 mHasShadow = false; 117 118 memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices)); 119 120 mFirstSnapshot = new Snapshot; 121 122 GLint maxTextureUnits; 123 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits); 124 if (maxTextureUnits < REQUIRED_TEXTURE_UNITS_COUNT) { 125 LOGW("At least %d texture units are required!", REQUIRED_TEXTURE_UNITS_COUNT); 126 } 127 128 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize); 129} 130 131OpenGLRenderer::~OpenGLRenderer() { 132 LOGD("Destroy OpenGLRenderer"); 133} 134 135/////////////////////////////////////////////////////////////////////////////// 136// Setup 137/////////////////////////////////////////////////////////////////////////////// 138 139void OpenGLRenderer::setViewport(int width, int height) { 140 glViewport(0, 0, width, height); 141 mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1); 142 143 mWidth = width; 144 mHeight = height; 145} 146 147void OpenGLRenderer::prepare() { 148 mSnapshot = new Snapshot(mFirstSnapshot, 149 SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag); 150 mSaveCount = 1; 151 152 glViewport(0, 0, mWidth, mHeight); 153 154 glDisable(GL_DITHER); 155 glDisable(GL_SCISSOR_TEST); 156 157 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 158 glClear(GL_COLOR_BUFFER_BIT); 159 160 glEnable(GL_SCISSOR_TEST); 161 glScissor(0, 0, mWidth, mHeight); 162 163 mSnapshot->setClip(0.0f, 0.0f, mWidth, mHeight); 164} 165 166void OpenGLRenderer::finish() { 167#if DEBUG_OPENGL 168 GLenum status = GL_NO_ERROR; 169 while ((status = glGetError()) != GL_NO_ERROR) { 170 LOGD("GL error from OpenGLRenderer: 0x%x", status); 171 } 172#endif 173} 174 175void OpenGLRenderer::acquireContext() { 176 if (mCaches.currentProgram) { 177 if (mCaches.currentProgram->isInUse()) { 178 mCaches.currentProgram->remove(); 179 mCaches.currentProgram = NULL; 180 } 181 } 182} 183 184void OpenGLRenderer::releaseContext() { 185 glViewport(0, 0, mWidth, mHeight); 186 187 glEnable(GL_SCISSOR_TEST); 188 setScissorFromClip(); 189 190 glDisable(GL_DITHER); 191 192 glBindFramebuffer(GL_FRAMEBUFFER, 0); 193 194 if (mCaches.blend) { 195 glEnable(GL_BLEND); 196 glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode); 197 glBlendEquation(GL_FUNC_ADD); 198 } else { 199 glDisable(GL_BLEND); 200 } 201} 202 203/////////////////////////////////////////////////////////////////////////////// 204// State management 205/////////////////////////////////////////////////////////////////////////////// 206 207int OpenGLRenderer::getSaveCount() const { 208 return mSaveCount; 209} 210 211int OpenGLRenderer::save(int flags) { 212 return saveSnapshot(flags); 213} 214 215void OpenGLRenderer::restore() { 216 if (mSaveCount > 1) { 217 restoreSnapshot(); 218 } 219} 220 221void OpenGLRenderer::restoreToCount(int saveCount) { 222 if (saveCount < 1) saveCount = 1; 223 224 while (mSaveCount > saveCount) { 225 restoreSnapshot(); 226 } 227} 228 229int OpenGLRenderer::saveSnapshot(int flags) { 230 mSnapshot = new Snapshot(mSnapshot, flags); 231 return mSaveCount++; 232} 233 234bool OpenGLRenderer::restoreSnapshot() { 235 bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet; 236 bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer; 237 238 sp<Snapshot> current = mSnapshot; 239 sp<Snapshot> previous = mSnapshot->previous; 240 241 mSaveCount--; 242 mSnapshot = previous; 243 244 if (restoreLayer) { 245 composeLayer(current, previous); 246 } 247 248 if (restoreClip) { 249 setScissorFromClip(); 250 } 251 252 return restoreClip; 253} 254 255/////////////////////////////////////////////////////////////////////////////// 256// Layers 257/////////////////////////////////////////////////////////////////////////////// 258 259int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom, 260 const SkPaint* p, int flags) { 261 int count = saveSnapshot(flags); 262 263 int alpha = 255; 264 SkXfermode::Mode mode; 265 266 if (p) { 267 alpha = p->getAlpha(); 268 if (!mExtensions.hasFramebufferFetch()) { 269 const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode); 270 if (!isMode) { 271 // Assume SRC_OVER 272 mode = SkXfermode::kSrcOver_Mode; 273 } 274 } else { 275 mode = getXfermode(p->getXfermode()); 276 } 277 } else { 278 mode = SkXfermode::kSrcOver_Mode; 279 } 280 281 createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags); 282 283 return count; 284} 285 286int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom, 287 int alpha, int flags) { 288 if (alpha == 0xff) { 289 return saveLayer(left, top, right, bottom, NULL, flags); 290 } else { 291 SkPaint paint; 292 paint.setAlpha(alpha); 293 return saveLayer(left, top, right, bottom, &paint, flags); 294 } 295} 296 297/** 298 * Layers are viewed by Skia are slightly different than layers in image editing 299 * programs (for instance.) When a layer is created, previously created layers 300 * and the frame buffer still receive every drawing command. For instance, if a 301 * layer is created and a shape intersecting the bounds of the layers and the 302 * framebuffer is draw, the shape will be drawn on both (unless the layer was 303 * created with the SkCanvas::kClipToLayer_SaveFlag flag.) 304 * 305 * A way to implement layers is to create an FBO for each layer, backed by an RGBA 306 * texture. Unfortunately, this is inefficient as it requires every primitive to 307 * be drawn n + 1 times, where n is the number of active layers. In practice this 308 * means, for every primitive: 309 * - Switch active frame buffer 310 * - Change viewport, clip and projection matrix 311 * - Issue the drawing 312 * 313 * Switching rendering target n + 1 times per drawn primitive is extremely costly. 314 * To avoid this, layers are implemented in a different way here. 315 * 316 * This implementation relies on the frame buffer being at least RGBA 8888. When 317 * a layer is created, only a texture is created, not an FBO. The content of the 318 * frame buffer contained within the layer's bounds is copied into this texture 319 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame 320 * buffer and drawing continues as normal. This technique therefore treats the 321 * frame buffer as a scratch buffer for the layers. 322 * 323 * To compose the layers back onto the frame buffer, each layer texture 324 * (containing the original frame buffer data) is drawn as a simple quad over 325 * the frame buffer. The trick is that the quad is set as the composition 326 * destination in the blending equation, and the frame buffer becomes the source 327 * of the composition. 328 * 329 * Drawing layers with an alpha value requires an extra step before composition. 330 * An empty quad is drawn over the layer's region in the frame buffer. This quad 331 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the 332 * quad is used to multiply the colors in the frame buffer. This is achieved by 333 * changing the GL blend functions for the GL_FUNC_ADD blend equation to 334 * GL_ZERO, GL_SRC_ALPHA. 335 * 336 * Because glCopyTexImage2D() can be slow, an alternative implementation might 337 * be use to draw a single clipped layer. The implementation described above 338 * is correct in every case. 339 * 340 * (1) The frame buffer is actually not cleared right away. To allow the GPU 341 * to potentially optimize series of calls to glCopyTexImage2D, the frame 342 * buffer is left untouched until the first drawing operation. Only when 343 * something actually gets drawn are the layers regions cleared. 344 */ 345bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top, 346 float right, float bottom, int alpha, SkXfermode::Mode mode,int flags) { 347 LAYER_LOGD("Requesting layer %fx%f", right - left, bottom - top); 348 LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize()); 349 350 // Window coordinates of the layer 351 Rect bounds(left, top, right, bottom); 352 mSnapshot->transform->mapRect(bounds); 353 354 // Layers only make sense if they are in the framebuffer's bounds 355 bounds.intersect(*mSnapshot->clipRect); 356 bounds.snapToPixelBoundaries(); 357 358 if (bounds.isEmpty() || bounds.getWidth() > mMaxTextureSize || 359 bounds.getHeight() > mMaxTextureSize) { 360 return false; 361 } 362 363 LayerSize size(bounds.getWidth(), bounds.getHeight()); 364 Layer* layer = mCaches.layerCache.get(size); 365 if (!layer) { 366 return false; 367 } 368 369 layer->mode = mode; 370 layer->alpha = alpha; 371 layer->layer.set(bounds); 372 373 // Save the layer in the snapshot 374 snapshot->flags |= Snapshot::kFlagIsLayer; 375 snapshot->layer = layer; 376 377 // Copy the framebuffer into the layer 378 glBindTexture(GL_TEXTURE_2D, layer->texture); 379 glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left, mHeight - bounds.bottom, 380 bounds.getWidth(), bounds.getHeight(), 0); 381 382 if (flags & SkCanvas::kClipToLayer_SaveFlag) { 383 if (mSnapshot->clipTransformed(bounds)) setScissorFromClip(); 384 } 385 386 // Enqueue the buffer coordinates to clear the corresponding region later 387 mLayers.push(new Rect(bounds)); 388 389 return true; 390} 391 392/** 393 * Read the documentation of createLayer() before doing anything in this method. 394 */ 395void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) { 396 if (!current->layer) { 397 LOGE("Attempting to compose a layer that does not exist"); 398 return; 399 } 400 401 // Restore the clip from the previous snapshot 402 const Rect& clip = *previous->clipRect; 403 glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight()); 404 405 Layer* layer = current->layer; 406 const Rect& rect = layer->layer; 407 408 if (layer->alpha < 255) { 409 drawColorRect(rect.left, rect.top, rect.right, rect.bottom, 410 layer->alpha << 24, SkXfermode::kDstIn_Mode, true); 411 } 412 413 // Layers are already drawn with a top-left origin, don't flip the texture 414 resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f); 415 416 drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture, 417 1.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0], 418 &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, true, true); 419 420 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 421 422 LayerSize size(rect.getWidth(), rect.getHeight()); 423 // Failing to add the layer to the cache should happen only if the 424 // layer is too large 425 if (!mCaches.layerCache.put(size, layer)) { 426 LAYER_LOGD("Deleting layer"); 427 428 glDeleteTextures(1, &layer->texture); 429 430 delete layer; 431 } 432} 433 434void OpenGLRenderer::clearLayerRegions() { 435 if (mLayers.size() == 0) return; 436 437 for (uint32_t i = 0; i < mLayers.size(); i++) { 438 Rect* bounds = mLayers.itemAt(i); 439 440 // Clear the framebuffer where the layer will draw 441 glScissor(bounds->left, mHeight - bounds->bottom, 442 bounds->getWidth(), bounds->getHeight()); 443 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 444 glClear(GL_COLOR_BUFFER_BIT); 445 446 delete bounds; 447 } 448 mLayers.clear(); 449 450 // Restore the clip 451 setScissorFromClip(); 452} 453 454/////////////////////////////////////////////////////////////////////////////// 455// Transforms 456/////////////////////////////////////////////////////////////////////////////// 457 458void OpenGLRenderer::translate(float dx, float dy) { 459 mSnapshot->transform->translate(dx, dy, 0.0f); 460} 461 462void OpenGLRenderer::rotate(float degrees) { 463 mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f); 464} 465 466void OpenGLRenderer::scale(float sx, float sy) { 467 mSnapshot->transform->scale(sx, sy, 1.0f); 468} 469 470void OpenGLRenderer::setMatrix(SkMatrix* matrix) { 471 mSnapshot->transform->load(*matrix); 472} 473 474void OpenGLRenderer::getMatrix(SkMatrix* matrix) { 475 mSnapshot->transform->copyTo(*matrix); 476} 477 478void OpenGLRenderer::concatMatrix(SkMatrix* matrix) { 479 mat4 m(*matrix); 480 mSnapshot->transform->multiply(m); 481} 482 483/////////////////////////////////////////////////////////////////////////////// 484// Clipping 485/////////////////////////////////////////////////////////////////////////////// 486 487void OpenGLRenderer::setScissorFromClip() { 488 const Rect& clip = *mSnapshot->clipRect; 489 glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight()); 490} 491 492const Rect& OpenGLRenderer::getClipBounds() { 493 return mSnapshot->getLocalClip(); 494} 495 496bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) { 497 Rect r(left, top, right, bottom); 498 mSnapshot->transform->mapRect(r); 499 return !mSnapshot->clipRect->intersects(r); 500} 501 502bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) { 503 bool clipped = mSnapshot->clip(left, top, right, bottom, op); 504 if (clipped) { 505 setScissorFromClip(); 506 } 507 return !mSnapshot->clipRect->isEmpty(); 508} 509 510/////////////////////////////////////////////////////////////////////////////// 511// Drawing 512/////////////////////////////////////////////////////////////////////////////// 513 514void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) { 515 const float right = left + bitmap->width(); 516 const float bottom = top + bitmap->height(); 517 518 if (quickReject(left, top, right, bottom)) { 519 return; 520 } 521 522 glActiveTexture(GL_TEXTURE0); 523 const Texture* texture = mCaches.textureCache.get(bitmap); 524 if (!texture) return; 525 const AutoTexture autoCleanup(texture); 526 527 drawTextureRect(left, top, right, bottom, texture, paint); 528} 529 530void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) { 531 Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height()); 532 const mat4 transform(*matrix); 533 transform.mapRect(r); 534 535 if (quickReject(r.left, r.top, r.right, r.bottom)) { 536 return; 537 } 538 539 glActiveTexture(GL_TEXTURE0); 540 const Texture* texture = mCaches.textureCache.get(bitmap); 541 if (!texture) return; 542 const AutoTexture autoCleanup(texture); 543 544 drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint); 545} 546 547void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, 548 float srcLeft, float srcTop, float srcRight, float srcBottom, 549 float dstLeft, float dstTop, float dstRight, float dstBottom, 550 const SkPaint* paint) { 551 if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) { 552 return; 553 } 554 555 glActiveTexture(GL_TEXTURE0); 556 const Texture* texture = mCaches.textureCache.get(bitmap); 557 if (!texture) return; 558 const AutoTexture autoCleanup(texture); 559 560 const float width = texture->width; 561 const float height = texture->height; 562 563 const float u1 = srcLeft / width; 564 const float v1 = srcTop / height; 565 const float u2 = srcRight / width; 566 const float v2 = srcBottom / height; 567 568 resetDrawTextureTexCoords(u1, v1, u2, v2); 569 570 drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture, paint); 571 572 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 573} 574 575void OpenGLRenderer::drawPatch(SkBitmap* bitmap, Res_png_9patch* patch, 576 float left, float top, float right, float bottom, const SkPaint* paint) { 577 if (quickReject(left, top, right, bottom)) { 578 return; 579 } 580 581 glActiveTexture(GL_TEXTURE0); 582 const Texture* texture = mCaches.textureCache.get(bitmap); 583 if (!texture) return; 584 const AutoTexture autoCleanup(texture); 585 586 int alpha; 587 SkXfermode::Mode mode; 588 getAlphaAndMode(paint, &alpha, &mode); 589 590 Patch* mesh = mCaches.patchCache.get(patch); 591 mesh->updateVertices(bitmap, left, top, right, bottom, 592 &patch->xDivs[0], &patch->yDivs[0], patch->numXDivs, patch->numYDivs); 593 594 // Specify right and bottom as +1.0f from left/top to prevent scaling since the 595 // patch mesh already defines the final size 596 drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f, 597 mode, texture->blend, &mesh->vertices[0].position[0], 598 &mesh->vertices[0].texture[0], GL_TRIANGLES, mesh->verticesCount); 599} 600 601void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 602 const Rect& clip = *mSnapshot->clipRect; 603 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true); 604} 605 606void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) { 607 if (quickReject(left, top, right, bottom)) { 608 return; 609 } 610 611 SkXfermode::Mode mode; 612 if (!mExtensions.hasFramebufferFetch()) { 613 const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode); 614 if (!isMode) { 615 // Assume SRC_OVER 616 mode = SkXfermode::kSrcOver_Mode; 617 } 618 } else { 619 mode = getXfermode(p->getXfermode()); 620 } 621 622 // Skia draws using the color's alpha channel if < 255 623 // Otherwise, it uses the paint's alpha 624 int color = p->getColor(); 625 if (((color >> 24) & 0xff) == 255) { 626 color |= p->getAlpha() << 24; 627 } 628 629 drawColorRect(left, top, right, bottom, color, mode); 630} 631 632void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, 633 float x, float y, SkPaint* paint) { 634 if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) { 635 return; 636 } 637 paint->setAntiAlias(true); 638 639 float length = -1.0f; 640 switch (paint->getTextAlign()) { 641 case SkPaint::kCenter_Align: 642 length = paint->measureText(text, bytesCount); 643 x -= length / 2.0f; 644 break; 645 case SkPaint::kRight_Align: 646 length = paint->measureText(text, bytesCount); 647 x -= length; 648 break; 649 default: 650 break; 651 } 652 653 int alpha; 654 SkXfermode::Mode mode; 655 getAlphaAndMode(paint, &alpha, &mode); 656 657 uint32_t color = paint->getColor(); 658 const GLfloat a = alpha / 255.0f; 659 const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f; 660 const GLfloat g = a * ((color >> 8) & 0xFF) / 255.0f; 661 const GLfloat b = a * ((color ) & 0xFF) / 255.0f; 662 663 FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint); 664 fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), 665 paint->getTextSize()); 666 if (mHasShadow) { 667 glActiveTexture(gTextureUnits[0]); 668 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 669 const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount, 670 count, mShadowRadius); 671 const AutoTexture autoCleanup(shadow); 672 673 setupShadow(shadow, x, y, mode, a); 674 675 // Draw the mesh 676 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 677 glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords")); 678 } 679 680 GLuint textureUnit = 0; 681 glActiveTexture(gTextureUnits[textureUnit]); 682 683 setupTextureAlpha8(fontRenderer.getTexture(), 0, 0, textureUnit, x, y, r, g, b, a, 684 mode, false, true); 685 686 const Rect& clip = mSnapshot->getLocalClip(); 687 clearLayerRegions(); 688 fontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y); 689 690 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); 691 glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords")); 692 693 drawTextDecorations(text, bytesCount, length, x, y, paint); 694} 695 696void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) { 697 GLuint textureUnit = 0; 698 glActiveTexture(gTextureUnits[textureUnit]); 699 700 const PathTexture* texture = mCaches.pathCache.get(path, paint); 701 if (!texture) return; 702 const AutoTexture autoCleanup(texture); 703 704 const float x = texture->left - texture->offset; 705 const float y = texture->top - texture->offset; 706 707 if (quickReject(x, y, x + texture->width, y + texture->height)) { 708 return; 709 } 710 711 int alpha; 712 SkXfermode::Mode mode; 713 getAlphaAndMode(paint, &alpha, &mode); 714 715 uint32_t color = paint->getColor(); 716 const GLfloat a = alpha / 255.0f; 717 const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f; 718 const GLfloat g = a * ((color >> 8) & 0xFF) / 255.0f; 719 const GLfloat b = a * ((color ) & 0xFF) / 255.0f; 720 721 setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true); 722 723 clearLayerRegions(); 724 725 // Draw the mesh 726 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 727 glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords")); 728} 729 730/////////////////////////////////////////////////////////////////////////////// 731// Shaders 732/////////////////////////////////////////////////////////////////////////////// 733 734void OpenGLRenderer::resetShader() { 735 mShader = NULL; 736} 737 738void OpenGLRenderer::setupShader(SkiaShader* shader) { 739 mShader = shader; 740 if (mShader) { 741 mShader->set(&mCaches.textureCache, &mCaches.gradientCache); 742 } 743} 744 745/////////////////////////////////////////////////////////////////////////////// 746// Color filters 747/////////////////////////////////////////////////////////////////////////////// 748 749void OpenGLRenderer::resetColorFilter() { 750 mColorFilter = NULL; 751} 752 753void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) { 754 mColorFilter = filter; 755} 756 757/////////////////////////////////////////////////////////////////////////////// 758// Drop shadow 759/////////////////////////////////////////////////////////////////////////////// 760 761void OpenGLRenderer::resetShadow() { 762 mHasShadow = false; 763} 764 765void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) { 766 mHasShadow = true; 767 mShadowRadius = radius; 768 mShadowDx = dx; 769 mShadowDy = dy; 770 mShadowColor = color; 771} 772 773/////////////////////////////////////////////////////////////////////////////// 774// Drawing implementation 775/////////////////////////////////////////////////////////////////////////////// 776 777void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y, 778 SkXfermode::Mode mode, float alpha) { 779 const float sx = x - texture->left + mShadowDx; 780 const float sy = y - texture->top + mShadowDy; 781 782 const int shadowAlpha = ((mShadowColor >> 24) & 0xFF); 783 const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha; 784 const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f; 785 const GLfloat g = a * ((mShadowColor >> 8) & 0xFF) / 255.0f; 786 const GLfloat b = a * ((mShadowColor ) & 0xFF) / 255.0f; 787 788 GLuint textureUnit = 0; 789 setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false); 790} 791 792void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit, 793 float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode, 794 bool transforms, bool applyFilters) { 795 setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit, 796 x, y, r, g, b, a, mode, transforms, applyFilters); 797} 798 799void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height, 800 GLuint& textureUnit, float x, float y, float r, float g, float b, float a, 801 SkXfermode::Mode mode, bool transforms, bool applyFilters) { 802 // Describe the required shaders 803 ProgramDescription description; 804 description.hasTexture = true; 805 description.hasAlpha8Texture = true; 806 807 if (applyFilters) { 808 if (mShader) { 809 mShader->describe(description, mExtensions); 810 } 811 if (mColorFilter) { 812 mColorFilter->describe(description, mExtensions); 813 } 814 } 815 816 // Setup the blending mode 817 chooseBlending(true, mode, description); 818 819 // Build and use the appropriate shader 820 useProgram(mCaches.programCache.get(description)); 821 822 bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, textureUnit); 823 glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit); 824 825 int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords"); 826 glEnableVertexAttribArray(texCoordsSlot); 827 828 // Setup attributes 829 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 830 gMeshStride, &mMeshVertices[0].position[0]); 831 glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, 832 gMeshStride, &mMeshVertices[0].texture[0]); 833 834 // Setup uniforms 835 if (transforms) { 836 mModelView.loadTranslate(x, y, 0.0f); 837 mModelView.scale(width, height, 1.0f); 838 } else { 839 mModelView.loadIdentity(); 840 } 841 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 842 glUniform4f(mCaches.currentProgram->color, r, g, b, a); 843 844 textureUnit++; 845 if (applyFilters) { 846 // Setup attributes and uniforms required by the shaders 847 if (mShader) { 848 mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit); 849 } 850 if (mColorFilter) { 851 mColorFilter->setupProgram(mCaches.currentProgram); 852 } 853 } 854} 855 856// Same values used by Skia 857#define kStdStrikeThru_Offset (-6.0f / 21.0f) 858#define kStdUnderline_Offset (1.0f / 9.0f) 859#define kStdUnderline_Thickness (1.0f / 18.0f) 860 861void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length, 862 float x, float y, SkPaint* paint) { 863 // Handle underline and strike-through 864 uint32_t flags = paint->getFlags(); 865 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) { 866 float underlineWidth = length; 867 // If length is > 0.0f, we already measured the text for the text alignment 868 if (length <= 0.0f) { 869 underlineWidth = paint->measureText(text, bytesCount); 870 } 871 872 float offsetX = 0; 873 switch (paint->getTextAlign()) { 874 case SkPaint::kCenter_Align: 875 offsetX = underlineWidth * 0.5f; 876 break; 877 case SkPaint::kRight_Align: 878 offsetX = underlineWidth; 879 break; 880 default: 881 break; 882 } 883 884 if (underlineWidth > 0.0f) { 885 float textSize = paint->getTextSize(); 886 float height = textSize * kStdUnderline_Thickness; 887 888 float left = x - offsetX; 889 float top = 0.0f; 890 float right = left + underlineWidth; 891 float bottom = 0.0f; 892 893 if (flags & SkPaint::kUnderlineText_Flag) { 894 top = y + textSize * kStdUnderline_Offset; 895 bottom = top + height; 896 drawRect(left, top, right, bottom, paint); 897 } 898 899 if (flags & SkPaint::kStrikeThruText_Flag) { 900 top = y + textSize * kStdStrikeThru_Offset; 901 bottom = top + height; 902 drawRect(left, top, right, bottom, paint); 903 } 904 } 905 } 906} 907 908void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 909 int color, SkXfermode::Mode mode, bool ignoreTransform) { 910 clearLayerRegions(); 911 912 // If a shader is set, preserve only the alpha 913 if (mShader) { 914 color |= 0x00ffffff; 915 } 916 917 // Render using pre-multiplied alpha 918 const int alpha = (color >> 24) & 0xFF; 919 const GLfloat a = alpha / 255.0f; 920 const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f; 921 const GLfloat g = a * ((color >> 8) & 0xFF) / 255.0f; 922 const GLfloat b = a * ((color ) & 0xFF) / 255.0f; 923 924 GLuint textureUnit = 0; 925 926 // Describe the required shaders 927 ProgramDescription description; 928 if (mShader) { 929 mShader->describe(description, mExtensions); 930 } 931 if (mColorFilter) { 932 mColorFilter->describe(description, mExtensions); 933 } 934 935 // Setup the blending mode 936 chooseBlending(alpha < 255 || (mShader && mShader->blend()), mode, description); 937 938 // Build and use the appropriate shader 939 useProgram(mCaches.programCache.get(description)); 940 941 // Setup attributes 942 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 943 gMeshStride, &mMeshVertices[0].position[0]); 944 945 // Setup uniforms 946 mModelView.loadTranslate(left, top, 0.0f); 947 mModelView.scale(right - left, bottom - top, 1.0f); 948 if (!ignoreTransform) { 949 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 950 } else { 951 mat4 identity; 952 mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity); 953 } 954 glUniform4f(mCaches.currentProgram->color, r, g, b, a); 955 956 // Setup attributes and uniforms required by the shaders 957 if (mShader) { 958 mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit); 959 } 960 if (mColorFilter) { 961 mColorFilter->setupProgram(mCaches.currentProgram); 962 } 963 964 // Draw the mesh 965 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 966} 967 968void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 969 const Texture* texture, const SkPaint* paint) { 970 int alpha; 971 SkXfermode::Mode mode; 972 getAlphaAndMode(paint, &alpha, &mode); 973 974 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, 975 texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], 976 GL_TRIANGLE_STRIP, gMeshCount); 977} 978 979void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 980 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) { 981 drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend, 982 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], 983 GL_TRIANGLE_STRIP, gMeshCount); 984} 985 986void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom, 987 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend, 988 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 989 bool swapSrcDst, bool ignoreTransform) { 990 clearLayerRegions(); 991 992 ProgramDescription description; 993 description.hasTexture = true; 994 if (mColorFilter) { 995 mColorFilter->describe(description, mExtensions); 996 } 997 998 mModelView.loadTranslate(left, top, 0.0f); 999 mModelView.scale(right - left, bottom - top, 1.0f); 1000 1001 chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst); 1002 1003 useProgram(mCaches.programCache.get(description)); 1004 if (!ignoreTransform) { 1005 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 1006 } else { 1007 mat4 m; 1008 mCaches.currentProgram->set(mOrthoMatrix, mModelView, m); 1009 } 1010 1011 // Texture 1012 bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, 0); 1013 glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0); 1014 1015 // Always premultiplied 1016 glUniform4f(mCaches.currentProgram->color, alpha, alpha, alpha, alpha); 1017 1018 // Mesh 1019 int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords"); 1020 glEnableVertexAttribArray(texCoordsSlot); 1021 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 1022 gMeshStride, vertices); 1023 glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords); 1024 1025 // Color filter 1026 if (mColorFilter) { 1027 mColorFilter->setupProgram(mCaches.currentProgram); 1028 } 1029 1030 glDrawArrays(drawMode, 0, elementsCount); 1031 glDisableVertexAttribArray(texCoordsSlot); 1032} 1033 1034void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, 1035 ProgramDescription& description, bool swapSrcDst) { 1036 blend = blend || mode != SkXfermode::kSrcOver_Mode; 1037 if (blend) { 1038 if (mode < SkXfermode::kPlus_Mode) { 1039 if (!mCaches.blend) { 1040 glEnable(GL_BLEND); 1041 } 1042 1043 GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src; 1044 GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst; 1045 1046 if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) { 1047 glBlendFunc(sourceMode, destMode); 1048 mCaches.lastSrcMode = sourceMode; 1049 mCaches.lastDstMode = destMode; 1050 } 1051 } else { 1052 // These blend modes are not supported by OpenGL directly and have 1053 // to be implemented using shaders. Since the shader will perform 1054 // the blending, turn blending off here 1055 if (mExtensions.hasFramebufferFetch()) { 1056 description.framebufferMode = mode; 1057 description.swapSrcDst = swapSrcDst; 1058 } 1059 1060 if (mCaches.blend) { 1061 glDisable(GL_BLEND); 1062 } 1063 blend = false; 1064 } 1065 } else if (mCaches.blend) { 1066 glDisable(GL_BLEND); 1067 } 1068 mCaches.blend = blend; 1069} 1070 1071bool OpenGLRenderer::useProgram(Program* program) { 1072 if (!program->isInUse()) { 1073 if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove(); 1074 program->use(); 1075 mCaches.currentProgram = program; 1076 return false; 1077 } 1078 return true; 1079} 1080 1081void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) { 1082 TextureVertex* v = &mMeshVertices[0]; 1083 TextureVertex::setUV(v++, u1, v1); 1084 TextureVertex::setUV(v++, u2, v1); 1085 TextureVertex::setUV(v++, u1, v2); 1086 TextureVertex::setUV(v++, u2, v2); 1087} 1088 1089void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) { 1090 if (paint) { 1091 if (!mExtensions.hasFramebufferFetch()) { 1092 const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode); 1093 if (!isMode) { 1094 // Assume SRC_OVER 1095 *mode = SkXfermode::kSrcOver_Mode; 1096 } 1097 } else { 1098 *mode = getXfermode(paint->getXfermode()); 1099 } 1100 1101 // Skia draws using the color's alpha channel if < 255 1102 // Otherwise, it uses the paint's alpha 1103 int color = paint->getColor(); 1104 *alpha = (color >> 24) & 0xFF; 1105 if (*alpha == 255) { 1106 *alpha = paint->getAlpha(); 1107 } 1108 } else { 1109 *mode = SkXfermode::kSrcOver_Mode; 1110 *alpha = 255; 1111 } 1112} 1113 1114SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) { 1115 if (mode == NULL) { 1116 return SkXfermode::kSrcOver_Mode; 1117 } 1118 return mode->fMode; 1119} 1120 1121void OpenGLRenderer::bindTexture(GLuint texture, GLenum wrapS, GLenum wrapT, GLuint textureUnit) { 1122 glActiveTexture(gTextureUnits[textureUnit]); 1123 glBindTexture(GL_TEXTURE_2D, texture); 1124 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS); 1125 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT); 1126} 1127 1128}; // namespace uirenderer 1129}; // namespace android 1130