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