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