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