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