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