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