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