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