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