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