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