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