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