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