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