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