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