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