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