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