OpenGLRenderer.cpp revision deeda3d337aed1eee218b89a7aba5992ced371f0
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 "DeferredDisplayList.h" 35#include "DisplayListRenderer.h" 36#include "Fence.h" 37#include "PathTessellator.h" 38#include "Properties.h" 39#include "ShadowTessellator.h" 40#include "utils/GLUtils.h" 41#include "Vector.h" 42#include "VertexBuffer.h" 43 44namespace android { 45namespace uirenderer { 46 47/////////////////////////////////////////////////////////////////////////////// 48// Defines 49/////////////////////////////////////////////////////////////////////////////// 50 51#define RAD_TO_DEG (180.0f / 3.14159265f) 52#define MIN_ANGLE 0.001f 53 54#define ALPHA_THRESHOLD 0 55 56static GLenum getFilter(const SkPaint* paint) { 57 if (!paint || paint->getFilterLevel() != SkPaint::kNone_FilterLevel) { 58 return GL_LINEAR; 59 } 60 return GL_NEAREST; 61} 62 63/////////////////////////////////////////////////////////////////////////////// 64// Globals 65/////////////////////////////////////////////////////////////////////////////// 66 67/** 68 * Structure mapping Skia xfermodes to OpenGL blending factors. 69 */ 70struct Blender { 71 SkXfermode::Mode mode; 72 GLenum src; 73 GLenum dst; 74}; // struct Blender 75 76// In this array, the index of each Blender equals the value of the first 77// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode] 78static const Blender gBlends[] = { 79 { SkXfermode::kClear_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 80 { SkXfermode::kSrc_Mode, GL_ONE, GL_ZERO }, 81 { SkXfermode::kDst_Mode, GL_ZERO, GL_ONE }, 82 { SkXfermode::kSrcOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA }, 83 { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE }, 84 { SkXfermode::kSrcIn_Mode, GL_DST_ALPHA, GL_ZERO }, 85 { SkXfermode::kDstIn_Mode, GL_ZERO, GL_SRC_ALPHA }, 86 { SkXfermode::kSrcOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 87 { SkXfermode::kDstOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 88 { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 89 { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA }, 90 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 91 { SkXfermode::kPlus_Mode, GL_ONE, GL_ONE }, 92 { SkXfermode::kModulate_Mode, GL_ZERO, GL_SRC_COLOR }, 93 { SkXfermode::kScreen_Mode, GL_ONE, GL_ONE_MINUS_SRC_COLOR } 94}; 95 96// This array contains the swapped version of each SkXfermode. For instance 97// this array's SrcOver blending mode is actually DstOver. You can refer to 98// createLayer() for more information on the purpose of this array. 99static const Blender gBlendsSwap[] = { 100 { SkXfermode::kClear_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 101 { SkXfermode::kSrc_Mode, GL_ZERO, GL_ONE }, 102 { SkXfermode::kDst_Mode, GL_ONE, GL_ZERO }, 103 { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE }, 104 { SkXfermode::kDstOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA }, 105 { SkXfermode::kSrcIn_Mode, GL_ZERO, GL_SRC_ALPHA }, 106 { SkXfermode::kDstIn_Mode, GL_DST_ALPHA, GL_ZERO }, 107 { SkXfermode::kSrcOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 108 { SkXfermode::kDstOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 109 { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA }, 110 { SkXfermode::kDstATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 111 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 112 { SkXfermode::kPlus_Mode, GL_ONE, GL_ONE }, 113 { SkXfermode::kModulate_Mode, GL_DST_COLOR, GL_ZERO }, 114 { SkXfermode::kScreen_Mode, GL_ONE_MINUS_DST_COLOR, GL_ONE } 115}; 116 117/////////////////////////////////////////////////////////////////////////////// 118// Functions 119/////////////////////////////////////////////////////////////////////////////// 120 121template<typename T> 122static inline T min(T a, T b) { 123 return a < b ? a : b; 124} 125 126/////////////////////////////////////////////////////////////////////////////// 127// Constructors/destructor 128/////////////////////////////////////////////////////////////////////////////// 129 130OpenGLRenderer::OpenGLRenderer(): 131 mCaches(Caches::getInstance()), mExtensions(Extensions::getInstance()) { 132 // *set* draw modifiers to be 0 133 memset(&mDrawModifiers, 0, sizeof(mDrawModifiers)); 134 mDrawModifiers.mOverrideLayerAlpha = 1.0f; 135 136 memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices)); 137 138 mFrameStarted = false; 139 mCountOverdraw = false; 140 141 mScissorOptimizationDisabled = false; 142} 143 144OpenGLRenderer::~OpenGLRenderer() { 145 // The context has already been destroyed at this point, do not call 146 // GL APIs. All GL state should be kept in Caches.h 147} 148 149void OpenGLRenderer::initProperties() { 150 char property[PROPERTY_VALUE_MAX]; 151 if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) { 152 mScissorOptimizationDisabled = !strcasecmp(property, "true"); 153 INIT_LOGD(" Scissor optimization %s", 154 mScissorOptimizationDisabled ? "disabled" : "enabled"); 155 } else { 156 INIT_LOGD(" Scissor optimization enabled"); 157 } 158} 159 160/////////////////////////////////////////////////////////////////////////////// 161// Setup 162/////////////////////////////////////////////////////////////////////////////// 163 164void OpenGLRenderer::setViewport(int width, int height) { 165 initializeViewport(width, height); 166 167 glDisable(GL_DITHER); 168 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 169 170 glEnableVertexAttribArray(Program::kBindingPosition); 171} 172 173void OpenGLRenderer::setupFrameState(float left, float top, 174 float right, float bottom, bool opaque) { 175 mCaches.clearGarbage(); 176 177 initializeSaveStack(left, top, right, bottom); 178 mOpaque = opaque; 179 mTilingClip.set(left, top, right, bottom); 180} 181 182status_t OpenGLRenderer::startFrame() { 183 if (mFrameStarted) return DrawGlInfo::kStatusDone; 184 mFrameStarted = true; 185 186 mDirtyClip = true; 187 188 discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom); 189 190 glViewport(0, 0, getWidth(), getHeight()); 191 192 // Functors break the tiling extension in pretty spectacular ways 193 // This ensures we don't use tiling when a functor is going to be 194 // invoked during the frame 195 mSuppressTiling = mCaches.hasRegisteredFunctors(); 196 197 startTilingCurrentClip(true); 198 199 debugOverdraw(true, true); 200 201 return clear(mTilingClip.left, mTilingClip.top, 202 mTilingClip.right, mTilingClip.bottom, mOpaque); 203} 204 205status_t OpenGLRenderer::prepareDirty(float left, float top, 206 float right, float bottom, bool opaque) { 207 208 setupFrameState(left, top, right, bottom, opaque); 209 210 // Layer renderers will start the frame immediately 211 // The framebuffer renderer will first defer the display list 212 // for each layer and wait until the first drawing command 213 // to start the frame 214 if (currentSnapshot()->fbo == 0) { 215 syncState(); 216 updateLayers(); 217 } else { 218 return startFrame(); 219 } 220 221 return DrawGlInfo::kStatusDone; 222} 223 224void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) { 225 // If we know that we are going to redraw the entire framebuffer, 226 // perform a discard to let the driver know we don't need to preserve 227 // the back buffer for this frame. 228 if (mExtensions.hasDiscardFramebuffer() && 229 left <= 0.0f && top <= 0.0f && right >= getWidth() && bottom >= getHeight()) { 230 const bool isFbo = getTargetFbo() == 0; 231 const GLenum attachments[] = { 232 isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0, 233 isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT }; 234 glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments); 235 } 236} 237 238status_t OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) { 239 if (!opaque || mCountOverdraw) { 240 mCaches.enableScissor(); 241 mCaches.setScissor(left, getViewportHeight() - bottom, right - left, bottom - top); 242 glClear(GL_COLOR_BUFFER_BIT); 243 return DrawGlInfo::kStatusDrew; 244 } 245 246 mCaches.resetScissor(); 247 return DrawGlInfo::kStatusDone; 248} 249 250void OpenGLRenderer::syncState() { 251 if (mCaches.blend) { 252 glEnable(GL_BLEND); 253 } else { 254 glDisable(GL_BLEND); 255 } 256} 257 258void OpenGLRenderer::startTilingCurrentClip(bool opaque) { 259 if (!mSuppressTiling) { 260 const Snapshot* snapshot = currentSnapshot(); 261 262 const Rect* clip = &mTilingClip; 263 if (snapshot->flags & Snapshot::kFlagFboTarget) { 264 clip = &(snapshot->layer->clipRect); 265 } 266 267 startTiling(*clip, getViewportHeight(), opaque); 268 } 269} 270 271void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque) { 272 if (!mSuppressTiling) { 273 mCaches.startTiling(clip.left, windowHeight - clip.bottom, 274 clip.right - clip.left, clip.bottom - clip.top, opaque); 275 } 276} 277 278void OpenGLRenderer::endTiling() { 279 if (!mSuppressTiling) mCaches.endTiling(); 280} 281 282void OpenGLRenderer::finish() { 283 renderOverdraw(); 284 endTiling(); 285 286 // When finish() is invoked on FBO 0 we've reached the end 287 // of the current frame 288 if (getTargetFbo() == 0) { 289 mCaches.pathCache.trim(); 290 } 291 292 if (!suppressErrorChecks()) { 293#if DEBUG_OPENGL 294 GLUtils::dumpGLErrors(); 295#endif 296 297#if DEBUG_MEMORY_USAGE 298 mCaches.dumpMemoryUsage(); 299#else 300 if (mCaches.getDebugLevel() & kDebugMemory) { 301 mCaches.dumpMemoryUsage(); 302 } 303#endif 304 } 305 306 if (mCountOverdraw) { 307 countOverdraw(); 308 } 309 310 mFrameStarted = false; 311} 312 313void OpenGLRenderer::interrupt() { 314 if (mCaches.currentProgram) { 315 if (mCaches.currentProgram->isInUse()) { 316 mCaches.currentProgram->remove(); 317 mCaches.currentProgram = NULL; 318 } 319 } 320 mCaches.resetActiveTexture(); 321 mCaches.unbindMeshBuffer(); 322 mCaches.unbindIndicesBuffer(); 323 mCaches.resetVertexPointers(); 324 mCaches.disableTexCoordsVertexArray(); 325 debugOverdraw(false, false); 326} 327 328void OpenGLRenderer::resume() { 329 const Snapshot* snapshot = currentSnapshot(); 330 glViewport(0, 0, getViewportWidth(), getViewportHeight()); 331 glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo); 332 debugOverdraw(true, false); 333 334 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 335 336 mCaches.scissorEnabled = glIsEnabled(GL_SCISSOR_TEST); 337 mCaches.enableScissor(); 338 mCaches.resetScissor(); 339 dirtyClip(); 340 341 mCaches.activeTexture(0); 342 mCaches.resetBoundTextures(); 343 344 mCaches.blend = true; 345 glEnable(GL_BLEND); 346 glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode); 347 glBlendEquation(GL_FUNC_ADD); 348} 349 350void OpenGLRenderer::resumeAfterLayer() { 351 glViewport(0, 0, getViewportWidth(), getViewportHeight()); 352 glBindFramebuffer(GL_FRAMEBUFFER, currentSnapshot()->fbo); 353 debugOverdraw(true, false); 354 355 mCaches.resetScissor(); 356 dirtyClip(); 357} 358 359status_t OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) { 360 if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone; 361 362 Rect clip(*currentClipRect()); 363 clip.snapToPixelBoundaries(); 364 365 // Since we don't know what the functor will draw, let's dirty 366 // the entire clip region 367 if (hasLayer()) { 368 dirtyLayerUnchecked(clip, getRegion()); 369 } 370 371 DrawGlInfo info; 372 info.clipLeft = clip.left; 373 info.clipTop = clip.top; 374 info.clipRight = clip.right; 375 info.clipBottom = clip.bottom; 376 info.isLayer = hasLayer(); 377 info.width = getViewportWidth(); 378 info.height = getViewportHeight(); 379 currentTransform()->copyTo(&info.transform[0]); 380 381 bool dirtyClip = mDirtyClip; 382 // setup GL state for functor 383 if (mDirtyClip) { 384 setStencilFromClip(); // can issue draws, so must precede enableScissor()/interrupt() 385 } 386 if (mCaches.enableScissor() || dirtyClip) { 387 setScissorFromClip(); 388 } 389 interrupt(); 390 391 // call functor immediately after GL state setup 392 (*functor)(DrawGlInfo::kModeDraw, &info); 393 394 resume(); 395 return DrawGlInfo::kStatusDrew; 396} 397 398/////////////////////////////////////////////////////////////////////////////// 399// Debug 400/////////////////////////////////////////////////////////////////////////////// 401 402void OpenGLRenderer::eventMark(const char* name) const { 403 mCaches.eventMark(0, name); 404} 405 406void OpenGLRenderer::startMark(const char* name) const { 407 mCaches.startMark(0, name); 408} 409 410void OpenGLRenderer::endMark() const { 411 mCaches.endMark(); 412} 413 414void OpenGLRenderer::debugOverdraw(bool enable, bool clear) { 415 if (mCaches.debugOverdraw && getTargetFbo() == 0) { 416 if (clear) { 417 mCaches.disableScissor(); 418 mCaches.stencil.clear(); 419 } 420 if (enable) { 421 mCaches.stencil.enableDebugWrite(); 422 } else { 423 mCaches.stencil.disable(); 424 } 425 } 426} 427 428void OpenGLRenderer::renderOverdraw() { 429 if (mCaches.debugOverdraw && getTargetFbo() == 0) { 430 const Rect* clip = &mTilingClip; 431 432 mCaches.enableScissor(); 433 mCaches.setScissor(clip->left, firstSnapshot()->getViewportHeight() - clip->bottom, 434 clip->right - clip->left, clip->bottom - clip->top); 435 436 // 1x overdraw 437 mCaches.stencil.enableDebugTest(2); 438 drawColor(mCaches.getOverdrawColor(1), SkXfermode::kSrcOver_Mode); 439 440 // 2x overdraw 441 mCaches.stencil.enableDebugTest(3); 442 drawColor(mCaches.getOverdrawColor(2), SkXfermode::kSrcOver_Mode); 443 444 // 3x overdraw 445 mCaches.stencil.enableDebugTest(4); 446 drawColor(mCaches.getOverdrawColor(3), SkXfermode::kSrcOver_Mode); 447 448 // 4x overdraw and higher 449 mCaches.stencil.enableDebugTest(4, true); 450 drawColor(mCaches.getOverdrawColor(4), SkXfermode::kSrcOver_Mode); 451 452 mCaches.stencil.disable(); 453 } 454} 455 456void OpenGLRenderer::countOverdraw() { 457 size_t count = getWidth() * getHeight(); 458 uint32_t* buffer = new uint32_t[count]; 459 glReadPixels(0, 0, getWidth(), getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, &buffer[0]); 460 461 size_t total = 0; 462 for (size_t i = 0; i < count; i++) { 463 total += buffer[i] & 0xff; 464 } 465 466 mOverdraw = total / float(count); 467 468 delete[] buffer; 469} 470 471/////////////////////////////////////////////////////////////////////////////// 472// Layers 473/////////////////////////////////////////////////////////////////////////////// 474 475bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) { 476 if (layer->deferredUpdateScheduled && layer->renderer && 477 layer->displayList.get() && layer->displayList->isRenderable()) { 478 ATRACE_CALL(); 479 480 Rect& dirty = layer->dirtyRect; 481 482 if (inFrame) { 483 endTiling(); 484 debugOverdraw(false, false); 485 } 486 487 if (CC_UNLIKELY(inFrame || mCaches.drawDeferDisabled)) { 488 layer->render(); 489 } else { 490 layer->defer(); 491 } 492 493 if (inFrame) { 494 resumeAfterLayer(); 495 startTilingCurrentClip(); 496 } 497 498 layer->debugDrawUpdate = mCaches.debugLayersUpdates; 499 layer->hasDrawnSinceUpdate = false; 500 501 return true; 502 } 503 504 return false; 505} 506 507void OpenGLRenderer::updateLayers() { 508 // If draw deferring is enabled this method will simply defer 509 // the display list of each individual layer. The layers remain 510 // in the layer updates list which will be cleared by flushLayers(). 511 int count = mLayerUpdates.size(); 512 if (count > 0) { 513 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 514 startMark("Layer Updates"); 515 } else { 516 startMark("Defer Layer Updates"); 517 } 518 519 // Note: it is very important to update the layers in order 520 for (int i = 0; i < count; i++) { 521 Layer* layer = mLayerUpdates.itemAt(i); 522 updateLayer(layer, false); 523 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 524 mCaches.resourceCache.decrementRefcount(layer); 525 } 526 } 527 528 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 529 mLayerUpdates.clear(); 530 glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo()); 531 } 532 endMark(); 533 } 534} 535 536void OpenGLRenderer::flushLayers() { 537 int count = mLayerUpdates.size(); 538 if (count > 0) { 539 startMark("Apply Layer Updates"); 540 char layerName[12]; 541 542 // Note: it is very important to update the layers in order 543 for (int i = 0; i < count; i++) { 544 sprintf(layerName, "Layer #%d", i); 545 startMark(layerName); 546 547 ATRACE_BEGIN("flushLayer"); 548 Layer* layer = mLayerUpdates.itemAt(i); 549 layer->flush(); 550 ATRACE_END(); 551 552 mCaches.resourceCache.decrementRefcount(layer); 553 554 endMark(); 555 } 556 557 mLayerUpdates.clear(); 558 glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo()); 559 560 endMark(); 561 } 562} 563 564void OpenGLRenderer::pushLayerUpdate(Layer* layer) { 565 if (layer) { 566 // Make sure we don't introduce duplicates. 567 // SortedVector would do this automatically but we need to respect 568 // the insertion order. The linear search is not an issue since 569 // this list is usually very short (typically one item, at most a few) 570 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) { 571 if (mLayerUpdates.itemAt(i) == layer) { 572 return; 573 } 574 } 575 mLayerUpdates.push_back(layer); 576 mCaches.resourceCache.incrementRefcount(layer); 577 } 578} 579 580void OpenGLRenderer::cancelLayerUpdate(Layer* layer) { 581 if (layer) { 582 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) { 583 if (mLayerUpdates.itemAt(i) == layer) { 584 mLayerUpdates.removeAt(i); 585 mCaches.resourceCache.decrementRefcount(layer); 586 break; 587 } 588 } 589 } 590} 591 592void OpenGLRenderer::clearLayerUpdates() { 593 size_t count = mLayerUpdates.size(); 594 if (count > 0) { 595 mCaches.resourceCache.lock(); 596 for (size_t i = 0; i < count; i++) { 597 mCaches.resourceCache.decrementRefcountLocked(mLayerUpdates.itemAt(i)); 598 } 599 mCaches.resourceCache.unlock(); 600 mLayerUpdates.clear(); 601 } 602} 603 604void OpenGLRenderer::flushLayerUpdates() { 605 syncState(); 606 updateLayers(); 607 flushLayers(); 608 // Wait for all the layer updates to be executed 609 AutoFence fence; 610} 611 612/////////////////////////////////////////////////////////////////////////////// 613// State management 614/////////////////////////////////////////////////////////////////////////////// 615 616void OpenGLRenderer::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) { 617 bool restoreViewport = removed.flags & Snapshot::kFlagIsFboLayer; 618 bool restoreClip = removed.flags & Snapshot::kFlagClipSet; 619 bool restoreLayer = removed.flags & Snapshot::kFlagIsLayer; 620 621 if (restoreViewport) { 622 glViewport(0, 0, getViewportWidth(), getViewportHeight()); 623 } 624 625 if (restoreClip) { 626 dirtyClip(); 627 } 628 629 if (restoreLayer) { 630 endMark(); // Savelayer 631 startMark("ComposeLayer"); 632 composeLayer(removed, restored); 633 endMark(); 634 } 635} 636 637/////////////////////////////////////////////////////////////////////////////// 638// Layers 639/////////////////////////////////////////////////////////////////////////////// 640 641int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom, 642 const SkPaint* paint, int flags, const SkPath* convexMask) { 643 const int count = saveSnapshot(flags); 644 645 if (!currentSnapshot()->isIgnored()) { 646 createLayer(left, top, right, bottom, paint, flags, convexMask); 647 } 648 649 return count; 650} 651 652void OpenGLRenderer::calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer) { 653 const Rect untransformedBounds(bounds); 654 655 currentTransform()->mapRect(bounds); 656 657 // Layers only make sense if they are in the framebuffer's bounds 658 if (bounds.intersect(*currentClipRect())) { 659 // We cannot work with sub-pixels in this case 660 bounds.snapToPixelBoundaries(); 661 662 // When the layer is not an FBO, we may use glCopyTexImage so we 663 // need to make sure the layer does not extend outside the bounds 664 // of the framebuffer 665 if (!bounds.intersect(Rect(0, 0, getViewportWidth(), getViewportHeight()))) { 666 bounds.setEmpty(); 667 } else if (fboLayer) { 668 clip.set(bounds); 669 mat4 inverse; 670 inverse.loadInverse(*currentTransform()); 671 inverse.mapRect(clip); 672 clip.snapToPixelBoundaries(); 673 if (clip.intersect(untransformedBounds)) { 674 clip.translate(-untransformedBounds.left, -untransformedBounds.top); 675 bounds.set(untransformedBounds); 676 } else { 677 clip.setEmpty(); 678 } 679 } 680 } else { 681 bounds.setEmpty(); 682 } 683} 684 685void OpenGLRenderer::updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip, 686 bool fboLayer, int alpha) { 687 if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize || 688 bounds.getHeight() > mCaches.maxTextureSize || 689 (fboLayer && clip.isEmpty())) { 690 mSnapshot->empty = fboLayer; 691 } else { 692 mSnapshot->invisible = mSnapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer); 693 } 694} 695 696int OpenGLRenderer::saveLayerDeferred(float left, float top, float right, float bottom, 697 const SkPaint* paint, int flags) { 698 const int count = saveSnapshot(flags); 699 700 if (!currentSnapshot()->isIgnored() && (flags & SkCanvas::kClipToLayer_SaveFlag)) { 701 // initialize the snapshot as though it almost represents an FBO layer so deferred draw 702 // operations will be able to store and restore the current clip and transform info, and 703 // quick rejection will be correct (for display lists) 704 705 Rect bounds(left, top, right, bottom); 706 Rect clip; 707 calculateLayerBoundsAndClip(bounds, clip, true); 708 updateSnapshotIgnoreForLayer(bounds, clip, true, getAlphaDirect(paint)); 709 710 if (!currentSnapshot()->isIgnored()) { 711 mSnapshot->resetTransform(-bounds.left, -bounds.top, 0.0f); 712 mSnapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom); 713 mSnapshot->initializeViewport(bounds.getWidth(), bounds.getHeight()); 714 mSnapshot->roundRectClipState = NULL; 715 } 716 } 717 718 return count; 719} 720 721/** 722 * Layers are viewed by Skia are slightly different than layers in image editing 723 * programs (for instance.) When a layer is created, previously created layers 724 * and the frame buffer still receive every drawing command. For instance, if a 725 * layer is created and a shape intersecting the bounds of the layers and the 726 * framebuffer is draw, the shape will be drawn on both (unless the layer was 727 * created with the SkCanvas::kClipToLayer_SaveFlag flag.) 728 * 729 * A way to implement layers is to create an FBO for each layer, backed by an RGBA 730 * texture. Unfortunately, this is inefficient as it requires every primitive to 731 * be drawn n + 1 times, where n is the number of active layers. In practice this 732 * means, for every primitive: 733 * - Switch active frame buffer 734 * - Change viewport, clip and projection matrix 735 * - Issue the drawing 736 * 737 * Switching rendering target n + 1 times per drawn primitive is extremely costly. 738 * To avoid this, layers are implemented in a different way here, at least in the 739 * general case. FBOs are used, as an optimization, when the "clip to layer" flag 740 * is set. When this flag is set we can redirect all drawing operations into a 741 * single FBO. 742 * 743 * This implementation relies on the frame buffer being at least RGBA 8888. When 744 * a layer is created, only a texture is created, not an FBO. The content of the 745 * frame buffer contained within the layer's bounds is copied into this texture 746 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame 747 * buffer and drawing continues as normal. This technique therefore treats the 748 * frame buffer as a scratch buffer for the layers. 749 * 750 * To compose the layers back onto the frame buffer, each layer texture 751 * (containing the original frame buffer data) is drawn as a simple quad over 752 * the frame buffer. The trick is that the quad is set as the composition 753 * destination in the blending equation, and the frame buffer becomes the source 754 * of the composition. 755 * 756 * Drawing layers with an alpha value requires an extra step before composition. 757 * An empty quad is drawn over the layer's region in the frame buffer. This quad 758 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the 759 * quad is used to multiply the colors in the frame buffer. This is achieved by 760 * changing the GL blend functions for the GL_FUNC_ADD blend equation to 761 * GL_ZERO, GL_SRC_ALPHA. 762 * 763 * Because glCopyTexImage2D() can be slow, an alternative implementation might 764 * be use to draw a single clipped layer. The implementation described above 765 * is correct in every case. 766 * 767 * (1) The frame buffer is actually not cleared right away. To allow the GPU 768 * to potentially optimize series of calls to glCopyTexImage2D, the frame 769 * buffer is left untouched until the first drawing operation. Only when 770 * something actually gets drawn are the layers regions cleared. 771 */ 772bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom, 773 const SkPaint* paint, int flags, const SkPath* convexMask) { 774 LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top); 775 LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize()); 776 777 const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag; 778 779 // Window coordinates of the layer 780 Rect clip; 781 Rect bounds(left, top, right, bottom); 782 calculateLayerBoundsAndClip(bounds, clip, fboLayer); 783 updateSnapshotIgnoreForLayer(bounds, clip, fboLayer, getAlphaDirect(paint)); 784 785 // Bail out if we won't draw in this snapshot 786 if (currentSnapshot()->isIgnored()) { 787 return false; 788 } 789 790 mCaches.activeTexture(0); 791 Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight()); 792 if (!layer) { 793 return false; 794 } 795 796 layer->setPaint(paint); 797 layer->layer.set(bounds); 798 layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()), 799 bounds.getWidth() / float(layer->getWidth()), 0.0f); 800 801 layer->setBlend(true); 802 layer->setDirty(false); 803 layer->setConvexMask(convexMask); // note: the mask must be cleared before returning to the cache 804 805 // Save the layer in the snapshot 806 mSnapshot->flags |= Snapshot::kFlagIsLayer; 807 mSnapshot->layer = layer; 808 809 startMark("SaveLayer"); 810 if (fboLayer) { 811 return createFboLayer(layer, bounds, clip); 812 } else { 813 // Copy the framebuffer into the layer 814 layer->bindTexture(); 815 if (!bounds.isEmpty()) { 816 if (layer->isEmpty()) { 817 // Workaround for some GL drivers. When reading pixels lying outside 818 // of the window we should get undefined values for those pixels. 819 // Unfortunately some drivers will turn the entire target texture black 820 // when reading outside of the window. 821 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->getWidth(), layer->getHeight(), 822 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); 823 layer->setEmpty(false); 824 } 825 826 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 827 bounds.left, getViewportHeight() - bounds.bottom, 828 bounds.getWidth(), bounds.getHeight()); 829 830 // Enqueue the buffer coordinates to clear the corresponding region later 831 mLayers.push(new Rect(bounds)); 832 } 833 } 834 835 return true; 836} 837 838bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip) { 839 layer->clipRect.set(clip); 840 layer->setFbo(mCaches.fboCache.get()); 841 842 mSnapshot->region = &mSnapshot->layer->region; 843 mSnapshot->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer; 844 mSnapshot->fbo = layer->getFbo(); 845 mSnapshot->resetTransform(-bounds.left, -bounds.top, 0.0f); 846 mSnapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom); 847 mSnapshot->initializeViewport(bounds.getWidth(), bounds.getHeight()); 848 mSnapshot->roundRectClipState = NULL; 849 850 endTiling(); 851 debugOverdraw(false, false); 852 // Bind texture to FBO 853 glBindFramebuffer(GL_FRAMEBUFFER, layer->getFbo()); 854 layer->bindTexture(); 855 856 // Initialize the texture if needed 857 if (layer->isEmpty()) { 858 layer->allocateTexture(); 859 layer->setEmpty(false); 860 } 861 862 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 863 layer->getTexture(), 0); 864 865 startTilingCurrentClip(true); 866 867 // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering 868 mCaches.enableScissor(); 869 mCaches.setScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f, 870 clip.getWidth() + 2.0f, clip.getHeight() + 2.0f); 871 glClear(GL_COLOR_BUFFER_BIT); 872 873 dirtyClip(); 874 875 // Change the ortho projection 876 glViewport(0, 0, bounds.getWidth(), bounds.getHeight()); 877 return true; 878} 879 880/** 881 * Read the documentation of createLayer() before doing anything in this method. 882 */ 883void OpenGLRenderer::composeLayer(const Snapshot& removed, const Snapshot& restored) { 884 if (!removed.layer) { 885 ALOGE("Attempting to compose a layer that does not exist"); 886 return; 887 } 888 889 Layer* layer = removed.layer; 890 const Rect& rect = layer->layer; 891 const bool fboLayer = removed.flags & Snapshot::kFlagIsFboLayer; 892 893 bool clipRequired = false; 894 calculateQuickRejectForScissor(rect.left, rect.top, rect.right, rect.bottom, 895 &clipRequired, NULL, false); // safely ignore return, should never be rejected 896 mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired); 897 898 if (fboLayer) { 899 endTiling(); 900 901 // Detach the texture from the FBO 902 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); 903 904 layer->removeFbo(false); 905 906 // Unbind current FBO and restore previous one 907 glBindFramebuffer(GL_FRAMEBUFFER, restored.fbo); 908 debugOverdraw(true, false); 909 910 startTilingCurrentClip(); 911 } 912 913 if (!fboLayer && layer->getAlpha() < 255) { 914 SkPaint layerPaint; 915 layerPaint.setAlpha(layer->getAlpha()); 916 layerPaint.setXfermodeMode(SkXfermode::kDstIn_Mode); 917 layerPaint.setColorFilter(layer->getColorFilter()); 918 919 drawColorRect(rect.left, rect.top, rect.right, rect.bottom, &layerPaint, true); 920 // Required below, composeLayerRect() will divide by 255 921 layer->setAlpha(255); 922 } 923 924 mCaches.unbindMeshBuffer(); 925 926 mCaches.activeTexture(0); 927 928 // When the layer is stored in an FBO, we can save a bit of fillrate by 929 // drawing only the dirty region 930 if (fboLayer) { 931 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *restored.transform); 932 composeLayerRegion(layer, rect); 933 } else if (!rect.isEmpty()) { 934 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom); 935 936 save(0); 937 // the layer contains screen buffer content that shouldn't be alpha modulated 938 // (and any necessary alpha modulation was handled drawing into the layer) 939 mSnapshot->alpha = 1.0f; 940 composeLayerRect(layer, rect, true); 941 restore(); 942 } 943 944 dirtyClip(); 945 946 // Failing to add the layer to the cache should happen only if the layer is too large 947 layer->setConvexMask(NULL); 948 if (!mCaches.layerCache.put(layer)) { 949 LAYER_LOGD("Deleting layer"); 950 Caches::getInstance().resourceCache.decrementRefcount(layer); 951 } 952} 953 954void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) { 955 float alpha = getLayerAlpha(layer); 956 957 setupDraw(); 958 if (layer->getRenderTarget() == GL_TEXTURE_2D) { 959 setupDrawWithTexture(); 960 } else { 961 setupDrawWithExternalTexture(); 962 } 963 setupDrawTextureTransform(); 964 setupDrawColor(alpha, alpha, alpha, alpha); 965 setupDrawColorFilter(layer->getColorFilter()); 966 setupDrawBlending(layer); 967 setupDrawProgram(); 968 setupDrawPureColorUniforms(); 969 setupDrawColorFilterUniforms(layer->getColorFilter()); 970 if (layer->getRenderTarget() == GL_TEXTURE_2D) { 971 setupDrawTexture(layer->getTexture()); 972 } else { 973 setupDrawExternalTexture(layer->getTexture()); 974 } 975 if (currentTransform()->isPureTranslate() && 976 !layer->getForceFilter() && 977 layer->getWidth() == (uint32_t) rect.getWidth() && 978 layer->getHeight() == (uint32_t) rect.getHeight()) { 979 const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f); 980 const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f); 981 982 layer->setFilter(GL_NEAREST); 983 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 984 x, y, x + rect.getWidth(), y + rect.getHeight(), true); 985 } else { 986 layer->setFilter(GL_LINEAR); 987 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 988 rect.left, rect.top, rect.right, rect.bottom); 989 } 990 setupDrawTextureTransformUniforms(layer->getTexTransform()); 991 setupDrawMesh(&mMeshVertices[0].x, &mMeshVertices[0].u); 992 993 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 994} 995 996void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) { 997 if (!layer->isTextureLayer()) { 998 const Rect& texCoords = layer->texCoords; 999 resetDrawTextureTexCoords(texCoords.left, texCoords.top, 1000 texCoords.right, texCoords.bottom); 1001 1002 float x = rect.left; 1003 float y = rect.top; 1004 bool simpleTransform = currentTransform()->isPureTranslate() && 1005 layer->getWidth() == (uint32_t) rect.getWidth() && 1006 layer->getHeight() == (uint32_t) rect.getHeight(); 1007 1008 if (simpleTransform) { 1009 // When we're swapping, the layer is already in screen coordinates 1010 if (!swap) { 1011 x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f); 1012 y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f); 1013 } 1014 1015 layer->setFilter(GL_NEAREST, true); 1016 } else { 1017 layer->setFilter(GL_LINEAR, true); 1018 } 1019 1020 SkPaint layerPaint; 1021 layerPaint.setAlpha(getLayerAlpha(layer) * 255); 1022 layerPaint.setXfermodeMode(layer->getMode()); 1023 layerPaint.setColorFilter(layer->getColorFilter()); 1024 1025 bool blend = layer->isBlend() || getLayerAlpha(layer) < 1.0f; 1026 drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(), 1027 layer->getTexture(), &layerPaint, blend, 1028 &mMeshVertices[0].x, &mMeshVertices[0].u, 1029 GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform); 1030 1031 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 1032 } else { 1033 resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f); 1034 drawTextureLayer(layer, rect); 1035 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 1036 } 1037} 1038 1039/** 1040 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated 1041 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw 1042 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used 1043 * by saveLayer's restore 1044 */ 1045#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) { \ 1046 DRAW_COMMAND; \ 1047 if (CC_UNLIKELY(mCaches.debugOverdraw && getTargetFbo() == 0 && COND)) { \ 1048 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); \ 1049 DRAW_COMMAND; \ 1050 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); \ 1051 } \ 1052 } 1053 1054#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND) 1055 1056void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) { 1057 if (CC_UNLIKELY(layer->region.isEmpty())) return; // nothing to draw 1058 1059 if (layer->getConvexMask()) { 1060 save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag); 1061 1062 // clip to the area of the layer the mask can be larger 1063 clipRect(rect.left, rect.top, rect.right, rect.bottom, SkRegion::kIntersect_Op); 1064 1065 SkPaint paint; 1066 paint.setAntiAlias(true); 1067 paint.setColor(SkColorSetARGB(int(getLayerAlpha(layer) * 255), 0, 0, 0)); 1068 1069 SkiaShader* oldShader = mDrawModifiers.mShader; 1070 1071 // create LayerShader to map SaveLayer content into subsequent draw 1072 SkMatrix shaderMatrix; 1073 shaderMatrix.setTranslate(rect.left, rect.bottom); 1074 shaderMatrix.preScale(1, -1); 1075 SkiaLayerShader layerShader(layer, &shaderMatrix); 1076 mDrawModifiers.mShader = &layerShader; 1077 1078 // Since the drawing primitive is defined in local drawing space, 1079 // we don't need to modify the draw matrix 1080 const SkPath* maskPath = layer->getConvexMask(); 1081 DRAW_DOUBLE_STENCIL(drawConvexPath(*maskPath, &paint)); 1082 1083 mDrawModifiers.mShader = oldShader; 1084 restore(); 1085 1086 return; 1087 } 1088 1089 if (layer->region.isRect()) { 1090 layer->setRegionAsRect(); 1091 1092 DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect)); 1093 1094 layer->region.clear(); 1095 return; 1096 } 1097 1098 // standard Region based draw 1099 size_t count; 1100 const android::Rect* rects; 1101 Region safeRegion; 1102 if (CC_LIKELY(hasRectToRectTransform())) { 1103 rects = layer->region.getArray(&count); 1104 } else { 1105 safeRegion = Region::createTJunctionFreeRegion(layer->region); 1106 rects = safeRegion.getArray(&count); 1107 } 1108 1109 const float alpha = getLayerAlpha(layer); 1110 const float texX = 1.0f / float(layer->getWidth()); 1111 const float texY = 1.0f / float(layer->getHeight()); 1112 const float height = rect.getHeight(); 1113 1114 setupDraw(); 1115 1116 // We must get (and therefore bind) the region mesh buffer 1117 // after we setup drawing in case we need to mess with the 1118 // stencil buffer in setupDraw() 1119 TextureVertex* mesh = mCaches.getRegionMesh(); 1120 uint32_t numQuads = 0; 1121 1122 setupDrawWithTexture(); 1123 setupDrawColor(alpha, alpha, alpha, alpha); 1124 setupDrawColorFilter(layer->getColorFilter()); 1125 setupDrawBlending(layer); 1126 setupDrawProgram(); 1127 setupDrawDirtyRegionsDisabled(); 1128 setupDrawPureColorUniforms(); 1129 setupDrawColorFilterUniforms(layer->getColorFilter()); 1130 setupDrawTexture(layer->getTexture()); 1131 if (currentTransform()->isPureTranslate()) { 1132 const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f); 1133 const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f); 1134 1135 layer->setFilter(GL_NEAREST); 1136 setupDrawModelView(kModelViewMode_Translate, false, 1137 x, y, x + rect.getWidth(), y + rect.getHeight(), true); 1138 } else { 1139 layer->setFilter(GL_LINEAR); 1140 setupDrawModelView(kModelViewMode_Translate, false, 1141 rect.left, rect.top, rect.right, rect.bottom); 1142 } 1143 setupDrawMeshIndices(&mesh[0].x, &mesh[0].u); 1144 1145 for (size_t i = 0; i < count; i++) { 1146 const android::Rect* r = &rects[i]; 1147 1148 const float u1 = r->left * texX; 1149 const float v1 = (height - r->top) * texY; 1150 const float u2 = r->right * texX; 1151 const float v2 = (height - r->bottom) * texY; 1152 1153 // TODO: Reject quads outside of the clip 1154 TextureVertex::set(mesh++, r->left, r->top, u1, v1); 1155 TextureVertex::set(mesh++, r->right, r->top, u2, v1); 1156 TextureVertex::set(mesh++, r->left, r->bottom, u1, v2); 1157 TextureVertex::set(mesh++, r->right, r->bottom, u2, v2); 1158 1159 numQuads++; 1160 1161 if (numQuads >= gMaxNumberOfQuads) { 1162 DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6, 1163 GL_UNSIGNED_SHORT, NULL)); 1164 numQuads = 0; 1165 mesh = mCaches.getRegionMesh(); 1166 } 1167 } 1168 1169 if (numQuads > 0) { 1170 DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6, 1171 GL_UNSIGNED_SHORT, NULL)); 1172 } 1173 1174#if DEBUG_LAYERS_AS_REGIONS 1175 drawRegionRectsDebug(layer->region); 1176#endif 1177 1178 layer->region.clear(); 1179} 1180 1181#if DEBUG_LAYERS_AS_REGIONS 1182void OpenGLRenderer::drawRegionRectsDebug(const Region& region) { 1183 size_t count; 1184 const android::Rect* rects = region.getArray(&count); 1185 1186 uint32_t colors[] = { 1187 0x7fff0000, 0x7f00ff00, 1188 0x7f0000ff, 0x7fff00ff, 1189 }; 1190 1191 int offset = 0; 1192 int32_t top = rects[0].top; 1193 1194 for (size_t i = 0; i < count; i++) { 1195 if (top != rects[i].top) { 1196 offset ^= 0x2; 1197 top = rects[i].top; 1198 } 1199 1200 SkPaint paint; 1201 paint.setColor(colors[offset + (i & 0x1)]); 1202 Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom); 1203 drawColorRect(r.left, r.top, r.right, r.bottom, paint); 1204 } 1205} 1206#endif 1207 1208void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) { 1209 Vector<float> rects; 1210 1211 SkRegion::Iterator it(region); 1212 while (!it.done()) { 1213 const SkIRect& r = it.rect(); 1214 rects.push(r.fLeft); 1215 rects.push(r.fTop); 1216 rects.push(r.fRight); 1217 rects.push(r.fBottom); 1218 it.next(); 1219 } 1220 1221 drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false); 1222} 1223 1224void OpenGLRenderer::dirtyLayer(const float left, const float top, 1225 const float right, const float bottom, const mat4 transform) { 1226 if (hasLayer()) { 1227 Rect bounds(left, top, right, bottom); 1228 transform.mapRect(bounds); 1229 dirtyLayerUnchecked(bounds, getRegion()); 1230 } 1231} 1232 1233void OpenGLRenderer::dirtyLayer(const float left, const float top, 1234 const float right, const float bottom) { 1235 if (hasLayer()) { 1236 Rect bounds(left, top, right, bottom); 1237 dirtyLayerUnchecked(bounds, getRegion()); 1238 } 1239} 1240 1241void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) { 1242 if (bounds.intersect(*currentClipRect())) { 1243 bounds.snapToPixelBoundaries(); 1244 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom); 1245 if (!dirty.isEmpty()) { 1246 region->orSelf(dirty); 1247 } 1248 } 1249} 1250 1251void OpenGLRenderer::issueIndexedQuadDraw(Vertex* mesh, GLsizei quadsCount) { 1252 GLsizei elementsCount = quadsCount * 6; 1253 while (elementsCount > 0) { 1254 GLsizei drawCount = min(elementsCount, (GLsizei) gMaxNumberOfQuads * 6); 1255 1256 setupDrawIndexedVertices(&mesh[0].x); 1257 glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, NULL); 1258 1259 elementsCount -= drawCount; 1260 // Though there are 4 vertices in a quad, we use 6 indices per 1261 // quad to draw with GL_TRIANGLES 1262 mesh += (drawCount / 6) * 4; 1263 } 1264} 1265 1266void OpenGLRenderer::clearLayerRegions() { 1267 const size_t count = mLayers.size(); 1268 if (count == 0) return; 1269 1270 if (!currentSnapshot()->isIgnored()) { 1271 // Doing several glScissor/glClear here can negatively impact 1272 // GPUs with a tiler architecture, instead we draw quads with 1273 // the Clear blending mode 1274 1275 // The list contains bounds that have already been clipped 1276 // against their initial clip rect, and the current clip 1277 // is likely different so we need to disable clipping here 1278 bool scissorChanged = mCaches.disableScissor(); 1279 1280 Vertex mesh[count * 4]; 1281 Vertex* vertex = mesh; 1282 1283 for (uint32_t i = 0; i < count; i++) { 1284 Rect* bounds = mLayers.itemAt(i); 1285 1286 Vertex::set(vertex++, bounds->left, bounds->top); 1287 Vertex::set(vertex++, bounds->right, bounds->top); 1288 Vertex::set(vertex++, bounds->left, bounds->bottom); 1289 Vertex::set(vertex++, bounds->right, bounds->bottom); 1290 1291 delete bounds; 1292 } 1293 // We must clear the list of dirty rects before we 1294 // call setupDraw() to prevent stencil setup to do 1295 // the same thing again 1296 mLayers.clear(); 1297 1298 SkPaint clearPaint; 1299 clearPaint.setXfermodeMode(SkXfermode::kClear_Mode); 1300 1301 setupDraw(false); 1302 setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f); 1303 setupDrawBlending(&clearPaint, true); 1304 setupDrawProgram(); 1305 setupDrawPureColorUniforms(); 1306 setupDrawModelView(kModelViewMode_Translate, false, 1307 0.0f, 0.0f, 0.0f, 0.0f, true); 1308 1309 issueIndexedQuadDraw(&mesh[0], count); 1310 1311 if (scissorChanged) mCaches.enableScissor(); 1312 } else { 1313 for (uint32_t i = 0; i < count; i++) { 1314 delete mLayers.itemAt(i); 1315 } 1316 mLayers.clear(); 1317 } 1318} 1319 1320/////////////////////////////////////////////////////////////////////////////// 1321// State Deferral 1322/////////////////////////////////////////////////////////////////////////////// 1323 1324bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) { 1325 const Rect* currentClip = currentClipRect(); 1326 const mat4* currentMatrix = currentTransform(); 1327 1328 if (stateDeferFlags & kStateDeferFlag_Draw) { 1329 // state has bounds initialized in local coordinates 1330 if (!state.mBounds.isEmpty()) { 1331 currentMatrix->mapRect(state.mBounds); 1332 Rect clippedBounds(state.mBounds); 1333 // NOTE: if we ever want to use this clipping info to drive whether the scissor 1334 // is used, it should more closely duplicate the quickReject logic (in how it uses 1335 // snapToPixelBoundaries) 1336 1337 if(!clippedBounds.intersect(*currentClip)) { 1338 // quick rejected 1339 return true; 1340 } 1341 1342 state.mClipSideFlags = kClipSide_None; 1343 if (!currentClip->contains(state.mBounds)) { 1344 int& flags = state.mClipSideFlags; 1345 // op partially clipped, so record which sides are clipped for clip-aware merging 1346 if (currentClip->left > state.mBounds.left) flags |= kClipSide_Left; 1347 if (currentClip->top > state.mBounds.top) flags |= kClipSide_Top; 1348 if (currentClip->right < state.mBounds.right) flags |= kClipSide_Right; 1349 if (currentClip->bottom < state.mBounds.bottom) flags |= kClipSide_Bottom; 1350 } 1351 state.mBounds.set(clippedBounds); 1352 } else { 1353 // Empty bounds implies size unknown. Label op as conservatively clipped to disable 1354 // overdraw avoidance (since we don't know what it overlaps) 1355 state.mClipSideFlags = kClipSide_ConservativeFull; 1356 state.mBounds.set(*currentClip); 1357 } 1358 } 1359 1360 state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip); 1361 if (state.mClipValid) { 1362 state.mClip.set(*currentClip); 1363 } 1364 1365 // Transform, drawModifiers, and alpha always deferred, since they are used by state operations 1366 // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything) 1367 state.mMatrix.load(*currentMatrix); 1368 state.mDrawModifiers = mDrawModifiers; 1369 state.mAlpha = currentSnapshot()->alpha; 1370 1371 // always store/restore, since it's just a pointer 1372 state.mRoundRectClipState = currentSnapshot()->roundRectClipState; 1373 return false; 1374} 1375 1376void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) { 1377 setMatrix(state.mMatrix); 1378 mSnapshot->alpha = state.mAlpha; 1379 mDrawModifiers = state.mDrawModifiers; 1380 mSnapshot->roundRectClipState = state.mRoundRectClipState; 1381 1382 if (state.mClipValid && !skipClipRestore) { 1383 mSnapshot->setClip(state.mClip.left, state.mClip.top, 1384 state.mClip.right, state.mClip.bottom); 1385 dirtyClip(); 1386 } 1387} 1388 1389/** 1390 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done 1391 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at 1392 * least one op is clipped), or disabled entirely (because no merged op is clipped) 1393 * 1394 * This method should be called when restoreDisplayState() won't be restoring the clip 1395 */ 1396void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) { 1397 if (clipRect != NULL) { 1398 mSnapshot->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom); 1399 } else { 1400 mSnapshot->setClip(0, 0, getWidth(), getHeight()); 1401 } 1402 dirtyClip(); 1403 mCaches.setScissorEnabled(clipRect != NULL || mScissorOptimizationDisabled); 1404} 1405 1406/////////////////////////////////////////////////////////////////////////////// 1407// Clipping 1408/////////////////////////////////////////////////////////////////////////////// 1409 1410void OpenGLRenderer::setScissorFromClip() { 1411 Rect clip(*currentClipRect()); 1412 clip.snapToPixelBoundaries(); 1413 1414 if (mCaches.setScissor(clip.left, getViewportHeight() - clip.bottom, 1415 clip.getWidth(), clip.getHeight())) { 1416 mDirtyClip = false; 1417 } 1418} 1419 1420void OpenGLRenderer::ensureStencilBuffer() { 1421 // Thanks to the mismatch between EGL and OpenGL ES FBO we 1422 // cannot attach a stencil buffer to fbo0 dynamically. Let's 1423 // just hope we have one when hasLayer() returns false. 1424 if (hasLayer()) { 1425 attachStencilBufferToLayer(currentSnapshot()->layer); 1426 } 1427} 1428 1429void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) { 1430 // The layer's FBO is already bound when we reach this stage 1431 if (!layer->getStencilRenderBuffer()) { 1432 // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer 1433 // is attached after we initiated tiling. We must turn it off, 1434 // attach the new render buffer then turn tiling back on 1435 endTiling(); 1436 1437 RenderBuffer* buffer = mCaches.renderBufferCache.get( 1438 Stencil::getSmallestStencilFormat(), layer->getWidth(), layer->getHeight()); 1439 layer->setStencilRenderBuffer(buffer); 1440 1441 startTiling(layer->clipRect, layer->layer.getHeight()); 1442 } 1443} 1444 1445void OpenGLRenderer::setStencilFromClip() { 1446 if (!mCaches.debugOverdraw) { 1447 if (!currentSnapshot()->clipRegion->isEmpty()) { 1448 // NOTE: The order here is important, we must set dirtyClip to false 1449 // before any draw call to avoid calling back into this method 1450 mDirtyClip = false; 1451 1452 ensureStencilBuffer(); 1453 1454 mCaches.stencil.enableWrite(); 1455 1456 // Clear and update the stencil, but first make sure we restrict drawing 1457 // to the region's bounds 1458 bool resetScissor = mCaches.enableScissor(); 1459 if (resetScissor) { 1460 // The scissor was not set so we now need to update it 1461 setScissorFromClip(); 1462 } 1463 mCaches.stencil.clear(); 1464 1465 // stash and disable the outline clip state, since stencil doesn't account for outline 1466 bool storedSkipOutlineClip = mSkipOutlineClip; 1467 mSkipOutlineClip = true; 1468 1469 SkPaint paint; 1470 paint.setColor(0xff000000); 1471 paint.setXfermodeMode(SkXfermode::kSrc_Mode); 1472 1473 // NOTE: We could use the region contour path to generate a smaller mesh 1474 // Since we are using the stencil we could use the red book path 1475 // drawing technique. It might increase bandwidth usage though. 1476 1477 // The last parameter is important: we are not drawing in the color buffer 1478 // so we don't want to dirty the current layer, if any 1479 drawRegionRects(*(currentSnapshot()->clipRegion), paint, false); 1480 if (resetScissor) mCaches.disableScissor(); 1481 mSkipOutlineClip = storedSkipOutlineClip; 1482 1483 mCaches.stencil.enableTest(); 1484 1485 // Draw the region used to generate the stencil if the appropriate debug 1486 // mode is enabled 1487 if (mCaches.debugStencilClip == Caches::kStencilShowRegion) { 1488 paint.setColor(0x7f0000ff); 1489 paint.setXfermodeMode(SkXfermode::kSrcOver_Mode); 1490 drawRegionRects(*(currentSnapshot()->clipRegion), paint); 1491 } 1492 } else { 1493 mCaches.stencil.disable(); 1494 } 1495 } 1496} 1497 1498/** 1499 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out. 1500 * 1501 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint 1502 * style, and tessellated AA ramp 1503 */ 1504bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom, 1505 const SkPaint* paint) { 1506 bool snapOut = paint && paint->isAntiAlias(); 1507 1508 if (paint && paint->getStyle() != SkPaint::kFill_Style) { 1509 float outset = paint->getStrokeWidth() * 0.5f; 1510 left -= outset; 1511 top -= outset; 1512 right += outset; 1513 bottom += outset; 1514 } 1515 1516 bool clipRequired = false; 1517 bool roundRectClipRequired = false; 1518 if (calculateQuickRejectForScissor(left, top, right, bottom, 1519 &clipRequired, &roundRectClipRequired, snapOut)) { 1520 return true; 1521 } 1522 1523 if (!isRecording()) { 1524 // not quick rejected, so enable the scissor if clipRequired 1525 mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired); 1526 mSkipOutlineClip = !roundRectClipRequired; 1527 } 1528 return false; 1529} 1530 1531void OpenGLRenderer::debugClip() { 1532#if DEBUG_CLIP_REGIONS 1533 if (!isRecording() && !currentSnapshot()->clipRegion->isEmpty()) { 1534 SkPaint paint; 1535 paint.setColor(0x7f00ff00); 1536 drawRegionRects(*(currentSnapshot()->clipRegion, paint); 1537 1538 } 1539#endif 1540} 1541 1542/////////////////////////////////////////////////////////////////////////////// 1543// Drawing commands 1544/////////////////////////////////////////////////////////////////////////////// 1545 1546void OpenGLRenderer::setupDraw(bool clear) { 1547 // TODO: It would be best if we could do this before quickRejectSetupScissor() 1548 // changes the scissor test state 1549 if (clear) clearLayerRegions(); 1550 // Make sure setScissor & setStencil happen at the beginning of 1551 // this method 1552 if (mDirtyClip) { 1553 if (mCaches.scissorEnabled) { 1554 setScissorFromClip(); 1555 } 1556 setStencilFromClip(); 1557 } 1558 1559 mDescription.reset(); 1560 1561 mSetShaderColor = false; 1562 mColorSet = false; 1563 mColorA = mColorR = mColorG = mColorB = 0.0f; 1564 mTextureUnit = 0; 1565 mTrackDirtyRegions = true; 1566 1567 // Enable debug highlight when what we're about to draw is tested against 1568 // the stencil buffer and if stencil highlight debugging is on 1569 mDescription.hasDebugHighlight = !mCaches.debugOverdraw && 1570 mCaches.debugStencilClip == Caches::kStencilShowHighlight && 1571 mCaches.stencil.isTestEnabled(); 1572 1573 mDescription.emulateStencil = mCountOverdraw; 1574} 1575 1576void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) { 1577 mDescription.hasTexture = true; 1578 mDescription.hasAlpha8Texture = isAlpha8; 1579} 1580 1581void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) { 1582 mDescription.hasTexture = true; 1583 mDescription.hasColors = true; 1584 mDescription.hasAlpha8Texture = isAlpha8; 1585} 1586 1587void OpenGLRenderer::setupDrawWithExternalTexture() { 1588 mDescription.hasExternalTexture = true; 1589} 1590 1591void OpenGLRenderer::setupDrawNoTexture() { 1592 mCaches.disableTexCoordsVertexArray(); 1593} 1594 1595void OpenGLRenderer::setupDrawAA() { 1596 mDescription.isAA = true; 1597} 1598 1599void OpenGLRenderer::setupDrawColor(int color, int alpha) { 1600 mColorA = alpha / 255.0f; 1601 mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f; 1602 mColorG = mColorA * ((color >> 8) & 0xFF) / 255.0f; 1603 mColorB = mColorA * ((color ) & 0xFF) / 255.0f; 1604 mColorSet = true; 1605 mSetShaderColor = mDescription.setColorModulate(mColorA); 1606} 1607 1608void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) { 1609 mColorA = alpha / 255.0f; 1610 mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f; 1611 mColorG = mColorA * ((color >> 8) & 0xFF) / 255.0f; 1612 mColorB = mColorA * ((color ) & 0xFF) / 255.0f; 1613 mColorSet = true; 1614 mSetShaderColor = mDescription.setAlpha8ColorModulate(mColorR, mColorG, mColorB, mColorA); 1615} 1616 1617void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) { 1618 mCaches.fontRenderer->describe(mDescription, paint); 1619} 1620 1621void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) { 1622 mColorA = a; 1623 mColorR = r; 1624 mColorG = g; 1625 mColorB = b; 1626 mColorSet = true; 1627 mSetShaderColor = mDescription.setColorModulate(a); 1628} 1629 1630void OpenGLRenderer::setupDrawShader() { 1631 if (mDrawModifiers.mShader) { 1632 mDrawModifiers.mShader->describe(mDescription, mExtensions); 1633 } 1634} 1635 1636void OpenGLRenderer::setupDrawColorFilter(const SkColorFilter* filter) { 1637 if (filter == NULL) { 1638 return; 1639 } 1640 1641 SkXfermode::Mode mode; 1642 if (filter->asColorMode(NULL, &mode)) { 1643 mDescription.colorOp = ProgramDescription::kColorBlend; 1644 mDescription.colorMode = mode; 1645 } else if (filter->asColorMatrix(NULL)) { 1646 mDescription.colorOp = ProgramDescription::kColorMatrix; 1647 } 1648} 1649 1650void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) { 1651 if (mColorSet && mode == SkXfermode::kClear_Mode) { 1652 mColorA = 1.0f; 1653 mColorR = mColorG = mColorB = 0.0f; 1654 mSetShaderColor = mDescription.modulate = true; 1655 } 1656} 1657 1658void OpenGLRenderer::setupDrawBlending(const Layer* layer, bool swapSrcDst) { 1659 SkXfermode::Mode mode = layer->getMode(); 1660 // When the blending mode is kClear_Mode, we need to use a modulate color 1661 // argb=1,0,0,0 1662 accountForClear(mode); 1663 bool blend = layer->isBlend() || getLayerAlpha(layer) < 1.0f || 1664 (mColorSet && mColorA < 1.0f) || 1665 (mDrawModifiers.mShader && mDrawModifiers.mShader->blend()) || 1666 layer->getColorFilter(); 1667 chooseBlending(blend, mode, mDescription, swapSrcDst); 1668} 1669 1670void OpenGLRenderer::setupDrawBlending(const SkPaint* paint, bool blend, bool swapSrcDst) { 1671 SkXfermode::Mode mode = getXfermodeDirect(paint); 1672 // When the blending mode is kClear_Mode, we need to use a modulate color 1673 // argb=1,0,0,0 1674 accountForClear(mode); 1675 blend |= (mColorSet && mColorA < 1.0f) || 1676 (mDrawModifiers.mShader && mDrawModifiers.mShader->blend()) || 1677 (paint && paint->getColorFilter()); 1678 chooseBlending(blend, mode, mDescription, swapSrcDst); 1679} 1680 1681void OpenGLRenderer::setupDrawProgram() { 1682 useProgram(mCaches.programCache.get(mDescription)); 1683 if (mDescription.hasRoundRectClip) { 1684 // TODO: avoid doing this repeatedly, stashing state pointer in program 1685 const RoundRectClipState* state = mSnapshot->roundRectClipState; 1686 const Rect& innerRect = state->outlineInnerRect; 1687 glUniform4f(mCaches.currentProgram->getUniform("roundRectInnerRectLTRB"), 1688 innerRect.left, innerRect.top, 1689 innerRect.right, innerRect.bottom); 1690 glUniform1f(mCaches.currentProgram->getUniform("roundRectRadius"), 1691 state->outlineRadius); 1692 glUniformMatrix4fv(mCaches.currentProgram->getUniform("roundRectInvTransform"), 1693 1, GL_FALSE, &state->matrix.data[0]); 1694 } 1695} 1696 1697void OpenGLRenderer::setupDrawDirtyRegionsDisabled() { 1698 mTrackDirtyRegions = false; 1699} 1700 1701void OpenGLRenderer::setupDrawModelView(ModelViewMode mode, bool offset, 1702 float left, float top, float right, float bottom, bool ignoreTransform) { 1703 mModelViewMatrix.loadTranslate(left, top, 0.0f); 1704 if (mode == kModelViewMode_TranslateAndScale) { 1705 mModelViewMatrix.scale(right - left, bottom - top, 1.0f); 1706 } 1707 1708 bool dirty = right - left > 0.0f && bottom - top > 0.0f; 1709 const Matrix4& transformMatrix = ignoreTransform ? Matrix4::identity() : *currentTransform(); 1710 mCaches.currentProgram->set(mSnapshot->getOrthoMatrix(), mModelViewMatrix, transformMatrix, offset); 1711 if (dirty && mTrackDirtyRegions) { 1712 if (!ignoreTransform) { 1713 dirtyLayer(left, top, right, bottom, *currentTransform()); 1714 } else { 1715 dirtyLayer(left, top, right, bottom); 1716 } 1717 } 1718} 1719 1720void OpenGLRenderer::setupDrawColorUniforms() { 1721 if ((mColorSet && !mDrawModifiers.mShader) || (mDrawModifiers.mShader && mSetShaderColor)) { 1722 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1723 } 1724} 1725 1726void OpenGLRenderer::setupDrawPureColorUniforms() { 1727 if (mSetShaderColor) { 1728 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1729 } 1730} 1731 1732void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) { 1733 if (mDrawModifiers.mShader) { 1734 if (ignoreTransform) { 1735 // if ignoreTransform=true was passed to setupDrawModelView, undo currentTransform() 1736 // because it was built into modelView / the geometry, and the SkiaShader needs to 1737 // compensate. 1738 mat4 modelViewWithoutTransform; 1739 modelViewWithoutTransform.loadInverse(*currentTransform()); 1740 modelViewWithoutTransform.multiply(mModelViewMatrix); 1741 mModelViewMatrix.load(modelViewWithoutTransform); 1742 } 1743 mDrawModifiers.mShader->setupProgram(mCaches.currentProgram, 1744 mModelViewMatrix, *mSnapshot, &mTextureUnit); 1745 } 1746} 1747 1748void OpenGLRenderer::setupDrawColorFilterUniforms(const SkColorFilter* filter) { 1749 if (NULL == filter) { 1750 return; 1751 } 1752 1753 SkColor color; 1754 SkXfermode::Mode mode; 1755 if (filter->asColorMode(&color, &mode)) { 1756 const int alpha = SkColorGetA(color); 1757 const GLfloat a = alpha / 255.0f; 1758 const GLfloat r = a * SkColorGetR(color) / 255.0f; 1759 const GLfloat g = a * SkColorGetG(color) / 255.0f; 1760 const GLfloat b = a * SkColorGetB(color) / 255.0f; 1761 glUniform4f(mCaches.currentProgram->getUniform("colorBlend"), r, g, b, a); 1762 return; 1763 } 1764 1765 SkScalar srcColorMatrix[20]; 1766 if (filter->asColorMatrix(srcColorMatrix)) { 1767 1768 float colorMatrix[16]; 1769 memcpy(colorMatrix, srcColorMatrix, 4 * sizeof(float)); 1770 memcpy(&colorMatrix[4], &srcColorMatrix[5], 4 * sizeof(float)); 1771 memcpy(&colorMatrix[8], &srcColorMatrix[10], 4 * sizeof(float)); 1772 memcpy(&colorMatrix[12], &srcColorMatrix[15], 4 * sizeof(float)); 1773 1774 // Skia uses the range [0..255] for the addition vector, but we need 1775 // the [0..1] range to apply the vector in GLSL 1776 float colorVector[4]; 1777 colorVector[0] = srcColorMatrix[4] / 255.0f; 1778 colorVector[1] = srcColorMatrix[9] / 255.0f; 1779 colorVector[2] = srcColorMatrix[14] / 255.0f; 1780 colorVector[3] = srcColorMatrix[19] / 255.0f; 1781 1782 glUniformMatrix4fv(mCaches.currentProgram->getUniform("colorMatrix"), 1, 1783 GL_FALSE, colorMatrix); 1784 glUniform4fv(mCaches.currentProgram->getUniform("colorMatrixVector"), 1, colorVector); 1785 return; 1786 } 1787 1788 // it is an error if we ever get here 1789} 1790 1791void OpenGLRenderer::setupDrawTextGammaUniforms() { 1792 mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram); 1793} 1794 1795void OpenGLRenderer::setupDrawSimpleMesh() { 1796 bool force = mCaches.bindMeshBuffer(); 1797 mCaches.bindPositionVertexPointer(force, 0); 1798 mCaches.unbindIndicesBuffer(); 1799} 1800 1801void OpenGLRenderer::setupDrawTexture(GLuint texture) { 1802 if (texture) bindTexture(texture); 1803 mTextureUnit++; 1804 mCaches.enableTexCoordsVertexArray(); 1805} 1806 1807void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) { 1808 bindExternalTexture(texture); 1809 mTextureUnit++; 1810 mCaches.enableTexCoordsVertexArray(); 1811} 1812 1813void OpenGLRenderer::setupDrawTextureTransform() { 1814 mDescription.hasTextureTransform = true; 1815} 1816 1817void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) { 1818 glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1, 1819 GL_FALSE, &transform.data[0]); 1820} 1821 1822void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices, 1823 const GLvoid* texCoords, GLuint vbo) { 1824 bool force = false; 1825 if (!vertices || vbo) { 1826 force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo); 1827 } else { 1828 force = mCaches.unbindMeshBuffer(); 1829 } 1830 1831 mCaches.bindPositionVertexPointer(force, vertices); 1832 if (mCaches.currentProgram->texCoords >= 0) { 1833 mCaches.bindTexCoordsVertexPointer(force, texCoords); 1834 } 1835 1836 mCaches.unbindIndicesBuffer(); 1837} 1838 1839void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices, 1840 const GLvoid* texCoords, const GLvoid* colors) { 1841 bool force = mCaches.unbindMeshBuffer(); 1842 GLsizei stride = sizeof(ColorTextureVertex); 1843 1844 mCaches.bindPositionVertexPointer(force, vertices, stride); 1845 if (mCaches.currentProgram->texCoords >= 0) { 1846 mCaches.bindTexCoordsVertexPointer(force, texCoords, stride); 1847 } 1848 int slot = mCaches.currentProgram->getAttrib("colors"); 1849 if (slot >= 0) { 1850 glEnableVertexAttribArray(slot); 1851 glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors); 1852 } 1853 1854 mCaches.unbindIndicesBuffer(); 1855} 1856 1857void OpenGLRenderer::setupDrawMeshIndices(const GLvoid* vertices, 1858 const GLvoid* texCoords, GLuint vbo) { 1859 bool force = false; 1860 // If vbo is != 0 we want to treat the vertices parameter as an offset inside 1861 // a VBO. However, if vertices is set to NULL and vbo == 0 then we want to 1862 // use the default VBO found in Caches 1863 if (!vertices || vbo) { 1864 force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo); 1865 } else { 1866 force = mCaches.unbindMeshBuffer(); 1867 } 1868 mCaches.bindQuadIndicesBuffer(); 1869 1870 mCaches.bindPositionVertexPointer(force, vertices); 1871 if (mCaches.currentProgram->texCoords >= 0) { 1872 mCaches.bindTexCoordsVertexPointer(force, texCoords); 1873 } 1874} 1875 1876void OpenGLRenderer::setupDrawIndexedVertices(GLvoid* vertices) { 1877 bool force = mCaches.unbindMeshBuffer(); 1878 mCaches.bindQuadIndicesBuffer(); 1879 mCaches.bindPositionVertexPointer(force, vertices, gVertexStride); 1880} 1881 1882/////////////////////////////////////////////////////////////////////////////// 1883// Drawing 1884/////////////////////////////////////////////////////////////////////////////// 1885 1886status_t OpenGLRenderer::drawDisplayList(RenderNode* displayList, Rect& dirty, 1887 int32_t replayFlags) { 1888 status_t status; 1889 // All the usual checks and setup operations (quickReject, setupDraw, etc.) 1890 // will be performed by the display list itself 1891 if (displayList && displayList->isRenderable()) { 1892 // compute 3d ordering 1893 displayList->computeOrdering(); 1894 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 1895 status = startFrame(); 1896 ReplayStateStruct replayStruct(*this, dirty, replayFlags); 1897 displayList->replayNodeTree(replayStruct); 1898 return status | replayStruct.mDrawGlStatus; 1899 } 1900 1901 bool avoidOverdraw = !mCaches.debugOverdraw && !mCountOverdraw; // shh, don't tell devs! 1902 DeferredDisplayList deferredList(*currentClipRect(), avoidOverdraw); 1903 DeferStateStruct deferStruct(deferredList, *this, replayFlags); 1904 displayList->deferNodeTree(deferStruct); 1905 1906 flushLayers(); 1907 status = startFrame(); 1908 1909 return deferredList.flush(*this, dirty) | status; 1910 } 1911 1912 return DrawGlInfo::kStatusDone; 1913} 1914 1915void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, const SkPaint* paint) { 1916 int color = paint != NULL ? paint->getColor() : 0; 1917 1918 float x = left; 1919 float y = top; 1920 1921 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1922 1923 bool ignoreTransform = false; 1924 if (currentTransform()->isPureTranslate()) { 1925 x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f); 1926 y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f); 1927 ignoreTransform = true; 1928 1929 texture->setFilter(GL_NEAREST, true); 1930 } else { 1931 texture->setFilter(getFilter(paint), true); 1932 } 1933 1934 // No need to check for a UV mapper on the texture object, only ARGB_8888 1935 // bitmaps get packed in the atlas 1936 drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 1937 paint, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, 1938 GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform); 1939} 1940 1941/** 1942 * Important note: this method is intended to draw batches of bitmaps and 1943 * will not set the scissor enable or dirty the current layer, if any. 1944 * The caller is responsible for properly dirtying the current layer. 1945 */ 1946status_t OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 1947 int bitmapCount, TextureVertex* vertices, bool pureTranslate, 1948 const Rect& bounds, const SkPaint* paint) { 1949 mCaches.activeTexture(0); 1950 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 1951 if (!texture) return DrawGlInfo::kStatusDone; 1952 1953 const AutoTexture autoCleanup(texture); 1954 1955 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1956 texture->setFilter(pureTranslate ? GL_NEAREST : getFilter(paint), true); 1957 1958 const float x = (int) floorf(bounds.left + 0.5f); 1959 const float y = (int) floorf(bounds.top + 0.5f); 1960 if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) { 1961 drawAlpha8TextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(), 1962 texture->id, paint, &vertices[0].x, &vertices[0].u, 1963 GL_TRIANGLES, bitmapCount * 6, true, 1964 kModelViewMode_Translate, false); 1965 } else { 1966 drawTextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(), 1967 texture->id, paint, texture->blend, &vertices[0].x, &vertices[0].u, 1968 GL_TRIANGLES, bitmapCount * 6, false, true, 0, 1969 kModelViewMode_Translate, false); 1970 } 1971 1972 return DrawGlInfo::kStatusDrew; 1973} 1974 1975status_t OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, float left, float top, 1976 const SkPaint* paint) { 1977 const float right = left + bitmap->width(); 1978 const float bottom = top + bitmap->height(); 1979 1980 if (quickRejectSetupScissor(left, top, right, bottom)) { 1981 return DrawGlInfo::kStatusDone; 1982 } 1983 1984 mCaches.activeTexture(0); 1985 Texture* texture = getTexture(bitmap); 1986 if (!texture) return DrawGlInfo::kStatusDone; 1987 const AutoTexture autoCleanup(texture); 1988 1989 if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) { 1990 drawAlphaBitmap(texture, left, top, paint); 1991 } else { 1992 drawTextureRect(left, top, right, bottom, texture, paint); 1993 } 1994 1995 return DrawGlInfo::kStatusDrew; 1996} 1997 1998status_t OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkMatrix* matrix, 1999 const SkPaint* paint) { 2000 Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height()); 2001 const mat4 transform(*matrix); 2002 transform.mapRect(r); 2003 2004 if (quickRejectSetupScissor(r.left, r.top, r.right, r.bottom)) { 2005 return DrawGlInfo::kStatusDone; 2006 } 2007 2008 mCaches.activeTexture(0); 2009 Texture* texture = getTexture(bitmap); 2010 if (!texture) return DrawGlInfo::kStatusDone; 2011 const AutoTexture autoCleanup(texture); 2012 2013 // This could be done in a cheaper way, all we need is pass the matrix 2014 // to the vertex shader. The save/restore is a bit overkill. 2015 save(SkCanvas::kMatrix_SaveFlag); 2016 concatMatrix(matrix); 2017 if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) { 2018 drawAlphaBitmap(texture, 0.0f, 0.0f, paint); 2019 } else { 2020 drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint); 2021 } 2022 restore(); 2023 2024 return DrawGlInfo::kStatusDrew; 2025} 2026 2027status_t OpenGLRenderer::drawBitmapData(const SkBitmap* bitmap, float left, float top, 2028 const SkPaint* paint) { 2029 const float right = left + bitmap->width(); 2030 const float bottom = top + bitmap->height(); 2031 2032 if (quickRejectSetupScissor(left, top, right, bottom)) { 2033 return DrawGlInfo::kStatusDone; 2034 } 2035 2036 mCaches.activeTexture(0); 2037 Texture* texture = mCaches.textureCache.getTransient(bitmap); 2038 const AutoTexture autoCleanup(texture); 2039 2040 if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) { 2041 drawAlphaBitmap(texture, left, top, paint); 2042 } else { 2043 drawTextureRect(left, top, right, bottom, texture, paint); 2044 } 2045 2046 return DrawGlInfo::kStatusDrew; 2047} 2048 2049status_t OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight, 2050 const float* vertices, const int* colors, const SkPaint* paint) { 2051 if (!vertices || currentSnapshot()->isIgnored()) { 2052 return DrawGlInfo::kStatusDone; 2053 } 2054 2055 // TODO: use quickReject on bounds from vertices 2056 mCaches.enableScissor(); 2057 2058 float left = FLT_MAX; 2059 float top = FLT_MAX; 2060 float right = FLT_MIN; 2061 float bottom = FLT_MIN; 2062 2063 const uint32_t count = meshWidth * meshHeight * 6; 2064 2065 Vector<ColorTextureVertex> mesh; // TODO: use C++11 unique_ptr 2066 mesh.setCapacity(count); 2067 ColorTextureVertex* vertex = mesh.editArray(); 2068 2069 bool cleanupColors = false; 2070 if (!colors) { 2071 uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1); 2072 int* newColors = new int[colorsCount]; 2073 memset(newColors, 0xff, colorsCount * sizeof(int)); 2074 colors = newColors; 2075 cleanupColors = true; 2076 } 2077 2078 mCaches.activeTexture(0); 2079 Texture* texture = mCaches.assetAtlas.getEntryTexture(bitmap); 2080 const UvMapper& mapper(getMapper(texture)); 2081 2082 for (int32_t y = 0; y < meshHeight; y++) { 2083 for (int32_t x = 0; x < meshWidth; x++) { 2084 uint32_t i = (y * (meshWidth + 1) + x) * 2; 2085 2086 float u1 = float(x) / meshWidth; 2087 float u2 = float(x + 1) / meshWidth; 2088 float v1 = float(y) / meshHeight; 2089 float v2 = float(y + 1) / meshHeight; 2090 2091 mapper.map(u1, v1, u2, v2); 2092 2093 int ax = i + (meshWidth + 1) * 2; 2094 int ay = ax + 1; 2095 int bx = i; 2096 int by = bx + 1; 2097 int cx = i + 2; 2098 int cy = cx + 1; 2099 int dx = i + (meshWidth + 1) * 2 + 2; 2100 int dy = dx + 1; 2101 2102 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 2103 ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]); 2104 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 2105 2106 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 2107 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 2108 ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]); 2109 2110 left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx]))); 2111 top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy]))); 2112 right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx]))); 2113 bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy]))); 2114 } 2115 } 2116 2117 if (quickRejectSetupScissor(left, top, right, bottom)) { 2118 if (cleanupColors) delete[] colors; 2119 return DrawGlInfo::kStatusDone; 2120 } 2121 2122 if (!texture) { 2123 texture = mCaches.textureCache.get(bitmap); 2124 if (!texture) { 2125 if (cleanupColors) delete[] colors; 2126 return DrawGlInfo::kStatusDone; 2127 } 2128 } 2129 const AutoTexture autoCleanup(texture); 2130 2131 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2132 texture->setFilter(getFilter(paint), true); 2133 2134 int alpha; 2135 SkXfermode::Mode mode; 2136 getAlphaAndMode(paint, &alpha, &mode); 2137 2138 float a = alpha / 255.0f; 2139 2140 if (hasLayer()) { 2141 dirtyLayer(left, top, right, bottom, *currentTransform()); 2142 } 2143 2144 setupDraw(); 2145 setupDrawWithTextureAndColor(); 2146 setupDrawColor(a, a, a, a); 2147 setupDrawColorFilter(getColorFilter(paint)); 2148 setupDrawBlending(paint, true); 2149 setupDrawProgram(); 2150 setupDrawDirtyRegionsDisabled(); 2151 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 0.0f, 0.0f, 1.0f, 1.0f); 2152 setupDrawTexture(texture->id); 2153 setupDrawPureColorUniforms(); 2154 setupDrawColorFilterUniforms(getColorFilter(paint)); 2155 setupDrawMesh(&mesh[0].x, &mesh[0].u, &mesh[0].r); 2156 2157 glDrawArrays(GL_TRIANGLES, 0, count); 2158 2159 int slot = mCaches.currentProgram->getAttrib("colors"); 2160 if (slot >= 0) { 2161 glDisableVertexAttribArray(slot); 2162 } 2163 2164 if (cleanupColors) delete[] colors; 2165 2166 return DrawGlInfo::kStatusDrew; 2167} 2168 2169status_t OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, 2170 float srcLeft, float srcTop, float srcRight, float srcBottom, 2171 float dstLeft, float dstTop, float dstRight, float dstBottom, 2172 const SkPaint* paint) { 2173 if (quickRejectSetupScissor(dstLeft, dstTop, dstRight, dstBottom)) { 2174 return DrawGlInfo::kStatusDone; 2175 } 2176 2177 mCaches.activeTexture(0); 2178 Texture* texture = getTexture(bitmap); 2179 if (!texture) return DrawGlInfo::kStatusDone; 2180 const AutoTexture autoCleanup(texture); 2181 2182 const float width = texture->width; 2183 const float height = texture->height; 2184 2185 float u1 = fmax(0.0f, srcLeft / width); 2186 float v1 = fmax(0.0f, srcTop / height); 2187 float u2 = fmin(1.0f, srcRight / width); 2188 float v2 = fmin(1.0f, srcBottom / height); 2189 2190 getMapper(texture).map(u1, v1, u2, v2); 2191 2192 mCaches.unbindMeshBuffer(); 2193 resetDrawTextureTexCoords(u1, v1, u2, v2); 2194 2195 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2196 2197 float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft); 2198 float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop); 2199 2200 bool scaled = scaleX != 1.0f || scaleY != 1.0f; 2201 // Apply a scale transform on the canvas only when a shader is in use 2202 // Skia handles the ratio between the dst and src rects as a scale factor 2203 // when a shader is set 2204 bool useScaleTransform = mDrawModifiers.mShader && scaled; 2205 bool ignoreTransform = false; 2206 2207 if (CC_LIKELY(currentTransform()->isPureTranslate() && !useScaleTransform)) { 2208 float x = (int) floorf(dstLeft + currentTransform()->getTranslateX() + 0.5f); 2209 float y = (int) floorf(dstTop + currentTransform()->getTranslateY() + 0.5f); 2210 2211 dstRight = x + (dstRight - dstLeft); 2212 dstBottom = y + (dstBottom - dstTop); 2213 2214 dstLeft = x; 2215 dstTop = y; 2216 2217 texture->setFilter(scaled ? getFilter(paint) : GL_NEAREST, true); 2218 ignoreTransform = true; 2219 } else { 2220 texture->setFilter(getFilter(paint), true); 2221 } 2222 2223 if (CC_UNLIKELY(useScaleTransform)) { 2224 save(SkCanvas::kMatrix_SaveFlag); 2225 translate(dstLeft, dstTop); 2226 scale(scaleX, scaleY); 2227 2228 dstLeft = 0.0f; 2229 dstTop = 0.0f; 2230 2231 dstRight = srcRight - srcLeft; 2232 dstBottom = srcBottom - srcTop; 2233 } 2234 2235 if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) { 2236 drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom, 2237 texture->id, paint, 2238 &mMeshVertices[0].x, &mMeshVertices[0].u, 2239 GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform); 2240 } else { 2241 drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, 2242 texture->id, paint, texture->blend, 2243 &mMeshVertices[0].x, &mMeshVertices[0].u, 2244 GL_TRIANGLE_STRIP, gMeshCount, false, ignoreTransform); 2245 } 2246 2247 if (CC_UNLIKELY(useScaleTransform)) { 2248 restore(); 2249 } 2250 2251 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 2252 2253 return DrawGlInfo::kStatusDrew; 2254} 2255 2256status_t OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch, 2257 float left, float top, float right, float bottom, const SkPaint* paint) { 2258 if (quickRejectSetupScissor(left, top, right, bottom)) { 2259 return DrawGlInfo::kStatusDone; 2260 } 2261 2262 AssetAtlas::Entry* entry = mCaches.assetAtlas.getEntry(bitmap); 2263 const Patch* mesh = mCaches.patchCache.get(entry, bitmap->width(), bitmap->height(), 2264 right - left, bottom - top, patch); 2265 2266 return drawPatch(bitmap, mesh, entry, left, top, right, bottom, paint); 2267} 2268 2269status_t OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh, 2270 AssetAtlas::Entry* entry, float left, float top, float right, float bottom, 2271 const SkPaint* paint) { 2272 if (quickRejectSetupScissor(left, top, right, bottom)) { 2273 return DrawGlInfo::kStatusDone; 2274 } 2275 2276 if (CC_LIKELY(mesh && mesh->verticesCount > 0)) { 2277 mCaches.activeTexture(0); 2278 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 2279 if (!texture) return DrawGlInfo::kStatusDone; 2280 const AutoTexture autoCleanup(texture); 2281 2282 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2283 texture->setFilter(GL_LINEAR, true); 2284 2285 const bool pureTranslate = currentTransform()->isPureTranslate(); 2286 // Mark the current layer dirty where we are going to draw the patch 2287 if (hasLayer() && mesh->hasEmptyQuads) { 2288 const float offsetX = left + currentTransform()->getTranslateX(); 2289 const float offsetY = top + currentTransform()->getTranslateY(); 2290 const size_t count = mesh->quads.size(); 2291 for (size_t i = 0; i < count; i++) { 2292 const Rect& bounds = mesh->quads.itemAt(i); 2293 if (CC_LIKELY(pureTranslate)) { 2294 const float x = (int) floorf(bounds.left + offsetX + 0.5f); 2295 const float y = (int) floorf(bounds.top + offsetY + 0.5f); 2296 dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight()); 2297 } else { 2298 dirtyLayer(left + bounds.left, top + bounds.top, 2299 left + bounds.right, top + bounds.bottom, *currentTransform()); 2300 } 2301 } 2302 } 2303 2304 bool ignoreTransform = false; 2305 if (CC_LIKELY(pureTranslate)) { 2306 const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f); 2307 const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f); 2308 2309 right = x + right - left; 2310 bottom = y + bottom - top; 2311 left = x; 2312 top = y; 2313 ignoreTransform = true; 2314 } 2315 drawIndexedTextureMesh(left, top, right, bottom, texture->id, paint, 2316 texture->blend, (GLvoid*) mesh->offset, (GLvoid*) mesh->textureOffset, 2317 GL_TRIANGLES, mesh->indexCount, false, ignoreTransform, 2318 mCaches.patchCache.getMeshBuffer(), kModelViewMode_Translate, !mesh->hasEmptyQuads); 2319 } 2320 2321 return DrawGlInfo::kStatusDrew; 2322} 2323 2324/** 2325 * Important note: this method is intended to draw batches of 9-patch objects and 2326 * will not set the scissor enable or dirty the current layer, if any. 2327 * The caller is responsible for properly dirtying the current layer. 2328 */ 2329status_t OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 2330 TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint) { 2331 mCaches.activeTexture(0); 2332 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 2333 if (!texture) return DrawGlInfo::kStatusDone; 2334 const AutoTexture autoCleanup(texture); 2335 2336 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2337 texture->setFilter(GL_LINEAR, true); 2338 2339 drawIndexedTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, paint, 2340 texture->blend, &vertices[0].x, &vertices[0].u, 2341 GL_TRIANGLES, indexCount, false, true, 0, kModelViewMode_Translate, false); 2342 2343 return DrawGlInfo::kStatusDrew; 2344} 2345 2346status_t OpenGLRenderer::drawVertexBuffer(VertexBufferMode mode, 2347 const VertexBuffer& vertexBuffer, const SkPaint* paint, bool useOffset) { 2348 // not missing call to quickReject/dirtyLayer, always done at a higher level 2349 if (!vertexBuffer.getVertexCount()) { 2350 // no vertices to draw 2351 return DrawGlInfo::kStatusDone; 2352 } 2353 2354 int color = paint->getColor(); 2355 bool isAA = paint->isAntiAlias(); 2356 2357 setupDraw(); 2358 setupDrawNoTexture(); 2359 if (isAA) setupDrawAA(); 2360 setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha); 2361 setupDrawColorFilter(getColorFilter(paint)); 2362 setupDrawShader(); 2363 setupDrawBlending(paint, isAA); 2364 setupDrawProgram(); 2365 setupDrawModelView(kModelViewMode_Translate, useOffset, 0, 0, 0, 0); 2366 setupDrawColorUniforms(); 2367 setupDrawColorFilterUniforms(getColorFilter(paint)); 2368 setupDrawShaderUniforms(); 2369 2370 const void* vertices = vertexBuffer.getBuffer(); 2371 bool force = mCaches.unbindMeshBuffer(); 2372 mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride); 2373 mCaches.resetTexCoordsVertexPointer(); 2374 2375 2376 int alphaSlot = -1; 2377 if (isAA) { 2378 void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset; 2379 alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha"); 2380 // TODO: avoid enable/disable in back to back uses of the alpha attribute 2381 glEnableVertexAttribArray(alphaSlot); 2382 glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords); 2383 } 2384 2385 if (mode == kVertexBufferMode_Standard) { 2386 mCaches.unbindIndicesBuffer(); 2387 glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getVertexCount()); 2388 } else if (mode == kVertexBufferMode_OnePolyRingShadow) { 2389 mCaches.bindShadowIndicesBuffer(); 2390 glDrawElements(GL_TRIANGLE_STRIP, ONE_POLY_RING_SHADOW_INDEX_COUNT, GL_UNSIGNED_SHORT, 0); 2391 } else if (mode == kVertexBufferMode_TwoPolyRingShadow) { 2392 mCaches.bindShadowIndicesBuffer(); 2393 glDrawElements(GL_TRIANGLE_STRIP, TWO_POLY_RING_SHADOW_INDEX_COUNT, GL_UNSIGNED_SHORT, 0); 2394 } 2395 2396 if (isAA) { 2397 glDisableVertexAttribArray(alphaSlot); 2398 } 2399 2400 return DrawGlInfo::kStatusDrew; 2401} 2402 2403/** 2404 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to 2405 * that of AA lines in the drawLines() function. We expand the convex path by a half pixel in 2406 * screen space in all directions. However, instead of using a fragment shader to compute the 2407 * translucency of the color from its position, we simply use a varying parameter to define how far 2408 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used. 2409 * 2410 * Doesn't yet support joins, caps, or path effects. 2411 */ 2412status_t OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) { 2413 VertexBuffer vertexBuffer; 2414 // TODO: try clipping large paths to viewport 2415 PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer); 2416 2417 if (hasLayer()) { 2418 SkRect bounds = path.getBounds(); 2419 PathTessellator::expandBoundsForStroke(bounds, paint); 2420 dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *currentTransform()); 2421 } 2422 2423 return drawVertexBuffer(kVertexBufferMode_Standard, vertexBuffer, paint); 2424} 2425 2426/** 2427 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha 2428 * and additional geometry for defining an alpha slope perimeter. 2429 * 2430 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some 2431 * unexpected results, and may vary between hardware devices. Previously we used a varying-base 2432 * in-shader alpha region, but found it to be taxing on some GPUs. 2433 * 2434 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce 2435 * memory transfer by removing need for degenerate vertices. 2436 */ 2437status_t OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) { 2438 if (currentSnapshot()->isIgnored() || count < 4) return DrawGlInfo::kStatusDone; 2439 2440 count &= ~0x3; // round down to nearest four 2441 2442 VertexBuffer buffer; 2443 SkRect bounds; 2444 PathTessellator::tessellateLines(points, count, paint, *currentTransform(), bounds, buffer); 2445 2446 // can't pass paint, since style would be checked for outset. outset done by tessellation. 2447 if (quickRejectSetupScissor(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom)) { 2448 return DrawGlInfo::kStatusDone; 2449 } 2450 2451 dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *currentTransform()); 2452 2453 bool useOffset = !paint->isAntiAlias(); 2454 return drawVertexBuffer(kVertexBufferMode_Standard, buffer, paint, useOffset); 2455} 2456 2457status_t OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) { 2458 if (currentSnapshot()->isIgnored() || count < 2) return DrawGlInfo::kStatusDone; 2459 2460 count &= ~0x1; // round down to nearest two 2461 2462 VertexBuffer buffer; 2463 SkRect bounds; 2464 PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), bounds, buffer); 2465 2466 // can't pass paint, since style would be checked for outset. outset done by tessellation. 2467 if (quickRejectSetupScissor(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom)) { 2468 return DrawGlInfo::kStatusDone; 2469 } 2470 2471 dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *currentTransform()); 2472 2473 bool useOffset = !paint->isAntiAlias(); 2474 return drawVertexBuffer(kVertexBufferMode_Standard, buffer, paint, useOffset); 2475} 2476 2477status_t OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 2478 // No need to check against the clip, we fill the clip region 2479 if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone; 2480 2481 Rect clip(*currentClipRect()); 2482 clip.snapToPixelBoundaries(); 2483 2484 SkPaint paint; 2485 paint.setColor(color); 2486 paint.setXfermodeMode(mode); 2487 2488 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true); 2489 2490 return DrawGlInfo::kStatusDrew; 2491} 2492 2493status_t OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, 2494 const SkPaint* paint) { 2495 if (!texture) return DrawGlInfo::kStatusDone; 2496 const AutoTexture autoCleanup(texture); 2497 2498 const float x = left + texture->left - texture->offset; 2499 const float y = top + texture->top - texture->offset; 2500 2501 drawPathTexture(texture, x, y, paint); 2502 2503 return DrawGlInfo::kStatusDrew; 2504} 2505 2506status_t OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom, 2507 float rx, float ry, const SkPaint* p) { 2508 if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) || 2509 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) { 2510 return DrawGlInfo::kStatusDone; 2511 } 2512 2513 if (p->getPathEffect() != 0) { 2514 mCaches.activeTexture(0); 2515 const PathTexture* texture = mCaches.pathCache.getRoundRect( 2516 right - left, bottom - top, rx, ry, p); 2517 return drawShape(left, top, texture, p); 2518 } 2519 2520 SkPath path; 2521 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2522 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2523 float outset = p->getStrokeWidth() / 2; 2524 rect.outset(outset, outset); 2525 rx += outset; 2526 ry += outset; 2527 } 2528 path.addRoundRect(rect, rx, ry); 2529 return drawConvexPath(path, p); 2530} 2531 2532status_t OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) { 2533 if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(x - radius, y - radius, 2534 x + radius, y + radius, p) || 2535 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) { 2536 return DrawGlInfo::kStatusDone; 2537 } 2538 if (p->getPathEffect() != 0) { 2539 mCaches.activeTexture(0); 2540 const PathTexture* texture = mCaches.pathCache.getCircle(radius, p); 2541 return drawShape(x - radius, y - radius, texture, p); 2542 } 2543 2544 SkPath path; 2545 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2546 path.addCircle(x, y, radius + p->getStrokeWidth() / 2); 2547 } else { 2548 path.addCircle(x, y, radius); 2549 } 2550 return drawConvexPath(path, p); 2551} 2552 2553status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom, 2554 const SkPaint* p) { 2555 if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) || 2556 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) { 2557 return DrawGlInfo::kStatusDone; 2558 } 2559 2560 if (p->getPathEffect() != 0) { 2561 mCaches.activeTexture(0); 2562 const PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p); 2563 return drawShape(left, top, texture, p); 2564 } 2565 2566 SkPath path; 2567 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2568 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2569 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2570 } 2571 path.addOval(rect); 2572 return drawConvexPath(path, p); 2573} 2574 2575status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom, 2576 float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) { 2577 if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) || 2578 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) { 2579 return DrawGlInfo::kStatusDone; 2580 } 2581 2582 if (fabs(sweepAngle) >= 360.0f) { 2583 return drawOval(left, top, right, bottom, p); 2584 } 2585 2586 // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180) 2587 if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || useCenter) { 2588 mCaches.activeTexture(0); 2589 const PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top, 2590 startAngle, sweepAngle, useCenter, p); 2591 return drawShape(left, top, texture, p); 2592 } 2593 2594 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2595 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2596 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2597 } 2598 2599 SkPath path; 2600 if (useCenter) { 2601 path.moveTo(rect.centerX(), rect.centerY()); 2602 } 2603 path.arcTo(rect, startAngle, sweepAngle, !useCenter); 2604 if (useCenter) { 2605 path.close(); 2606 } 2607 return drawConvexPath(path, p); 2608} 2609 2610// See SkPaintDefaults.h 2611#define SkPaintDefaults_MiterLimit SkIntToScalar(4) 2612 2613status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom, 2614 const SkPaint* p) { 2615 if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) || 2616 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) { 2617 return DrawGlInfo::kStatusDone; 2618 } 2619 2620 if (p->getStyle() != SkPaint::kFill_Style) { 2621 // only fill style is supported by drawConvexPath, since others have to handle joins 2622 if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join || 2623 p->getStrokeMiter() != SkPaintDefaults_MiterLimit) { 2624 mCaches.activeTexture(0); 2625 const PathTexture* texture = 2626 mCaches.pathCache.getRect(right - left, bottom - top, p); 2627 return drawShape(left, top, texture, p); 2628 } 2629 2630 SkPath path; 2631 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2632 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2633 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2634 } 2635 path.addRect(rect); 2636 return drawConvexPath(path, p); 2637 } 2638 2639 if (p->isAntiAlias() && !currentTransform()->isSimple()) { 2640 SkPath path; 2641 path.addRect(left, top, right, bottom); 2642 return drawConvexPath(path, p); 2643 } else { 2644 drawColorRect(left, top, right, bottom, p); 2645 return DrawGlInfo::kStatusDrew; 2646 } 2647} 2648 2649void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text, 2650 int bytesCount, int count, const float* positions, 2651 FontRenderer& fontRenderer, int alpha, float x, float y) { 2652 mCaches.activeTexture(0); 2653 2654 TextShadow textShadow; 2655 if (!getTextShadow(paint, &textShadow)) { 2656 LOG_ALWAYS_FATAL("failed to query shadow attributes"); 2657 } 2658 2659 // NOTE: The drop shadow will not perform gamma correction 2660 // if shader-based correction is enabled 2661 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 2662 const ShadowTexture* shadow = mCaches.dropShadowCache.get( 2663 paint, text, bytesCount, count, textShadow.radius, positions); 2664 // If the drop shadow exceeds the max texture size or couldn't be 2665 // allocated, skip drawing 2666 if (!shadow) return; 2667 const AutoTexture autoCleanup(shadow); 2668 2669 const float sx = x - shadow->left + textShadow.dx; 2670 const float sy = y - shadow->top + textShadow.dy; 2671 2672 const int shadowAlpha = ((textShadow.color >> 24) & 0xFF) * mSnapshot->alpha; 2673 if (mDrawModifiers.mShader) { 2674 textShadow.color = SK_ColorWHITE; 2675 } 2676 2677 setupDraw(); 2678 setupDrawWithTexture(true); 2679 setupDrawAlpha8Color(textShadow.color, shadowAlpha < 255 ? shadowAlpha : alpha); 2680 setupDrawColorFilter(getColorFilter(paint)); 2681 setupDrawShader(); 2682 setupDrawBlending(paint, true); 2683 setupDrawProgram(); 2684 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 2685 sx, sy, sx + shadow->width, sy + shadow->height); 2686 setupDrawTexture(shadow->id); 2687 setupDrawPureColorUniforms(); 2688 setupDrawColorFilterUniforms(getColorFilter(paint)); 2689 setupDrawShaderUniforms(); 2690 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 2691 2692 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 2693} 2694 2695bool OpenGLRenderer::canSkipText(const SkPaint* paint) const { 2696 float alpha = (hasTextShadow(paint) ? 1.0f : paint->getAlpha()) * mSnapshot->alpha; 2697 return alpha == 0.0f && getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode; 2698} 2699 2700status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count, 2701 const float* positions, const SkPaint* paint) { 2702 if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint)) { 2703 return DrawGlInfo::kStatusDone; 2704 } 2705 2706 // NOTE: Skia does not support perspective transform on drawPosText yet 2707 if (!currentTransform()->isSimple()) { 2708 return DrawGlInfo::kStatusDone; 2709 } 2710 2711 mCaches.enableScissor(); 2712 2713 float x = 0.0f; 2714 float y = 0.0f; 2715 const bool pureTranslate = currentTransform()->isPureTranslate(); 2716 if (pureTranslate) { 2717 x = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f); 2718 y = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f); 2719 } 2720 2721 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2722 fontRenderer.setFont(paint, mat4::identity()); 2723 2724 int alpha; 2725 SkXfermode::Mode mode; 2726 getAlphaAndMode(paint, &alpha, &mode); 2727 2728 if (CC_UNLIKELY(hasTextShadow(paint))) { 2729 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, 2730 alpha, 0.0f, 0.0f); 2731 } 2732 2733 // Pick the appropriate texture filtering 2734 bool linearFilter = currentTransform()->changesBounds(); 2735 if (pureTranslate && !linearFilter) { 2736 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2737 } 2738 fontRenderer.setTextureFiltering(linearFilter); 2739 2740 const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip(); 2741 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2742 2743 const bool hasActiveLayer = hasLayer(); 2744 2745 TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint); 2746 if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y, 2747 positions, hasActiveLayer ? &bounds : NULL, &functor)) { 2748 if (hasActiveLayer) { 2749 if (!pureTranslate) { 2750 currentTransform()->mapRect(bounds); 2751 } 2752 dirtyLayerUnchecked(bounds, getRegion()); 2753 } 2754 } 2755 2756 return DrawGlInfo::kStatusDrew; 2757} 2758 2759mat4 OpenGLRenderer::findBestFontTransform(const mat4& transform) const { 2760 mat4 fontTransform; 2761 if (CC_LIKELY(transform.isPureTranslate())) { 2762 fontTransform = mat4::identity(); 2763 } else { 2764 if (CC_UNLIKELY(transform.isPerspective())) { 2765 fontTransform = mat4::identity(); 2766 } else { 2767 float sx, sy; 2768 currentTransform()->decomposeScale(sx, sy); 2769 fontTransform.loadScale(sx, sy, 1.0f); 2770 } 2771 } 2772 return fontTransform; 2773} 2774 2775status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y, 2776 const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds, 2777 DrawOpMode drawOpMode) { 2778 2779 if (drawOpMode == kDrawOpMode_Immediate) { 2780 // The checks for corner-case ignorable text and quick rejection is only done for immediate 2781 // drawing as ops from DeferredDisplayList are already filtered for these 2782 if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint) || 2783 quickRejectSetupScissor(bounds)) { 2784 return DrawGlInfo::kStatusDone; 2785 } 2786 } 2787 2788 const float oldX = x; 2789 const float oldY = y; 2790 2791 const mat4& transform = *currentTransform(); 2792 const bool pureTranslate = transform.isPureTranslate(); 2793 2794 if (CC_LIKELY(pureTranslate)) { 2795 x = (int) floorf(x + transform.getTranslateX() + 0.5f); 2796 y = (int) floorf(y + transform.getTranslateY() + 0.5f); 2797 } 2798 2799 int alpha; 2800 SkXfermode::Mode mode; 2801 getAlphaAndMode(paint, &alpha, &mode); 2802 2803 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2804 2805 if (CC_UNLIKELY(hasTextShadow(paint))) { 2806 fontRenderer.setFont(paint, mat4::identity()); 2807 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, 2808 alpha, oldX, oldY); 2809 } 2810 2811 const bool hasActiveLayer = hasLayer(); 2812 2813 // We only pass a partial transform to the font renderer. That partial 2814 // matrix defines how glyphs are rasterized. Typically we want glyphs 2815 // to be rasterized at their final size on screen, which means the partial 2816 // matrix needs to take the scale factor into account. 2817 // When a partial matrix is used to transform glyphs during rasterization, 2818 // the mesh is generated with the inverse transform (in the case of scale, 2819 // the mesh is generated at 1.0 / scale for instance.) This allows us to 2820 // apply the full transform matrix at draw time in the vertex shader. 2821 // Applying the full matrix in the shader is the easiest way to handle 2822 // rotation and perspective and allows us to always generated quads in the 2823 // font renderer which greatly simplifies the code, clipping in particular. 2824 mat4 fontTransform = findBestFontTransform(transform); 2825 fontRenderer.setFont(paint, fontTransform); 2826 2827 // Pick the appropriate texture filtering 2828 bool linearFilter = !pureTranslate || fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2829 fontRenderer.setTextureFiltering(linearFilter); 2830 2831 // TODO: Implement better clipping for scaled/rotated text 2832 const Rect* clip = !pureTranslate ? NULL : currentClipRect(); 2833 Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2834 2835 bool status; 2836 TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint); 2837 2838 // don't call issuedrawcommand, do it at end of batch 2839 bool forceFinish = (drawOpMode != kDrawOpMode_Defer); 2840 if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) { 2841 SkPaint paintCopy(*paint); 2842 paintCopy.setTextAlign(SkPaint::kLeft_Align); 2843 status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y, 2844 positions, hasActiveLayer ? &layerBounds : NULL, &functor, forceFinish); 2845 } else { 2846 status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y, 2847 positions, hasActiveLayer ? &layerBounds : NULL, &functor, forceFinish); 2848 } 2849 2850 if ((status || drawOpMode != kDrawOpMode_Immediate) && hasActiveLayer) { 2851 if (!pureTranslate) { 2852 transform.mapRect(layerBounds); 2853 } 2854 dirtyLayerUnchecked(layerBounds, getRegion()); 2855 } 2856 2857 drawTextDecorations(totalAdvance, oldX, oldY, paint); 2858 2859 return DrawGlInfo::kStatusDrew; 2860} 2861 2862status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, 2863 const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) { 2864 if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint)) { 2865 return DrawGlInfo::kStatusDone; 2866 } 2867 2868 // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics 2869 mCaches.enableScissor(); 2870 2871 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2872 fontRenderer.setFont(paint, mat4::identity()); 2873 fontRenderer.setTextureFiltering(true); 2874 2875 int alpha; 2876 SkXfermode::Mode mode; 2877 getAlphaAndMode(paint, &alpha, &mode); 2878 TextSetupFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint); 2879 2880 const Rect* clip = &mSnapshot->getLocalClip(); 2881 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2882 2883 const bool hasActiveLayer = hasLayer(); 2884 2885 if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path, 2886 hOffset, vOffset, hasActiveLayer ? &bounds : NULL, &functor)) { 2887 if (hasActiveLayer) { 2888 currentTransform()->mapRect(bounds); 2889 dirtyLayerUnchecked(bounds, getRegion()); 2890 } 2891 } 2892 2893 return DrawGlInfo::kStatusDrew; 2894} 2895 2896status_t OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) { 2897 if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone; 2898 2899 mCaches.activeTexture(0); 2900 2901 const PathTexture* texture = mCaches.pathCache.get(path, paint); 2902 if (!texture) return DrawGlInfo::kStatusDone; 2903 const AutoTexture autoCleanup(texture); 2904 2905 const float x = texture->left - texture->offset; 2906 const float y = texture->top - texture->offset; 2907 2908 drawPathTexture(texture, x, y, paint); 2909 2910 return DrawGlInfo::kStatusDrew; 2911} 2912 2913status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y) { 2914 if (!layer) { 2915 return DrawGlInfo::kStatusDone; 2916 } 2917 2918 mat4* transform = NULL; 2919 if (layer->isTextureLayer()) { 2920 transform = &layer->getTransform(); 2921 if (!transform->isIdentity()) { 2922 save(SkCanvas::kMatrix_SaveFlag); 2923 concatMatrix(*transform); 2924 } 2925 } 2926 2927 bool clipRequired = false; 2928 const bool rejected = calculateQuickRejectForScissor(x, y, 2929 x + layer->layer.getWidth(), y + layer->layer.getHeight(), &clipRequired, NULL, false); 2930 2931 if (rejected) { 2932 if (transform && !transform->isIdentity()) { 2933 restore(); 2934 } 2935 return DrawGlInfo::kStatusDone; 2936 } 2937 2938 updateLayer(layer, true); 2939 2940 mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired); 2941 mCaches.activeTexture(0); 2942 2943 if (CC_LIKELY(!layer->region.isEmpty())) { 2944 if (layer->region.isRect()) { 2945 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, 2946 composeLayerRect(layer, layer->regionRect)); 2947 } else if (layer->mesh) { 2948 2949 const float a = getLayerAlpha(layer); 2950 setupDraw(); 2951 setupDrawWithTexture(); 2952 setupDrawColor(a, a, a, a); 2953 setupDrawColorFilter(layer->getColorFilter()); 2954 setupDrawBlending(layer); 2955 setupDrawProgram(); 2956 setupDrawPureColorUniforms(); 2957 setupDrawColorFilterUniforms(layer->getColorFilter()); 2958 setupDrawTexture(layer->getTexture()); 2959 if (CC_LIKELY(currentTransform()->isPureTranslate())) { 2960 int tx = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f); 2961 int ty = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f); 2962 2963 layer->setFilter(GL_NEAREST); 2964 setupDrawModelView(kModelViewMode_Translate, false, tx, ty, 2965 tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true); 2966 } else { 2967 layer->setFilter(GL_LINEAR); 2968 setupDrawModelView(kModelViewMode_Translate, false, x, y, 2969 x + layer->layer.getWidth(), y + layer->layer.getHeight()); 2970 } 2971 2972 TextureVertex* mesh = &layer->mesh[0]; 2973 GLsizei elementsCount = layer->meshElementCount; 2974 2975 while (elementsCount > 0) { 2976 GLsizei drawCount = min(elementsCount, (GLsizei) gMaxNumberOfQuads * 6); 2977 2978 setupDrawMeshIndices(&mesh[0].x, &mesh[0].u); 2979 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, 2980 glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, NULL)); 2981 2982 elementsCount -= drawCount; 2983 // Though there are 4 vertices in a quad, we use 6 indices per 2984 // quad to draw with GL_TRIANGLES 2985 mesh += (drawCount / 6) * 4; 2986 } 2987 2988#if DEBUG_LAYERS_AS_REGIONS 2989 drawRegionRectsDebug(layer->region); 2990#endif 2991 } 2992 2993 if (layer->debugDrawUpdate) { 2994 layer->debugDrawUpdate = false; 2995 2996 SkPaint paint; 2997 paint.setColor(0x7f00ff00); 2998 drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint); 2999 } 3000 } 3001 layer->hasDrawnSinceUpdate = true; 3002 3003 if (transform && !transform->isIdentity()) { 3004 restore(); 3005 } 3006 3007 return DrawGlInfo::kStatusDrew; 3008} 3009 3010/////////////////////////////////////////////////////////////////////////////// 3011// Shaders 3012/////////////////////////////////////////////////////////////////////////////// 3013 3014void OpenGLRenderer::resetShader() { 3015 mDrawModifiers.mShader = NULL; 3016} 3017 3018void OpenGLRenderer::setupShader(SkiaShader* shader) { 3019 mDrawModifiers.mShader = shader; 3020 if (mDrawModifiers.mShader) { 3021 mDrawModifiers.mShader->setCaches(mCaches); 3022 } 3023} 3024 3025/////////////////////////////////////////////////////////////////////////////// 3026// Draw filters 3027/////////////////////////////////////////////////////////////////////////////// 3028 3029void OpenGLRenderer::resetPaintFilter() { 3030 // when clearing the PaintFilter, the masks should also be cleared for simple DrawModifier 3031 // comparison, see MergingDrawBatch::canMergeWith 3032 mDrawModifiers.mHasDrawFilter = false; 3033 mDrawModifiers.mPaintFilterClearBits = 0; 3034 mDrawModifiers.mPaintFilterSetBits = 0; 3035} 3036 3037void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) { 3038 mDrawModifiers.mHasDrawFilter = true; 3039 mDrawModifiers.mPaintFilterClearBits = clearBits & SkPaint::kAllFlags; 3040 mDrawModifiers.mPaintFilterSetBits = setBits & SkPaint::kAllFlags; 3041} 3042 3043const SkPaint* OpenGLRenderer::filterPaint(const SkPaint* paint) { 3044 if (CC_LIKELY(!mDrawModifiers.mHasDrawFilter || !paint)) { 3045 return paint; 3046 } 3047 3048 uint32_t flags = paint->getFlags(); 3049 3050 mFilteredPaint = *paint; 3051 mFilteredPaint.setFlags((flags & ~mDrawModifiers.mPaintFilterClearBits) | 3052 mDrawModifiers.mPaintFilterSetBits); 3053 3054 return &mFilteredPaint; 3055} 3056 3057/////////////////////////////////////////////////////////////////////////////// 3058// Drawing implementation 3059/////////////////////////////////////////////////////////////////////////////// 3060 3061Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) { 3062 Texture* texture = mCaches.assetAtlas.getEntryTexture(bitmap); 3063 if (!texture) { 3064 return mCaches.textureCache.get(bitmap); 3065 } 3066 return texture; 3067} 3068 3069void OpenGLRenderer::drawPathTexture(const PathTexture* texture, 3070 float x, float y, const SkPaint* paint) { 3071 if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) { 3072 return; 3073 } 3074 3075 int alpha; 3076 SkXfermode::Mode mode; 3077 getAlphaAndMode(paint, &alpha, &mode); 3078 3079 setupDraw(); 3080 setupDrawWithTexture(true); 3081 setupDrawAlpha8Color(paint->getColor(), alpha); 3082 setupDrawColorFilter(getColorFilter(paint)); 3083 setupDrawShader(); 3084 setupDrawBlending(paint, true); 3085 setupDrawProgram(); 3086 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 3087 x, y, x + texture->width, y + texture->height); 3088 setupDrawTexture(texture->id); 3089 setupDrawPureColorUniforms(); 3090 setupDrawColorFilterUniforms(getColorFilter(paint)); 3091 setupDrawShaderUniforms(); 3092 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 3093 3094 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 3095} 3096 3097// Same values used by Skia 3098#define kStdStrikeThru_Offset (-6.0f / 21.0f) 3099#define kStdUnderline_Offset (1.0f / 9.0f) 3100#define kStdUnderline_Thickness (1.0f / 18.0f) 3101 3102void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y, 3103 const SkPaint* paint) { 3104 // Handle underline and strike-through 3105 uint32_t flags = paint->getFlags(); 3106 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) { 3107 SkPaint paintCopy(*paint); 3108 3109 if (CC_LIKELY(underlineWidth > 0.0f)) { 3110 const float textSize = paintCopy.getTextSize(); 3111 const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f); 3112 3113 const float left = x; 3114 float top = 0.0f; 3115 3116 int linesCount = 0; 3117 if (flags & SkPaint::kUnderlineText_Flag) linesCount++; 3118 if (flags & SkPaint::kStrikeThruText_Flag) linesCount++; 3119 3120 const int pointsCount = 4 * linesCount; 3121 float points[pointsCount]; 3122 int currentPoint = 0; 3123 3124 if (flags & SkPaint::kUnderlineText_Flag) { 3125 top = y + textSize * kStdUnderline_Offset; 3126 points[currentPoint++] = left; 3127 points[currentPoint++] = top; 3128 points[currentPoint++] = left + underlineWidth; 3129 points[currentPoint++] = top; 3130 } 3131 3132 if (flags & SkPaint::kStrikeThruText_Flag) { 3133 top = y + textSize * kStdStrikeThru_Offset; 3134 points[currentPoint++] = left; 3135 points[currentPoint++] = top; 3136 points[currentPoint++] = left + underlineWidth; 3137 points[currentPoint++] = top; 3138 } 3139 3140 paintCopy.setStrokeWidth(strokeWidth); 3141 3142 drawLines(&points[0], pointsCount, &paintCopy); 3143 } 3144 } 3145} 3146 3147status_t OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) { 3148 if (currentSnapshot()->isIgnored()) { 3149 return DrawGlInfo::kStatusDone; 3150 } 3151 3152 return drawColorRects(rects, count, paint, false, true, true); 3153} 3154 3155static void mapPointFakeZ(Vector3& point, const mat4& transformXY, const mat4& transformZ) { 3156 // map z coordinate with true 3d matrix 3157 point.z = transformZ.mapZ(point); 3158 3159 // map x,y coordinates with draw/Skia matrix 3160 transformXY.mapPoint(point.x, point.y); 3161} 3162 3163status_t OpenGLRenderer::drawShadow(const mat4& casterTransformXY, const mat4& casterTransformZ, 3164 float casterAlpha, bool casterUnclipped, const SkPath* casterPerimeter) { 3165 if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone; 3166 3167 // TODO: use quickRejectWithScissor. For now, always force enable scissor. 3168 mCaches.enableScissor(); 3169 3170 SkPaint paint; 3171 paint.setAntiAlias(true); // want to use AlphaVertex 3172 3173 // tessellate caster outline into a 2d polygon 3174 Vector<Vertex> casterVertices2d; 3175 const float casterRefinementThresholdSquared = 20.0f; // TODO: experiment with this value 3176 PathTessellator::approximatePathOutlineVertices(*casterPerimeter, 3177 casterRefinementThresholdSquared, casterVertices2d); 3178 if (!ShadowTessellator::isClockwisePath(*casterPerimeter)) { 3179 ShadowTessellator::reverseVertexArray(casterVertices2d.editArray(), 3180 casterVertices2d.size()); 3181 } 3182 3183 if (casterVertices2d.size() == 0) { 3184 // empty caster polygon computed from path 3185 return DrawGlInfo::kStatusDone; 3186 } 3187 3188 // map 2d caster poly into 3d 3189 const int casterVertexCount = casterVertices2d.size(); 3190 Vector3 casterPolygon[casterVertexCount]; 3191 float minZ = FLT_MAX; 3192 float maxZ = -FLT_MAX; 3193 for (int i = 0; i < casterVertexCount; i++) { 3194 const Vertex& point2d = casterVertices2d[i]; 3195 casterPolygon[i] = Vector3(point2d.x, point2d.y, 0); 3196 mapPointFakeZ(casterPolygon[i], casterTransformXY, casterTransformZ); 3197 minZ = fmin(minZ, casterPolygon[i].z); 3198 maxZ = fmax(maxZ, casterPolygon[i].z); 3199 } 3200 3201 // map the centroid of the caster into 3d 3202 Vector2 centroid = ShadowTessellator::centroid2d( 3203 reinterpret_cast<const Vector2*>(casterVertices2d.array()), 3204 casterVertexCount); 3205 Vector3 centroid3d(centroid.x, centroid.y, 0); 3206 mapPointFakeZ(centroid3d, casterTransformXY, casterTransformZ); 3207 3208 // if the caster intersects the z=0 plane, lift it in Z so it doesn't 3209 if (minZ < SHADOW_MIN_CASTER_Z) { 3210 float casterLift = SHADOW_MIN_CASTER_Z - minZ; 3211 for (int i = 0; i < casterVertexCount; i++) { 3212 casterPolygon[i].z += casterLift; 3213 } 3214 centroid3d.z += casterLift; 3215 } 3216 3217 // Check whether we want to draw the shadow at all by checking the caster's 3218 // bounds against clip. 3219 // We only have ortho projection, so we can just ignore the Z in caster for 3220 // simple rejection calculation. 3221 Rect localClip = mSnapshot->getLocalClip(); 3222 Rect casterBounds(casterPerimeter->getBounds()); 3223 casterTransformXY.mapRect(casterBounds); 3224 3225 bool isCasterOpaque = (casterAlpha == 1.0f) && casterUnclipped; 3226 // draw caster's shadows 3227 if (mCaches.propertyAmbientShadowStrength > 0) { 3228 paint.setARGB(casterAlpha * mCaches.propertyAmbientShadowStrength, 0, 0, 0); 3229 VertexBuffer ambientShadowVertexBuffer; 3230 VertexBufferMode vertexBufferMode = ShadowTessellator::tessellateAmbientShadow( 3231 isCasterOpaque, casterPolygon, casterVertexCount, centroid3d, 3232 casterBounds, localClip, maxZ, ambientShadowVertexBuffer); 3233 drawVertexBuffer(vertexBufferMode, ambientShadowVertexBuffer, &paint); 3234 } 3235 3236 if (mCaches.propertySpotShadowStrength > 0) { 3237 paint.setARGB(casterAlpha * mCaches.propertySpotShadowStrength, 0, 0, 0); 3238 VertexBuffer spotShadowVertexBuffer; 3239 VertexBufferMode vertexBufferMode = ShadowTessellator::tessellateSpotShadow( 3240 isCasterOpaque, casterPolygon, casterVertexCount, 3241 *currentTransform(), getWidth(), getHeight(), casterBounds, localClip, 3242 spotShadowVertexBuffer); 3243 drawVertexBuffer(vertexBufferMode, spotShadowVertexBuffer, &paint); 3244 } 3245 3246 return DrawGlInfo::kStatusDrew; 3247} 3248 3249status_t OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint, 3250 bool ignoreTransform, bool dirty, bool clip) { 3251 if (count == 0) { 3252 return DrawGlInfo::kStatusDone; 3253 } 3254 3255 int color = paint->getColor(); 3256 // If a shader is set, preserve only the alpha 3257 if (mDrawModifiers.mShader) { 3258 color |= 0x00ffffff; 3259 } 3260 3261 float left = FLT_MAX; 3262 float top = FLT_MAX; 3263 float right = FLT_MIN; 3264 float bottom = FLT_MIN; 3265 3266 Vertex mesh[count]; 3267 Vertex* vertex = mesh; 3268 3269 for (int index = 0; index < count; index += 4) { 3270 float l = rects[index + 0]; 3271 float t = rects[index + 1]; 3272 float r = rects[index + 2]; 3273 float b = rects[index + 3]; 3274 3275 Vertex::set(vertex++, l, t); 3276 Vertex::set(vertex++, r, t); 3277 Vertex::set(vertex++, l, b); 3278 Vertex::set(vertex++, r, b); 3279 3280 left = fminf(left, l); 3281 top = fminf(top, t); 3282 right = fmaxf(right, r); 3283 bottom = fmaxf(bottom, b); 3284 } 3285 3286 if (clip && quickRejectSetupScissor(left, top, right, bottom)) { 3287 return DrawGlInfo::kStatusDone; 3288 } 3289 3290 setupDraw(); 3291 setupDrawNoTexture(); 3292 setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha); 3293 setupDrawShader(); 3294 setupDrawColorFilter(getColorFilter(paint)); 3295 setupDrawBlending(paint); 3296 setupDrawProgram(); 3297 setupDrawDirtyRegionsDisabled(); 3298 setupDrawModelView(kModelViewMode_Translate, false, 3299 0.0f, 0.0f, 0.0f, 0.0f, ignoreTransform); 3300 setupDrawColorUniforms(); 3301 setupDrawShaderUniforms(); 3302 setupDrawColorFilterUniforms(getColorFilter(paint)); 3303 3304 if (dirty && hasLayer()) { 3305 dirtyLayer(left, top, right, bottom, *currentTransform()); 3306 } 3307 3308 issueIndexedQuadDraw(&mesh[0], count / 4); 3309 3310 return DrawGlInfo::kStatusDrew; 3311} 3312 3313void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 3314 const SkPaint* paint, bool ignoreTransform) { 3315 int color = paint->getColor(); 3316 // If a shader is set, preserve only the alpha 3317 if (mDrawModifiers.mShader) { 3318 color |= 0x00ffffff; 3319 } 3320 3321 setupDraw(); 3322 setupDrawNoTexture(); 3323 setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha); 3324 setupDrawShader(); 3325 setupDrawColorFilter(getColorFilter(paint)); 3326 setupDrawBlending(paint); 3327 setupDrawProgram(); 3328 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 3329 left, top, right, bottom, ignoreTransform); 3330 setupDrawColorUniforms(); 3331 setupDrawShaderUniforms(ignoreTransform); 3332 setupDrawColorFilterUniforms(getColorFilter(paint)); 3333 setupDrawSimpleMesh(); 3334 3335 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 3336} 3337 3338void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 3339 Texture* texture, const SkPaint* paint) { 3340 texture->setWrap(GL_CLAMP_TO_EDGE, true); 3341 3342 GLvoid* vertices = (GLvoid*) NULL; 3343 GLvoid* texCoords = (GLvoid*) gMeshTextureOffset; 3344 3345 if (texture->uvMapper) { 3346 vertices = &mMeshVertices[0].x; 3347 texCoords = &mMeshVertices[0].u; 3348 3349 Rect uvs(0.0f, 0.0f, 1.0f, 1.0f); 3350 texture->uvMapper->map(uvs); 3351 3352 resetDrawTextureTexCoords(uvs.left, uvs.top, uvs.right, uvs.bottom); 3353 } 3354 3355 if (CC_LIKELY(currentTransform()->isPureTranslate())) { 3356 const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f); 3357 const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f); 3358 3359 texture->setFilter(GL_NEAREST, true); 3360 drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 3361 paint, texture->blend, vertices, texCoords, 3362 GL_TRIANGLE_STRIP, gMeshCount, false, true); 3363 } else { 3364 texture->setFilter(getFilter(paint), true); 3365 drawTextureMesh(left, top, right, bottom, texture->id, paint, 3366 texture->blend, vertices, texCoords, GL_TRIANGLE_STRIP, gMeshCount); 3367 } 3368 3369 if (texture->uvMapper) { 3370 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 3371 } 3372} 3373 3374void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom, 3375 GLuint texture, const SkPaint* paint, bool blend, 3376 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3377 bool swapSrcDst, bool ignoreTransform, GLuint vbo, 3378 ModelViewMode modelViewMode, bool dirty) { 3379 3380 int a; 3381 SkXfermode::Mode mode; 3382 getAlphaAndMode(paint, &a, &mode); 3383 const float alpha = a / 255.0f; 3384 3385 setupDraw(); 3386 setupDrawWithTexture(); 3387 setupDrawColor(alpha, alpha, alpha, alpha); 3388 setupDrawColorFilter(getColorFilter(paint)); 3389 setupDrawBlending(paint, blend, swapSrcDst); 3390 setupDrawProgram(); 3391 if (!dirty) setupDrawDirtyRegionsDisabled(); 3392 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3393 setupDrawTexture(texture); 3394 setupDrawPureColorUniforms(); 3395 setupDrawColorFilterUniforms(getColorFilter(paint)); 3396 setupDrawMesh(vertices, texCoords, vbo); 3397 3398 glDrawArrays(drawMode, 0, elementsCount); 3399} 3400 3401void OpenGLRenderer::drawIndexedTextureMesh(float left, float top, float right, float bottom, 3402 GLuint texture, const SkPaint* paint, bool blend, 3403 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3404 bool swapSrcDst, bool ignoreTransform, GLuint vbo, 3405 ModelViewMode modelViewMode, bool dirty) { 3406 3407 int a; 3408 SkXfermode::Mode mode; 3409 getAlphaAndMode(paint, &a, &mode); 3410 const float alpha = a / 255.0f; 3411 3412 setupDraw(); 3413 setupDrawWithTexture(); 3414 setupDrawColor(alpha, alpha, alpha, alpha); 3415 setupDrawColorFilter(getColorFilter(paint)); 3416 setupDrawBlending(paint, blend, swapSrcDst); 3417 setupDrawProgram(); 3418 if (!dirty) setupDrawDirtyRegionsDisabled(); 3419 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3420 setupDrawTexture(texture); 3421 setupDrawPureColorUniforms(); 3422 setupDrawColorFilterUniforms(getColorFilter(paint)); 3423 setupDrawMeshIndices(vertices, texCoords, vbo); 3424 3425 glDrawElements(drawMode, elementsCount, GL_UNSIGNED_SHORT, NULL); 3426} 3427 3428void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom, 3429 GLuint texture, const SkPaint* paint, 3430 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3431 bool ignoreTransform, ModelViewMode modelViewMode, bool dirty) { 3432 3433 int color = paint != NULL ? paint->getColor() : 0; 3434 int alpha; 3435 SkXfermode::Mode mode; 3436 getAlphaAndMode(paint, &alpha, &mode); 3437 3438 setupDraw(); 3439 setupDrawWithTexture(true); 3440 if (paint != NULL) { 3441 setupDrawAlpha8Color(color, alpha); 3442 } 3443 setupDrawColorFilter(getColorFilter(paint)); 3444 setupDrawShader(); 3445 setupDrawBlending(paint, true); 3446 setupDrawProgram(); 3447 if (!dirty) setupDrawDirtyRegionsDisabled(); 3448 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3449 setupDrawTexture(texture); 3450 setupDrawPureColorUniforms(); 3451 setupDrawColorFilterUniforms(getColorFilter(paint)); 3452 setupDrawShaderUniforms(ignoreTransform); 3453 setupDrawMesh(vertices, texCoords); 3454 3455 glDrawArrays(drawMode, 0, elementsCount); 3456} 3457 3458void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, 3459 ProgramDescription& description, bool swapSrcDst) { 3460 3461 if (mSnapshot->roundRectClipState != NULL /*&& !mSkipOutlineClip*/) { 3462 blend = true; 3463 mDescription.hasRoundRectClip = true; 3464 } 3465 mSkipOutlineClip = true; 3466 3467 if (mCountOverdraw) { 3468 if (!mCaches.blend) glEnable(GL_BLEND); 3469 if (mCaches.lastSrcMode != GL_ONE || mCaches.lastDstMode != GL_ONE) { 3470 glBlendFunc(GL_ONE, GL_ONE); 3471 } 3472 3473 mCaches.blend = true; 3474 mCaches.lastSrcMode = GL_ONE; 3475 mCaches.lastDstMode = GL_ONE; 3476 3477 return; 3478 } 3479 3480 blend = blend || mode != SkXfermode::kSrcOver_Mode; 3481 3482 if (blend) { 3483 // These blend modes are not supported by OpenGL directly and have 3484 // to be implemented using shaders. Since the shader will perform 3485 // the blending, turn blending off here 3486 // If the blend mode cannot be implemented using shaders, fall 3487 // back to the default SrcOver blend mode instead 3488 if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) { 3489 if (CC_UNLIKELY(mExtensions.hasFramebufferFetch())) { 3490 description.framebufferMode = mode; 3491 description.swapSrcDst = swapSrcDst; 3492 3493 if (mCaches.blend) { 3494 glDisable(GL_BLEND); 3495 mCaches.blend = false; 3496 } 3497 3498 return; 3499 } else { 3500 mode = SkXfermode::kSrcOver_Mode; 3501 } 3502 } 3503 3504 if (!mCaches.blend) { 3505 glEnable(GL_BLEND); 3506 } 3507 3508 GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src; 3509 GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst; 3510 3511 if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) { 3512 glBlendFunc(sourceMode, destMode); 3513 mCaches.lastSrcMode = sourceMode; 3514 mCaches.lastDstMode = destMode; 3515 } 3516 } else if (mCaches.blend) { 3517 glDisable(GL_BLEND); 3518 } 3519 mCaches.blend = blend; 3520} 3521 3522bool OpenGLRenderer::useProgram(Program* program) { 3523 if (!program->isInUse()) { 3524 if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove(); 3525 program->use(); 3526 mCaches.currentProgram = program; 3527 return false; 3528 } 3529 return true; 3530} 3531 3532void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) { 3533 TextureVertex* v = &mMeshVertices[0]; 3534 TextureVertex::setUV(v++, u1, v1); 3535 TextureVertex::setUV(v++, u2, v1); 3536 TextureVertex::setUV(v++, u1, v2); 3537 TextureVertex::setUV(v++, u2, v2); 3538} 3539 3540void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const { 3541 getAlphaAndModeDirect(paint, alpha, mode); 3542 if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) { 3543 // if drawing a layer, ignore the paint's alpha 3544 *alpha = mDrawModifiers.mOverrideLayerAlpha * 255; 3545 } 3546 *alpha *= currentSnapshot()->alpha; 3547} 3548 3549float OpenGLRenderer::getLayerAlpha(const Layer* layer) const { 3550 float alpha; 3551 if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) { 3552 alpha = mDrawModifiers.mOverrideLayerAlpha; 3553 } else { 3554 alpha = layer->getAlpha() / 255.0f; 3555 } 3556 return alpha * currentSnapshot()->alpha; 3557} 3558 3559}; // namespace uirenderer 3560}; // namespace android 3561