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