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