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