OpenGLRenderer.cpp revision 8198c3a8f525c07e2b848852f6ad3e351e3b5461
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 const SkPaint* paint, int flags) { 735 const int count = saveSnapshot(flags); 736 737 if (!currentSnapshot()->isIgnored()) { 738 createLayer(left, top, right, bottom, paint, 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 const SkPaint* paint, 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, getAlphaDirect(paint)); 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 const SkPaint* paint, 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, getAlphaDirect(paint)); 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->setPaint(paint); 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 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 SkPaint layerPaint; 1011 layerPaint.setAlpha(layer->getAlpha()); 1012 layerPaint.setXfermodeMode(SkXfermode::kDstIn_Mode); 1013 layerPaint.setColorFilter(layer->getColorFilter()); 1014 1015 drawColorRect(rect.left, rect.top, rect.right, rect.bottom, &layerPaint, true); 1016 // Required below, composeLayerRect() will divide by 255 1017 layer->setAlpha(255); 1018 } 1019 1020 mCaches.unbindMeshBuffer(); 1021 1022 mCaches.activeTexture(0); 1023 1024 // When the layer is stored in an FBO, we can save a bit of fillrate by 1025 // drawing only the dirty region 1026 if (fboLayer) { 1027 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *restored.transform); 1028 composeLayerRegion(layer, rect); 1029 } else if (!rect.isEmpty()) { 1030 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom); 1031 1032 save(0); 1033 // the layer contains screen buffer content that shouldn't be alpha modulated 1034 // (and any necessary alpha modulation was handled drawing into the layer) 1035 mSnapshot->alpha = 1.0f; 1036 composeLayerRect(layer, rect, true); 1037 restore(); 1038 } 1039 1040 dirtyClip(); 1041 1042 // Failing to add the layer to the cache should happen only if the layer is too large 1043 if (!mCaches.layerCache.put(layer)) { 1044 LAYER_LOGD("Deleting layer"); 1045 Caches::getInstance().resourceCache.decrementRefcount(layer); 1046 } 1047} 1048 1049void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) { 1050 float alpha = getLayerAlpha(layer); 1051 1052 setupDraw(); 1053 if (layer->getRenderTarget() == GL_TEXTURE_2D) { 1054 setupDrawWithTexture(); 1055 } else { 1056 setupDrawWithExternalTexture(); 1057 } 1058 setupDrawTextureTransform(); 1059 setupDrawColor(alpha, alpha, alpha, alpha); 1060 setupDrawColorFilter(layer->getColorFilter()); 1061 setupDrawBlending(layer); 1062 setupDrawProgram(); 1063 setupDrawPureColorUniforms(); 1064 setupDrawColorFilterUniforms(layer->getColorFilter()); 1065 if (layer->getRenderTarget() == GL_TEXTURE_2D) { 1066 setupDrawTexture(layer->getTexture()); 1067 } else { 1068 setupDrawExternalTexture(layer->getTexture()); 1069 } 1070 if (currentTransform()->isPureTranslate() && 1071 layer->getWidth() == (uint32_t) rect.getWidth() && 1072 layer->getHeight() == (uint32_t) rect.getHeight()) { 1073 const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f); 1074 const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f); 1075 1076 layer->setFilter(GL_NEAREST); 1077 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 1078 x, y, x + rect.getWidth(), y + rect.getHeight(), true); 1079 } else { 1080 layer->setFilter(GL_LINEAR); 1081 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 1082 rect.left, rect.top, rect.right, rect.bottom); 1083 } 1084 setupDrawTextureTransformUniforms(layer->getTexTransform()); 1085 setupDrawMesh(&mMeshVertices[0].x, &mMeshVertices[0].u); 1086 1087 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 1088} 1089 1090void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) { 1091 if (!layer->isTextureLayer()) { 1092 const Rect& texCoords = layer->texCoords; 1093 resetDrawTextureTexCoords(texCoords.left, texCoords.top, 1094 texCoords.right, texCoords.bottom); 1095 1096 float x = rect.left; 1097 float y = rect.top; 1098 bool simpleTransform = currentTransform()->isPureTranslate() && 1099 layer->getWidth() == (uint32_t) rect.getWidth() && 1100 layer->getHeight() == (uint32_t) rect.getHeight(); 1101 1102 if (simpleTransform) { 1103 // When we're swapping, the layer is already in screen coordinates 1104 if (!swap) { 1105 x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f); 1106 y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f); 1107 } 1108 1109 layer->setFilter(GL_NEAREST, true); 1110 } else { 1111 layer->setFilter(GL_LINEAR, true); 1112 } 1113 1114 SkPaint layerPaint; 1115 layerPaint.setAlpha(getLayerAlpha(layer) * 255); 1116 layerPaint.setXfermodeMode(layer->getMode()); 1117 layerPaint.setColorFilter(layer->getColorFilter()); 1118 1119 bool blend = layer->isBlend() || getLayerAlpha(layer) < 1.0f; 1120 drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(), 1121 layer->getTexture(), &layerPaint, blend, 1122 &mMeshVertices[0].x, &mMeshVertices[0].u, 1123 GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform); 1124 1125 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 1126 } else { 1127 resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f); 1128 drawTextureLayer(layer, rect); 1129 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 1130 } 1131} 1132 1133/** 1134 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated 1135 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw 1136 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used 1137 * by saveLayer's restore 1138 */ 1139#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) { \ 1140 DRAW_COMMAND; \ 1141 if (CC_UNLIKELY(mCaches.debugOverdraw && getTargetFbo() == 0 && COND)) { \ 1142 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); \ 1143 DRAW_COMMAND; \ 1144 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); \ 1145 } \ 1146 } 1147 1148#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND) 1149 1150void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) { 1151 if (layer->region.isRect()) { 1152 layer->setRegionAsRect(); 1153 1154 DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect)); 1155 1156 layer->region.clear(); 1157 return; 1158 } 1159 1160 if (CC_LIKELY(!layer->region.isEmpty())) { 1161 size_t count; 1162 const android::Rect* rects; 1163 Region safeRegion; 1164 if (CC_LIKELY(hasRectToRectTransform())) { 1165 rects = layer->region.getArray(&count); 1166 } else { 1167 safeRegion = Region::createTJunctionFreeRegion(layer->region); 1168 rects = safeRegion.getArray(&count); 1169 } 1170 1171 const float alpha = getLayerAlpha(layer); 1172 const float texX = 1.0f / float(layer->getWidth()); 1173 const float texY = 1.0f / float(layer->getHeight()); 1174 const float height = rect.getHeight(); 1175 1176 setupDraw(); 1177 1178 // We must get (and therefore bind) the region mesh buffer 1179 // after we setup drawing in case we need to mess with the 1180 // stencil buffer in setupDraw() 1181 TextureVertex* mesh = mCaches.getRegionMesh(); 1182 uint32_t numQuads = 0; 1183 1184 setupDrawWithTexture(); 1185 setupDrawColor(alpha, alpha, alpha, alpha); 1186 setupDrawColorFilter(layer->getColorFilter()); 1187 setupDrawBlending(layer); 1188 setupDrawProgram(); 1189 setupDrawDirtyRegionsDisabled(); 1190 setupDrawPureColorUniforms(); 1191 setupDrawColorFilterUniforms(layer->getColorFilter()); 1192 setupDrawTexture(layer->getTexture()); 1193 if (currentTransform()->isPureTranslate()) { 1194 const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f); 1195 const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f); 1196 1197 layer->setFilter(GL_NEAREST); 1198 setupDrawModelView(kModelViewMode_Translate, false, 1199 x, y, x + rect.getWidth(), y + rect.getHeight(), true); 1200 } else { 1201 layer->setFilter(GL_LINEAR); 1202 setupDrawModelView(kModelViewMode_Translate, false, 1203 rect.left, rect.top, rect.right, rect.bottom); 1204 } 1205 setupDrawMeshIndices(&mesh[0].x, &mesh[0].u); 1206 1207 for (size_t i = 0; i < count; i++) { 1208 const android::Rect* r = &rects[i]; 1209 1210 const float u1 = r->left * texX; 1211 const float v1 = (height - r->top) * texY; 1212 const float u2 = r->right * texX; 1213 const float v2 = (height - r->bottom) * texY; 1214 1215 // TODO: Reject quads outside of the clip 1216 TextureVertex::set(mesh++, r->left, r->top, u1, v1); 1217 TextureVertex::set(mesh++, r->right, r->top, u2, v1); 1218 TextureVertex::set(mesh++, r->left, r->bottom, u1, v2); 1219 TextureVertex::set(mesh++, r->right, r->bottom, u2, v2); 1220 1221 numQuads++; 1222 1223 if (numQuads >= gMaxNumberOfQuads) { 1224 DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6, 1225 GL_UNSIGNED_SHORT, NULL)); 1226 numQuads = 0; 1227 mesh = mCaches.getRegionMesh(); 1228 } 1229 } 1230 1231 if (numQuads > 0) { 1232 DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6, 1233 GL_UNSIGNED_SHORT, NULL)); 1234 } 1235 1236#if DEBUG_LAYERS_AS_REGIONS 1237 drawRegionRectsDebug(layer->region); 1238#endif 1239 1240 layer->region.clear(); 1241 } 1242} 1243 1244#if DEBUG_LAYERS_AS_REGIONS 1245void OpenGLRenderer::drawRegionRectsDebug(const Region& region) { 1246 size_t count; 1247 const android::Rect* rects = region.getArray(&count); 1248 1249 uint32_t colors[] = { 1250 0x7fff0000, 0x7f00ff00, 1251 0x7f0000ff, 0x7fff00ff, 1252 }; 1253 1254 int offset = 0; 1255 int32_t top = rects[0].top; 1256 1257 for (size_t i = 0; i < count; i++) { 1258 if (top != rects[i].top) { 1259 offset ^= 0x2; 1260 top = rects[i].top; 1261 } 1262 1263 SkPaint paint; 1264 paint.setColor(colors[offset + (i & 0x1)]); 1265 Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom); 1266 drawColorRect(r.left, r.top, r.right, r.bottom, paint); 1267 } 1268} 1269#endif 1270 1271void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) { 1272 Vector<float> rects; 1273 1274 SkRegion::Iterator it(region); 1275 while (!it.done()) { 1276 const SkIRect& r = it.rect(); 1277 rects.push(r.fLeft); 1278 rects.push(r.fTop); 1279 rects.push(r.fRight); 1280 rects.push(r.fBottom); 1281 it.next(); 1282 } 1283 1284 drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false); 1285} 1286 1287void OpenGLRenderer::dirtyLayer(const float left, const float top, 1288 const float right, const float bottom, const mat4 transform) { 1289 if (hasLayer()) { 1290 Rect bounds(left, top, right, bottom); 1291 transform.mapRect(bounds); 1292 dirtyLayerUnchecked(bounds, getRegion()); 1293 } 1294} 1295 1296void OpenGLRenderer::dirtyLayer(const float left, const float top, 1297 const float right, const float bottom) { 1298 if (hasLayer()) { 1299 Rect bounds(left, top, right, bottom); 1300 dirtyLayerUnchecked(bounds, getRegion()); 1301 } 1302} 1303 1304void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) { 1305 if (bounds.intersect(*currentClipRect())) { 1306 bounds.snapToPixelBoundaries(); 1307 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom); 1308 if (!dirty.isEmpty()) { 1309 region->orSelf(dirty); 1310 } 1311 } 1312} 1313 1314void OpenGLRenderer::issueIndexedQuadDraw(Vertex* mesh, GLsizei quadsCount) { 1315 GLsizei elementsCount = quadsCount * 6; 1316 while (elementsCount > 0) { 1317 GLsizei drawCount = min(elementsCount, (GLsizei) gMaxNumberOfQuads * 6); 1318 1319 setupDrawIndexedVertices(&mesh[0].x); 1320 glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, NULL); 1321 1322 elementsCount -= drawCount; 1323 // Though there are 4 vertices in a quad, we use 6 indices per 1324 // quad to draw with GL_TRIANGLES 1325 mesh += (drawCount / 6) * 4; 1326 } 1327} 1328 1329void OpenGLRenderer::clearLayerRegions() { 1330 const size_t count = mLayers.size(); 1331 if (count == 0) return; 1332 1333 if (!currentSnapshot()->isIgnored()) { 1334 // Doing several glScissor/glClear here can negatively impact 1335 // GPUs with a tiler architecture, instead we draw quads with 1336 // the Clear blending mode 1337 1338 // The list contains bounds that have already been clipped 1339 // against their initial clip rect, and the current clip 1340 // is likely different so we need to disable clipping here 1341 bool scissorChanged = mCaches.disableScissor(); 1342 1343 Vertex mesh[count * 4]; 1344 Vertex* vertex = mesh; 1345 1346 for (uint32_t i = 0; i < count; i++) { 1347 Rect* bounds = mLayers.itemAt(i); 1348 1349 Vertex::set(vertex++, bounds->left, bounds->top); 1350 Vertex::set(vertex++, bounds->right, bounds->top); 1351 Vertex::set(vertex++, bounds->left, bounds->bottom); 1352 Vertex::set(vertex++, bounds->right, bounds->bottom); 1353 1354 delete bounds; 1355 } 1356 // We must clear the list of dirty rects before we 1357 // call setupDraw() to prevent stencil setup to do 1358 // the same thing again 1359 mLayers.clear(); 1360 1361 SkPaint clearPaint; 1362 clearPaint.setXfermodeMode(SkXfermode::kClear_Mode); 1363 1364 setupDraw(false); 1365 setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f); 1366 setupDrawBlending(&clearPaint, true); 1367 setupDrawProgram(); 1368 setupDrawPureColorUniforms(); 1369 setupDrawModelView(kModelViewMode_Translate, false, 1370 0.0f, 0.0f, 0.0f, 0.0f, true); 1371 1372 issueIndexedQuadDraw(&mesh[0], count); 1373 1374 if (scissorChanged) mCaches.enableScissor(); 1375 } else { 1376 for (uint32_t i = 0; i < count; i++) { 1377 delete mLayers.itemAt(i); 1378 } 1379 mLayers.clear(); 1380 } 1381} 1382 1383/////////////////////////////////////////////////////////////////////////////// 1384// State Deferral 1385/////////////////////////////////////////////////////////////////////////////// 1386 1387bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) { 1388 const Rect* currentClip = currentClipRect(); 1389 const mat4* currentMatrix = currentTransform(); 1390 1391 if (stateDeferFlags & kStateDeferFlag_Draw) { 1392 // state has bounds initialized in local coordinates 1393 if (!state.mBounds.isEmpty()) { 1394 currentMatrix->mapRect(state.mBounds); 1395 Rect clippedBounds(state.mBounds); 1396 // NOTE: if we ever want to use this clipping info to drive whether the scissor 1397 // is used, it should more closely duplicate the quickReject logic (in how it uses 1398 // snapToPixelBoundaries) 1399 1400 if(!clippedBounds.intersect(*currentClip)) { 1401 // quick rejected 1402 return true; 1403 } 1404 1405 state.mClipSideFlags = kClipSide_None; 1406 if (!currentClip->contains(state.mBounds)) { 1407 int& flags = state.mClipSideFlags; 1408 // op partially clipped, so record which sides are clipped for clip-aware merging 1409 if (currentClip->left > state.mBounds.left) flags |= kClipSide_Left; 1410 if (currentClip->top > state.mBounds.top) flags |= kClipSide_Top; 1411 if (currentClip->right < state.mBounds.right) flags |= kClipSide_Right; 1412 if (currentClip->bottom < state.mBounds.bottom) flags |= kClipSide_Bottom; 1413 } 1414 state.mBounds.set(clippedBounds); 1415 } else { 1416 // Empty bounds implies size unknown. Label op as conservatively clipped to disable 1417 // overdraw avoidance (since we don't know what it overlaps) 1418 state.mClipSideFlags = kClipSide_ConservativeFull; 1419 state.mBounds.set(*currentClip); 1420 } 1421 } 1422 1423 state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip); 1424 if (state.mClipValid) { 1425 state.mClip.set(*currentClip); 1426 } 1427 1428 // Transform, drawModifiers, and alpha always deferred, since they are used by state operations 1429 // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything) 1430 state.mMatrix.load(*currentMatrix); 1431 state.mDrawModifiers = mDrawModifiers; 1432 state.mAlpha = currentSnapshot()->alpha; 1433 return false; 1434} 1435 1436void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) { 1437 setMatrix(state.mMatrix); 1438 mSnapshot->alpha = state.mAlpha; 1439 mDrawModifiers = state.mDrawModifiers; 1440 1441 if (state.mClipValid && !skipClipRestore) { 1442 mSnapshot->setClip(state.mClip.left, state.mClip.top, 1443 state.mClip.right, state.mClip.bottom); 1444 dirtyClip(); 1445 } 1446} 1447 1448/** 1449 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done 1450 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at 1451 * least one op is clipped), or disabled entirely (because no merged op is clipped) 1452 * 1453 * This method should be called when restoreDisplayState() won't be restoring the clip 1454 */ 1455void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) { 1456 if (clipRect != NULL) { 1457 mSnapshot->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom); 1458 } else { 1459 mSnapshot->setClip(0, 0, getWidth(), getHeight()); 1460 } 1461 dirtyClip(); 1462 mCaches.setScissorEnabled(clipRect != NULL || mScissorOptimizationDisabled); 1463} 1464 1465/////////////////////////////////////////////////////////////////////////////// 1466// Clipping 1467/////////////////////////////////////////////////////////////////////////////// 1468 1469void OpenGLRenderer::setScissorFromClip() { 1470 Rect clip(*currentClipRect()); 1471 clip.snapToPixelBoundaries(); 1472 1473 if (mCaches.setScissor(clip.left, currentSnapshot()->height - clip.bottom, 1474 clip.getWidth(), clip.getHeight())) { 1475 mDirtyClip = false; 1476 } 1477} 1478 1479void OpenGLRenderer::ensureStencilBuffer() { 1480 // Thanks to the mismatch between EGL and OpenGL ES FBO we 1481 // cannot attach a stencil buffer to fbo0 dynamically. Let's 1482 // just hope we have one when hasLayer() returns false. 1483 if (hasLayer()) { 1484 attachStencilBufferToLayer(currentSnapshot()->layer); 1485 } 1486} 1487 1488void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) { 1489 // The layer's FBO is already bound when we reach this stage 1490 if (!layer->getStencilRenderBuffer()) { 1491 // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer 1492 // is attached after we initiated tiling. We must turn it off, 1493 // attach the new render buffer then turn tiling back on 1494 endTiling(); 1495 1496 RenderBuffer* buffer = mCaches.renderBufferCache.get( 1497 Stencil::getSmallestStencilFormat(), layer->getWidth(), layer->getHeight()); 1498 layer->setStencilRenderBuffer(buffer); 1499 1500 startTiling(layer->clipRect, layer->layer.getHeight()); 1501 } 1502} 1503 1504void OpenGLRenderer::setStencilFromClip() { 1505 if (!mCaches.debugOverdraw) { 1506 if (!currentSnapshot()->clipRegion->isEmpty()) { 1507 // NOTE: The order here is important, we must set dirtyClip to false 1508 // before any draw call to avoid calling back into this method 1509 mDirtyClip = false; 1510 1511 ensureStencilBuffer(); 1512 1513 mCaches.stencil.enableWrite(); 1514 1515 // Clear the stencil but first make sure we restrict drawing 1516 // to the region's bounds 1517 bool resetScissor = mCaches.enableScissor(); 1518 if (resetScissor) { 1519 // The scissor was not set so we now need to update it 1520 setScissorFromClip(); 1521 } 1522 mCaches.stencil.clear(); 1523 if (resetScissor) mCaches.disableScissor(); 1524 1525 SkPaint paint; 1526 paint.setColor(0xff000000); 1527 paint.setXfermodeMode(SkXfermode::kSrc_Mode); 1528 1529 // NOTE: We could use the region contour path to generate a smaller mesh 1530 // Since we are using the stencil we could use the red book path 1531 // drawing technique. It might increase bandwidth usage though. 1532 1533 // The last parameter is important: we are not drawing in the color buffer 1534 // so we don't want to dirty the current layer, if any 1535 drawRegionRects(*(currentSnapshot()->clipRegion), paint, false); 1536 1537 mCaches.stencil.enableTest(); 1538 1539 // Draw the region used to generate the stencil if the appropriate debug 1540 // mode is enabled 1541 if (mCaches.debugStencilClip == Caches::kStencilShowRegion) { 1542 paint.setColor(0x7f0000ff); 1543 paint.setXfermodeMode(SkXfermode::kSrcOver_Mode); 1544 drawRegionRects(*(currentSnapshot()->clipRegion), paint); 1545 } 1546 } else { 1547 mCaches.stencil.disable(); 1548 } 1549 } 1550} 1551 1552/** 1553 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out. 1554 * 1555 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint 1556 * style, and tessellated AA ramp 1557 */ 1558bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom, 1559 const SkPaint* paint) { 1560 bool clipRequired = false; 1561 bool snapOut = paint && paint->isAntiAlias(); 1562 1563 if (paint && paint->getStyle() != SkPaint::kFill_Style) { 1564 float outset = paint->getStrokeWidth() * 0.5f; 1565 left -= outset; 1566 top -= outset; 1567 right += outset; 1568 bottom += outset; 1569 } 1570 1571 if (calculateQuickRejectForScissor(left, top, right, bottom, &clipRequired, snapOut)) { 1572 return true; 1573 } 1574 1575 if (!isRecording()) { 1576 // not quick rejected, so enable the scissor if clipRequired 1577 mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired); 1578 } 1579 return false; 1580} 1581 1582void OpenGLRenderer::debugClip() { 1583#if DEBUG_CLIP_REGIONS 1584 if (!isRecording() && !currentSnapshot()->clipRegion->isEmpty()) { 1585 SkPaint paint; 1586 paint.setColor(0x7f00ff00); 1587 drawRegionRects(*(currentSnapshot()->clipRegion, paint); 1588 1589 } 1590#endif 1591} 1592 1593/////////////////////////////////////////////////////////////////////////////// 1594// Drawing commands 1595/////////////////////////////////////////////////////////////////////////////// 1596 1597void OpenGLRenderer::setupDraw(bool clear) { 1598 // TODO: It would be best if we could do this before quickRejectSetupScissor() 1599 // changes the scissor test state 1600 if (clear) clearLayerRegions(); 1601 // Make sure setScissor & setStencil happen at the beginning of 1602 // this method 1603 if (mDirtyClip) { 1604 if (mCaches.scissorEnabled) { 1605 setScissorFromClip(); 1606 } 1607 setStencilFromClip(); 1608 } 1609 1610 mDescription.reset(); 1611 1612 mSetShaderColor = false; 1613 mColorSet = false; 1614 mColorA = mColorR = mColorG = mColorB = 0.0f; 1615 mTextureUnit = 0; 1616 mTrackDirtyRegions = true; 1617 1618 // Enable debug highlight when what we're about to draw is tested against 1619 // the stencil buffer and if stencil highlight debugging is on 1620 mDescription.hasDebugHighlight = !mCaches.debugOverdraw && 1621 mCaches.debugStencilClip == Caches::kStencilShowHighlight && 1622 mCaches.stencil.isTestEnabled(); 1623 1624 mDescription.emulateStencil = mCountOverdraw; 1625} 1626 1627void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) { 1628 mDescription.hasTexture = true; 1629 mDescription.hasAlpha8Texture = isAlpha8; 1630} 1631 1632void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) { 1633 mDescription.hasTexture = true; 1634 mDescription.hasColors = true; 1635 mDescription.hasAlpha8Texture = isAlpha8; 1636} 1637 1638void OpenGLRenderer::setupDrawWithExternalTexture() { 1639 mDescription.hasExternalTexture = true; 1640} 1641 1642void OpenGLRenderer::setupDrawNoTexture() { 1643 mCaches.disableTexCoordsVertexArray(); 1644} 1645 1646void OpenGLRenderer::setupDrawAA() { 1647 mDescription.isAA = true; 1648} 1649 1650void OpenGLRenderer::setupDrawColor(int color, int alpha) { 1651 mColorA = alpha / 255.0f; 1652 mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f; 1653 mColorG = mColorA * ((color >> 8) & 0xFF) / 255.0f; 1654 mColorB = mColorA * ((color ) & 0xFF) / 255.0f; 1655 mColorSet = true; 1656 mSetShaderColor = mDescription.setColorModulate(mColorA); 1657} 1658 1659void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) { 1660 mColorA = alpha / 255.0f; 1661 mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f; 1662 mColorG = mColorA * ((color >> 8) & 0xFF) / 255.0f; 1663 mColorB = mColorA * ((color ) & 0xFF) / 255.0f; 1664 mColorSet = true; 1665 mSetShaderColor = mDescription.setAlpha8ColorModulate(mColorR, mColorG, mColorB, mColorA); 1666} 1667 1668void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) { 1669 mCaches.fontRenderer->describe(mDescription, paint); 1670} 1671 1672void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) { 1673 mColorA = a; 1674 mColorR = r; 1675 mColorG = g; 1676 mColorB = b; 1677 mColorSet = true; 1678 mSetShaderColor = mDescription.setColorModulate(a); 1679} 1680 1681void OpenGLRenderer::setupDrawShader() { 1682 if (mDrawModifiers.mShader) { 1683 mDrawModifiers.mShader->describe(mDescription, mExtensions); 1684 } 1685} 1686 1687void OpenGLRenderer::setupDrawColorFilter(const SkColorFilter* filter) { 1688 if (filter == NULL) { 1689 return; 1690 } 1691 1692 SkXfermode::Mode mode; 1693 if (filter->asColorMode(NULL, &mode)) { 1694 mDescription.colorOp = ProgramDescription::kColorBlend; 1695 mDescription.colorMode = mode; 1696 } else if (filter->asColorMatrix(NULL)) { 1697 mDescription.colorOp = ProgramDescription::kColorMatrix; 1698 } 1699} 1700 1701void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) { 1702 if (mColorSet && mode == SkXfermode::kClear_Mode) { 1703 mColorA = 1.0f; 1704 mColorR = mColorG = mColorB = 0.0f; 1705 mSetShaderColor = mDescription.modulate = true; 1706 } 1707} 1708 1709void OpenGLRenderer::setupDrawBlending(const Layer* layer, bool swapSrcDst) { 1710 SkXfermode::Mode mode = layer->getMode(); 1711 // When the blending mode is kClear_Mode, we need to use a modulate color 1712 // argb=1,0,0,0 1713 accountForClear(mode); 1714 bool blend = layer->isBlend() || getLayerAlpha(layer) < 1.0f || 1715 (mColorSet && mColorA < 1.0f) || 1716 (mDrawModifiers.mShader && mDrawModifiers.mShader->blend()) || 1717 layer->getColorFilter(); 1718 chooseBlending(blend, mode, mDescription, swapSrcDst); 1719} 1720 1721void OpenGLRenderer::setupDrawBlending(const SkPaint* paint, bool blend, bool swapSrcDst) { 1722 SkXfermode::Mode mode = getXfermodeDirect(paint); 1723 // When the blending mode is kClear_Mode, we need to use a modulate color 1724 // argb=1,0,0,0 1725 accountForClear(mode); 1726 blend |= (mColorSet && mColorA < 1.0f) || 1727 (mDrawModifiers.mShader && mDrawModifiers.mShader->blend()) || 1728 (paint && paint->getColorFilter()); 1729 chooseBlending(blend, mode, mDescription, swapSrcDst); 1730} 1731 1732void OpenGLRenderer::setupDrawProgram() { 1733 useProgram(mCaches.programCache.get(mDescription)); 1734} 1735 1736void OpenGLRenderer::setupDrawDirtyRegionsDisabled() { 1737 mTrackDirtyRegions = false; 1738} 1739 1740void OpenGLRenderer::setupDrawModelView(ModelViewMode mode, bool offset, 1741 float left, float top, float right, float bottom, bool ignoreTransform) { 1742 mModelView.loadTranslate(left, top, 0.0f); 1743 if (mode == kModelViewMode_TranslateAndScale) { 1744 mModelView.scale(right - left, bottom - top, 1.0f); 1745 } 1746 1747 bool dirty = right - left > 0.0f && bottom - top > 0.0f; 1748 if (!ignoreTransform) { 1749 mCaches.currentProgram->set(mViewProjMatrix, mModelView, *currentTransform(), offset); 1750 if (dirty && mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *currentTransform()); 1751 } else { 1752 mCaches.currentProgram->set(mViewProjMatrix, mModelView, mat4::identity(), offset); 1753 if (dirty && mTrackDirtyRegions) dirtyLayer(left, top, right, bottom); 1754 } 1755} 1756 1757void OpenGLRenderer::setupDrawColorUniforms() { 1758 if ((mColorSet && !mDrawModifiers.mShader) || (mDrawModifiers.mShader && mSetShaderColor)) { 1759 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1760 } 1761} 1762 1763void OpenGLRenderer::setupDrawPureColorUniforms() { 1764 if (mSetShaderColor) { 1765 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1766 } 1767} 1768 1769void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) { 1770 if (mDrawModifiers.mShader) { 1771 if (ignoreTransform) { 1772 // if ignoreTransform=true was passed to setupDrawModelView, undo currentTransform() 1773 // because it was built into modelView / the geometry, and the SkiaShader needs to 1774 // compensate. 1775 mat4 modelViewWithoutTransform; 1776 modelViewWithoutTransform.loadInverse(*currentTransform()); 1777 modelViewWithoutTransform.multiply(mModelView); 1778 mModelView.load(modelViewWithoutTransform); 1779 } 1780 mDrawModifiers.mShader->setupProgram(mCaches.currentProgram, 1781 mModelView, *mSnapshot, &mTextureUnit); 1782 } 1783} 1784 1785void OpenGLRenderer::setupDrawColorFilterUniforms(const SkColorFilter* filter) { 1786 if (NULL == filter) { 1787 return; 1788 } 1789 1790 SkColor color; 1791 SkXfermode::Mode mode; 1792 if (filter->asColorMode(&color, &mode)) { 1793 const int alpha = SkColorGetA(color); 1794 const GLfloat a = alpha / 255.0f; 1795 const GLfloat r = a * SkColorGetR(color) / 255.0f; 1796 const GLfloat g = a * SkColorGetG(color) / 255.0f; 1797 const GLfloat b = a * SkColorGetB(color) / 255.0f; 1798 glUniform4f(mCaches.currentProgram->getUniform("colorBlend"), r, g, b, a); 1799 return; 1800 } 1801 1802 SkScalar srcColorMatrix[20]; 1803 if (filter->asColorMatrix(srcColorMatrix)) { 1804 1805 float colorMatrix[16]; 1806 memcpy(colorMatrix, srcColorMatrix, 4 * sizeof(float)); 1807 memcpy(&colorMatrix[4], &srcColorMatrix[5], 4 * sizeof(float)); 1808 memcpy(&colorMatrix[8], &srcColorMatrix[10], 4 * sizeof(float)); 1809 memcpy(&colorMatrix[12], &srcColorMatrix[15], 4 * sizeof(float)); 1810 1811 // Skia uses the range [0..255] for the addition vector, but we need 1812 // the [0..1] range to apply the vector in GLSL 1813 float colorVector[4]; 1814 colorVector[0] = srcColorMatrix[4] / 255.0f; 1815 colorVector[1] = srcColorMatrix[9] / 255.0f; 1816 colorVector[2] = srcColorMatrix[14] / 255.0f; 1817 colorVector[3] = srcColorMatrix[19] / 255.0f; 1818 1819 glUniformMatrix4fv(mCaches.currentProgram->getUniform("colorMatrix"), 1, 1820 GL_FALSE, colorMatrix); 1821 glUniform4fv(mCaches.currentProgram->getUniform("colorMatrixVector"), 1, colorVector); 1822 return; 1823 } 1824 1825 // it is an error if we ever get here 1826} 1827 1828void OpenGLRenderer::setupDrawTextGammaUniforms() { 1829 mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram); 1830} 1831 1832void OpenGLRenderer::setupDrawSimpleMesh() { 1833 bool force = mCaches.bindMeshBuffer(); 1834 mCaches.bindPositionVertexPointer(force, 0); 1835 mCaches.unbindIndicesBuffer(); 1836} 1837 1838void OpenGLRenderer::setupDrawTexture(GLuint texture) { 1839 if (texture) bindTexture(texture); 1840 mTextureUnit++; 1841 mCaches.enableTexCoordsVertexArray(); 1842} 1843 1844void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) { 1845 bindExternalTexture(texture); 1846 mTextureUnit++; 1847 mCaches.enableTexCoordsVertexArray(); 1848} 1849 1850void OpenGLRenderer::setupDrawTextureTransform() { 1851 mDescription.hasTextureTransform = true; 1852} 1853 1854void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) { 1855 glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1, 1856 GL_FALSE, &transform.data[0]); 1857} 1858 1859void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices, 1860 const GLvoid* texCoords, GLuint vbo) { 1861 bool force = false; 1862 if (!vertices || vbo) { 1863 force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo); 1864 } else { 1865 force = mCaches.unbindMeshBuffer(); 1866 } 1867 1868 mCaches.bindPositionVertexPointer(force, vertices); 1869 if (mCaches.currentProgram->texCoords >= 0) { 1870 mCaches.bindTexCoordsVertexPointer(force, texCoords); 1871 } 1872 1873 mCaches.unbindIndicesBuffer(); 1874} 1875 1876void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices, 1877 const GLvoid* texCoords, const GLvoid* colors) { 1878 bool force = mCaches.unbindMeshBuffer(); 1879 GLsizei stride = sizeof(ColorTextureVertex); 1880 1881 mCaches.bindPositionVertexPointer(force, vertices, stride); 1882 if (mCaches.currentProgram->texCoords >= 0) { 1883 mCaches.bindTexCoordsVertexPointer(force, texCoords, stride); 1884 } 1885 int slot = mCaches.currentProgram->getAttrib("colors"); 1886 if (slot >= 0) { 1887 glEnableVertexAttribArray(slot); 1888 glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors); 1889 } 1890 1891 mCaches.unbindIndicesBuffer(); 1892} 1893 1894void OpenGLRenderer::setupDrawMeshIndices(const GLvoid* vertices, 1895 const GLvoid* texCoords, GLuint vbo) { 1896 bool force = false; 1897 // If vbo is != 0 we want to treat the vertices parameter as an offset inside 1898 // a VBO. However, if vertices is set to NULL and vbo == 0 then we want to 1899 // use the default VBO found in Caches 1900 if (!vertices || vbo) { 1901 force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo); 1902 } else { 1903 force = mCaches.unbindMeshBuffer(); 1904 } 1905 mCaches.bindQuadIndicesBuffer(); 1906 1907 mCaches.bindPositionVertexPointer(force, vertices); 1908 if (mCaches.currentProgram->texCoords >= 0) { 1909 mCaches.bindTexCoordsVertexPointer(force, texCoords); 1910 } 1911} 1912 1913void OpenGLRenderer::setupDrawIndexedVertices(GLvoid* vertices) { 1914 bool force = mCaches.unbindMeshBuffer(); 1915 mCaches.bindQuadIndicesBuffer(); 1916 mCaches.bindPositionVertexPointer(force, vertices, gVertexStride); 1917} 1918 1919/////////////////////////////////////////////////////////////////////////////// 1920// Drawing 1921/////////////////////////////////////////////////////////////////////////////// 1922 1923status_t OpenGLRenderer::drawDisplayList(DisplayList* displayList, Rect& dirty, 1924 int32_t replayFlags) { 1925 status_t status; 1926 1927 if (mCaches.propertyDirtyViewport) { 1928 // force recalc of view/proj matrices 1929 setViewport(getWidth(), getHeight()); 1930 mCaches.propertyDirtyViewport = false; 1931 } 1932 1933 // All the usual checks and setup operations (quickReject, setupDraw, etc.) 1934 // will be performed by the display list itself 1935 if (displayList && displayList->isRenderable()) { 1936 // compute 3d ordering 1937 displayList->computeOrdering(); 1938 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 1939 status = startFrame(); 1940 ReplayStateStruct replayStruct(*this, dirty, replayFlags); 1941 displayList->replay(replayStruct, 0); 1942 return status | replayStruct.mDrawGlStatus; 1943 } 1944 1945 bool avoidOverdraw = !mCaches.debugOverdraw && !mCountOverdraw; // shh, don't tell devs! 1946 DeferredDisplayList deferredList(*currentClipRect(), avoidOverdraw); 1947 DeferStateStruct deferStruct(deferredList, *this, replayFlags); 1948 displayList->defer(deferStruct, 0); 1949 1950 flushLayers(); 1951 status = startFrame(); 1952 1953 return deferredList.flush(*this, dirty) | status; 1954 } 1955 1956 return DrawGlInfo::kStatusDone; 1957} 1958 1959void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, const SkPaint* paint) { 1960 int color = paint != NULL ? paint->getColor() : 0; 1961 1962 float x = left; 1963 float y = top; 1964 1965 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1966 1967 bool ignoreTransform = false; 1968 if (currentTransform()->isPureTranslate()) { 1969 x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f); 1970 y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f); 1971 ignoreTransform = true; 1972 1973 texture->setFilter(GL_NEAREST, true); 1974 } else { 1975 texture->setFilter(FILTER(paint), true); 1976 } 1977 1978 // No need to check for a UV mapper on the texture object, only ARGB_8888 1979 // bitmaps get packed in the atlas 1980 drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 1981 paint, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, 1982 GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform); 1983} 1984 1985/** 1986 * Important note: this method is intended to draw batches of bitmaps and 1987 * will not set the scissor enable or dirty the current layer, if any. 1988 * The caller is responsible for properly dirtying the current layer. 1989 */ 1990status_t OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 1991 int bitmapCount, TextureVertex* vertices, bool pureTranslate, 1992 const Rect& bounds, const SkPaint* paint) { 1993 mCaches.activeTexture(0); 1994 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 1995 if (!texture) return DrawGlInfo::kStatusDone; 1996 1997 const AutoTexture autoCleanup(texture); 1998 1999 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2000 texture->setFilter(pureTranslate ? GL_NEAREST : FILTER(paint), true); 2001 2002 const float x = (int) floorf(bounds.left + 0.5f); 2003 const float y = (int) floorf(bounds.top + 0.5f); 2004 if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) { 2005 drawAlpha8TextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(), 2006 texture->id, paint, &vertices[0].x, &vertices[0].u, 2007 GL_TRIANGLES, bitmapCount * 6, true, 2008 kModelViewMode_Translate, false); 2009 } else { 2010 drawTextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(), 2011 texture->id, paint, texture->blend, &vertices[0].x, &vertices[0].u, 2012 GL_TRIANGLES, bitmapCount * 6, false, true, 0, 2013 kModelViewMode_Translate, false); 2014 } 2015 2016 return DrawGlInfo::kStatusDrew; 2017} 2018 2019status_t OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, float left, float top, 2020 const SkPaint* paint) { 2021 const float right = left + bitmap->width(); 2022 const float bottom = top + bitmap->height(); 2023 2024 if (quickRejectSetupScissor(left, top, right, bottom)) { 2025 return DrawGlInfo::kStatusDone; 2026 } 2027 2028 mCaches.activeTexture(0); 2029 Texture* texture = getTexture(bitmap); 2030 if (!texture) return DrawGlInfo::kStatusDone; 2031 const AutoTexture autoCleanup(texture); 2032 2033 if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) { 2034 drawAlphaBitmap(texture, left, top, paint); 2035 } else { 2036 drawTextureRect(left, top, right, bottom, texture, paint); 2037 } 2038 2039 return DrawGlInfo::kStatusDrew; 2040} 2041 2042status_t OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkMatrix* matrix, 2043 const SkPaint* paint) { 2044 Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height()); 2045 const mat4 transform(*matrix); 2046 transform.mapRect(r); 2047 2048 if (quickRejectSetupScissor(r.left, r.top, r.right, r.bottom)) { 2049 return DrawGlInfo::kStatusDone; 2050 } 2051 2052 mCaches.activeTexture(0); 2053 Texture* texture = getTexture(bitmap); 2054 if (!texture) return DrawGlInfo::kStatusDone; 2055 const AutoTexture autoCleanup(texture); 2056 2057 // This could be done in a cheaper way, all we need is pass the matrix 2058 // to the vertex shader. The save/restore is a bit overkill. 2059 save(SkCanvas::kMatrix_SaveFlag); 2060 concatMatrix(matrix); 2061 if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) { 2062 drawAlphaBitmap(texture, 0.0f, 0.0f, paint); 2063 } else { 2064 drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint); 2065 } 2066 restore(); 2067 2068 return DrawGlInfo::kStatusDrew; 2069} 2070 2071status_t OpenGLRenderer::drawBitmapData(const SkBitmap* bitmap, float left, float top, 2072 const SkPaint* paint) { 2073 const float right = left + bitmap->width(); 2074 const float bottom = top + bitmap->height(); 2075 2076 if (quickRejectSetupScissor(left, top, right, bottom)) { 2077 return DrawGlInfo::kStatusDone; 2078 } 2079 2080 mCaches.activeTexture(0); 2081 Texture* texture = mCaches.textureCache.getTransient(bitmap); 2082 const AutoTexture autoCleanup(texture); 2083 2084 if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) { 2085 drawAlphaBitmap(texture, left, top, paint); 2086 } else { 2087 drawTextureRect(left, top, right, bottom, texture, paint); 2088 } 2089 2090 return DrawGlInfo::kStatusDrew; 2091} 2092 2093status_t OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight, 2094 const float* vertices, const int* colors, const SkPaint* paint) { 2095 if (!vertices || currentSnapshot()->isIgnored()) { 2096 return DrawGlInfo::kStatusDone; 2097 } 2098 2099 // TODO: use quickReject on bounds from vertices 2100 mCaches.enableScissor(); 2101 2102 float left = FLT_MAX; 2103 float top = FLT_MAX; 2104 float right = FLT_MIN; 2105 float bottom = FLT_MIN; 2106 2107 const uint32_t count = meshWidth * meshHeight * 6; 2108 2109 Vector<ColorTextureVertex> mesh; // TODO: use C++11 unique_ptr 2110 mesh.setCapacity(count); 2111 ColorTextureVertex* vertex = mesh.editArray(); 2112 2113 bool cleanupColors = false; 2114 if (!colors) { 2115 uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1); 2116 int* newColors = new int[colorsCount]; 2117 memset(newColors, 0xff, colorsCount * sizeof(int)); 2118 colors = newColors; 2119 cleanupColors = true; 2120 } 2121 2122 mCaches.activeTexture(0); 2123 Texture* texture = mCaches.assetAtlas.getEntryTexture(bitmap); 2124 const UvMapper& mapper(getMapper(texture)); 2125 2126 for (int32_t y = 0; y < meshHeight; y++) { 2127 for (int32_t x = 0; x < meshWidth; x++) { 2128 uint32_t i = (y * (meshWidth + 1) + x) * 2; 2129 2130 float u1 = float(x) / meshWidth; 2131 float u2 = float(x + 1) / meshWidth; 2132 float v1 = float(y) / meshHeight; 2133 float v2 = float(y + 1) / meshHeight; 2134 2135 mapper.map(u1, v1, u2, v2); 2136 2137 int ax = i + (meshWidth + 1) * 2; 2138 int ay = ax + 1; 2139 int bx = i; 2140 int by = bx + 1; 2141 int cx = i + 2; 2142 int cy = cx + 1; 2143 int dx = i + (meshWidth + 1) * 2 + 2; 2144 int dy = dx + 1; 2145 2146 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 2147 ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]); 2148 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 2149 2150 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 2151 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 2152 ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]); 2153 2154 left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx]))); 2155 top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy]))); 2156 right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx]))); 2157 bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy]))); 2158 } 2159 } 2160 2161 if (quickRejectSetupScissor(left, top, right, bottom)) { 2162 if (cleanupColors) delete[] colors; 2163 return DrawGlInfo::kStatusDone; 2164 } 2165 2166 if (!texture) { 2167 texture = mCaches.textureCache.get(bitmap); 2168 if (!texture) { 2169 if (cleanupColors) delete[] colors; 2170 return DrawGlInfo::kStatusDone; 2171 } 2172 } 2173 const AutoTexture autoCleanup(texture); 2174 2175 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2176 texture->setFilter(FILTER(paint), true); 2177 2178 int alpha; 2179 SkXfermode::Mode mode; 2180 getAlphaAndMode(paint, &alpha, &mode); 2181 2182 float a = alpha / 255.0f; 2183 2184 if (hasLayer()) { 2185 dirtyLayer(left, top, right, bottom, *currentTransform()); 2186 } 2187 2188 setupDraw(); 2189 setupDrawWithTextureAndColor(); 2190 setupDrawColor(a, a, a, a); 2191 setupDrawColorFilter(getColorFilter(paint)); 2192 setupDrawBlending(paint, true); 2193 setupDrawProgram(); 2194 setupDrawDirtyRegionsDisabled(); 2195 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 0.0f, 0.0f, 1.0f, 1.0f); 2196 setupDrawTexture(texture->id); 2197 setupDrawPureColorUniforms(); 2198 setupDrawColorFilterUniforms(getColorFilter(paint)); 2199 setupDrawMesh(&mesh[0].x, &mesh[0].u, &mesh[0].r); 2200 2201 glDrawArrays(GL_TRIANGLES, 0, count); 2202 2203 int slot = mCaches.currentProgram->getAttrib("colors"); 2204 if (slot >= 0) { 2205 glDisableVertexAttribArray(slot); 2206 } 2207 2208 if (cleanupColors) delete[] colors; 2209 2210 return DrawGlInfo::kStatusDrew; 2211} 2212 2213status_t OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, 2214 float srcLeft, float srcTop, float srcRight, float srcBottom, 2215 float dstLeft, float dstTop, float dstRight, float dstBottom, 2216 const SkPaint* paint) { 2217 if (quickRejectSetupScissor(dstLeft, dstTop, dstRight, dstBottom)) { 2218 return DrawGlInfo::kStatusDone; 2219 } 2220 2221 mCaches.activeTexture(0); 2222 Texture* texture = getTexture(bitmap); 2223 if (!texture) return DrawGlInfo::kStatusDone; 2224 const AutoTexture autoCleanup(texture); 2225 2226 const float width = texture->width; 2227 const float height = texture->height; 2228 2229 float u1 = fmax(0.0f, srcLeft / width); 2230 float v1 = fmax(0.0f, srcTop / height); 2231 float u2 = fmin(1.0f, srcRight / width); 2232 float v2 = fmin(1.0f, srcBottom / height); 2233 2234 getMapper(texture).map(u1, v1, u2, v2); 2235 2236 mCaches.unbindMeshBuffer(); 2237 resetDrawTextureTexCoords(u1, v1, u2, v2); 2238 2239 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2240 2241 float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft); 2242 float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop); 2243 2244 bool scaled = scaleX != 1.0f || scaleY != 1.0f; 2245 // Apply a scale transform on the canvas only when a shader is in use 2246 // Skia handles the ratio between the dst and src rects as a scale factor 2247 // when a shader is set 2248 bool useScaleTransform = mDrawModifiers.mShader && scaled; 2249 bool ignoreTransform = false; 2250 2251 if (CC_LIKELY(currentTransform()->isPureTranslate() && !useScaleTransform)) { 2252 float x = (int) floorf(dstLeft + currentTransform()->getTranslateX() + 0.5f); 2253 float y = (int) floorf(dstTop + currentTransform()->getTranslateY() + 0.5f); 2254 2255 dstRight = x + (dstRight - dstLeft); 2256 dstBottom = y + (dstBottom - dstTop); 2257 2258 dstLeft = x; 2259 dstTop = y; 2260 2261 texture->setFilter(scaled ? FILTER(paint) : GL_NEAREST, true); 2262 ignoreTransform = true; 2263 } else { 2264 texture->setFilter(FILTER(paint), true); 2265 } 2266 2267 if (CC_UNLIKELY(useScaleTransform)) { 2268 save(SkCanvas::kMatrix_SaveFlag); 2269 translate(dstLeft, dstTop); 2270 scale(scaleX, scaleY); 2271 2272 dstLeft = 0.0f; 2273 dstTop = 0.0f; 2274 2275 dstRight = srcRight - srcLeft; 2276 dstBottom = srcBottom - srcTop; 2277 } 2278 2279 if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) { 2280 drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom, 2281 texture->id, paint, 2282 &mMeshVertices[0].x, &mMeshVertices[0].u, 2283 GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform); 2284 } else { 2285 drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, 2286 texture->id, paint, texture->blend, 2287 &mMeshVertices[0].x, &mMeshVertices[0].u, 2288 GL_TRIANGLE_STRIP, gMeshCount, false, ignoreTransform); 2289 } 2290 2291 if (CC_UNLIKELY(useScaleTransform)) { 2292 restore(); 2293 } 2294 2295 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 2296 2297 return DrawGlInfo::kStatusDrew; 2298} 2299 2300status_t OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch, 2301 float left, float top, float right, float bottom, const SkPaint* paint) { 2302 if (quickRejectSetupScissor(left, top, right, bottom)) { 2303 return DrawGlInfo::kStatusDone; 2304 } 2305 2306 AssetAtlas::Entry* entry = mCaches.assetAtlas.getEntry(bitmap); 2307 const Patch* mesh = mCaches.patchCache.get(entry, bitmap->width(), bitmap->height(), 2308 right - left, bottom - top, patch); 2309 2310 return drawPatch(bitmap, mesh, entry, left, top, right, bottom, paint); 2311} 2312 2313status_t OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh, 2314 AssetAtlas::Entry* entry, float left, float top, float right, float bottom, 2315 const SkPaint* paint) { 2316 if (quickRejectSetupScissor(left, top, right, bottom)) { 2317 return DrawGlInfo::kStatusDone; 2318 } 2319 2320 if (CC_LIKELY(mesh && mesh->verticesCount > 0)) { 2321 mCaches.activeTexture(0); 2322 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 2323 if (!texture) return DrawGlInfo::kStatusDone; 2324 const AutoTexture autoCleanup(texture); 2325 2326 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2327 texture->setFilter(GL_LINEAR, true); 2328 2329 const bool pureTranslate = currentTransform()->isPureTranslate(); 2330 // Mark the current layer dirty where we are going to draw the patch 2331 if (hasLayer() && mesh->hasEmptyQuads) { 2332 const float offsetX = left + currentTransform()->getTranslateX(); 2333 const float offsetY = top + currentTransform()->getTranslateY(); 2334 const size_t count = mesh->quads.size(); 2335 for (size_t i = 0; i < count; i++) { 2336 const Rect& bounds = mesh->quads.itemAt(i); 2337 if (CC_LIKELY(pureTranslate)) { 2338 const float x = (int) floorf(bounds.left + offsetX + 0.5f); 2339 const float y = (int) floorf(bounds.top + offsetY + 0.5f); 2340 dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight()); 2341 } else { 2342 dirtyLayer(left + bounds.left, top + bounds.top, 2343 left + bounds.right, top + bounds.bottom, *currentTransform()); 2344 } 2345 } 2346 } 2347 2348 bool ignoreTransform = false; 2349 if (CC_LIKELY(pureTranslate)) { 2350 const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f); 2351 const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f); 2352 2353 right = x + right - left; 2354 bottom = y + bottom - top; 2355 left = x; 2356 top = y; 2357 ignoreTransform = true; 2358 } 2359 drawIndexedTextureMesh(left, top, right, bottom, texture->id, paint, 2360 texture->blend, (GLvoid*) mesh->offset, (GLvoid*) mesh->textureOffset, 2361 GL_TRIANGLES, mesh->indexCount, false, ignoreTransform, 2362 mCaches.patchCache.getMeshBuffer(), kModelViewMode_Translate, !mesh->hasEmptyQuads); 2363 } 2364 2365 return DrawGlInfo::kStatusDrew; 2366} 2367 2368/** 2369 * Important note: this method is intended to draw batches of 9-patch objects and 2370 * will not set the scissor enable or dirty the current layer, if any. 2371 * The caller is responsible for properly dirtying the current layer. 2372 */ 2373status_t OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 2374 TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint) { 2375 mCaches.activeTexture(0); 2376 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 2377 if (!texture) return DrawGlInfo::kStatusDone; 2378 const AutoTexture autoCleanup(texture); 2379 2380 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2381 texture->setFilter(GL_LINEAR, true); 2382 2383 drawIndexedTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, paint, 2384 texture->blend, &vertices[0].x, &vertices[0].u, 2385 GL_TRIANGLES, indexCount, false, true, 0, kModelViewMode_Translate, false); 2386 2387 return DrawGlInfo::kStatusDrew; 2388} 2389 2390status_t OpenGLRenderer::drawVertexBuffer(VertexBufferMode mode, 2391 const VertexBuffer& vertexBuffer, const SkPaint* paint, bool useOffset) { 2392 // not missing call to quickReject/dirtyLayer, always done at a higher level 2393 if (!vertexBuffer.getVertexCount()) { 2394 // no vertices to draw 2395 return DrawGlInfo::kStatusDone; 2396 } 2397 2398 int color = paint->getColor(); 2399 bool isAA = paint->isAntiAlias(); 2400 2401 setupDraw(); 2402 setupDrawNoTexture(); 2403 if (isAA) setupDrawAA(); 2404 setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha); 2405 setupDrawColorFilter(getColorFilter(paint)); 2406 setupDrawShader(); 2407 setupDrawBlending(paint, isAA); 2408 setupDrawProgram(); 2409 setupDrawModelView(kModelViewMode_Translate, useOffset, 0, 0, 0, 0); 2410 setupDrawColorUniforms(); 2411 setupDrawColorFilterUniforms(getColorFilter(paint)); 2412 setupDrawShaderUniforms(); 2413 2414 const void* vertices = vertexBuffer.getBuffer(); 2415 bool force = mCaches.unbindMeshBuffer(); 2416 mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride); 2417 mCaches.resetTexCoordsVertexPointer(); 2418 2419 2420 int alphaSlot = -1; 2421 if (isAA) { 2422 void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset; 2423 alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha"); 2424 // TODO: avoid enable/disable in back to back uses of the alpha attribute 2425 glEnableVertexAttribArray(alphaSlot); 2426 glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords); 2427 } 2428 2429 if (mode == kVertexBufferMode_Standard) { 2430 mCaches.unbindIndicesBuffer(); 2431 glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getVertexCount()); 2432 } else { 2433 mCaches.bindShadowIndicesBuffer(); 2434 glDrawElements(GL_TRIANGLE_STRIP, SHADOW_INDEX_COUNT, GL_UNSIGNED_SHORT, 0); 2435 } 2436 2437 if (isAA) { 2438 glDisableVertexAttribArray(alphaSlot); 2439 } 2440 2441 return DrawGlInfo::kStatusDrew; 2442} 2443 2444/** 2445 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to 2446 * that of AA lines in the drawLines() function. We expand the convex path by a half pixel in 2447 * screen space in all directions. However, instead of using a fragment shader to compute the 2448 * translucency of the color from its position, we simply use a varying parameter to define how far 2449 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used. 2450 * 2451 * Doesn't yet support joins, caps, or path effects. 2452 */ 2453status_t OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) { 2454 VertexBuffer vertexBuffer; 2455 // TODO: try clipping large paths to viewport 2456 PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer); 2457 2458 if (hasLayer()) { 2459 SkRect bounds = path.getBounds(); 2460 PathTessellator::expandBoundsForStroke(bounds, paint); 2461 dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *currentTransform()); 2462 } 2463 2464 return drawVertexBuffer(kVertexBufferMode_Standard, vertexBuffer, paint); 2465} 2466 2467/** 2468 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha 2469 * and additional geometry for defining an alpha slope perimeter. 2470 * 2471 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some 2472 * unexpected results, and may vary between hardware devices. Previously we used a varying-base 2473 * in-shader alpha region, but found it to be taxing on some GPUs. 2474 * 2475 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce 2476 * memory transfer by removing need for degenerate vertices. 2477 */ 2478status_t OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) { 2479 if (currentSnapshot()->isIgnored() || count < 4) return DrawGlInfo::kStatusDone; 2480 2481 count &= ~0x3; // round down to nearest four 2482 2483 VertexBuffer buffer; 2484 SkRect bounds; 2485 PathTessellator::tessellateLines(points, count, paint, *currentTransform(), bounds, buffer); 2486 2487 // can't pass paint, since style would be checked for outset. outset done by tessellation. 2488 if (quickRejectSetupScissor(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom)) { 2489 return DrawGlInfo::kStatusDone; 2490 } 2491 2492 dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *currentTransform()); 2493 2494 bool useOffset = !paint->isAntiAlias(); 2495 return drawVertexBuffer(kVertexBufferMode_Standard, buffer, paint, useOffset); 2496} 2497 2498status_t OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) { 2499 if (currentSnapshot()->isIgnored() || count < 2) return DrawGlInfo::kStatusDone; 2500 2501 count &= ~0x1; // round down to nearest two 2502 2503 VertexBuffer buffer; 2504 SkRect bounds; 2505 PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), bounds, buffer); 2506 2507 // can't pass paint, since style would be checked for outset. outset done by tessellation. 2508 if (quickRejectSetupScissor(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom)) { 2509 return DrawGlInfo::kStatusDone; 2510 } 2511 2512 dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *currentTransform()); 2513 2514 bool useOffset = !paint->isAntiAlias(); 2515 return drawVertexBuffer(kVertexBufferMode_Standard, buffer, paint, useOffset); 2516} 2517 2518status_t OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 2519 // No need to check against the clip, we fill the clip region 2520 if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone; 2521 2522 Rect clip(*currentClipRect()); 2523 clip.snapToPixelBoundaries(); 2524 2525 SkPaint paint; 2526 paint.setColor(color); 2527 paint.setXfermodeMode(mode); 2528 2529 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true); 2530 2531 return DrawGlInfo::kStatusDrew; 2532} 2533 2534status_t OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, 2535 const SkPaint* paint) { 2536 if (!texture) return DrawGlInfo::kStatusDone; 2537 const AutoTexture autoCleanup(texture); 2538 2539 const float x = left + texture->left - texture->offset; 2540 const float y = top + texture->top - texture->offset; 2541 2542 drawPathTexture(texture, x, y, paint); 2543 2544 return DrawGlInfo::kStatusDrew; 2545} 2546 2547status_t OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom, 2548 float rx, float ry, const SkPaint* p) { 2549 if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) || 2550 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) { 2551 return DrawGlInfo::kStatusDone; 2552 } 2553 2554 if (p->getPathEffect() != 0) { 2555 mCaches.activeTexture(0); 2556 const PathTexture* texture = mCaches.pathCache.getRoundRect( 2557 right - left, bottom - top, rx, ry, p); 2558 return drawShape(left, top, texture, p); 2559 } 2560 2561 SkPath path; 2562 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2563 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2564 float outset = p->getStrokeWidth() / 2; 2565 rect.outset(outset, outset); 2566 rx += outset; 2567 ry += outset; 2568 } 2569 path.addRoundRect(rect, rx, ry); 2570 return drawConvexPath(path, p); 2571} 2572 2573status_t OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) { 2574 if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(x - radius, y - radius, 2575 x + radius, y + radius, p) || 2576 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) { 2577 return DrawGlInfo::kStatusDone; 2578 } 2579 if (p->getPathEffect() != 0) { 2580 mCaches.activeTexture(0); 2581 const PathTexture* texture = mCaches.pathCache.getCircle(radius, p); 2582 return drawShape(x - radius, y - radius, texture, p); 2583 } 2584 2585 SkPath path; 2586 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2587 path.addCircle(x, y, radius + p->getStrokeWidth() / 2); 2588 } else { 2589 path.addCircle(x, y, radius); 2590 } 2591 return drawConvexPath(path, p); 2592} 2593 2594status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom, 2595 const SkPaint* p) { 2596 if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) || 2597 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) { 2598 return DrawGlInfo::kStatusDone; 2599 } 2600 2601 if (p->getPathEffect() != 0) { 2602 mCaches.activeTexture(0); 2603 const PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p); 2604 return drawShape(left, top, texture, p); 2605 } 2606 2607 SkPath path; 2608 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2609 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2610 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2611 } 2612 path.addOval(rect); 2613 return drawConvexPath(path, p); 2614} 2615 2616status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom, 2617 float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) { 2618 if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) || 2619 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) { 2620 return DrawGlInfo::kStatusDone; 2621 } 2622 2623 if (fabs(sweepAngle) >= 360.0f) { 2624 return drawOval(left, top, right, bottom, p); 2625 } 2626 2627 // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180) 2628 if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || useCenter) { 2629 mCaches.activeTexture(0); 2630 const PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top, 2631 startAngle, sweepAngle, useCenter, p); 2632 return drawShape(left, top, texture, p); 2633 } 2634 2635 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2636 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2637 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2638 } 2639 2640 SkPath path; 2641 if (useCenter) { 2642 path.moveTo(rect.centerX(), rect.centerY()); 2643 } 2644 path.arcTo(rect, startAngle, sweepAngle, !useCenter); 2645 if (useCenter) { 2646 path.close(); 2647 } 2648 return drawConvexPath(path, p); 2649} 2650 2651// See SkPaintDefaults.h 2652#define SkPaintDefaults_MiterLimit SkIntToScalar(4) 2653 2654status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom, 2655 const SkPaint* p) { 2656 if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) || 2657 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) { 2658 return DrawGlInfo::kStatusDone; 2659 } 2660 2661 if (p->getStyle() != SkPaint::kFill_Style) { 2662 // only fill style is supported by drawConvexPath, since others have to handle joins 2663 if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join || 2664 p->getStrokeMiter() != SkPaintDefaults_MiterLimit) { 2665 mCaches.activeTexture(0); 2666 const PathTexture* texture = 2667 mCaches.pathCache.getRect(right - left, bottom - top, p); 2668 return drawShape(left, top, texture, p); 2669 } 2670 2671 SkPath path; 2672 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2673 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2674 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2675 } 2676 path.addRect(rect); 2677 return drawConvexPath(path, p); 2678 } 2679 2680 if (p->isAntiAlias() && !currentTransform()->isSimple()) { 2681 SkPath path; 2682 path.addRect(left, top, right, bottom); 2683 return drawConvexPath(path, p); 2684 } else { 2685 drawColorRect(left, top, right, bottom, p); 2686 return DrawGlInfo::kStatusDrew; 2687 } 2688} 2689 2690void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text, 2691 int bytesCount, int count, const float* positions, 2692 FontRenderer& fontRenderer, int alpha, float x, float y) { 2693 mCaches.activeTexture(0); 2694 2695 // NOTE: The drop shadow will not perform gamma correction 2696 // if shader-based correction is enabled 2697 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 2698 const ShadowTexture* shadow = mCaches.dropShadowCache.get( 2699 paint, text, bytesCount, count, mDrawModifiers.mShadowRadius, positions); 2700 // If the drop shadow exceeds the max texture size or couldn't be 2701 // allocated, skip drawing 2702 if (!shadow) return; 2703 const AutoTexture autoCleanup(shadow); 2704 2705 const float sx = x - shadow->left + mDrawModifiers.mShadowDx; 2706 const float sy = y - shadow->top + mDrawModifiers.mShadowDy; 2707 2708 const int shadowAlpha = ((mDrawModifiers.mShadowColor >> 24) & 0xFF) * mSnapshot->alpha; 2709 int shadowColor = mDrawModifiers.mShadowColor; 2710 if (mDrawModifiers.mShader) { 2711 shadowColor = 0xffffffff; 2712 } 2713 2714 setupDraw(); 2715 setupDrawWithTexture(true); 2716 setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha); 2717 setupDrawColorFilter(getColorFilter(paint)); 2718 setupDrawShader(); 2719 setupDrawBlending(paint, true); 2720 setupDrawProgram(); 2721 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 2722 sx, sy, sx + shadow->width, sy + shadow->height); 2723 setupDrawTexture(shadow->id); 2724 setupDrawPureColorUniforms(); 2725 setupDrawColorFilterUniforms(getColorFilter(paint)); 2726 setupDrawShaderUniforms(); 2727 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 2728 2729 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 2730} 2731 2732bool OpenGLRenderer::canSkipText(const SkPaint* paint) const { 2733 float alpha = (mDrawModifiers.mHasShadow ? 1.0f : paint->getAlpha()) * mSnapshot->alpha; 2734 return alpha == 0.0f && getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode; 2735} 2736 2737status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count, 2738 const float* positions, const SkPaint* paint) { 2739 if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint)) { 2740 return DrawGlInfo::kStatusDone; 2741 } 2742 2743 // NOTE: Skia does not support perspective transform on drawPosText yet 2744 if (!currentTransform()->isSimple()) { 2745 return DrawGlInfo::kStatusDone; 2746 } 2747 2748 mCaches.enableScissor(); 2749 2750 float x = 0.0f; 2751 float y = 0.0f; 2752 const bool pureTranslate = currentTransform()->isPureTranslate(); 2753 if (pureTranslate) { 2754 x = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f); 2755 y = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f); 2756 } 2757 2758 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2759 fontRenderer.setFont(paint, mat4::identity()); 2760 2761 int alpha; 2762 SkXfermode::Mode mode; 2763 getAlphaAndMode(paint, &alpha, &mode); 2764 2765 if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) { 2766 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, 2767 alpha, 0.0f, 0.0f); 2768 } 2769 2770 // Pick the appropriate texture filtering 2771 bool linearFilter = currentTransform()->changesBounds(); 2772 if (pureTranslate && !linearFilter) { 2773 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2774 } 2775 fontRenderer.setTextureFiltering(linearFilter); 2776 2777 const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip(); 2778 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2779 2780 const bool hasActiveLayer = hasLayer(); 2781 2782 TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint); 2783 if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y, 2784 positions, hasActiveLayer ? &bounds : NULL, &functor)) { 2785 if (hasActiveLayer) { 2786 if (!pureTranslate) { 2787 currentTransform()->mapRect(bounds); 2788 } 2789 dirtyLayerUnchecked(bounds, getRegion()); 2790 } 2791 } 2792 2793 return DrawGlInfo::kStatusDrew; 2794} 2795 2796mat4 OpenGLRenderer::findBestFontTransform(const mat4& transform) const { 2797 mat4 fontTransform; 2798 if (CC_LIKELY(transform.isPureTranslate())) { 2799 fontTransform = mat4::identity(); 2800 } else { 2801 if (CC_UNLIKELY(transform.isPerspective())) { 2802 fontTransform = mat4::identity(); 2803 } else { 2804 float sx, sy; 2805 currentTransform()->decomposeScale(sx, sy); 2806 fontTransform.loadScale(sx, sy, 1.0f); 2807 } 2808 } 2809 return fontTransform; 2810} 2811 2812status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y, 2813 const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds, 2814 DrawOpMode drawOpMode) { 2815 2816 if (drawOpMode == kDrawOpMode_Immediate) { 2817 // The checks for corner-case ignorable text and quick rejection is only done for immediate 2818 // drawing as ops from DeferredDisplayList are already filtered for these 2819 if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint) || 2820 quickRejectSetupScissor(bounds)) { 2821 return DrawGlInfo::kStatusDone; 2822 } 2823 } 2824 2825 const float oldX = x; 2826 const float oldY = y; 2827 2828 const mat4& transform = *currentTransform(); 2829 const bool pureTranslate = transform.isPureTranslate(); 2830 2831 if (CC_LIKELY(pureTranslate)) { 2832 x = (int) floorf(x + transform.getTranslateX() + 0.5f); 2833 y = (int) floorf(y + transform.getTranslateY() + 0.5f); 2834 } 2835 2836 int alpha; 2837 SkXfermode::Mode mode; 2838 getAlphaAndMode(paint, &alpha, &mode); 2839 2840 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2841 2842 if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) { 2843 fontRenderer.setFont(paint, mat4::identity()); 2844 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, 2845 alpha, oldX, oldY); 2846 } 2847 2848 const bool hasActiveLayer = hasLayer(); 2849 2850 // We only pass a partial transform to the font renderer. That partial 2851 // matrix defines how glyphs are rasterized. Typically we want glyphs 2852 // to be rasterized at their final size on screen, which means the partial 2853 // matrix needs to take the scale factor into account. 2854 // When a partial matrix is used to transform glyphs during rasterization, 2855 // the mesh is generated with the inverse transform (in the case of scale, 2856 // the mesh is generated at 1.0 / scale for instance.) This allows us to 2857 // apply the full transform matrix at draw time in the vertex shader. 2858 // Applying the full matrix in the shader is the easiest way to handle 2859 // rotation and perspective and allows us to always generated quads in the 2860 // font renderer which greatly simplifies the code, clipping in particular. 2861 mat4 fontTransform = findBestFontTransform(transform); 2862 fontRenderer.setFont(paint, fontTransform); 2863 2864 // Pick the appropriate texture filtering 2865 bool linearFilter = !pureTranslate || fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2866 fontRenderer.setTextureFiltering(linearFilter); 2867 2868 // TODO: Implement better clipping for scaled/rotated text 2869 const Rect* clip = !pureTranslate ? NULL : currentClipRect(); 2870 Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2871 2872 bool status; 2873 TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint); 2874 2875 // don't call issuedrawcommand, do it at end of batch 2876 bool forceFinish = (drawOpMode != kDrawOpMode_Defer); 2877 if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) { 2878 SkPaint paintCopy(*paint); 2879 paintCopy.setTextAlign(SkPaint::kLeft_Align); 2880 status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y, 2881 positions, hasActiveLayer ? &layerBounds : NULL, &functor, forceFinish); 2882 } else { 2883 status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y, 2884 positions, hasActiveLayer ? &layerBounds : NULL, &functor, forceFinish); 2885 } 2886 2887 if ((status || drawOpMode != kDrawOpMode_Immediate) && hasActiveLayer) { 2888 if (!pureTranslate) { 2889 transform.mapRect(layerBounds); 2890 } 2891 dirtyLayerUnchecked(layerBounds, getRegion()); 2892 } 2893 2894 drawTextDecorations(totalAdvance, oldX, oldY, paint); 2895 2896 return DrawGlInfo::kStatusDrew; 2897} 2898 2899status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, 2900 const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) { 2901 if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint)) { 2902 return DrawGlInfo::kStatusDone; 2903 } 2904 2905 // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics 2906 mCaches.enableScissor(); 2907 2908 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2909 fontRenderer.setFont(paint, mat4::identity()); 2910 fontRenderer.setTextureFiltering(true); 2911 2912 int alpha; 2913 SkXfermode::Mode mode; 2914 getAlphaAndMode(paint, &alpha, &mode); 2915 TextSetupFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint); 2916 2917 const Rect* clip = &mSnapshot->getLocalClip(); 2918 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2919 2920 const bool hasActiveLayer = hasLayer(); 2921 2922 if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path, 2923 hOffset, vOffset, hasActiveLayer ? &bounds : NULL, &functor)) { 2924 if (hasActiveLayer) { 2925 currentTransform()->mapRect(bounds); 2926 dirtyLayerUnchecked(bounds, getRegion()); 2927 } 2928 } 2929 2930 return DrawGlInfo::kStatusDrew; 2931} 2932 2933status_t OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) { 2934 if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone; 2935 2936 mCaches.activeTexture(0); 2937 2938 const PathTexture* texture = mCaches.pathCache.get(path, paint); 2939 if (!texture) return DrawGlInfo::kStatusDone; 2940 const AutoTexture autoCleanup(texture); 2941 2942 const float x = texture->left - texture->offset; 2943 const float y = texture->top - texture->offset; 2944 2945 drawPathTexture(texture, x, y, paint); 2946 2947 return DrawGlInfo::kStatusDrew; 2948} 2949 2950status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y) { 2951 if (!layer) { 2952 return DrawGlInfo::kStatusDone; 2953 } 2954 2955 mat4* transform = NULL; 2956 if (layer->isTextureLayer()) { 2957 transform = &layer->getTransform(); 2958 if (!transform->isIdentity()) { 2959 save(0); 2960 concatMatrix(*transform); 2961 } 2962 } 2963 2964 bool clipRequired = false; 2965 const bool rejected = calculateQuickRejectForScissor(x, y, 2966 x + layer->layer.getWidth(), y + layer->layer.getHeight(), &clipRequired, false); 2967 2968 if (rejected) { 2969 if (transform && !transform->isIdentity()) { 2970 restore(); 2971 } 2972 return DrawGlInfo::kStatusDone; 2973 } 2974 2975 updateLayer(layer, true); 2976 2977 mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired); 2978 mCaches.activeTexture(0); 2979 2980 if (CC_LIKELY(!layer->region.isEmpty())) { 2981 if (layer->region.isRect()) { 2982 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, 2983 composeLayerRect(layer, layer->regionRect)); 2984 } else if (layer->mesh) { 2985 2986 const float a = getLayerAlpha(layer); 2987 setupDraw(); 2988 setupDrawWithTexture(); 2989 setupDrawColor(a, a, a, a); 2990 setupDrawColorFilter(layer->getColorFilter()); 2991 setupDrawBlending(layer); 2992 setupDrawProgram(); 2993 setupDrawPureColorUniforms(); 2994 setupDrawColorFilterUniforms(layer->getColorFilter()); 2995 setupDrawTexture(layer->getTexture()); 2996 if (CC_LIKELY(currentTransform()->isPureTranslate())) { 2997 int tx = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f); 2998 int ty = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f); 2999 3000 layer->setFilter(GL_NEAREST); 3001 setupDrawModelView(kModelViewMode_Translate, false, tx, ty, 3002 tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true); 3003 } else { 3004 layer->setFilter(GL_LINEAR); 3005 setupDrawModelView(kModelViewMode_Translate, false, x, y, 3006 x + layer->layer.getWidth(), y + layer->layer.getHeight()); 3007 } 3008 3009 TextureVertex* mesh = &layer->mesh[0]; 3010 GLsizei elementsCount = layer->meshElementCount; 3011 3012 while (elementsCount > 0) { 3013 GLsizei drawCount = min(elementsCount, (GLsizei) gMaxNumberOfQuads * 6); 3014 3015 setupDrawMeshIndices(&mesh[0].x, &mesh[0].u); 3016 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, 3017 glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, NULL)); 3018 3019 elementsCount -= drawCount; 3020 // Though there are 4 vertices in a quad, we use 6 indices per 3021 // quad to draw with GL_TRIANGLES 3022 mesh += (drawCount / 6) * 4; 3023 } 3024 3025#if DEBUG_LAYERS_AS_REGIONS 3026 drawRegionRectsDebug(layer->region); 3027#endif 3028 } 3029 3030 if (layer->debugDrawUpdate) { 3031 layer->debugDrawUpdate = false; 3032 3033 SkPaint paint; 3034 paint.setColor(0x7f00ff00); 3035 drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint); 3036 } 3037 } 3038 layer->hasDrawnSinceUpdate = true; 3039 3040 if (transform && !transform->isIdentity()) { 3041 restore(); 3042 } 3043 3044 return DrawGlInfo::kStatusDrew; 3045} 3046 3047/////////////////////////////////////////////////////////////////////////////// 3048// Shaders 3049/////////////////////////////////////////////////////////////////////////////// 3050 3051void OpenGLRenderer::resetShader() { 3052 mDrawModifiers.mShader = NULL; 3053} 3054 3055void OpenGLRenderer::setupShader(SkiaShader* shader) { 3056 mDrawModifiers.mShader = shader; 3057 if (mDrawModifiers.mShader) { 3058 mDrawModifiers.mShader->setCaches(mCaches); 3059 } 3060} 3061 3062/////////////////////////////////////////////////////////////////////////////// 3063// Drop shadow 3064/////////////////////////////////////////////////////////////////////////////// 3065 3066void OpenGLRenderer::resetShadow() { 3067 mDrawModifiers.mHasShadow = false; 3068} 3069 3070void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) { 3071 mDrawModifiers.mHasShadow = true; 3072 mDrawModifiers.mShadowRadius = radius; 3073 mDrawModifiers.mShadowDx = dx; 3074 mDrawModifiers.mShadowDy = dy; 3075 mDrawModifiers.mShadowColor = color; 3076} 3077 3078/////////////////////////////////////////////////////////////////////////////// 3079// Draw filters 3080/////////////////////////////////////////////////////////////////////////////// 3081 3082void OpenGLRenderer::resetPaintFilter() { 3083 // when clearing the PaintFilter, the masks should also be cleared for simple DrawModifier 3084 // comparison, see MergingDrawBatch::canMergeWith 3085 mDrawModifiers.mHasDrawFilter = false; 3086 mDrawModifiers.mPaintFilterClearBits = 0; 3087 mDrawModifiers.mPaintFilterSetBits = 0; 3088} 3089 3090void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) { 3091 mDrawModifiers.mHasDrawFilter = true; 3092 mDrawModifiers.mPaintFilterClearBits = clearBits & SkPaint::kAllFlags; 3093 mDrawModifiers.mPaintFilterSetBits = setBits & SkPaint::kAllFlags; 3094} 3095 3096const SkPaint* OpenGLRenderer::filterPaint(const SkPaint* paint) { 3097 if (CC_LIKELY(!mDrawModifiers.mHasDrawFilter || !paint)) { 3098 return paint; 3099 } 3100 3101 uint32_t flags = paint->getFlags(); 3102 3103 mFilteredPaint = *paint; 3104 mFilteredPaint.setFlags((flags & ~mDrawModifiers.mPaintFilterClearBits) | 3105 mDrawModifiers.mPaintFilterSetBits); 3106 3107 return &mFilteredPaint; 3108} 3109 3110/////////////////////////////////////////////////////////////////////////////// 3111// Drawing implementation 3112/////////////////////////////////////////////////////////////////////////////// 3113 3114Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) { 3115 Texture* texture = mCaches.assetAtlas.getEntryTexture(bitmap); 3116 if (!texture) { 3117 return mCaches.textureCache.get(bitmap); 3118 } 3119 return texture; 3120} 3121 3122void OpenGLRenderer::drawPathTexture(const PathTexture* texture, 3123 float x, float y, const SkPaint* paint) { 3124 if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) { 3125 return; 3126 } 3127 3128 int alpha; 3129 SkXfermode::Mode mode; 3130 getAlphaAndMode(paint, &alpha, &mode); 3131 3132 setupDraw(); 3133 setupDrawWithTexture(true); 3134 setupDrawAlpha8Color(paint->getColor(), alpha); 3135 setupDrawColorFilter(getColorFilter(paint)); 3136 setupDrawShader(); 3137 setupDrawBlending(paint, true); 3138 setupDrawProgram(); 3139 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 3140 x, y, x + texture->width, y + texture->height); 3141 setupDrawTexture(texture->id); 3142 setupDrawPureColorUniforms(); 3143 setupDrawColorFilterUniforms(getColorFilter(paint)); 3144 setupDrawShaderUniforms(); 3145 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 3146 3147 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 3148} 3149 3150// Same values used by Skia 3151#define kStdStrikeThru_Offset (-6.0f / 21.0f) 3152#define kStdUnderline_Offset (1.0f / 9.0f) 3153#define kStdUnderline_Thickness (1.0f / 18.0f) 3154 3155void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y, 3156 const SkPaint* paint) { 3157 // Handle underline and strike-through 3158 uint32_t flags = paint->getFlags(); 3159 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) { 3160 SkPaint paintCopy(*paint); 3161 3162 if (CC_LIKELY(underlineWidth > 0.0f)) { 3163 const float textSize = paintCopy.getTextSize(); 3164 const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f); 3165 3166 const float left = x; 3167 float top = 0.0f; 3168 3169 int linesCount = 0; 3170 if (flags & SkPaint::kUnderlineText_Flag) linesCount++; 3171 if (flags & SkPaint::kStrikeThruText_Flag) linesCount++; 3172 3173 const int pointsCount = 4 * linesCount; 3174 float points[pointsCount]; 3175 int currentPoint = 0; 3176 3177 if (flags & SkPaint::kUnderlineText_Flag) { 3178 top = y + textSize * kStdUnderline_Offset; 3179 points[currentPoint++] = left; 3180 points[currentPoint++] = top; 3181 points[currentPoint++] = left + underlineWidth; 3182 points[currentPoint++] = top; 3183 } 3184 3185 if (flags & SkPaint::kStrikeThruText_Flag) { 3186 top = y + textSize * kStdStrikeThru_Offset; 3187 points[currentPoint++] = left; 3188 points[currentPoint++] = top; 3189 points[currentPoint++] = left + underlineWidth; 3190 points[currentPoint++] = top; 3191 } 3192 3193 paintCopy.setStrokeWidth(strokeWidth); 3194 3195 drawLines(&points[0], pointsCount, &paintCopy); 3196 } 3197 } 3198} 3199 3200status_t OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) { 3201 if (currentSnapshot()->isIgnored()) { 3202 return DrawGlInfo::kStatusDone; 3203 } 3204 3205 return drawColorRects(rects, count, paint, false, true, true); 3206} 3207 3208status_t OpenGLRenderer::drawShadow(const mat4& casterTransform, float casterAlpha, 3209 const SkPath* casterOutline) { 3210 if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone; 3211 3212 // TODO: use quickRejectWithScissor. For now, always force enable scissor. 3213 mCaches.enableScissor(); 3214 3215 SkPaint paint; 3216 paint.setAntiAlias(true); // want to use AlphaVertex 3217 3218 // tessellate caster outline into a 2d polygon 3219 Vector<Vertex> casterVertices2d; 3220 const float casterRefinementThresholdSquared = 20.0f; // TODO: experiment with this value 3221 PathTessellator::approximatePathOutlineVertices(*casterOutline, 3222 casterRefinementThresholdSquared, casterVertices2d); 3223 3224 if (casterVertices2d.size() == 0) { 3225 // empty caster polygon computed from path 3226 return DrawGlInfo::kStatusDone; 3227 } 3228 3229 // map 2d caster poly into 3d 3230 const int casterVertexCount = casterVertices2d.size(); 3231 Vector3 casterPolygon[casterVertexCount]; 3232 for (int i = 0; i < casterVertexCount; i++) { 3233 const Vertex& point2d = casterVertices2d[i]; 3234 casterPolygon[i] = Vector3(point2d.x, point2d.y, 0); 3235 casterTransform.mapPoint3d(casterPolygon[i]); 3236 } 3237 3238 // map the centroid of the caster into 3d 3239 Vector2 centroid = ShadowTessellator::centroid2d( 3240 reinterpret_cast<const Vector2*>(casterVertices2d.array()), 3241 casterVertexCount); 3242 Vector3 centroid3d(centroid.x, centroid.y, 0); 3243 casterTransform.mapPoint3d(centroid3d); 3244 3245 // draw caster's shadows 3246 if (mCaches.propertyAmbientShadowStrength > 0) { 3247 paint.setARGB(casterAlpha * mCaches.propertyAmbientShadowStrength, 0, 0, 0); 3248 VertexBuffer ambientShadowVertexBuffer; 3249 ShadowTessellator::tessellateAmbientShadow(casterPolygon, casterVertexCount, 3250 centroid3d, ambientShadowVertexBuffer); 3251 drawVertexBuffer(kVertexBufferMode_Shadow, ambientShadowVertexBuffer, &paint); 3252 } 3253 3254 if (mCaches.propertySpotShadowStrength > 0) { 3255 paint.setARGB(casterAlpha * mCaches.propertySpotShadowStrength, 0, 0, 0); 3256 VertexBuffer spotShadowVertexBuffer; 3257 Vector3 lightPosScale(mCaches.propertyLightPosXScale, 3258 mCaches.propertyLightPosYScale, mCaches.propertyLightPosZScale); 3259 ShadowTessellator::tessellateSpotShadow(casterPolygon, casterVertexCount, 3260 lightPosScale, *currentTransform(), getWidth(), getHeight(), 3261 spotShadowVertexBuffer); 3262 3263 drawVertexBuffer(kVertexBufferMode_Shadow, spotShadowVertexBuffer, &paint); 3264 } 3265 3266 return DrawGlInfo::kStatusDrew; 3267} 3268 3269status_t OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint, 3270 bool ignoreTransform, bool dirty, bool clip) { 3271 if (count == 0) { 3272 return DrawGlInfo::kStatusDone; 3273 } 3274 3275 int color = paint->getColor(); 3276 // If a shader is set, preserve only the alpha 3277 if (mDrawModifiers.mShader) { 3278 color |= 0x00ffffff; 3279 } 3280 3281 float left = FLT_MAX; 3282 float top = FLT_MAX; 3283 float right = FLT_MIN; 3284 float bottom = FLT_MIN; 3285 3286 Vertex mesh[count]; 3287 Vertex* vertex = mesh; 3288 3289 for (int index = 0; index < count; index += 4) { 3290 float l = rects[index + 0]; 3291 float t = rects[index + 1]; 3292 float r = rects[index + 2]; 3293 float b = rects[index + 3]; 3294 3295 Vertex::set(vertex++, l, t); 3296 Vertex::set(vertex++, r, t); 3297 Vertex::set(vertex++, l, b); 3298 Vertex::set(vertex++, r, b); 3299 3300 left = fminf(left, l); 3301 top = fminf(top, t); 3302 right = fmaxf(right, r); 3303 bottom = fmaxf(bottom, b); 3304 } 3305 3306 if (clip && quickRejectSetupScissor(left, top, right, bottom)) { 3307 return DrawGlInfo::kStatusDone; 3308 } 3309 3310 setupDraw(); 3311 setupDrawNoTexture(); 3312 setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha); 3313 setupDrawShader(); 3314 setupDrawColorFilter(getColorFilter(paint)); 3315 setupDrawBlending(paint); 3316 setupDrawProgram(); 3317 setupDrawDirtyRegionsDisabled(); 3318 setupDrawModelView(kModelViewMode_Translate, false, 3319 0.0f, 0.0f, 0.0f, 0.0f, ignoreTransform); 3320 setupDrawColorUniforms(); 3321 setupDrawShaderUniforms(); 3322 setupDrawColorFilterUniforms(getColorFilter(paint)); 3323 3324 if (dirty && hasLayer()) { 3325 dirtyLayer(left, top, right, bottom, *currentTransform()); 3326 } 3327 3328 issueIndexedQuadDraw(&mesh[0], count / 4); 3329 3330 return DrawGlInfo::kStatusDrew; 3331} 3332 3333void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 3334 const SkPaint* paint, bool ignoreTransform) { 3335 int color = paint->getColor(); 3336 // If a shader is set, preserve only the alpha 3337 if (mDrawModifiers.mShader) { 3338 color |= 0x00ffffff; 3339 } 3340 3341 setupDraw(); 3342 setupDrawNoTexture(); 3343 setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha); 3344 setupDrawShader(); 3345 setupDrawColorFilter(getColorFilter(paint)); 3346 setupDrawBlending(paint); 3347 setupDrawProgram(); 3348 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 3349 left, top, right, bottom, ignoreTransform); 3350 setupDrawColorUniforms(); 3351 setupDrawShaderUniforms(ignoreTransform); 3352 setupDrawColorFilterUniforms(getColorFilter(paint)); 3353 setupDrawSimpleMesh(); 3354 3355 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 3356} 3357 3358void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 3359 Texture* texture, const SkPaint* paint) { 3360 texture->setWrap(GL_CLAMP_TO_EDGE, true); 3361 3362 GLvoid* vertices = (GLvoid*) NULL; 3363 GLvoid* texCoords = (GLvoid*) gMeshTextureOffset; 3364 3365 if (texture->uvMapper) { 3366 vertices = &mMeshVertices[0].x; 3367 texCoords = &mMeshVertices[0].u; 3368 3369 Rect uvs(0.0f, 0.0f, 1.0f, 1.0f); 3370 texture->uvMapper->map(uvs); 3371 3372 resetDrawTextureTexCoords(uvs.left, uvs.top, uvs.right, uvs.bottom); 3373 } 3374 3375 if (CC_LIKELY(currentTransform()->isPureTranslate())) { 3376 const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f); 3377 const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f); 3378 3379 texture->setFilter(GL_NEAREST, true); 3380 drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 3381 paint, texture->blend, vertices, texCoords, 3382 GL_TRIANGLE_STRIP, gMeshCount, false, true); 3383 } else { 3384 texture->setFilter(FILTER(paint), true); 3385 drawTextureMesh(left, top, right, bottom, texture->id, paint, 3386 texture->blend, vertices, texCoords, GL_TRIANGLE_STRIP, gMeshCount); 3387 } 3388 3389 if (texture->uvMapper) { 3390 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 3391 } 3392} 3393 3394void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom, 3395 GLuint texture, const SkPaint* paint, bool blend, 3396 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3397 bool swapSrcDst, bool ignoreTransform, GLuint vbo, 3398 ModelViewMode modelViewMode, bool dirty) { 3399 3400 int a; 3401 SkXfermode::Mode mode; 3402 getAlphaAndMode(paint, &a, &mode); 3403 const float alpha = a / 255.0f; 3404 3405 setupDraw(); 3406 setupDrawWithTexture(); 3407 setupDrawColor(alpha, alpha, alpha, alpha); 3408 setupDrawColorFilter(getColorFilter(paint)); 3409 setupDrawBlending(paint, blend, swapSrcDst); 3410 setupDrawProgram(); 3411 if (!dirty) setupDrawDirtyRegionsDisabled(); 3412 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3413 setupDrawTexture(texture); 3414 setupDrawPureColorUniforms(); 3415 setupDrawColorFilterUniforms(getColorFilter(paint)); 3416 setupDrawMesh(vertices, texCoords, vbo); 3417 3418 glDrawArrays(drawMode, 0, elementsCount); 3419} 3420 3421void OpenGLRenderer::drawIndexedTextureMesh(float left, float top, float right, float bottom, 3422 GLuint texture, const SkPaint* paint, bool blend, 3423 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3424 bool swapSrcDst, bool ignoreTransform, GLuint vbo, 3425 ModelViewMode modelViewMode, bool dirty) { 3426 3427 int a; 3428 SkXfermode::Mode mode; 3429 getAlphaAndMode(paint, &a, &mode); 3430 const float alpha = a / 255.0f; 3431 3432 setupDraw(); 3433 setupDrawWithTexture(); 3434 setupDrawColor(alpha, alpha, alpha, alpha); 3435 setupDrawColorFilter(getColorFilter(paint)); 3436 setupDrawBlending(paint, blend, swapSrcDst); 3437 setupDrawProgram(); 3438 if (!dirty) setupDrawDirtyRegionsDisabled(); 3439 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3440 setupDrawTexture(texture); 3441 setupDrawPureColorUniforms(); 3442 setupDrawColorFilterUniforms(getColorFilter(paint)); 3443 setupDrawMeshIndices(vertices, texCoords, vbo); 3444 3445 glDrawElements(drawMode, elementsCount, GL_UNSIGNED_SHORT, NULL); 3446} 3447 3448void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom, 3449 GLuint texture, const SkPaint* paint, 3450 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3451 bool ignoreTransform, ModelViewMode modelViewMode, bool dirty) { 3452 3453 int color = paint != NULL ? paint->getColor() : 0; 3454 int alpha; 3455 SkXfermode::Mode mode; 3456 getAlphaAndMode(paint, &alpha, &mode); 3457 3458 setupDraw(); 3459 setupDrawWithTexture(true); 3460 if (paint != NULL) { 3461 setupDrawAlpha8Color(color, alpha); 3462 } 3463 setupDrawColorFilter(getColorFilter(paint)); 3464 setupDrawShader(); 3465 setupDrawBlending(paint, true); 3466 setupDrawProgram(); 3467 if (!dirty) setupDrawDirtyRegionsDisabled(); 3468 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3469 setupDrawTexture(texture); 3470 setupDrawPureColorUniforms(); 3471 setupDrawColorFilterUniforms(getColorFilter(paint)); 3472 setupDrawShaderUniforms(ignoreTransform); 3473 setupDrawMesh(vertices, texCoords); 3474 3475 glDrawArrays(drawMode, 0, elementsCount); 3476} 3477 3478void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, 3479 ProgramDescription& description, bool swapSrcDst) { 3480 if (mCountOverdraw) { 3481 if (!mCaches.blend) glEnable(GL_BLEND); 3482 if (mCaches.lastSrcMode != GL_ONE || mCaches.lastDstMode != GL_ONE) { 3483 glBlendFunc(GL_ONE, GL_ONE); 3484 } 3485 3486 mCaches.blend = true; 3487 mCaches.lastSrcMode = GL_ONE; 3488 mCaches.lastDstMode = GL_ONE; 3489 3490 return; 3491 } 3492 3493 blend = blend || mode != SkXfermode::kSrcOver_Mode; 3494 3495 if (blend) { 3496 // These blend modes are not supported by OpenGL directly and have 3497 // to be implemented using shaders. Since the shader will perform 3498 // the blending, turn blending off here 3499 // If the blend mode cannot be implemented using shaders, fall 3500 // back to the default SrcOver blend mode instead 3501 if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) { 3502 if (CC_UNLIKELY(mExtensions.hasFramebufferFetch())) { 3503 description.framebufferMode = mode; 3504 description.swapSrcDst = swapSrcDst; 3505 3506 if (mCaches.blend) { 3507 glDisable(GL_BLEND); 3508 mCaches.blend = false; 3509 } 3510 3511 return; 3512 } else { 3513 mode = SkXfermode::kSrcOver_Mode; 3514 } 3515 } 3516 3517 if (!mCaches.blend) { 3518 glEnable(GL_BLEND); 3519 } 3520 3521 GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src; 3522 GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst; 3523 3524 if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) { 3525 glBlendFunc(sourceMode, destMode); 3526 mCaches.lastSrcMode = sourceMode; 3527 mCaches.lastDstMode = destMode; 3528 } 3529 } else if (mCaches.blend) { 3530 glDisable(GL_BLEND); 3531 } 3532 mCaches.blend = blend; 3533} 3534 3535bool OpenGLRenderer::useProgram(Program* program) { 3536 if (!program->isInUse()) { 3537 if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove(); 3538 program->use(); 3539 mCaches.currentProgram = program; 3540 return false; 3541 } 3542 return true; 3543} 3544 3545void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) { 3546 TextureVertex* v = &mMeshVertices[0]; 3547 TextureVertex::setUV(v++, u1, v1); 3548 TextureVertex::setUV(v++, u2, v1); 3549 TextureVertex::setUV(v++, u1, v2); 3550 TextureVertex::setUV(v++, u2, v2); 3551} 3552 3553void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const { 3554 getAlphaAndModeDirect(paint, alpha, mode); 3555 if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) { 3556 // if drawing a layer, ignore the paint's alpha 3557 *alpha = mDrawModifiers.mOverrideLayerAlpha * 255; 3558 } 3559 *alpha *= currentSnapshot()->alpha; 3560} 3561 3562float OpenGLRenderer::getLayerAlpha(const Layer* layer) const { 3563 float alpha; 3564 if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) { 3565 alpha = mDrawModifiers.mOverrideLayerAlpha; 3566 } else { 3567 alpha = layer->getAlpha() / 255.0f; 3568 } 3569 return alpha * currentSnapshot()->alpha; 3570} 3571 3572}; // namespace uirenderer 3573}; // namespace android 3574