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