OpenGLRenderer.cpp revision 3e263fac8c9c0e0fb242186b514a7af8efb40961
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 <private/hwui/DrawGlInfo.h> 30 31#include <ui/Rect.h> 32 33#include "OpenGLRenderer.h" 34#include "DisplayListRenderer.h" 35#include "Vector.h" 36 37namespace android { 38namespace uirenderer { 39 40/////////////////////////////////////////////////////////////////////////////// 41// Defines 42/////////////////////////////////////////////////////////////////////////////// 43 44#define RAD_TO_DEG (180.0f / 3.14159265f) 45#define MIN_ANGLE 0.001f 46 47// TODO: This should be set in properties 48#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH) 49 50#define FILTER(paint) (paint && paint->isFilterBitmap() ? GL_LINEAR : GL_NEAREST) 51 52/////////////////////////////////////////////////////////////////////////////// 53// Globals 54/////////////////////////////////////////////////////////////////////////////// 55 56/** 57 * Structure mapping Skia xfermodes to OpenGL blending factors. 58 */ 59struct Blender { 60 SkXfermode::Mode mode; 61 GLenum src; 62 GLenum dst; 63}; // struct Blender 64 65// In this array, the index of each Blender equals the value of the first 66// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode] 67static const Blender gBlends[] = { 68 { SkXfermode::kClear_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 69 { SkXfermode::kSrc_Mode, GL_ONE, GL_ZERO }, 70 { SkXfermode::kDst_Mode, GL_ZERO, GL_ONE }, 71 { SkXfermode::kSrcOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA }, 72 { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE }, 73 { SkXfermode::kSrcIn_Mode, GL_DST_ALPHA, GL_ZERO }, 74 { SkXfermode::kDstIn_Mode, GL_ZERO, GL_SRC_ALPHA }, 75 { SkXfermode::kSrcOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 76 { SkXfermode::kDstOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 77 { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 78 { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA }, 79 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 80 { SkXfermode::kPlus_Mode, GL_ONE, GL_ONE }, 81 { SkXfermode::kMultiply_Mode, GL_ZERO, GL_SRC_COLOR }, 82 { SkXfermode::kScreen_Mode, GL_ONE, GL_ONE_MINUS_SRC_COLOR } 83}; 84 85// This array contains the swapped version of each SkXfermode. For instance 86// this array's SrcOver blending mode is actually DstOver. You can refer to 87// createLayer() for more information on the purpose of this array. 88static const Blender gBlendsSwap[] = { 89 { SkXfermode::kClear_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 90 { SkXfermode::kSrc_Mode, GL_ZERO, GL_ONE }, 91 { SkXfermode::kDst_Mode, GL_ONE, GL_ZERO }, 92 { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE }, 93 { SkXfermode::kDstOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA }, 94 { SkXfermode::kSrcIn_Mode, GL_ZERO, GL_SRC_ALPHA }, 95 { SkXfermode::kDstIn_Mode, GL_DST_ALPHA, GL_ZERO }, 96 { SkXfermode::kSrcOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 97 { SkXfermode::kDstOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 98 { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA }, 99 { SkXfermode::kDstATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 100 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 101 { SkXfermode::kPlus_Mode, GL_ONE, GL_ONE }, 102 { SkXfermode::kMultiply_Mode, GL_DST_COLOR, GL_ZERO }, 103 { SkXfermode::kScreen_Mode, GL_ONE_MINUS_DST_COLOR, GL_ONE } 104}; 105 106static const GLenum gTextureUnits[] = { 107 GL_TEXTURE0, 108 GL_TEXTURE1, 109 GL_TEXTURE2 110}; 111 112/////////////////////////////////////////////////////////////////////////////// 113// Constructors/destructor 114/////////////////////////////////////////////////////////////////////////////// 115 116OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) { 117 mShader = NULL; 118 mColorFilter = NULL; 119 mHasShadow = false; 120 121 memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices)); 122 123 mFirstSnapshot = new Snapshot; 124} 125 126OpenGLRenderer::~OpenGLRenderer() { 127 // The context has already been destroyed at this point, do not call 128 // GL APIs. All GL state should be kept in Caches.h 129} 130 131/////////////////////////////////////////////////////////////////////////////// 132// Setup 133/////////////////////////////////////////////////////////////////////////////// 134 135void OpenGLRenderer::setViewport(int width, int height) { 136 mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1); 137 138 mWidth = width; 139 mHeight = height; 140 141 mFirstSnapshot->height = height; 142 mFirstSnapshot->viewport.set(0, 0, width, height); 143 144 mDirtyClip = false; 145 146 glDisable(GL_DITHER); 147 glViewport(0, 0, width, height); 148 149 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 150 151 glEnableVertexAttribArray(Program::kBindingPosition); 152} 153 154void OpenGLRenderer::prepare(bool opaque) { 155 prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque); 156} 157 158void OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom, bool opaque) { 159 mCaches.clearGarbage(); 160 161 mSnapshot = new Snapshot(mFirstSnapshot, 162 SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag); 163 mSnapshot->fbo = getTargetFbo(); 164 165 mSaveCount = 1; 166 167 glEnable(GL_SCISSOR_TEST); 168 glScissor(left, mSnapshot->height - bottom, right - left, bottom - top); 169 mSnapshot->setClip(left, top, right, bottom); 170 171 if (!opaque) { 172 glClear(GL_COLOR_BUFFER_BIT); 173 } 174} 175 176void OpenGLRenderer::finish() { 177#if DEBUG_OPENGL 178 GLenum status = GL_NO_ERROR; 179 while ((status = glGetError()) != GL_NO_ERROR) { 180 LOGD("GL error from OpenGLRenderer: 0x%x", status); 181 switch (status) { 182 case GL_OUT_OF_MEMORY: 183 LOGE(" OpenGLRenderer is out of memory!"); 184 break; 185 } 186 } 187#endif 188#if DEBUG_MEMORY_USAGE 189 mCaches.dumpMemoryUsage(); 190#else 191 if (mCaches.getDebugLevel() & kDebugMemory) { 192 mCaches.dumpMemoryUsage(); 193 } 194#endif 195} 196 197void OpenGLRenderer::interrupt() { 198 if (mCaches.currentProgram) { 199 if (mCaches.currentProgram->isInUse()) { 200 mCaches.currentProgram->remove(); 201 mCaches.currentProgram = NULL; 202 } 203 } 204 mCaches.unbindMeshBuffer(); 205} 206 207void OpenGLRenderer::resume() { 208 sp<Snapshot> snapshot = (mSnapshot != NULL) ? mSnapshot : mFirstSnapshot; 209 210 glViewport(0, 0, snapshot->viewport.getWidth(), snapshot->viewport.getHeight()); 211 212 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 213 214 glEnable(GL_SCISSOR_TEST); 215 dirtyClip(); 216 217 glDisable(GL_DITHER); 218 219 glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo); 220 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); 221 222 glEnableVertexAttribArray(Program::kBindingPosition); 223 224 mCaches.blend = true; 225 glEnable(GL_BLEND); 226 glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode); 227 glBlendEquation(GL_FUNC_ADD); 228} 229 230bool OpenGLRenderer::callDrawGLFunction(Functor *functor, Rect& dirty) { 231 interrupt(); 232 if (mDirtyClip) { 233 setScissorFromClip(); 234 } 235 236 Rect clip(*mSnapshot->clipRect); 237 clip.snapToPixelBoundaries(); 238 239#if RENDER_LAYERS_AS_REGIONS 240 // Since we don't know what the functor will draw, let's dirty 241 // tne entire clip region 242 if (hasLayer()) { 243 dirtyLayerUnchecked(clip, getRegion()); 244 } 245#endif 246 247 DrawGlInfo info; 248 info.clipLeft = clip.left; 249 info.clipTop = clip.top; 250 info.clipRight = clip.right; 251 info.clipBottom = clip.bottom; 252 info.isLayer = hasLayer(); 253 getSnapshot()->transform->copyTo(&info.transform[0]); 254 255 status_t result = (*functor)(0, &info); 256 257 if (result != 0) { 258 Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom); 259 dirty.unionWith(localDirty); 260 } 261 262 resume(); 263 return result != 0; 264} 265 266/////////////////////////////////////////////////////////////////////////////// 267// State management 268/////////////////////////////////////////////////////////////////////////////// 269 270int OpenGLRenderer::getSaveCount() const { 271 return mSaveCount; 272} 273 274int OpenGLRenderer::save(int flags) { 275 return saveSnapshot(flags); 276} 277 278void OpenGLRenderer::restore() { 279 if (mSaveCount > 1) { 280 restoreSnapshot(); 281 } 282} 283 284void OpenGLRenderer::restoreToCount(int saveCount) { 285 if (saveCount < 1) saveCount = 1; 286 287 while (mSaveCount > saveCount) { 288 restoreSnapshot(); 289 } 290} 291 292int OpenGLRenderer::saveSnapshot(int flags) { 293 mSnapshot = new Snapshot(mSnapshot, flags); 294 return mSaveCount++; 295} 296 297bool OpenGLRenderer::restoreSnapshot() { 298 bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet; 299 bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer; 300 bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho; 301 302 sp<Snapshot> current = mSnapshot; 303 sp<Snapshot> previous = mSnapshot->previous; 304 305 if (restoreOrtho) { 306 Rect& r = previous->viewport; 307 glViewport(r.left, r.top, r.right, r.bottom); 308 mOrthoMatrix.load(current->orthoMatrix); 309 } 310 311 mSaveCount--; 312 mSnapshot = previous; 313 314 if (restoreClip) { 315 dirtyClip(); 316 } 317 318 if (restoreLayer) { 319 composeLayer(current, previous); 320 } 321 322 return restoreClip; 323} 324 325/////////////////////////////////////////////////////////////////////////////// 326// Layers 327/////////////////////////////////////////////////////////////////////////////// 328 329int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom, 330 SkPaint* p, int flags) { 331 const GLuint previousFbo = mSnapshot->fbo; 332 const int count = saveSnapshot(flags); 333 334 if (!mSnapshot->isIgnored()) { 335 int alpha = 255; 336 SkXfermode::Mode mode; 337 338 if (p) { 339 alpha = p->getAlpha(); 340 if (!mCaches.extensions.hasFramebufferFetch()) { 341 const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode); 342 if (!isMode) { 343 // Assume SRC_OVER 344 mode = SkXfermode::kSrcOver_Mode; 345 } 346 } else { 347 mode = getXfermode(p->getXfermode()); 348 } 349 } else { 350 mode = SkXfermode::kSrcOver_Mode; 351 } 352 353 createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo); 354 } 355 356 return count; 357} 358 359int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom, 360 int alpha, int flags) { 361 if (alpha >= 255 - ALPHA_THRESHOLD) { 362 return saveLayer(left, top, right, bottom, NULL, flags); 363 } else { 364 SkPaint paint; 365 paint.setAlpha(alpha); 366 return saveLayer(left, top, right, bottom, &paint, flags); 367 } 368} 369 370/** 371 * Layers are viewed by Skia are slightly different than layers in image editing 372 * programs (for instance.) When a layer is created, previously created layers 373 * and the frame buffer still receive every drawing command. For instance, if a 374 * layer is created and a shape intersecting the bounds of the layers and the 375 * framebuffer is draw, the shape will be drawn on both (unless the layer was 376 * created with the SkCanvas::kClipToLayer_SaveFlag flag.) 377 * 378 * A way to implement layers is to create an FBO for each layer, backed by an RGBA 379 * texture. Unfortunately, this is inefficient as it requires every primitive to 380 * be drawn n + 1 times, where n is the number of active layers. In practice this 381 * means, for every primitive: 382 * - Switch active frame buffer 383 * - Change viewport, clip and projection matrix 384 * - Issue the drawing 385 * 386 * Switching rendering target n + 1 times per drawn primitive is extremely costly. 387 * To avoid this, layers are implemented in a different way here, at least in the 388 * general case. FBOs are used, as an optimization, when the "clip to layer" flag 389 * is set. When this flag is set we can redirect all drawing operations into a 390 * single FBO. 391 * 392 * This implementation relies on the frame buffer being at least RGBA 8888. When 393 * a layer is created, only a texture is created, not an FBO. The content of the 394 * frame buffer contained within the layer's bounds is copied into this texture 395 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame 396 * buffer and drawing continues as normal. This technique therefore treats the 397 * frame buffer as a scratch buffer for the layers. 398 * 399 * To compose the layers back onto the frame buffer, each layer texture 400 * (containing the original frame buffer data) is drawn as a simple quad over 401 * the frame buffer. The trick is that the quad is set as the composition 402 * destination in the blending equation, and the frame buffer becomes the source 403 * of the composition. 404 * 405 * Drawing layers with an alpha value requires an extra step before composition. 406 * An empty quad is drawn over the layer's region in the frame buffer. This quad 407 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the 408 * quad is used to multiply the colors in the frame buffer. This is achieved by 409 * changing the GL blend functions for the GL_FUNC_ADD blend equation to 410 * GL_ZERO, GL_SRC_ALPHA. 411 * 412 * Because glCopyTexImage2D() can be slow, an alternative implementation might 413 * be use to draw a single clipped layer. The implementation described above 414 * is correct in every case. 415 * 416 * (1) The frame buffer is actually not cleared right away. To allow the GPU 417 * to potentially optimize series of calls to glCopyTexImage2D, the frame 418 * buffer is left untouched until the first drawing operation. Only when 419 * something actually gets drawn are the layers regions cleared. 420 */ 421bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top, 422 float right, float bottom, int alpha, SkXfermode::Mode mode, 423 int flags, GLuint previousFbo) { 424 LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top); 425 LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize()); 426 427 const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag; 428 429 // Window coordinates of the layer 430 Rect bounds(left, top, right, bottom); 431 if (!fboLayer) { 432 mSnapshot->transform->mapRect(bounds); 433 434 // Layers only make sense if they are in the framebuffer's bounds 435 if (bounds.intersect(*snapshot->clipRect)) { 436 // We cannot work with sub-pixels in this case 437 bounds.snapToPixelBoundaries(); 438 439 // When the layer is not an FBO, we may use glCopyTexImage so we 440 // need to make sure the layer does not extend outside the bounds 441 // of the framebuffer 442 if (!bounds.intersect(snapshot->previous->viewport)) { 443 bounds.setEmpty(); 444 } 445 } else { 446 bounds.setEmpty(); 447 } 448 } 449 450 if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize || 451 bounds.getHeight() > mCaches.maxTextureSize) { 452 snapshot->empty = fboLayer; 453 } else { 454 snapshot->invisible = snapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer); 455 } 456 457 // Bail out if we won't draw in this snapshot 458 if (snapshot->invisible || snapshot->empty) { 459 return false; 460 } 461 462 glActiveTexture(gTextureUnits[0]); 463 Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight()); 464 if (!layer) { 465 return false; 466 } 467 468 layer->setAlpha(alpha, mode); 469 layer->layer.set(bounds); 470 layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()), 471 bounds.getWidth() / float(layer->getWidth()), 0.0f); 472 layer->setColorFilter(mColorFilter); 473 474 // Save the layer in the snapshot 475 snapshot->flags |= Snapshot::kFlagIsLayer; 476 snapshot->layer = layer; 477 478 if (fboLayer) { 479 return createFboLayer(layer, bounds, snapshot, previousFbo); 480 } else { 481 // Copy the framebuffer into the layer 482 layer->bindTexture(); 483 if (!bounds.isEmpty()) { 484 if (layer->isEmpty()) { 485 glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 486 bounds.left, snapshot->height - bounds.bottom, 487 layer->getWidth(), layer->getHeight(), 0); 488 layer->setEmpty(false); 489 } else { 490 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left, 491 snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight()); 492 } 493 494 // Enqueue the buffer coordinates to clear the corresponding region later 495 mLayers.push(new Rect(bounds)); 496 } 497 } 498 499 return true; 500} 501 502bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot, 503 GLuint previousFbo) { 504 layer->setFbo(mCaches.fboCache.get()); 505 506#if RENDER_LAYERS_AS_REGIONS 507 snapshot->region = &snapshot->layer->region; 508 snapshot->flags |= Snapshot::kFlagFboTarget; 509#endif 510 511 Rect clip(bounds); 512 snapshot->transform->mapRect(clip); 513 clip.intersect(*snapshot->clipRect); 514 clip.snapToPixelBoundaries(); 515 clip.intersect(snapshot->previous->viewport); 516 517 mat4 inverse; 518 inverse.loadInverse(*mSnapshot->transform); 519 520 inverse.mapRect(clip); 521 clip.snapToPixelBoundaries(); 522 clip.intersect(bounds); 523 clip.translate(-bounds.left, -bounds.top); 524 525 snapshot->flags |= Snapshot::kFlagIsFboLayer; 526 snapshot->fbo = layer->getFbo(); 527 snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f); 528 snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom); 529 snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight()); 530 snapshot->height = bounds.getHeight(); 531 snapshot->flags |= Snapshot::kFlagDirtyOrtho; 532 snapshot->orthoMatrix.load(mOrthoMatrix); 533 534 // Bind texture to FBO 535 glBindFramebuffer(GL_FRAMEBUFFER, layer->getFbo()); 536 layer->bindTexture(); 537 538 // Initialize the texture if needed 539 if (layer->isEmpty()) { 540 layer->allocateTexture(GL_RGBA, GL_UNSIGNED_BYTE); 541 layer->setEmpty(false); 542 } 543 544 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 545 layer->getTexture(), 0); 546 547#if DEBUG_LAYERS_AS_REGIONS 548 GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); 549 if (status != GL_FRAMEBUFFER_COMPLETE) { 550 LOGE("Framebuffer incomplete (GL error code 0x%x)", status); 551 552 glBindFramebuffer(GL_FRAMEBUFFER, previousFbo); 553 layer->deleteTexture(); 554 mCaches.fboCache.put(layer->getFbo()); 555 556 delete layer; 557 558 return false; 559 } 560#endif 561 562 // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering 563 glScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f, 564 clip.getWidth() + 2.0f, clip.getHeight() + 2.0f); 565 glClear(GL_COLOR_BUFFER_BIT); 566 567 dirtyClip(); 568 569 // Change the ortho projection 570 glViewport(0, 0, bounds.getWidth(), bounds.getHeight()); 571 mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f); 572 573 return true; 574} 575 576/** 577 * Read the documentation of createLayer() before doing anything in this method. 578 */ 579void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) { 580 if (!current->layer) { 581 LOGE("Attempting to compose a layer that does not exist"); 582 return; 583 } 584 585 const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer; 586 587 if (fboLayer) { 588 // Unbind current FBO and restore previous one 589 glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo); 590 } 591 592 Layer* layer = current->layer; 593 const Rect& rect = layer->layer; 594 595 if (!fboLayer && layer->getAlpha() < 255) { 596 drawColorRect(rect.left, rect.top, rect.right, rect.bottom, 597 layer->getAlpha() << 24, SkXfermode::kDstIn_Mode, true); 598 // Required below, composeLayerRect() will divide by 255 599 layer->setAlpha(255); 600 } 601 602 mCaches.unbindMeshBuffer(); 603 604 glActiveTexture(gTextureUnits[0]); 605 606 // When the layer is stored in an FBO, we can save a bit of fillrate by 607 // drawing only the dirty region 608 if (fboLayer) { 609 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform); 610 if (layer->getColorFilter()) { 611 setupColorFilter(layer->getColorFilter()); 612 } 613 composeLayerRegion(layer, rect); 614 if (layer->getColorFilter()) { 615 resetColorFilter(); 616 } 617 } else if (!rect.isEmpty()) { 618 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom); 619 composeLayerRect(layer, rect, true); 620 } 621 622 if (fboLayer) { 623 // Note: No need to use glDiscardFramebufferEXT() since we never 624 // create/compose layers that are not on screen with this 625 // code path 626 // See LayerRenderer::destroyLayer(Layer*) 627 628 // Detach the texture from the FBO 629 glBindFramebuffer(GL_FRAMEBUFFER, current->fbo); 630 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); 631 glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo); 632 633 // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed 634 mCaches.fboCache.put(current->fbo); 635 } 636 637 dirtyClip(); 638 639 // Failing to add the layer to the cache should happen only if the layer is too large 640 if (!mCaches.layerCache.put(layer)) { 641 LAYER_LOGD("Deleting layer"); 642 layer->deleteTexture(); 643 delete layer; 644 } 645} 646 647void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) { 648 float alpha = layer->getAlpha() / 255.0f; 649 650 mat4& transform = layer->getTransform(); 651 if (!transform.isIdentity()) { 652 save(0); 653 mSnapshot->transform->multiply(transform); 654 } 655 656 setupDraw(); 657 if (layer->getRenderTarget() == GL_TEXTURE_2D) { 658 setupDrawWithTexture(); 659 } else { 660 setupDrawWithExternalTexture(); 661 } 662 setupDrawTextureTransform(); 663 setupDrawColor(alpha, alpha, alpha, alpha); 664 setupDrawColorFilter(); 665 setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode()); 666 setupDrawProgram(); 667 setupDrawPureColorUniforms(); 668 setupDrawColorFilterUniforms(); 669 if (layer->getRenderTarget() == GL_TEXTURE_2D) { 670 setupDrawTexture(layer->getTexture()); 671 } else { 672 setupDrawExternalTexture(layer->getTexture()); 673 } 674 if (mSnapshot->transform->isPureTranslate() && 675 layer->getWidth() == (uint32_t) rect.getWidth() && 676 layer->getHeight() == (uint32_t) rect.getHeight()) { 677 const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f); 678 const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f); 679 680 layer->setFilter(GL_NEAREST); 681 setupDrawModelView(x, y, x + rect.getWidth(), y + rect.getHeight(), true); 682 } else { 683 layer->setFilter(GL_LINEAR); 684 setupDrawModelView(rect.left, rect.top, rect.right, rect.bottom); 685 } 686 setupDrawTextureTransformUniforms(layer->getTexTransform()); 687 setupDrawMesh(&mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]); 688 689 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 690 691 finishDrawTexture(); 692 693 if (!transform.isIdentity()) { 694 restore(); 695 } 696} 697 698void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) { 699 if (!layer->isTextureLayer()) { 700 const Rect& texCoords = layer->texCoords; 701 resetDrawTextureTexCoords(texCoords.left, texCoords.top, 702 texCoords.right, texCoords.bottom); 703 704 float x = rect.left; 705 float y = rect.top; 706 bool simpleTransform = mSnapshot->transform->isPureTranslate() && 707 layer->getWidth() == (uint32_t) rect.getWidth() && 708 layer->getHeight() == (uint32_t) rect.getHeight(); 709 710 if (simpleTransform) { 711 // When we're swapping, the layer is already in screen coordinates 712 if (!swap) { 713 x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f); 714 y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f); 715 } 716 717 layer->setFilter(GL_NEAREST, true); 718 } else { 719 layer->setFilter(GL_LINEAR, true); 720 } 721 722 drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(), 723 layer->getTexture(), layer->getAlpha() / 255.0f, 724 layer->getMode(), layer->isBlend(), 725 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], 726 GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform); 727 728 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 729 } else { 730 resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f); 731 drawTextureLayer(layer, rect); 732 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 733 } 734} 735 736void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) { 737#if RENDER_LAYERS_AS_REGIONS 738 if (layer->region.isRect()) { 739 layer->setRegionAsRect(); 740 741 composeLayerRect(layer, layer->regionRect); 742 743 layer->region.clear(); 744 return; 745 } 746 747 // TODO: See LayerRenderer.cpp::generateMesh() for important 748 // information about this implementation 749 if (!layer->region.isEmpty()) { 750 size_t count; 751 const android::Rect* rects = layer->region.getArray(&count); 752 753 const float alpha = layer->getAlpha() / 255.0f; 754 const float texX = 1.0f / float(layer->getWidth()); 755 const float texY = 1.0f / float(layer->getHeight()); 756 const float height = rect.getHeight(); 757 758 TextureVertex* mesh = mCaches.getRegionMesh(); 759 GLsizei numQuads = 0; 760 761 setupDraw(); 762 setupDrawWithTexture(); 763 setupDrawColor(alpha, alpha, alpha, alpha); 764 setupDrawColorFilter(); 765 setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode(), false); 766 setupDrawProgram(); 767 setupDrawDirtyRegionsDisabled(); 768 setupDrawPureColorUniforms(); 769 setupDrawColorFilterUniforms(); 770 setupDrawTexture(layer->getTexture()); 771 if (mSnapshot->transform->isPureTranslate()) { 772 const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f); 773 const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f); 774 775 layer->setFilter(GL_NEAREST); 776 setupDrawModelViewTranslate(x, y, x + rect.getWidth(), y + rect.getHeight(), true); 777 } else { 778 layer->setFilter(GL_LINEAR); 779 setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom); 780 } 781 setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0]); 782 783 for (size_t i = 0; i < count; i++) { 784 const android::Rect* r = &rects[i]; 785 786 const float u1 = r->left * texX; 787 const float v1 = (height - r->top) * texY; 788 const float u2 = r->right * texX; 789 const float v2 = (height - r->bottom) * texY; 790 791 // TODO: Reject quads outside of the clip 792 TextureVertex::set(mesh++, r->left, r->top, u1, v1); 793 TextureVertex::set(mesh++, r->right, r->top, u2, v1); 794 TextureVertex::set(mesh++, r->left, r->bottom, u1, v2); 795 TextureVertex::set(mesh++, r->right, r->bottom, u2, v2); 796 797 numQuads++; 798 799 if (numQuads >= REGION_MESH_QUAD_COUNT) { 800 glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL); 801 numQuads = 0; 802 mesh = mCaches.getRegionMesh(); 803 } 804 } 805 806 if (numQuads > 0) { 807 glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL); 808 } 809 810 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); 811 finishDrawTexture(); 812 813#if DEBUG_LAYERS_AS_REGIONS 814 drawRegionRects(layer->region); 815#endif 816 817 layer->region.clear(); 818 } 819#else 820 composeLayerRect(layer, rect); 821#endif 822} 823 824void OpenGLRenderer::drawRegionRects(const Region& region) { 825#if DEBUG_LAYERS_AS_REGIONS 826 size_t count; 827 const android::Rect* rects = region.getArray(&count); 828 829 uint32_t colors[] = { 830 0x7fff0000, 0x7f00ff00, 831 0x7f0000ff, 0x7fff00ff, 832 }; 833 834 int offset = 0; 835 int32_t top = rects[0].top; 836 837 for (size_t i = 0; i < count; i++) { 838 if (top != rects[i].top) { 839 offset ^= 0x2; 840 top = rects[i].top; 841 } 842 843 Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom); 844 drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)], 845 SkXfermode::kSrcOver_Mode); 846 } 847#endif 848} 849 850void OpenGLRenderer::dirtyLayer(const float left, const float top, 851 const float right, const float bottom, const mat4 transform) { 852#if RENDER_LAYERS_AS_REGIONS 853 if (hasLayer()) { 854 Rect bounds(left, top, right, bottom); 855 transform.mapRect(bounds); 856 dirtyLayerUnchecked(bounds, getRegion()); 857 } 858#endif 859} 860 861void OpenGLRenderer::dirtyLayer(const float left, const float top, 862 const float right, const float bottom) { 863#if RENDER_LAYERS_AS_REGIONS 864 if (hasLayer()) { 865 Rect bounds(left, top, right, bottom); 866 dirtyLayerUnchecked(bounds, getRegion()); 867 } 868#endif 869} 870 871void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) { 872#if RENDER_LAYERS_AS_REGIONS 873 if (bounds.intersect(*mSnapshot->clipRect)) { 874 bounds.snapToPixelBoundaries(); 875 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom); 876 if (!dirty.isEmpty()) { 877 region->orSelf(dirty); 878 } 879 } 880#endif 881} 882 883void OpenGLRenderer::clearLayerRegions() { 884 const size_t count = mLayers.size(); 885 if (count == 0) return; 886 887 if (!mSnapshot->isIgnored()) { 888 // Doing several glScissor/glClear here can negatively impact 889 // GPUs with a tiler architecture, instead we draw quads with 890 // the Clear blending mode 891 892 // The list contains bounds that have already been clipped 893 // against their initial clip rect, and the current clip 894 // is likely different so we need to disable clipping here 895 glDisable(GL_SCISSOR_TEST); 896 897 Vertex mesh[count * 6]; 898 Vertex* vertex = mesh; 899 900 for (uint32_t i = 0; i < count; i++) { 901 Rect* bounds = mLayers.itemAt(i); 902 903 Vertex::set(vertex++, bounds->left, bounds->bottom); 904 Vertex::set(vertex++, bounds->left, bounds->top); 905 Vertex::set(vertex++, bounds->right, bounds->top); 906 Vertex::set(vertex++, bounds->left, bounds->bottom); 907 Vertex::set(vertex++, bounds->right, bounds->top); 908 Vertex::set(vertex++, bounds->right, bounds->bottom); 909 910 delete bounds; 911 } 912 913 setupDraw(false); 914 setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f); 915 setupDrawBlending(true, SkXfermode::kClear_Mode); 916 setupDrawProgram(); 917 setupDrawPureColorUniforms(); 918 setupDrawModelViewTranslate(0.0f, 0.0f, 0.0f, 0.0f, true); 919 920 mCaches.unbindMeshBuffer(); 921 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 922 gVertexStride, &mesh[0].position[0]); 923 glDrawArrays(GL_TRIANGLES, 0, count * 6); 924 925 glEnable(GL_SCISSOR_TEST); 926 } else { 927 for (uint32_t i = 0; i < count; i++) { 928 delete mLayers.itemAt(i); 929 } 930 } 931 932 mLayers.clear(); 933} 934 935/////////////////////////////////////////////////////////////////////////////// 936// Transforms 937/////////////////////////////////////////////////////////////////////////////// 938 939void OpenGLRenderer::translate(float dx, float dy) { 940 mSnapshot->transform->translate(dx, dy, 0.0f); 941} 942 943void OpenGLRenderer::rotate(float degrees) { 944 mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f); 945} 946 947void OpenGLRenderer::scale(float sx, float sy) { 948 mSnapshot->transform->scale(sx, sy, 1.0f); 949} 950 951void OpenGLRenderer::skew(float sx, float sy) { 952 mSnapshot->transform->skew(sx, sy); 953} 954 955void OpenGLRenderer::setMatrix(SkMatrix* matrix) { 956 if (matrix) { 957 mSnapshot->transform->load(*matrix); 958 } else { 959 mSnapshot->transform->loadIdentity(); 960 } 961} 962 963void OpenGLRenderer::getMatrix(SkMatrix* matrix) { 964 mSnapshot->transform->copyTo(*matrix); 965} 966 967void OpenGLRenderer::concatMatrix(SkMatrix* matrix) { 968 SkMatrix transform; 969 mSnapshot->transform->copyTo(transform); 970 transform.preConcat(*matrix); 971 mSnapshot->transform->load(transform); 972} 973 974/////////////////////////////////////////////////////////////////////////////// 975// Clipping 976/////////////////////////////////////////////////////////////////////////////// 977 978void OpenGLRenderer::setScissorFromClip() { 979 Rect clip(*mSnapshot->clipRect); 980 clip.snapToPixelBoundaries(); 981 glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight()); 982 mDirtyClip = false; 983} 984 985const Rect& OpenGLRenderer::getClipBounds() { 986 return mSnapshot->getLocalClip(); 987} 988 989bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) { 990 if (mSnapshot->isIgnored()) { 991 return true; 992 } 993 994 Rect r(left, top, right, bottom); 995 mSnapshot->transform->mapRect(r); 996 r.snapToPixelBoundaries(); 997 998 Rect clipRect(*mSnapshot->clipRect); 999 clipRect.snapToPixelBoundaries(); 1000 1001 return !clipRect.intersects(r); 1002} 1003 1004bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) { 1005 bool clipped = mSnapshot->clip(left, top, right, bottom, op); 1006 if (clipped) { 1007 dirtyClip(); 1008 } 1009 return !mSnapshot->clipRect->isEmpty(); 1010} 1011 1012/////////////////////////////////////////////////////////////////////////////// 1013// Drawing commands 1014/////////////////////////////////////////////////////////////////////////////// 1015 1016void OpenGLRenderer::setupDraw(bool clear) { 1017 if (clear) clearLayerRegions(); 1018 if (mDirtyClip) { 1019 setScissorFromClip(); 1020 } 1021 mDescription.reset(); 1022 mSetShaderColor = false; 1023 mColorSet = false; 1024 mColorA = mColorR = mColorG = mColorB = 0.0f; 1025 mTextureUnit = 0; 1026 mTrackDirtyRegions = true; 1027 mTexCoordsSlot = -1; 1028} 1029 1030void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) { 1031 mDescription.hasTexture = true; 1032 mDescription.hasAlpha8Texture = isAlpha8; 1033} 1034 1035void OpenGLRenderer::setupDrawWithExternalTexture() { 1036 mDescription.hasExternalTexture = true; 1037} 1038 1039void OpenGLRenderer::setupDrawAALine() { 1040 mDescription.isAA = true; 1041} 1042 1043void OpenGLRenderer::setupDrawPoint(float pointSize) { 1044 mDescription.isPoint = true; 1045 mDescription.pointSize = pointSize; 1046} 1047 1048void OpenGLRenderer::setupDrawColor(int color) { 1049 setupDrawColor(color, (color >> 24) & 0xFF); 1050} 1051 1052void OpenGLRenderer::setupDrawColor(int color, int alpha) { 1053 mColorA = alpha / 255.0f; 1054 // Second divide of a by 255 is an optimization, allowing us to simply multiply 1055 // the rgb values by a instead of also dividing by 255 1056 const float a = mColorA / 255.0f; 1057 mColorR = a * ((color >> 16) & 0xFF); 1058 mColorG = a * ((color >> 8) & 0xFF); 1059 mColorB = a * ((color ) & 0xFF); 1060 mColorSet = true; 1061 mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA); 1062} 1063 1064void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) { 1065 mColorA = alpha / 255.0f; 1066 // Double-divide of a by 255 is an optimization, allowing us to simply multiply 1067 // the rgb values by a instead of also dividing by 255 1068 const float a = mColorA / 255.0f; 1069 mColorR = a * ((color >> 16) & 0xFF); 1070 mColorG = a * ((color >> 8) & 0xFF); 1071 mColorB = a * ((color ) & 0xFF); 1072 mColorSet = true; 1073 mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA); 1074} 1075 1076void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) { 1077 mColorA = a; 1078 mColorR = r; 1079 mColorG = g; 1080 mColorB = b; 1081 mColorSet = true; 1082 mSetShaderColor = mDescription.setColor(r, g, b, a); 1083} 1084 1085void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) { 1086 mColorA = a; 1087 mColorR = r; 1088 mColorG = g; 1089 mColorB = b; 1090 mColorSet = true; 1091 mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a); 1092} 1093 1094void OpenGLRenderer::setupDrawShader() { 1095 if (mShader) { 1096 mShader->describe(mDescription, mCaches.extensions); 1097 } 1098} 1099 1100void OpenGLRenderer::setupDrawColorFilter() { 1101 if (mColorFilter) { 1102 mColorFilter->describe(mDescription, mCaches.extensions); 1103 } 1104} 1105 1106void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) { 1107 if (mColorSet && mode == SkXfermode::kClear_Mode) { 1108 mColorA = 1.0f; 1109 mColorR = mColorG = mColorB = 0.0f; 1110 mSetShaderColor = mDescription.modulate = true; 1111 } 1112} 1113 1114void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) { 1115 // When the blending mode is kClear_Mode, we need to use a modulate color 1116 // argb=1,0,0,0 1117 accountForClear(mode); 1118 chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode, 1119 mDescription, swapSrcDst); 1120} 1121 1122void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) { 1123 // When the blending mode is kClear_Mode, we need to use a modulate color 1124 // argb=1,0,0,0 1125 accountForClear(mode); 1126 chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode, 1127 mDescription, swapSrcDst); 1128} 1129 1130void OpenGLRenderer::setupDrawProgram() { 1131 useProgram(mCaches.programCache.get(mDescription)); 1132} 1133 1134void OpenGLRenderer::setupDrawDirtyRegionsDisabled() { 1135 mTrackDirtyRegions = false; 1136} 1137 1138void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom, 1139 bool ignoreTransform) { 1140 mModelView.loadTranslate(left, top, 0.0f); 1141 if (!ignoreTransform) { 1142 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 1143 if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1144 } else { 1145 mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity); 1146 if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom); 1147 } 1148} 1149 1150void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) { 1151 mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset); 1152} 1153 1154void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom, 1155 bool ignoreTransform, bool ignoreModelView) { 1156 if (!ignoreModelView) { 1157 mModelView.loadTranslate(left, top, 0.0f); 1158 mModelView.scale(right - left, bottom - top, 1.0f); 1159 } else { 1160 mModelView.loadIdentity(); 1161 } 1162 bool dirty = right - left > 0.0f && bottom - top > 0.0f; 1163 if (!ignoreTransform) { 1164 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 1165 if (mTrackDirtyRegions && dirty) { 1166 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1167 } 1168 } else { 1169 mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity); 1170 if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom); 1171 } 1172} 1173 1174void OpenGLRenderer::setupDrawPointUniforms() { 1175 int slot = mCaches.currentProgram->getUniform("pointSize"); 1176 glUniform1f(slot, mDescription.pointSize); 1177} 1178 1179void OpenGLRenderer::setupDrawColorUniforms() { 1180 if (mColorSet || (mShader && mSetShaderColor)) { 1181 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1182 } 1183} 1184 1185void OpenGLRenderer::setupDrawPureColorUniforms() { 1186 if (mSetShaderColor) { 1187 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1188 } 1189} 1190 1191void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) { 1192 if (mShader) { 1193 if (ignoreTransform) { 1194 mModelView.loadInverse(*mSnapshot->transform); 1195 } 1196 mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit); 1197 } 1198} 1199 1200void OpenGLRenderer::setupDrawShaderIdentityUniforms() { 1201 if (mShader) { 1202 mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit); 1203 } 1204} 1205 1206void OpenGLRenderer::setupDrawColorFilterUniforms() { 1207 if (mColorFilter) { 1208 mColorFilter->setupProgram(mCaches.currentProgram); 1209 } 1210} 1211 1212void OpenGLRenderer::setupDrawSimpleMesh() { 1213 mCaches.bindMeshBuffer(); 1214 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 1215 gMeshStride, 0); 1216} 1217 1218void OpenGLRenderer::setupDrawTexture(GLuint texture) { 1219 bindTexture(texture); 1220 glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++); 1221 1222 mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords"); 1223 glEnableVertexAttribArray(mTexCoordsSlot); 1224} 1225 1226void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) { 1227 bindExternalTexture(texture); 1228 glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++); 1229 1230 mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords"); 1231 glEnableVertexAttribArray(mTexCoordsSlot); 1232} 1233 1234void OpenGLRenderer::setupDrawTextureTransform() { 1235 mDescription.hasTextureTransform = true; 1236} 1237 1238void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) { 1239 glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1, 1240 GL_FALSE, &transform.data[0]); 1241} 1242 1243void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) { 1244 if (!vertices) { 1245 mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo); 1246 } else { 1247 mCaches.unbindMeshBuffer(); 1248 } 1249 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 1250 gMeshStride, vertices); 1251 if (mTexCoordsSlot >= 0) { 1252 glVertexAttribPointer(mTexCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords); 1253 } 1254} 1255 1256void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) { 1257 mCaches.unbindMeshBuffer(); 1258 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 1259 gVertexStride, vertices); 1260} 1261 1262/** 1263 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an 1264 * outer boundary that fades out to 0. The variables set in the shader define the proportion of 1265 * the width and length of the primitive occupied by the AA region. The vtxWidth and vtxLength 1266 * attributes (one per vertex) are values from zero to one that tells the fragment 1267 * shader where the fragment is in relation to the line width/length overall; these values are 1268 * then used to compute the proper color, based on whether the fragment lies in the fading AA 1269 * region of the line. 1270 * Note that we only pass down the width values in this setup function. The length coordinates 1271 * are set up for each individual segment. 1272 */ 1273void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* widthCoords, 1274 GLvoid* lengthCoords, float boundaryWidthProportion) { 1275 mCaches.unbindMeshBuffer(); 1276 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 1277 gAAVertexStride, vertices); 1278 int widthSlot = mCaches.currentProgram->getAttrib("vtxWidth"); 1279 glEnableVertexAttribArray(widthSlot); 1280 glVertexAttribPointer(widthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, widthCoords); 1281 int lengthSlot = mCaches.currentProgram->getAttrib("vtxLength"); 1282 glEnableVertexAttribArray(lengthSlot); 1283 glVertexAttribPointer(lengthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, lengthCoords); 1284 int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth"); 1285 glUniform1f(boundaryWidthSlot, boundaryWidthProportion); 1286 // Setting the inverse value saves computations per-fragment in the shader 1287 int inverseBoundaryWidthSlot = mCaches.currentProgram->getUniform("inverseBoundaryWidth"); 1288 glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion)); 1289} 1290 1291void OpenGLRenderer::finishDrawTexture() { 1292 glDisableVertexAttribArray(mTexCoordsSlot); 1293} 1294 1295/////////////////////////////////////////////////////////////////////////////// 1296// Drawing 1297/////////////////////////////////////////////////////////////////////////////// 1298 1299bool OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t width, uint32_t height, 1300 Rect& dirty, uint32_t level) { 1301 if (quickReject(0.0f, 0.0f, width, height)) { 1302 return false; 1303 } 1304 1305 // All the usual checks and setup operations (quickReject, setupDraw, etc.) 1306 // will be performed by the display list itself 1307 if (displayList && displayList->isRenderable()) { 1308 return displayList->replay(*this, dirty, level); 1309 } 1310 1311 return false; 1312} 1313 1314void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) { 1315 if (displayList) { 1316 displayList->output(*this, level); 1317 } 1318} 1319 1320void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) { 1321 int alpha; 1322 SkXfermode::Mode mode; 1323 getAlphaAndMode(paint, &alpha, &mode); 1324 1325 float x = left; 1326 float y = top; 1327 1328 GLenum filter = GL_LINEAR; 1329 bool ignoreTransform = false; 1330 if (mSnapshot->transform->isPureTranslate()) { 1331 x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f); 1332 y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f); 1333 ignoreTransform = true; 1334 filter = GL_NEAREST; 1335 } else { 1336 filter = FILTER(paint); 1337 } 1338 1339 setupDraw(); 1340 setupDrawWithTexture(true); 1341 if (paint) { 1342 setupDrawAlpha8Color(paint->getColor(), alpha); 1343 } 1344 setupDrawColorFilter(); 1345 setupDrawShader(); 1346 setupDrawBlending(true, mode); 1347 setupDrawProgram(); 1348 setupDrawModelView(x, y, x + texture->width, y + texture->height, ignoreTransform); 1349 1350 setupDrawTexture(texture->id); 1351 texture->setWrap(GL_CLAMP_TO_EDGE); 1352 texture->setFilter(filter); 1353 1354 setupDrawPureColorUniforms(); 1355 setupDrawColorFilterUniforms(); 1356 setupDrawShaderUniforms(); 1357 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 1358 1359 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 1360 1361 finishDrawTexture(); 1362} 1363 1364void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) { 1365 const float right = left + bitmap->width(); 1366 const float bottom = top + bitmap->height(); 1367 1368 if (quickReject(left, top, right, bottom)) { 1369 return; 1370 } 1371 1372 glActiveTexture(gTextureUnits[0]); 1373 Texture* texture = mCaches.textureCache.get(bitmap); 1374 if (!texture) return; 1375 const AutoTexture autoCleanup(texture); 1376 1377 if (bitmap->getConfig() == SkBitmap::kA8_Config) { 1378 drawAlphaBitmap(texture, left, top, paint); 1379 } else { 1380 drawTextureRect(left, top, right, bottom, texture, paint); 1381 } 1382} 1383 1384void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) { 1385 Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height()); 1386 const mat4 transform(*matrix); 1387 transform.mapRect(r); 1388 1389 if (quickReject(r.left, r.top, r.right, r.bottom)) { 1390 return; 1391 } 1392 1393 glActiveTexture(gTextureUnits[0]); 1394 Texture* texture = mCaches.textureCache.get(bitmap); 1395 if (!texture) return; 1396 const AutoTexture autoCleanup(texture); 1397 1398 // This could be done in a cheaper way, all we need is pass the matrix 1399 // to the vertex shader. The save/restore is a bit overkill. 1400 save(SkCanvas::kMatrix_SaveFlag); 1401 concatMatrix(matrix); 1402 drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint); 1403 restore(); 1404} 1405 1406void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight, 1407 float* vertices, int* colors, SkPaint* paint) { 1408 // TODO: Do a quickReject 1409 if (!vertices || mSnapshot->isIgnored()) { 1410 return; 1411 } 1412 1413 glActiveTexture(gTextureUnits[0]); 1414 Texture* texture = mCaches.textureCache.get(bitmap); 1415 if (!texture) return; 1416 const AutoTexture autoCleanup(texture); 1417 1418 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1419 texture->setFilter(FILTER(paint), true); 1420 1421 int alpha; 1422 SkXfermode::Mode mode; 1423 getAlphaAndMode(paint, &alpha, &mode); 1424 1425 const uint32_t count = meshWidth * meshHeight * 6; 1426 1427 float left = FLT_MAX; 1428 float top = FLT_MAX; 1429 float right = FLT_MIN; 1430 float bottom = FLT_MIN; 1431 1432#if RENDER_LAYERS_AS_REGIONS 1433 bool hasActiveLayer = hasLayer(); 1434#else 1435 bool hasActiveLayer = false; 1436#endif 1437 1438 // TODO: Support the colors array 1439 TextureVertex mesh[count]; 1440 TextureVertex* vertex = mesh; 1441 for (int32_t y = 0; y < meshHeight; y++) { 1442 for (int32_t x = 0; x < meshWidth; x++) { 1443 uint32_t i = (y * (meshWidth + 1) + x) * 2; 1444 1445 float u1 = float(x) / meshWidth; 1446 float u2 = float(x + 1) / meshWidth; 1447 float v1 = float(y) / meshHeight; 1448 float v2 = float(y + 1) / meshHeight; 1449 1450 int ax = i + (meshWidth + 1) * 2; 1451 int ay = ax + 1; 1452 int bx = i; 1453 int by = bx + 1; 1454 int cx = i + 2; 1455 int cy = cx + 1; 1456 int dx = i + (meshWidth + 1) * 2 + 2; 1457 int dy = dx + 1; 1458 1459 TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2); 1460 TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1); 1461 TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1); 1462 1463 TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2); 1464 TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1); 1465 TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2); 1466 1467#if RENDER_LAYERS_AS_REGIONS 1468 if (hasActiveLayer) { 1469 // TODO: This could be optimized to avoid unnecessary ops 1470 left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx]))); 1471 top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy]))); 1472 right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx]))); 1473 bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy]))); 1474 } 1475#endif 1476 } 1477 } 1478 1479#if RENDER_LAYERS_AS_REGIONS 1480 if (hasActiveLayer) { 1481 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1482 } 1483#endif 1484 1485 drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f, 1486 mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0], 1487 GL_TRIANGLES, count, false, false, 0, false, false); 1488} 1489 1490void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, 1491 float srcLeft, float srcTop, float srcRight, float srcBottom, 1492 float dstLeft, float dstTop, float dstRight, float dstBottom, 1493 SkPaint* paint) { 1494 if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) { 1495 return; 1496 } 1497 1498 glActiveTexture(gTextureUnits[0]); 1499 Texture* texture = mCaches.textureCache.get(bitmap); 1500 if (!texture) return; 1501 const AutoTexture autoCleanup(texture); 1502 1503 const float width = texture->width; 1504 const float height = texture->height; 1505 1506 const float u1 = fmax(0.0f, srcLeft / width); 1507 const float v1 = fmax(0.0f, srcTop / height); 1508 const float u2 = fmin(1.0f, srcRight / width); 1509 const float v2 = fmin(1.0f, srcBottom / height); 1510 1511 mCaches.unbindMeshBuffer(); 1512 resetDrawTextureTexCoords(u1, v1, u2, v2); 1513 1514 int alpha; 1515 SkXfermode::Mode mode; 1516 getAlphaAndMode(paint, &alpha, &mode); 1517 1518 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1519 1520 if (mSnapshot->transform->isPureTranslate()) { 1521 const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f); 1522 const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f); 1523 1524 GLenum filter = GL_NEAREST; 1525 // Enable linear filtering if the source rectangle is scaled 1526 if (srcRight - srcLeft != dstRight - dstLeft || srcBottom - srcTop != dstBottom - dstTop) { 1527 filter = FILTER(paint); 1528 } 1529 1530 texture->setFilter(filter, true); 1531 drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop), 1532 texture->id, alpha / 255.0f, mode, texture->blend, 1533 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], 1534 GL_TRIANGLE_STRIP, gMeshCount, false, true); 1535 } else { 1536 texture->setFilter(FILTER(paint), true); 1537 drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f, 1538 mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], 1539 GL_TRIANGLE_STRIP, gMeshCount); 1540 } 1541 1542 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 1543} 1544 1545void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs, 1546 const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors, 1547 float left, float top, float right, float bottom, SkPaint* paint) { 1548 if (quickReject(left, top, right, bottom)) { 1549 return; 1550 } 1551 1552 glActiveTexture(gTextureUnits[0]); 1553 Texture* texture = mCaches.textureCache.get(bitmap); 1554 if (!texture) return; 1555 const AutoTexture autoCleanup(texture); 1556 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1557 texture->setFilter(GL_LINEAR, true); 1558 1559 int alpha; 1560 SkXfermode::Mode mode; 1561 getAlphaAndMode(paint, &alpha, &mode); 1562 1563 const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(), 1564 right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors); 1565 1566 if (mesh && mesh->verticesCount > 0) { 1567 const bool pureTranslate = mSnapshot->transform->isPureTranslate(); 1568#if RENDER_LAYERS_AS_REGIONS 1569 // Mark the current layer dirty where we are going to draw the patch 1570 if (hasLayer() && mesh->hasEmptyQuads) { 1571 const float offsetX = left + mSnapshot->transform->getTranslateX(); 1572 const float offsetY = top + mSnapshot->transform->getTranslateY(); 1573 const size_t count = mesh->quads.size(); 1574 for (size_t i = 0; i < count; i++) { 1575 const Rect& bounds = mesh->quads.itemAt(i); 1576 if (pureTranslate) { 1577 const float x = (int) floorf(bounds.left + offsetX + 0.5f); 1578 const float y = (int) floorf(bounds.top + offsetY + 0.5f); 1579 dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight()); 1580 } else { 1581 dirtyLayer(left + bounds.left, top + bounds.top, 1582 left + bounds.right, top + bounds.bottom, *mSnapshot->transform); 1583 } 1584 } 1585 } 1586#endif 1587 1588 if (pureTranslate) { 1589 const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f); 1590 const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f); 1591 1592 drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f, 1593 mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset, 1594 GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer, 1595 true, !mesh->hasEmptyQuads); 1596 } else { 1597 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, 1598 mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset, 1599 GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer, 1600 true, !mesh->hasEmptyQuads); 1601 } 1602 } 1603} 1604 1605/** 1606 * This function uses a similar approach to that of AA lines in the drawLines() function. 1607 * We expand the rectangle by a half pixel in screen space on all sides, and use a fragment 1608 * shader to compute the translucency of the color, determined by whether a given pixel is 1609 * within that boundary region and how far into the region it is. 1610 */ 1611void OpenGLRenderer::drawAARect(float left, float top, float right, float bottom, 1612 int color, SkXfermode::Mode mode) { 1613 float inverseScaleX = 1.0f; 1614 float inverseScaleY = 1.0f; 1615 // The quad that we use needs to account for scaling. 1616 if (!mSnapshot->transform->isPureTranslate()) { 1617 Matrix4 *mat = mSnapshot->transform; 1618 float m00 = mat->data[Matrix4::kScaleX]; 1619 float m01 = mat->data[Matrix4::kSkewY]; 1620 float m02 = mat->data[2]; 1621 float m10 = mat->data[Matrix4::kSkewX]; 1622 float m11 = mat->data[Matrix4::kScaleX]; 1623 float m12 = mat->data[6]; 1624 float scaleX = sqrt(m00 * m00 + m01 * m01); 1625 float scaleY = sqrt(m10 * m10 + m11 * m11); 1626 inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0; 1627 inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0; 1628 } 1629 1630 setupDraw(); 1631 setupDrawAALine(); 1632 setupDrawColor(color); 1633 setupDrawColorFilter(); 1634 setupDrawShader(); 1635 setupDrawBlending(true, mode); 1636 setupDrawProgram(); 1637 setupDrawModelViewIdentity(true); 1638 setupDrawColorUniforms(); 1639 setupDrawColorFilterUniforms(); 1640 setupDrawShaderIdentityUniforms(); 1641 1642 AAVertex rects[4]; 1643 AAVertex* aaVertices = &rects[0]; 1644 void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset; 1645 void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset; 1646 1647 float boundarySizeX = .5 * inverseScaleX; 1648 float boundarySizeY = .5 * inverseScaleY; 1649 1650 // Adjust the rect by the AA boundary padding 1651 left -= boundarySizeX; 1652 right += boundarySizeX; 1653 top -= boundarySizeY; 1654 bottom += boundarySizeY; 1655 1656 float width = right - left; 1657 float height = bottom - top; 1658 1659 float boundaryWidthProportion = (width != 0) ? (2 * boundarySizeX) / width : 0; 1660 float boundaryHeightProportion = (height != 0) ? (2 * boundarySizeY) / height : 0; 1661 setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion); 1662 int boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength"); 1663 int inverseBoundaryLengthSlot = mCaches.currentProgram->getUniform("inverseBoundaryLength"); 1664 glUniform1f(boundaryLengthSlot, boundaryHeightProportion); 1665 glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryHeightProportion)); 1666 1667 if (!quickReject(left, top, right, bottom)) { 1668 AAVertex::set(aaVertices++, left, bottom, 1, 1); 1669 AAVertex::set(aaVertices++, left, top, 1, 0); 1670 AAVertex::set(aaVertices++, right, bottom, 0, 1); 1671 AAVertex::set(aaVertices++, right, top, 0, 0); 1672 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1673 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); 1674 } 1675} 1676 1677/** 1678 * We draw lines as quads (tristrips). Using GL_LINES can be difficult because the rasterization 1679 * rules for those lines produces some unexpected results, and may vary between hardware devices. 1680 * The basics of lines-as-quads is easy; we simply find the normal to the line and position the 1681 * corners of the quads on either side of each line endpoint, separated by the strokeWidth 1682 * of the line. Hairlines are more involved because we need to account for transform scaling 1683 * to end up with a one-pixel-wide line in screen space.. 1684 * Anti-aliased lines add another factor to the approach. We use a specialized fragment shader 1685 * in combination with values that we calculate and pass down in this method. The basic approach 1686 * is that the quad we create contains both the core line area plus a bounding area in which 1687 * the translucent/AA pixels are drawn. The values we calculate tell the shader what 1688 * proportion of the width and the length of a given segment is represented by the boundary 1689 * region. The quad ends up being exactly .5 pixel larger in all directions than the non-AA quad. 1690 * The bounding region is actually 1 pixel wide on all sides (half pixel on the outside, half pixel 1691 * on the inside). This ends up giving the result we want, with pixels that are completely 1692 * 'inside' the line area being filled opaquely and the other pixels being filled according to 1693 * how far into the boundary region they are, which is determined by shader interpolation. 1694 */ 1695void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) { 1696 if (mSnapshot->isIgnored()) return; 1697 1698 const bool isAA = paint->isAntiAlias(); 1699 // We use half the stroke width here because we're going to position the quad 1700 // corner vertices half of the width away from the line endpoints 1701 float halfStrokeWidth = paint->getStrokeWidth() * 0.5f; 1702 // A stroke width of 0 has a special meaning in Skia: 1703 // it draws a line 1 px wide regardless of current transform 1704 bool isHairLine = paint->getStrokeWidth() == 0.0f; 1705 float inverseScaleX = 1.0f; 1706 float inverseScaleY = 1.0f; 1707 bool scaled = false; 1708 int alpha; 1709 SkXfermode::Mode mode; 1710 int generatedVerticesCount = 0; 1711 int verticesCount = count; 1712 if (count > 4) { 1713 // Polyline: account for extra vertices needed for continuous tri-strip 1714 verticesCount += (count - 4); 1715 } 1716 1717 if (isHairLine || isAA) { 1718 // The quad that we use for AA and hairlines needs to account for scaling. For hairlines 1719 // the line on the screen should always be one pixel wide regardless of scale. For 1720 // AA lines, we only want one pixel of translucent boundary around the quad. 1721 if (!mSnapshot->transform->isPureTranslate()) { 1722 Matrix4 *mat = mSnapshot->transform; 1723 float m00 = mat->data[Matrix4::kScaleX]; 1724 float m01 = mat->data[Matrix4::kSkewY]; 1725 float m02 = mat->data[2]; 1726 float m10 = mat->data[Matrix4::kSkewX]; 1727 float m11 = mat->data[Matrix4::kScaleX]; 1728 float m12 = mat->data[6]; 1729 float scaleX = sqrt(m00*m00 + m01*m01); 1730 float scaleY = sqrt(m10*m10 + m11*m11); 1731 inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0; 1732 inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0; 1733 if (inverseScaleX != 1.0f || inverseScaleY != 1.0f) { 1734 scaled = true; 1735 } 1736 } 1737 } 1738 1739 getAlphaAndMode(paint, &alpha, &mode); 1740 setupDraw(); 1741 if (isAA) { 1742 setupDrawAALine(); 1743 } 1744 setupDrawColor(paint->getColor(), alpha); 1745 setupDrawColorFilter(); 1746 setupDrawShader(); 1747 if (isAA) { 1748 setupDrawBlending(true, mode); 1749 } else { 1750 setupDrawBlending(mode); 1751 } 1752 setupDrawProgram(); 1753 setupDrawModelViewIdentity(true); 1754 setupDrawColorUniforms(); 1755 setupDrawColorFilterUniforms(); 1756 setupDrawShaderIdentityUniforms(); 1757 1758 if (isHairLine) { 1759 // Set a real stroke width to be used in quad construction 1760 halfStrokeWidth = isAA? 1 : .5; 1761 } else if (isAA && !scaled) { 1762 // Expand boundary to enable AA calculations on the quad border 1763 halfStrokeWidth += .5f; 1764 } 1765 Vertex lines[verticesCount]; 1766 Vertex* vertices = &lines[0]; 1767 AAVertex wLines[verticesCount]; 1768 AAVertex* aaVertices = &wLines[0]; 1769 if (!isAA) { 1770 setupDrawVertices(vertices); 1771 } else { 1772 void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset; 1773 void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset; 1774 // innerProportion is the ratio of the inner (non-AA) part of the line to the total 1775 // AA stroke width (the base stroke width expanded by a half pixel on either side). 1776 // This value is used in the fragment shader to determine how to fill fragments. 1777 // We will need to calculate the actual width proportion on each segment for 1778 // scaled non-hairlines, since the boundary proportion may differ per-axis when scaled. 1779 float boundaryWidthProportion = 1 / (2 * halfStrokeWidth); 1780 setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion); 1781 } 1782 1783 AAVertex* prevAAVertex = NULL; 1784 Vertex* prevVertex = NULL; 1785 1786 int boundaryLengthSlot = -1; 1787 int inverseBoundaryLengthSlot = -1; 1788 int boundaryWidthSlot = -1; 1789 int inverseBoundaryWidthSlot = -1; 1790 for (int i = 0; i < count; i += 4) { 1791 // a = start point, b = end point 1792 vec2 a(points[i], points[i + 1]); 1793 vec2 b(points[i + 2], points[i + 3]); 1794 float length = 0; 1795 float boundaryLengthProportion = 0; 1796 float boundaryWidthProportion = 0; 1797 1798 // Find the normal to the line 1799 vec2 n = (b - a).copyNormalized() * halfStrokeWidth; 1800 if (isHairLine) { 1801 if (isAA) { 1802 float wideningFactor; 1803 if (fabs(n.x) >= fabs(n.y)) { 1804 wideningFactor = fabs(1.0f / n.x); 1805 } else { 1806 wideningFactor = fabs(1.0f / n.y); 1807 } 1808 n *= wideningFactor; 1809 } 1810 if (scaled) { 1811 n.x *= inverseScaleX; 1812 n.y *= inverseScaleY; 1813 } 1814 } else if (scaled) { 1815 // Extend n by .5 pixel on each side, post-transform 1816 vec2 extendedN = n.copyNormalized(); 1817 extendedN /= 2; 1818 extendedN.x *= inverseScaleX; 1819 extendedN.y *= inverseScaleY; 1820 float extendedNLength = extendedN.length(); 1821 // We need to set this value on the shader prior to drawing 1822 boundaryWidthProportion = extendedNLength / (halfStrokeWidth + extendedNLength); 1823 n += extendedN; 1824 } 1825 float x = n.x; 1826 n.x = -n.y; 1827 n.y = x; 1828 1829 // aa lines expand the endpoint vertices to encompass the AA boundary 1830 if (isAA) { 1831 vec2 abVector = (b - a); 1832 length = abVector.length(); 1833 abVector.normalize(); 1834 if (scaled) { 1835 abVector.x *= inverseScaleX; 1836 abVector.y *= inverseScaleY; 1837 float abLength = abVector.length(); 1838 boundaryLengthProportion = abLength / (length + abLength); 1839 } else { 1840 boundaryLengthProportion = .5 / (length + 1); 1841 } 1842 abVector /= 2; 1843 a -= abVector; 1844 b += abVector; 1845 } 1846 1847 // Four corners of the rectangle defining a thick line 1848 vec2 p1 = a - n; 1849 vec2 p2 = a + n; 1850 vec2 p3 = b + n; 1851 vec2 p4 = b - n; 1852 1853 1854 const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x))); 1855 const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x))); 1856 const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y))); 1857 const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y))); 1858 1859 if (!quickReject(left, top, right, bottom)) { 1860 if (!isAA) { 1861 if (prevVertex != NULL) { 1862 // Issue two repeat vertices to create degenerate triangles to bridge 1863 // between the previous line and the new one. This is necessary because 1864 // we are creating a single triangle_strip which will contain 1865 // potentially discontinuous line segments. 1866 Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]); 1867 Vertex::set(vertices++, p1.x, p1.y); 1868 generatedVerticesCount += 2; 1869 } 1870 Vertex::set(vertices++, p1.x, p1.y); 1871 Vertex::set(vertices++, p2.x, p2.y); 1872 Vertex::set(vertices++, p4.x, p4.y); 1873 Vertex::set(vertices++, p3.x, p3.y); 1874 prevVertex = vertices - 1; 1875 generatedVerticesCount += 4; 1876 } else { 1877 if (!isHairLine && scaled) { 1878 // Must set width proportions per-segment for scaled non-hairlines to use the 1879 // correct AA boundary dimensions 1880 if (boundaryWidthSlot < 0) { 1881 boundaryWidthSlot = 1882 mCaches.currentProgram->getUniform("boundaryWidth"); 1883 inverseBoundaryWidthSlot = 1884 mCaches.currentProgram->getUniform("inverseBoundaryWidth"); 1885 } 1886 glUniform1f(boundaryWidthSlot, boundaryWidthProportion); 1887 glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion)); 1888 } 1889 if (boundaryLengthSlot < 0) { 1890 boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength"); 1891 inverseBoundaryLengthSlot = 1892 mCaches.currentProgram->getUniform("inverseBoundaryLength"); 1893 } 1894 glUniform1f(boundaryLengthSlot, boundaryLengthProportion); 1895 glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryLengthProportion)); 1896 1897 if (prevAAVertex != NULL) { 1898 // Issue two repeat vertices to create degenerate triangles to bridge 1899 // between the previous line and the new one. This is necessary because 1900 // we are creating a single triangle_strip which will contain 1901 // potentially discontinuous line segments. 1902 AAVertex::set(aaVertices++,prevAAVertex->position[0], 1903 prevAAVertex->position[1], prevAAVertex->width, prevAAVertex->length); 1904 AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1); 1905 generatedVerticesCount += 2; 1906 } 1907 AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1); 1908 AAVertex::set(aaVertices++, p1.x, p1.y, 1, 0); 1909 AAVertex::set(aaVertices++, p3.x, p3.y, 0, 1); 1910 AAVertex::set(aaVertices++, p2.x, p2.y, 0, 0); 1911 prevAAVertex = aaVertices - 1; 1912 generatedVerticesCount += 4; 1913 } 1914 dirtyLayer(a.x == b.x ? left - 1 : left, a.y == b.y ? top - 1 : top, 1915 a.x == b.x ? right: right, a.y == b.y ? bottom: bottom, 1916 *mSnapshot->transform); 1917 } 1918 } 1919 if (generatedVerticesCount > 0) { 1920 glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount); 1921 } 1922} 1923 1924void OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) { 1925 if (mSnapshot->isIgnored()) return; 1926 1927 // TODO: The paint's cap style defines whether the points are square or circular 1928 // TODO: Handle AA for round points 1929 1930 // A stroke width of 0 has a special meaning in Skia: 1931 // it draws an unscaled 1px point 1932 float strokeWidth = paint->getStrokeWidth(); 1933 const bool isHairLine = paint->getStrokeWidth() == 0.0f; 1934 if (isHairLine) { 1935 // Now that we know it's hairline, we can set the effective width, to be used later 1936 strokeWidth = 1.0f; 1937 } 1938 const float halfWidth = strokeWidth / 2; 1939 int alpha; 1940 SkXfermode::Mode mode; 1941 getAlphaAndMode(paint, &alpha, &mode); 1942 1943 int verticesCount = count >> 1; 1944 int generatedVerticesCount = 0; 1945 1946 TextureVertex pointsData[verticesCount]; 1947 TextureVertex* vertex = &pointsData[0]; 1948 1949 setupDraw(); 1950 setupDrawPoint(strokeWidth); 1951 setupDrawColor(paint->getColor(), alpha); 1952 setupDrawColorFilter(); 1953 setupDrawShader(); 1954 setupDrawBlending(mode); 1955 setupDrawProgram(); 1956 setupDrawModelViewIdentity(true); 1957 setupDrawColorUniforms(); 1958 setupDrawColorFilterUniforms(); 1959 setupDrawPointUniforms(); 1960 setupDrawShaderIdentityUniforms(); 1961 setupDrawMesh(vertex); 1962 1963 for (int i = 0; i < count; i += 2) { 1964 TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f); 1965 generatedVerticesCount++; 1966 float left = points[i] - halfWidth; 1967 float right = points[i] + halfWidth; 1968 float top = points[i + 1] - halfWidth; 1969 float bottom = points [i + 1] + halfWidth; 1970 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1971 } 1972 1973 glDrawArrays(GL_POINTS, 0, generatedVerticesCount); 1974} 1975 1976void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 1977 // No need to check against the clip, we fill the clip region 1978 if (mSnapshot->isIgnored()) return; 1979 1980 Rect& clip(*mSnapshot->clipRect); 1981 clip.snapToPixelBoundaries(); 1982 1983 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true); 1984} 1985 1986void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) { 1987 if (!texture) return; 1988 const AutoTexture autoCleanup(texture); 1989 1990 const float x = left + texture->left - texture->offset; 1991 const float y = top + texture->top - texture->offset; 1992 1993 drawPathTexture(texture, x, y, paint); 1994} 1995 1996void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom, 1997 float rx, float ry, SkPaint* paint) { 1998 if (mSnapshot->isIgnored()) return; 1999 2000 glActiveTexture(gTextureUnits[0]); 2001 const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect( 2002 right - left, bottom - top, rx, ry, paint); 2003 drawShape(left, top, texture, paint); 2004} 2005 2006void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) { 2007 if (mSnapshot->isIgnored()) return; 2008 2009 glActiveTexture(gTextureUnits[0]); 2010 const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint); 2011 drawShape(x - radius, y - radius, texture, paint); 2012} 2013 2014void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) { 2015 if (mSnapshot->isIgnored()) return; 2016 2017 glActiveTexture(gTextureUnits[0]); 2018 const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint); 2019 drawShape(left, top, texture, paint); 2020} 2021 2022void OpenGLRenderer::drawArc(float left, float top, float right, float bottom, 2023 float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) { 2024 if (mSnapshot->isIgnored()) return; 2025 2026 if (fabs(sweepAngle) >= 360.0f) { 2027 drawOval(left, top, right, bottom, paint); 2028 return; 2029 } 2030 2031 glActiveTexture(gTextureUnits[0]); 2032 const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top, 2033 startAngle, sweepAngle, useCenter, paint); 2034 drawShape(left, top, texture, paint); 2035} 2036 2037void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom, 2038 SkPaint* paint) { 2039 if (mSnapshot->isIgnored()) return; 2040 2041 glActiveTexture(gTextureUnits[0]); 2042 const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint); 2043 drawShape(left, top, texture, paint); 2044} 2045 2046void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) { 2047 if (p->getStyle() != SkPaint::kFill_Style) { 2048 drawRectAsShape(left, top, right, bottom, p); 2049 return; 2050 } 2051 2052 if (quickReject(left, top, right, bottom)) { 2053 return; 2054 } 2055 2056 SkXfermode::Mode mode; 2057 if (!mCaches.extensions.hasFramebufferFetch()) { 2058 const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode); 2059 if (!isMode) { 2060 // Assume SRC_OVER 2061 mode = SkXfermode::kSrcOver_Mode; 2062 } 2063 } else { 2064 mode = getXfermode(p->getXfermode()); 2065 } 2066 2067 int color = p->getColor(); 2068 if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) { 2069 drawAARect(left, top, right, bottom, color, mode); 2070 } else { 2071 drawColorRect(left, top, right, bottom, color, mode); 2072 } 2073} 2074 2075void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, 2076 float x, float y, SkPaint* paint, float length) { 2077 if (text == NULL || count == 0) { 2078 return; 2079 } 2080 if (mSnapshot->isIgnored()) return; 2081 2082 // NOTE: AA and glyph id encoding are set in DisplayListRenderer.cpp 2083 2084 switch (paint->getTextAlign()) { 2085 case SkPaint::kCenter_Align: 2086 if (length < 0.0f) length = paint->measureText(text, bytesCount); 2087 x -= length / 2.0f; 2088 break; 2089 case SkPaint::kRight_Align: 2090 if (length < 0.0f) length = paint->measureText(text, bytesCount); 2091 x -= length; 2092 break; 2093 default: 2094 break; 2095 } 2096 2097 SkPaint::FontMetrics metrics; 2098 paint->getFontMetrics(&metrics, 0.0f); 2099 // If no length was specified, just perform the hit test on the Y axis 2100 if (quickReject(x, y + metrics.fTop, 2101 x + (length >= 0.0f ? length : INT_MAX / 2), y + metrics.fBottom)) { 2102 return; 2103 } 2104 2105 const float oldX = x; 2106 const float oldY = y; 2107 const bool pureTranslate = mSnapshot->transform->isPureTranslate(); 2108 if (pureTranslate) { 2109 x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f); 2110 y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f); 2111 } 2112 2113 FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint); 2114#if DEBUG_GLYPHS 2115 LOGD("OpenGLRenderer drawText() with FontID=%d", SkTypeface::UniqueID(paint->getTypeface())); 2116#endif 2117 fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), 2118 paint->getTextSize()); 2119 2120 int alpha; 2121 SkXfermode::Mode mode; 2122 getAlphaAndMode(paint, &alpha, &mode); 2123 2124 if (mHasShadow) { 2125 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 2126 const ShadowTexture* shadow = mCaches.dropShadowCache.get( 2127 paint, text, bytesCount, count, mShadowRadius); 2128 const AutoTexture autoCleanup(shadow); 2129 2130 const float sx = oldX - shadow->left + mShadowDx; 2131 const float sy = oldY - shadow->top + mShadowDy; 2132 2133 const int shadowAlpha = ((mShadowColor >> 24) & 0xFF); 2134 int shadowColor = mShadowColor; 2135 if (mShader) { 2136 shadowColor = 0xffffffff; 2137 } 2138 2139 glActiveTexture(gTextureUnits[0]); 2140 setupDraw(); 2141 setupDrawWithTexture(true); 2142 setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha); 2143 setupDrawColorFilter(); 2144 setupDrawShader(); 2145 setupDrawBlending(true, mode); 2146 setupDrawProgram(); 2147 setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height); 2148 setupDrawTexture(shadow->id); 2149 setupDrawPureColorUniforms(); 2150 setupDrawColorFilterUniforms(); 2151 setupDrawShaderUniforms(); 2152 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 2153 2154 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 2155 2156 finishDrawTexture(); 2157 } 2158 2159 if (paint->getAlpha() == 0 && paint->getXfermode() == NULL) { 2160 return; 2161 } 2162 2163 // Pick the appropriate texture filtering 2164 bool linearFilter = mSnapshot->transform->changesBounds(); 2165 if (pureTranslate && !linearFilter) { 2166 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2167 } 2168 2169 glActiveTexture(gTextureUnits[0]); 2170 setupDraw(); 2171 setupDrawDirtyRegionsDisabled(); 2172 setupDrawWithTexture(true); 2173 setupDrawAlpha8Color(paint->getColor(), alpha); 2174 setupDrawColorFilter(); 2175 setupDrawShader(); 2176 setupDrawBlending(true, mode); 2177 setupDrawProgram(); 2178 setupDrawModelView(x, y, x, y, pureTranslate, true); 2179 setupDrawTexture(fontRenderer.getTexture(linearFilter)); 2180 setupDrawPureColorUniforms(); 2181 setupDrawColorFilterUniforms(); 2182 setupDrawShaderUniforms(pureTranslate); 2183 2184 const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip(); 2185 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2186 2187#if RENDER_LAYERS_AS_REGIONS 2188 bool hasActiveLayer = hasLayer(); 2189#else 2190 bool hasActiveLayer = false; 2191#endif 2192 mCaches.unbindMeshBuffer(); 2193 2194 // Tell font renderer the locations of position and texture coord 2195 // attributes so it can bind its data properly 2196 int positionSlot = mCaches.currentProgram->position; 2197 fontRenderer.setAttributeBindingSlots(positionSlot, mTexCoordsSlot); 2198 if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y, 2199 hasActiveLayer ? &bounds : NULL)) { 2200#if RENDER_LAYERS_AS_REGIONS 2201 if (hasActiveLayer) { 2202 if (!pureTranslate) { 2203 mSnapshot->transform->mapRect(bounds); 2204 } 2205 dirtyLayerUnchecked(bounds, getRegion()); 2206 } 2207#endif 2208 } 2209 2210 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); 2211 glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords")); 2212 2213 drawTextDecorations(text, bytesCount, length, oldX, oldY, paint); 2214} 2215 2216void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) { 2217 if (mSnapshot->isIgnored()) return; 2218 2219 glActiveTexture(gTextureUnits[0]); 2220 2221 const PathTexture* texture = mCaches.pathCache.get(path, paint); 2222 if (!texture) return; 2223 const AutoTexture autoCleanup(texture); 2224 2225 const float x = texture->left - texture->offset; 2226 const float y = texture->top - texture->offset; 2227 2228 drawPathTexture(texture, x, y, paint); 2229} 2230 2231void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) { 2232 if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) { 2233 return; 2234 } 2235 2236 glActiveTexture(gTextureUnits[0]); 2237 2238 int alpha; 2239 SkXfermode::Mode mode; 2240 getAlphaAndMode(paint, &alpha, &mode); 2241 2242 layer->setAlpha(alpha, mode); 2243 2244#if RENDER_LAYERS_AS_REGIONS 2245 if (!layer->region.isEmpty()) { 2246 if (layer->region.isRect()) { 2247 composeLayerRect(layer, layer->regionRect); 2248 } else if (layer->mesh) { 2249 const float a = alpha / 255.0f; 2250 const Rect& rect = layer->layer; 2251 2252 setupDraw(); 2253 setupDrawWithTexture(); 2254 setupDrawColor(a, a, a, a); 2255 setupDrawColorFilter(); 2256 setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false); 2257 setupDrawProgram(); 2258 setupDrawPureColorUniforms(); 2259 setupDrawColorFilterUniforms(); 2260 setupDrawTexture(layer->getTexture()); 2261 if (mSnapshot->transform->isPureTranslate()) { 2262 x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f); 2263 y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f); 2264 2265 layer->setFilter(GL_NEAREST); 2266 setupDrawModelViewTranslate(x, y, 2267 x + layer->layer.getWidth(), y + layer->layer.getHeight(), true); 2268 } else { 2269 layer->setFilter(GL_LINEAR); 2270 setupDrawModelViewTranslate(x, y, 2271 x + layer->layer.getWidth(), y + layer->layer.getHeight()); 2272 } 2273 setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]); 2274 2275 glDrawElements(GL_TRIANGLES, layer->meshElementCount, 2276 GL_UNSIGNED_SHORT, layer->meshIndices); 2277 2278 finishDrawTexture(); 2279 2280#if DEBUG_LAYERS_AS_REGIONS 2281 drawRegionRects(layer->region); 2282#endif 2283 } 2284 } 2285#else 2286 const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight()); 2287 composeLayerRect(layer, r); 2288#endif 2289} 2290 2291/////////////////////////////////////////////////////////////////////////////// 2292// Shaders 2293/////////////////////////////////////////////////////////////////////////////// 2294 2295void OpenGLRenderer::resetShader() { 2296 mShader = NULL; 2297} 2298 2299void OpenGLRenderer::setupShader(SkiaShader* shader) { 2300 mShader = shader; 2301 if (mShader) { 2302 mShader->set(&mCaches.textureCache, &mCaches.gradientCache); 2303 } 2304} 2305 2306/////////////////////////////////////////////////////////////////////////////// 2307// Color filters 2308/////////////////////////////////////////////////////////////////////////////// 2309 2310void OpenGLRenderer::resetColorFilter() { 2311 mColorFilter = NULL; 2312} 2313 2314void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) { 2315 mColorFilter = filter; 2316} 2317 2318/////////////////////////////////////////////////////////////////////////////// 2319// Drop shadow 2320/////////////////////////////////////////////////////////////////////////////// 2321 2322void OpenGLRenderer::resetShadow() { 2323 mHasShadow = false; 2324} 2325 2326void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) { 2327 mHasShadow = true; 2328 mShadowRadius = radius; 2329 mShadowDx = dx; 2330 mShadowDy = dy; 2331 mShadowColor = color; 2332} 2333 2334/////////////////////////////////////////////////////////////////////////////// 2335// Drawing implementation 2336/////////////////////////////////////////////////////////////////////////////// 2337 2338void OpenGLRenderer::drawPathTexture(const PathTexture* texture, 2339 float x, float y, SkPaint* paint) { 2340 if (quickReject(x, y, x + texture->width, y + texture->height)) { 2341 return; 2342 } 2343 2344 int alpha; 2345 SkXfermode::Mode mode; 2346 getAlphaAndMode(paint, &alpha, &mode); 2347 2348 setupDraw(); 2349 setupDrawWithTexture(true); 2350 setupDrawAlpha8Color(paint->getColor(), alpha); 2351 setupDrawColorFilter(); 2352 setupDrawShader(); 2353 setupDrawBlending(true, mode); 2354 setupDrawProgram(); 2355 setupDrawModelView(x, y, x + texture->width, y + texture->height); 2356 setupDrawTexture(texture->id); 2357 setupDrawPureColorUniforms(); 2358 setupDrawColorFilterUniforms(); 2359 setupDrawShaderUniforms(); 2360 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 2361 2362 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 2363 2364 finishDrawTexture(); 2365} 2366 2367// Same values used by Skia 2368#define kStdStrikeThru_Offset (-6.0f / 21.0f) 2369#define kStdUnderline_Offset (1.0f / 9.0f) 2370#define kStdUnderline_Thickness (1.0f / 18.0f) 2371 2372void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length, 2373 float x, float y, SkPaint* paint) { 2374 // Handle underline and strike-through 2375 uint32_t flags = paint->getFlags(); 2376 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) { 2377 SkPaint paintCopy(*paint); 2378 float underlineWidth = length; 2379 // If length is > 0.0f, we already measured the text for the text alignment 2380 if (length <= 0.0f) { 2381 underlineWidth = paintCopy.measureText(text, bytesCount); 2382 } 2383 2384 float offsetX = 0; 2385 switch (paintCopy.getTextAlign()) { 2386 case SkPaint::kCenter_Align: 2387 offsetX = underlineWidth * 0.5f; 2388 break; 2389 case SkPaint::kRight_Align: 2390 offsetX = underlineWidth; 2391 break; 2392 default: 2393 break; 2394 } 2395 2396 if (underlineWidth > 0.0f) { 2397 const float textSize = paintCopy.getTextSize(); 2398 const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f); 2399 2400 const float left = x - offsetX; 2401 float top = 0.0f; 2402 2403 int linesCount = 0; 2404 if (flags & SkPaint::kUnderlineText_Flag) linesCount++; 2405 if (flags & SkPaint::kStrikeThruText_Flag) linesCount++; 2406 2407 const int pointsCount = 4 * linesCount; 2408 float points[pointsCount]; 2409 int currentPoint = 0; 2410 2411 if (flags & SkPaint::kUnderlineText_Flag) { 2412 top = y + textSize * kStdUnderline_Offset; 2413 points[currentPoint++] = left; 2414 points[currentPoint++] = top; 2415 points[currentPoint++] = left + underlineWidth; 2416 points[currentPoint++] = top; 2417 } 2418 2419 if (flags & SkPaint::kStrikeThruText_Flag) { 2420 top = y + textSize * kStdStrikeThru_Offset; 2421 points[currentPoint++] = left; 2422 points[currentPoint++] = top; 2423 points[currentPoint++] = left + underlineWidth; 2424 points[currentPoint++] = top; 2425 } 2426 2427 paintCopy.setStrokeWidth(strokeWidth); 2428 2429 drawLines(&points[0], pointsCount, &paintCopy); 2430 } 2431 } 2432} 2433 2434void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 2435 int color, SkXfermode::Mode mode, bool ignoreTransform) { 2436 // If a shader is set, preserve only the alpha 2437 if (mShader) { 2438 color |= 0x00ffffff; 2439 } 2440 2441 setupDraw(); 2442 setupDrawColor(color); 2443 setupDrawShader(); 2444 setupDrawColorFilter(); 2445 setupDrawBlending(mode); 2446 setupDrawProgram(); 2447 setupDrawModelView(left, top, right, bottom, ignoreTransform); 2448 setupDrawColorUniforms(); 2449 setupDrawShaderUniforms(ignoreTransform); 2450 setupDrawColorFilterUniforms(); 2451 setupDrawSimpleMesh(); 2452 2453 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 2454} 2455 2456void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 2457 Texture* texture, SkPaint* paint) { 2458 int alpha; 2459 SkXfermode::Mode mode; 2460 getAlphaAndMode(paint, &alpha, &mode); 2461 2462 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2463 2464 if (mSnapshot->transform->isPureTranslate()) { 2465 const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f); 2466 const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f); 2467 2468 texture->setFilter(GL_NEAREST, true); 2469 drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 2470 alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL, 2471 (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true); 2472 } else { 2473 texture->setFilter(FILTER(paint), true); 2474 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, 2475 texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, 2476 GL_TRIANGLE_STRIP, gMeshCount); 2477 } 2478} 2479 2480void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 2481 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) { 2482 drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend, 2483 (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount); 2484} 2485 2486void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom, 2487 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend, 2488 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 2489 bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) { 2490 2491 setupDraw(); 2492 setupDrawWithTexture(); 2493 setupDrawColor(alpha, alpha, alpha, alpha); 2494 setupDrawColorFilter(); 2495 setupDrawBlending(blend, mode, swapSrcDst); 2496 setupDrawProgram(); 2497 if (!dirty) { 2498 setupDrawDirtyRegionsDisabled(); 2499 } 2500 if (!ignoreScale) { 2501 setupDrawModelView(left, top, right, bottom, ignoreTransform); 2502 } else { 2503 setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform); 2504 } 2505 setupDrawPureColorUniforms(); 2506 setupDrawColorFilterUniforms(); 2507 setupDrawTexture(texture); 2508 setupDrawMesh(vertices, texCoords, vbo); 2509 2510 glDrawArrays(drawMode, 0, elementsCount); 2511 2512 finishDrawTexture(); 2513} 2514 2515void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, 2516 ProgramDescription& description, bool swapSrcDst) { 2517 blend = blend || mode != SkXfermode::kSrcOver_Mode; 2518 if (blend) { 2519 if (mode <= SkXfermode::kScreen_Mode) { 2520 if (!mCaches.blend) { 2521 glEnable(GL_BLEND); 2522 } 2523 2524 GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src; 2525 GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst; 2526 2527 if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) { 2528 glBlendFunc(sourceMode, destMode); 2529 mCaches.lastSrcMode = sourceMode; 2530 mCaches.lastDstMode = destMode; 2531 } 2532 } else { 2533 // These blend modes are not supported by OpenGL directly and have 2534 // to be implemented using shaders. Since the shader will perform 2535 // the blending, turn blending off here 2536 if (mCaches.extensions.hasFramebufferFetch()) { 2537 description.framebufferMode = mode; 2538 description.swapSrcDst = swapSrcDst; 2539 } 2540 2541 if (mCaches.blend) { 2542 glDisable(GL_BLEND); 2543 } 2544 blend = false; 2545 } 2546 } else if (mCaches.blend) { 2547 glDisable(GL_BLEND); 2548 } 2549 mCaches.blend = blend; 2550} 2551 2552bool OpenGLRenderer::useProgram(Program* program) { 2553 if (!program->isInUse()) { 2554 if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove(); 2555 program->use(); 2556 mCaches.currentProgram = program; 2557 return false; 2558 } 2559 return true; 2560} 2561 2562void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) { 2563 TextureVertex* v = &mMeshVertices[0]; 2564 TextureVertex::setUV(v++, u1, v1); 2565 TextureVertex::setUV(v++, u2, v1); 2566 TextureVertex::setUV(v++, u1, v2); 2567 TextureVertex::setUV(v++, u2, v2); 2568} 2569 2570void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) { 2571 if (paint) { 2572 *mode = getXfermode(paint->getXfermode()); 2573 2574 // Skia draws using the color's alpha channel if < 255 2575 // Otherwise, it uses the paint's alpha 2576 int color = paint->getColor(); 2577 *alpha = (color >> 24) & 0xFF; 2578 if (*alpha == 255) { 2579 *alpha = paint->getAlpha(); 2580 } 2581 } else { 2582 *mode = SkXfermode::kSrcOver_Mode; 2583 *alpha = 255; 2584 } 2585} 2586 2587SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) { 2588 SkXfermode::Mode resultMode; 2589 if (!SkXfermode::AsMode(mode, &resultMode)) { 2590 resultMode = SkXfermode::kSrcOver_Mode; 2591 } 2592 return resultMode; 2593} 2594 2595}; // namespace uirenderer 2596}; // namespace android 2597