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