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