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