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