OpenGLRenderer.cpp revision 886b275e529e44a59c54b933453d9bc902973178
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, SkPaint* paint) { 1258 if (paint->getStyle() != SkPaint::kFill_Style) { 1259 float outset = paint->getStrokeWidth() * 0.5f; 1260 return quickReject(left - outset, top - outset, right + outset, bottom + outset); 1261 } else { 1262 return quickReject(left, top, right, bottom); 1263 } 1264} 1265 1266bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) { 1267 if (mSnapshot->isIgnored() || bottom <= top || right <= left) { 1268 return true; 1269 } 1270 1271 Rect r(left, top, right, bottom); 1272 mSnapshot->transform->mapRect(r); 1273 r.snapToPixelBoundaries(); 1274 1275 Rect clipRect(*mSnapshot->clipRect); 1276 clipRect.snapToPixelBoundaries(); 1277 1278 bool rejected = !clipRect.intersects(r); 1279 if (!isDeferred() && !rejected) { 1280 mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clipRect.contains(r)); 1281 } 1282 1283 return rejected; 1284} 1285 1286bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) { 1287 bool clipped = mSnapshot->clip(left, top, right, bottom, op); 1288 if (clipped) { 1289 dirtyClip(); 1290 } 1291 return !mSnapshot->clipRect->isEmpty(); 1292} 1293 1294Rect* OpenGLRenderer::getClipRect() { 1295 return mSnapshot->clipRect; 1296} 1297 1298/////////////////////////////////////////////////////////////////////////////// 1299// Drawing commands 1300/////////////////////////////////////////////////////////////////////////////// 1301 1302void OpenGLRenderer::setupDraw(bool clear) { 1303 // TODO: It would be best if we could do this before quickReject() 1304 // changes the scissor test state 1305 if (clear) clearLayerRegions(); 1306 if (mDirtyClip) { 1307 setScissorFromClip(); 1308 } 1309 mDescription.reset(); 1310 mSetShaderColor = false; 1311 mColorSet = false; 1312 mColorA = mColorR = mColorG = mColorB = 0.0f; 1313 mTextureUnit = 0; 1314 mTrackDirtyRegions = true; 1315} 1316 1317void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) { 1318 mDescription.hasTexture = true; 1319 mDescription.hasAlpha8Texture = isAlpha8; 1320} 1321 1322void OpenGLRenderer::setupDrawWithExternalTexture() { 1323 mDescription.hasExternalTexture = true; 1324} 1325 1326void OpenGLRenderer::setupDrawNoTexture() { 1327 mCaches.disbaleTexCoordsVertexArray(); 1328} 1329 1330void OpenGLRenderer::setupDrawAA() { 1331 mDescription.isAA = true; 1332} 1333 1334void OpenGLRenderer::setupDrawVertexShape() { 1335 mDescription.isVertexShape = true; 1336} 1337 1338void OpenGLRenderer::setupDrawPoint(float pointSize) { 1339 mDescription.isPoint = true; 1340 mDescription.pointSize = pointSize; 1341} 1342 1343void OpenGLRenderer::setupDrawColor(int color, int alpha) { 1344 mColorA = alpha / 255.0f; 1345 mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f; 1346 mColorG = mColorA * ((color >> 8) & 0xFF) / 255.0f; 1347 mColorB = mColorA * ((color ) & 0xFF) / 255.0f; 1348 mColorSet = true; 1349 mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA); 1350} 1351 1352void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) { 1353 mColorA = alpha / 255.0f; 1354 mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f; 1355 mColorG = mColorA * ((color >> 8) & 0xFF) / 255.0f; 1356 mColorB = mColorA * ((color ) & 0xFF) / 255.0f; 1357 mColorSet = true; 1358 mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA); 1359} 1360 1361void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) { 1362 mCaches.fontRenderer->describe(mDescription, paint); 1363} 1364 1365void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) { 1366 mColorA = a; 1367 mColorR = r; 1368 mColorG = g; 1369 mColorB = b; 1370 mColorSet = true; 1371 mSetShaderColor = mDescription.setColor(r, g, b, a); 1372} 1373 1374void OpenGLRenderer::setupDrawShader() { 1375 if (mShader) { 1376 mShader->describe(mDescription, mCaches.extensions); 1377 } 1378} 1379 1380void OpenGLRenderer::setupDrawColorFilter() { 1381 if (mColorFilter) { 1382 mColorFilter->describe(mDescription, mCaches.extensions); 1383 } 1384} 1385 1386void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) { 1387 if (mColorSet && mode == SkXfermode::kClear_Mode) { 1388 mColorA = 1.0f; 1389 mColorR = mColorG = mColorB = 0.0f; 1390 mSetShaderColor = mDescription.modulate = true; 1391 } 1392} 1393 1394void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) { 1395 // When the blending mode is kClear_Mode, we need to use a modulate color 1396 // argb=1,0,0,0 1397 accountForClear(mode); 1398 chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode, 1399 mDescription, swapSrcDst); 1400} 1401 1402void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) { 1403 // When the blending mode is kClear_Mode, we need to use a modulate color 1404 // argb=1,0,0,0 1405 accountForClear(mode); 1406 chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()) || 1407 (mColorFilter && mColorFilter->blend()), mode, mDescription, swapSrcDst); 1408} 1409 1410void OpenGLRenderer::setupDrawProgram() { 1411 useProgram(mCaches.programCache.get(mDescription)); 1412} 1413 1414void OpenGLRenderer::setupDrawDirtyRegionsDisabled() { 1415 mTrackDirtyRegions = false; 1416} 1417 1418void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom, 1419 bool ignoreTransform) { 1420 mModelView.loadTranslate(left, top, 0.0f); 1421 if (!ignoreTransform) { 1422 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 1423 if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1424 } else { 1425 mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity); 1426 if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom); 1427 } 1428} 1429 1430void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) { 1431 mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset); 1432} 1433 1434void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom, 1435 bool ignoreTransform, bool ignoreModelView) { 1436 if (!ignoreModelView) { 1437 mModelView.loadTranslate(left, top, 0.0f); 1438 mModelView.scale(right - left, bottom - top, 1.0f); 1439 } else { 1440 mModelView.loadIdentity(); 1441 } 1442 bool dirty = right - left > 0.0f && bottom - top > 0.0f; 1443 if (!ignoreTransform) { 1444 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 1445 if (mTrackDirtyRegions && dirty) { 1446 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1447 } 1448 } else { 1449 mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity); 1450 if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom); 1451 } 1452} 1453 1454void OpenGLRenderer::setupDrawPointUniforms() { 1455 int slot = mCaches.currentProgram->getUniform("pointSize"); 1456 glUniform1f(slot, mDescription.pointSize); 1457} 1458 1459void OpenGLRenderer::setupDrawColorUniforms() { 1460 if ((mColorSet && !mShader) || (mShader && mSetShaderColor)) { 1461 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1462 } 1463} 1464 1465void OpenGLRenderer::setupDrawPureColorUniforms() { 1466 if (mSetShaderColor) { 1467 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1468 } 1469} 1470 1471void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) { 1472 if (mShader) { 1473 if (ignoreTransform) { 1474 mModelView.loadInverse(*mSnapshot->transform); 1475 } 1476 mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit); 1477 } 1478} 1479 1480void OpenGLRenderer::setupDrawShaderIdentityUniforms() { 1481 if (mShader) { 1482 mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit); 1483 } 1484} 1485 1486void OpenGLRenderer::setupDrawColorFilterUniforms() { 1487 if (mColorFilter) { 1488 mColorFilter->setupProgram(mCaches.currentProgram); 1489 } 1490} 1491 1492void OpenGLRenderer::setupDrawTextGammaUniforms() { 1493 mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram); 1494} 1495 1496void OpenGLRenderer::setupDrawSimpleMesh() { 1497 bool force = mCaches.bindMeshBuffer(); 1498 mCaches.bindPositionVertexPointer(force, 0); 1499 mCaches.unbindIndicesBuffer(); 1500} 1501 1502void OpenGLRenderer::setupDrawTexture(GLuint texture) { 1503 bindTexture(texture); 1504 mTextureUnit++; 1505 mCaches.enableTexCoordsVertexArray(); 1506} 1507 1508void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) { 1509 bindExternalTexture(texture); 1510 mTextureUnit++; 1511 mCaches.enableTexCoordsVertexArray(); 1512} 1513 1514void OpenGLRenderer::setupDrawTextureTransform() { 1515 mDescription.hasTextureTransform = true; 1516} 1517 1518void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) { 1519 glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1, 1520 GL_FALSE, &transform.data[0]); 1521} 1522 1523void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) { 1524 bool force = false; 1525 if (!vertices) { 1526 force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo); 1527 } else { 1528 force = mCaches.unbindMeshBuffer(); 1529 } 1530 1531 mCaches.bindPositionVertexPointer(force, vertices); 1532 if (mCaches.currentProgram->texCoords >= 0) { 1533 mCaches.bindTexCoordsVertexPointer(force, texCoords); 1534 } 1535 1536 mCaches.unbindIndicesBuffer(); 1537} 1538 1539void OpenGLRenderer::setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords) { 1540 bool force = mCaches.unbindMeshBuffer(); 1541 mCaches.bindPositionVertexPointer(force, vertices); 1542 if (mCaches.currentProgram->texCoords >= 0) { 1543 mCaches.bindTexCoordsVertexPointer(force, texCoords); 1544 } 1545} 1546 1547void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) { 1548 bool force = mCaches.unbindMeshBuffer(); 1549 mCaches.bindPositionVertexPointer(force, vertices, gVertexStride); 1550 mCaches.unbindIndicesBuffer(); 1551} 1552 1553/** 1554 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an 1555 * outer boundary that fades out to 0. The variables set in the shader define the proportion of 1556 * the width and length of the primitive occupied by the AA region. The vtxWidth and vtxLength 1557 * attributes (one per vertex) are values from zero to one that tells the fragment 1558 * shader where the fragment is in relation to the line width/length overall; these values are 1559 * then used to compute the proper color, based on whether the fragment lies in the fading AA 1560 * region of the line. 1561 * Note that we only pass down the width values in this setup function. The length coordinates 1562 * are set up for each individual segment. 1563 */ 1564void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* widthCoords, 1565 GLvoid* lengthCoords, float boundaryWidthProportion, int& widthSlot, int& lengthSlot) { 1566 bool force = mCaches.unbindMeshBuffer(); 1567 mCaches.bindPositionVertexPointer(force, vertices, gAAVertexStride); 1568 mCaches.resetTexCoordsVertexPointer(); 1569 mCaches.unbindIndicesBuffer(); 1570 1571 widthSlot = mCaches.currentProgram->getAttrib("vtxWidth"); 1572 glEnableVertexAttribArray(widthSlot); 1573 glVertexAttribPointer(widthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, widthCoords); 1574 1575 lengthSlot = mCaches.currentProgram->getAttrib("vtxLength"); 1576 glEnableVertexAttribArray(lengthSlot); 1577 glVertexAttribPointer(lengthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, lengthCoords); 1578 1579 int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth"); 1580 glUniform1f(boundaryWidthSlot, boundaryWidthProportion); 1581} 1582 1583void OpenGLRenderer::finishDrawAALine(const int widthSlot, const int lengthSlot) { 1584 glDisableVertexAttribArray(widthSlot); 1585 glDisableVertexAttribArray(lengthSlot); 1586} 1587 1588void OpenGLRenderer::finishDrawTexture() { 1589} 1590 1591/////////////////////////////////////////////////////////////////////////////// 1592// Drawing 1593/////////////////////////////////////////////////////////////////////////////// 1594 1595status_t OpenGLRenderer::drawDisplayList(DisplayList* displayList, 1596 Rect& dirty, int32_t flags, uint32_t level) { 1597 1598 // All the usual checks and setup operations (quickReject, setupDraw, etc.) 1599 // will be performed by the display list itself 1600 if (displayList && displayList->isRenderable()) { 1601 return displayList->replay(*this, dirty, flags, level); 1602 } 1603 1604 return DrawGlInfo::kStatusDone; 1605} 1606 1607void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) { 1608 if (displayList) { 1609 displayList->output(*this, level); 1610 } 1611} 1612 1613void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) { 1614 int alpha; 1615 SkXfermode::Mode mode; 1616 getAlphaAndMode(paint, &alpha, &mode); 1617 1618 int color = paint != NULL ? paint->getColor() : 0; 1619 1620 float x = left; 1621 float y = top; 1622 1623 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1624 1625 bool ignoreTransform = false; 1626 if (mSnapshot->transform->isPureTranslate()) { 1627 x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f); 1628 y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f); 1629 ignoreTransform = true; 1630 1631 texture->setFilter(GL_NEAREST, true); 1632 } else { 1633 texture->setFilter(FILTER(paint), true); 1634 } 1635 1636 drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 1637 paint != NULL, color, alpha, mode, (GLvoid*) NULL, 1638 (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform); 1639} 1640 1641status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) { 1642 const float right = left + bitmap->width(); 1643 const float bottom = top + bitmap->height(); 1644 1645 if (quickReject(left, top, right, bottom)) { 1646 return DrawGlInfo::kStatusDone; 1647 } 1648 1649 mCaches.activeTexture(0); 1650 Texture* texture = mCaches.textureCache.get(bitmap); 1651 if (!texture) return DrawGlInfo::kStatusDone; 1652 const AutoTexture autoCleanup(texture); 1653 1654 if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) { 1655 drawAlphaBitmap(texture, left, top, paint); 1656 } else { 1657 drawTextureRect(left, top, right, bottom, texture, paint); 1658 } 1659 1660 return DrawGlInfo::kStatusDrew; 1661} 1662 1663status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) { 1664 Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height()); 1665 const mat4 transform(*matrix); 1666 transform.mapRect(r); 1667 1668 if (quickReject(r.left, r.top, r.right, r.bottom)) { 1669 return DrawGlInfo::kStatusDone; 1670 } 1671 1672 mCaches.activeTexture(0); 1673 Texture* texture = mCaches.textureCache.get(bitmap); 1674 if (!texture) return DrawGlInfo::kStatusDone; 1675 const AutoTexture autoCleanup(texture); 1676 1677 // This could be done in a cheaper way, all we need is pass the matrix 1678 // to the vertex shader. The save/restore is a bit overkill. 1679 save(SkCanvas::kMatrix_SaveFlag); 1680 concatMatrix(matrix); 1681 if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) { 1682 drawAlphaBitmap(texture, 0.0f, 0.0f, paint); 1683 } else { 1684 drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint); 1685 } 1686 restore(); 1687 1688 return DrawGlInfo::kStatusDrew; 1689} 1690 1691status_t OpenGLRenderer::drawBitmapData(SkBitmap* bitmap, float left, float top, SkPaint* paint) { 1692 const float right = left + bitmap->width(); 1693 const float bottom = top + bitmap->height(); 1694 1695 if (quickReject(left, top, right, bottom)) { 1696 return DrawGlInfo::kStatusDone; 1697 } 1698 1699 mCaches.activeTexture(0); 1700 Texture* texture = mCaches.textureCache.getTransient(bitmap); 1701 const AutoTexture autoCleanup(texture); 1702 1703 if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) { 1704 drawAlphaBitmap(texture, left, top, paint); 1705 } else { 1706 drawTextureRect(left, top, right, bottom, texture, paint); 1707 } 1708 1709 return DrawGlInfo::kStatusDrew; 1710} 1711 1712status_t OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight, 1713 float* vertices, int* colors, SkPaint* paint) { 1714 if (!vertices || mSnapshot->isIgnored()) { 1715 return DrawGlInfo::kStatusDone; 1716 } 1717 1718 // TODO: We should compute the bounding box when recording the display list 1719 float left = FLT_MAX; 1720 float top = FLT_MAX; 1721 float right = FLT_MIN; 1722 float bottom = FLT_MIN; 1723 1724 const uint32_t count = meshWidth * meshHeight * 6; 1725 1726 // TODO: Support the colors array 1727 TextureVertex mesh[count]; 1728 TextureVertex* vertex = mesh; 1729 1730 for (int32_t y = 0; y < meshHeight; y++) { 1731 for (int32_t x = 0; x < meshWidth; x++) { 1732 uint32_t i = (y * (meshWidth + 1) + x) * 2; 1733 1734 float u1 = float(x) / meshWidth; 1735 float u2 = float(x + 1) / meshWidth; 1736 float v1 = float(y) / meshHeight; 1737 float v2 = float(y + 1) / meshHeight; 1738 1739 int ax = i + (meshWidth + 1) * 2; 1740 int ay = ax + 1; 1741 int bx = i; 1742 int by = bx + 1; 1743 int cx = i + 2; 1744 int cy = cx + 1; 1745 int dx = i + (meshWidth + 1) * 2 + 2; 1746 int dy = dx + 1; 1747 1748 TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2); 1749 TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1); 1750 TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1); 1751 1752 TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2); 1753 TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1); 1754 TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2); 1755 1756 // TODO: This could be optimized to avoid unnecessary ops 1757 left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx]))); 1758 top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy]))); 1759 right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx]))); 1760 bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy]))); 1761 } 1762 } 1763 1764 if (quickReject(left, top, right, bottom)) { 1765 return DrawGlInfo::kStatusDone; 1766 } 1767 1768 mCaches.activeTexture(0); 1769 Texture* texture = mCaches.textureCache.get(bitmap); 1770 if (!texture) return DrawGlInfo::kStatusDone; 1771 const AutoTexture autoCleanup(texture); 1772 1773 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1774 texture->setFilter(FILTER(paint), true); 1775 1776 int alpha; 1777 SkXfermode::Mode mode; 1778 getAlphaAndMode(paint, &alpha, &mode); 1779 1780 if (hasLayer()) { 1781 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1782 } 1783 1784 drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f, 1785 mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0], 1786 GL_TRIANGLES, count, false, false, 0, false, false); 1787 1788 return DrawGlInfo::kStatusDrew; 1789} 1790 1791status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, 1792 float srcLeft, float srcTop, float srcRight, float srcBottom, 1793 float dstLeft, float dstTop, float dstRight, float dstBottom, 1794 SkPaint* paint) { 1795 if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) { 1796 return DrawGlInfo::kStatusDone; 1797 } 1798 1799 mCaches.activeTexture(0); 1800 Texture* texture = mCaches.textureCache.get(bitmap); 1801 if (!texture) return DrawGlInfo::kStatusDone; 1802 const AutoTexture autoCleanup(texture); 1803 1804 const float width = texture->width; 1805 const float height = texture->height; 1806 1807 const float u1 = fmax(0.0f, srcLeft / width); 1808 const float v1 = fmax(0.0f, srcTop / height); 1809 const float u2 = fmin(1.0f, srcRight / width); 1810 const float v2 = fmin(1.0f, srcBottom / height); 1811 1812 mCaches.unbindMeshBuffer(); 1813 resetDrawTextureTexCoords(u1, v1, u2, v2); 1814 1815 int alpha; 1816 SkXfermode::Mode mode; 1817 getAlphaAndMode(paint, &alpha, &mode); 1818 1819 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1820 1821 float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft); 1822 float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop); 1823 1824 bool scaled = scaleX != 1.0f || scaleY != 1.0f; 1825 // Apply a scale transform on the canvas only when a shader is in use 1826 // Skia handles the ratio between the dst and src rects as a scale factor 1827 // when a shader is set 1828 bool useScaleTransform = mShader && scaled; 1829 bool ignoreTransform = false; 1830 1831 if (CC_LIKELY(mSnapshot->transform->isPureTranslate() && !useScaleTransform)) { 1832 float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f); 1833 float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f); 1834 1835 dstRight = x + (dstRight - dstLeft); 1836 dstBottom = y + (dstBottom - dstTop); 1837 1838 dstLeft = x; 1839 dstTop = y; 1840 1841 texture->setFilter(scaled ? FILTER(paint) : GL_NEAREST, true); 1842 ignoreTransform = true; 1843 } else { 1844 texture->setFilter(FILTER(paint), true); 1845 } 1846 1847 if (CC_UNLIKELY(useScaleTransform)) { 1848 save(SkCanvas::kMatrix_SaveFlag); 1849 translate(dstLeft, dstTop); 1850 scale(scaleX, scaleY); 1851 1852 dstLeft = 0.0f; 1853 dstTop = 0.0f; 1854 1855 dstRight = srcRight - srcLeft; 1856 dstBottom = srcBottom - srcTop; 1857 } 1858 1859 if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) { 1860 int color = paint ? paint->getColor() : 0; 1861 drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom, 1862 texture->id, paint != NULL, color, alpha, mode, 1863 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], 1864 GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform); 1865 } else { 1866 drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, 1867 texture->id, alpha / 255.0f, mode, texture->blend, 1868 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], 1869 GL_TRIANGLE_STRIP, gMeshCount, false, ignoreTransform); 1870 } 1871 1872 if (CC_UNLIKELY(useScaleTransform)) { 1873 restore(); 1874 } 1875 1876 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 1877 1878 return DrawGlInfo::kStatusDrew; 1879} 1880 1881status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs, 1882 const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors, 1883 float left, float top, float right, float bottom, SkPaint* paint) { 1884 int alpha; 1885 SkXfermode::Mode mode; 1886 getAlphaAndModeDirect(paint, &alpha, &mode); 1887 1888 return drawPatch(bitmap, xDivs, yDivs, colors, width, height, numColors, 1889 left, top, right, bottom, alpha, mode); 1890} 1891 1892status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs, 1893 const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors, 1894 float left, float top, float right, float bottom, int alpha, SkXfermode::Mode mode) { 1895 if (quickReject(left, top, right, bottom)) { 1896 return DrawGlInfo::kStatusDone; 1897 } 1898 1899 alpha *= mSnapshot->alpha; 1900 1901 mCaches.activeTexture(0); 1902 Texture* texture = mCaches.textureCache.get(bitmap); 1903 if (!texture) return DrawGlInfo::kStatusDone; 1904 const AutoTexture autoCleanup(texture); 1905 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1906 texture->setFilter(GL_LINEAR, true); 1907 1908 const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(), 1909 right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors); 1910 1911 if (CC_LIKELY(mesh && mesh->verticesCount > 0)) { 1912 const bool pureTranslate = mSnapshot->transform->isPureTranslate(); 1913 // Mark the current layer dirty where we are going to draw the patch 1914 if (hasLayer() && mesh->hasEmptyQuads) { 1915 const float offsetX = left + mSnapshot->transform->getTranslateX(); 1916 const float offsetY = top + mSnapshot->transform->getTranslateY(); 1917 const size_t count = mesh->quads.size(); 1918 for (size_t i = 0; i < count; i++) { 1919 const Rect& bounds = mesh->quads.itemAt(i); 1920 if (CC_LIKELY(pureTranslate)) { 1921 const float x = (int) floorf(bounds.left + offsetX + 0.5f); 1922 const float y = (int) floorf(bounds.top + offsetY + 0.5f); 1923 dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight()); 1924 } else { 1925 dirtyLayer(left + bounds.left, top + bounds.top, 1926 left + bounds.right, top + bounds.bottom, *mSnapshot->transform); 1927 } 1928 } 1929 } 1930 1931 if (CC_LIKELY(pureTranslate)) { 1932 const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f); 1933 const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f); 1934 1935 drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f, 1936 mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset, 1937 GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer, 1938 true, !mesh->hasEmptyQuads); 1939 } else { 1940 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, 1941 mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset, 1942 GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer, 1943 true, !mesh->hasEmptyQuads); 1944 } 1945 } 1946 1947 return DrawGlInfo::kStatusDrew; 1948} 1949 1950/** 1951 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to 1952 * that of AA lines in the drawLines() function. We expand the convex path by a half pixel in 1953 * screen space in all directions. However, instead of using a fragment shader to compute the 1954 * translucency of the color from its position, we simply use a varying parameter to define how far 1955 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used. 1956 * 1957 * Doesn't yet support joins, caps, or path effects. 1958 */ 1959void OpenGLRenderer::drawConvexPath(const SkPath& path, SkPaint* paint) { 1960 int color = paint->getColor(); 1961 SkPaint::Style style = paint->getStyle(); 1962 SkXfermode::Mode mode = getXfermode(paint->getXfermode()); 1963 bool isAA = paint->isAntiAlias(); 1964 1965 VertexBuffer vertexBuffer; 1966 // TODO: try clipping large paths to viewport 1967 PathRenderer::convexPathVertices(path, paint, mSnapshot->transform, vertexBuffer); 1968 1969 if (!vertexBuffer.getSize()) { 1970 // no vertices to draw 1971 return; 1972 } 1973 1974 setupDraw(); 1975 setupDrawNoTexture(); 1976 if (isAA) setupDrawAA(); 1977 setupDrawVertexShape(); 1978 setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha); 1979 setupDrawColorFilter(); 1980 setupDrawShader(); 1981 setupDrawBlending(isAA, mode); 1982 setupDrawProgram(); 1983 setupDrawModelViewIdentity(); 1984 setupDrawColorUniforms(); 1985 setupDrawColorFilterUniforms(); 1986 setupDrawShaderIdentityUniforms(); 1987 1988 void* vertices = vertexBuffer.getBuffer(); 1989 bool force = mCaches.unbindMeshBuffer(); 1990 mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride); 1991 mCaches.resetTexCoordsVertexPointer(); 1992 mCaches.unbindIndicesBuffer(); 1993 1994 int alphaSlot = -1; 1995 if (isAA) { 1996 void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset; 1997 alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha"); 1998 1999 // TODO: avoid enable/disable in back to back uses of the alpha attribute 2000 glEnableVertexAttribArray(alphaSlot); 2001 glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords); 2002 } 2003 2004 SkRect bounds = PathRenderer::computePathBounds(path, paint); 2005 dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *mSnapshot->transform); 2006 2007 glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getSize()); 2008 2009 if (isAA) { 2010 glDisableVertexAttribArray(alphaSlot); 2011 } 2012} 2013 2014/** 2015 * We draw lines as quads (tristrips). Using GL_LINES can be difficult because the rasterization 2016 * rules for those lines produces some unexpected results, and may vary between hardware devices. 2017 * The basics of lines-as-quads is easy; we simply find the normal to the line and position the 2018 * corners of the quads on either side of each line endpoint, separated by the strokeWidth 2019 * of the line. Hairlines are more involved because we need to account for transform scaling 2020 * to end up with a one-pixel-wide line in screen space.. 2021 * Anti-aliased lines add another factor to the approach. We use a specialized fragment shader 2022 * in combination with values that we calculate and pass down in this method. The basic approach 2023 * is that the quad we create contains both the core line area plus a bounding area in which 2024 * the translucent/AA pixels are drawn. The values we calculate tell the shader what 2025 * proportion of the width and the length of a given segment is represented by the boundary 2026 * region. The quad ends up being exactly .5 pixel larger in all directions than the non-AA quad. 2027 * The bounding region is actually 1 pixel wide on all sides (half pixel on the outside, half pixel 2028 * on the inside). This ends up giving the result we want, with pixels that are completely 2029 * 'inside' the line area being filled opaquely and the other pixels being filled according to 2030 * how far into the boundary region they are, which is determined by shader interpolation. 2031 */ 2032status_t OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) { 2033 if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone; 2034 2035 const bool isAA = paint->isAntiAlias(); 2036 // We use half the stroke width here because we're going to position the quad 2037 // corner vertices half of the width away from the line endpoints 2038 float halfStrokeWidth = paint->getStrokeWidth() * 0.5f; 2039 // A stroke width of 0 has a special meaning in Skia: 2040 // it draws a line 1 px wide regardless of current transform 2041 bool isHairLine = paint->getStrokeWidth() == 0.0f; 2042 2043 float inverseScaleX = 1.0f; 2044 float inverseScaleY = 1.0f; 2045 bool scaled = false; 2046 2047 int alpha; 2048 SkXfermode::Mode mode; 2049 2050 int generatedVerticesCount = 0; 2051 int verticesCount = count; 2052 if (count > 4) { 2053 // Polyline: account for extra vertices needed for continuous tri-strip 2054 verticesCount += (count - 4); 2055 } 2056 2057 if (isHairLine || isAA) { 2058 // The quad that we use for AA and hairlines needs to account for scaling. For hairlines 2059 // the line on the screen should always be one pixel wide regardless of scale. For 2060 // AA lines, we only want one pixel of translucent boundary around the quad. 2061 if (CC_UNLIKELY(!mSnapshot->transform->isPureTranslate())) { 2062 Matrix4 *mat = mSnapshot->transform; 2063 float m00 = mat->data[Matrix4::kScaleX]; 2064 float m01 = mat->data[Matrix4::kSkewY]; 2065 float m10 = mat->data[Matrix4::kSkewX]; 2066 float m11 = mat->data[Matrix4::kScaleY]; 2067 2068 float scaleX = sqrtf(m00 * m00 + m01 * m01); 2069 float scaleY = sqrtf(m10 * m10 + m11 * m11); 2070 2071 inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0; 2072 inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0; 2073 2074 if (inverseScaleX != 1.0f || inverseScaleY != 1.0f) { 2075 scaled = true; 2076 } 2077 } 2078 } 2079 2080 getAlphaAndMode(paint, &alpha, &mode); 2081 2082 mCaches.enableScissor(); 2083 2084 setupDraw(); 2085 setupDrawNoTexture(); 2086 if (isAA) { 2087 setupDrawAA(); 2088 } 2089 setupDrawColor(paint->getColor(), alpha); 2090 setupDrawColorFilter(); 2091 setupDrawShader(); 2092 setupDrawBlending(isAA, mode); 2093 setupDrawProgram(); 2094 setupDrawModelViewIdentity(true); 2095 setupDrawColorUniforms(); 2096 setupDrawColorFilterUniforms(); 2097 setupDrawShaderIdentityUniforms(); 2098 2099 if (isHairLine) { 2100 // Set a real stroke width to be used in quad construction 2101 halfStrokeWidth = isAA? 1 : .5; 2102 } else if (isAA && !scaled) { 2103 // Expand boundary to enable AA calculations on the quad border 2104 halfStrokeWidth += .5f; 2105 } 2106 2107 int widthSlot; 2108 int lengthSlot; 2109 2110 Vertex lines[verticesCount]; 2111 Vertex* vertices = &lines[0]; 2112 2113 AAVertex wLines[verticesCount]; 2114 AAVertex* aaVertices = &wLines[0]; 2115 2116 if (CC_UNLIKELY(!isAA)) { 2117 setupDrawVertices(vertices); 2118 } else { 2119 void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset; 2120 void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset; 2121 // innerProportion is the ratio of the inner (non-AA) part of the line to the total 2122 // AA stroke width (the base stroke width expanded by a half pixel on either side). 2123 // This value is used in the fragment shader to determine how to fill fragments. 2124 // We will need to calculate the actual width proportion on each segment for 2125 // scaled non-hairlines, since the boundary proportion may differ per-axis when scaled. 2126 float boundaryWidthProportion = .5 - 1 / (2 * halfStrokeWidth); 2127 setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, 2128 boundaryWidthProportion, widthSlot, lengthSlot); 2129 } 2130 2131 AAVertex* prevAAVertex = NULL; 2132 Vertex* prevVertex = NULL; 2133 2134 int boundaryLengthSlot = -1; 2135 int boundaryWidthSlot = -1; 2136 2137 for (int i = 0; i < count; i += 4) { 2138 // a = start point, b = end point 2139 vec2 a(points[i], points[i + 1]); 2140 vec2 b(points[i + 2], points[i + 3]); 2141 2142 float length = 0; 2143 float boundaryLengthProportion = 0; 2144 float boundaryWidthProportion = 0; 2145 2146 // Find the normal to the line 2147 vec2 n = (b - a).copyNormalized() * halfStrokeWidth; 2148 float x = n.x; 2149 n.x = -n.y; 2150 n.y = x; 2151 2152 if (isHairLine) { 2153 if (isAA) { 2154 float wideningFactor; 2155 if (fabs(n.x) >= fabs(n.y)) { 2156 wideningFactor = fabs(1.0f / n.x); 2157 } else { 2158 wideningFactor = fabs(1.0f / n.y); 2159 } 2160 n *= wideningFactor; 2161 } 2162 2163 if (scaled) { 2164 n.x *= inverseScaleX; 2165 n.y *= inverseScaleY; 2166 } 2167 } else if (scaled) { 2168 // Extend n by .5 pixel on each side, post-transform 2169 vec2 extendedN = n.copyNormalized(); 2170 extendedN /= 2; 2171 extendedN.x *= inverseScaleX; 2172 extendedN.y *= inverseScaleY; 2173 2174 float extendedNLength = extendedN.length(); 2175 // We need to set this value on the shader prior to drawing 2176 boundaryWidthProportion = .5 - extendedNLength / (halfStrokeWidth + extendedNLength); 2177 n += extendedN; 2178 } 2179 2180 // aa lines expand the endpoint vertices to encompass the AA boundary 2181 if (isAA) { 2182 vec2 abVector = (b - a); 2183 length = abVector.length(); 2184 abVector.normalize(); 2185 2186 if (scaled) { 2187 abVector.x *= inverseScaleX; 2188 abVector.y *= inverseScaleY; 2189 float abLength = abVector.length(); 2190 boundaryLengthProportion = .5 - abLength / (length + abLength); 2191 } else { 2192 boundaryLengthProportion = .5 - .5 / (length + 1); 2193 } 2194 2195 abVector /= 2; 2196 a -= abVector; 2197 b += abVector; 2198 } 2199 2200 // Four corners of the rectangle defining a thick line 2201 vec2 p1 = a - n; 2202 vec2 p2 = a + n; 2203 vec2 p3 = b + n; 2204 vec2 p4 = b - n; 2205 2206 2207 const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x))); 2208 const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x))); 2209 const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y))); 2210 const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y))); 2211 2212 if (!quickRejectNoScissor(left, top, right, bottom)) { 2213 if (!isAA) { 2214 if (prevVertex != NULL) { 2215 // Issue two repeat vertices to create degenerate triangles to bridge 2216 // between the previous line and the new one. This is necessary because 2217 // we are creating a single triangle_strip which will contain 2218 // potentially discontinuous line segments. 2219 Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]); 2220 Vertex::set(vertices++, p1.x, p1.y); 2221 generatedVerticesCount += 2; 2222 } 2223 2224 Vertex::set(vertices++, p1.x, p1.y); 2225 Vertex::set(vertices++, p2.x, p2.y); 2226 Vertex::set(vertices++, p4.x, p4.y); 2227 Vertex::set(vertices++, p3.x, p3.y); 2228 2229 prevVertex = vertices - 1; 2230 generatedVerticesCount += 4; 2231 } else { 2232 if (!isHairLine && scaled) { 2233 // Must set width proportions per-segment for scaled non-hairlines to use the 2234 // correct AA boundary dimensions 2235 if (boundaryWidthSlot < 0) { 2236 boundaryWidthSlot = 2237 mCaches.currentProgram->getUniform("boundaryWidth"); 2238 } 2239 2240 glUniform1f(boundaryWidthSlot, boundaryWidthProportion); 2241 } 2242 2243 if (boundaryLengthSlot < 0) { 2244 boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength"); 2245 } 2246 2247 glUniform1f(boundaryLengthSlot, boundaryLengthProportion); 2248 2249 if (prevAAVertex != NULL) { 2250 // Issue two repeat vertices to create degenerate triangles to bridge 2251 // between the previous line and the new one. This is necessary because 2252 // we are creating a single triangle_strip which will contain 2253 // potentially discontinuous line segments. 2254 AAVertex::set(aaVertices++,prevAAVertex->position[0], 2255 prevAAVertex->position[1], prevAAVertex->width, prevAAVertex->length); 2256 AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1); 2257 generatedVerticesCount += 2; 2258 } 2259 2260 AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1); 2261 AAVertex::set(aaVertices++, p1.x, p1.y, 1, 0); 2262 AAVertex::set(aaVertices++, p3.x, p3.y, 0, 1); 2263 AAVertex::set(aaVertices++, p2.x, p2.y, 0, 0); 2264 2265 prevAAVertex = aaVertices - 1; 2266 generatedVerticesCount += 4; 2267 } 2268 2269 dirtyLayer(a.x == b.x ? left - 1 : left, a.y == b.y ? top - 1 : top, 2270 a.x == b.x ? right: right, a.y == b.y ? bottom: bottom, 2271 *mSnapshot->transform); 2272 } 2273 } 2274 2275 if (generatedVerticesCount > 0) { 2276 glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount); 2277 } 2278 2279 if (isAA) { 2280 finishDrawAALine(widthSlot, lengthSlot); 2281 } 2282 2283 return DrawGlInfo::kStatusDrew; 2284} 2285 2286status_t OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) { 2287 if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone; 2288 2289 // TODO: The paint's cap style defines whether the points are square or circular 2290 // TODO: Handle AA for round points 2291 2292 // A stroke width of 0 has a special meaning in Skia: 2293 // it draws an unscaled 1px point 2294 float strokeWidth = paint->getStrokeWidth(); 2295 const bool isHairLine = paint->getStrokeWidth() == 0.0f; 2296 if (isHairLine) { 2297 // Now that we know it's hairline, we can set the effective width, to be used later 2298 strokeWidth = 1.0f; 2299 } 2300 const float halfWidth = strokeWidth / 2; 2301 int alpha; 2302 SkXfermode::Mode mode; 2303 getAlphaAndMode(paint, &alpha, &mode); 2304 2305 int verticesCount = count >> 1; 2306 int generatedVerticesCount = 0; 2307 2308 TextureVertex pointsData[verticesCount]; 2309 TextureVertex* vertex = &pointsData[0]; 2310 2311 // TODO: We should optimize this method to not generate vertices for points 2312 // that lie outside of the clip. 2313 mCaches.enableScissor(); 2314 2315 setupDraw(); 2316 setupDrawNoTexture(); 2317 setupDrawPoint(strokeWidth); 2318 setupDrawColor(paint->getColor(), alpha); 2319 setupDrawColorFilter(); 2320 setupDrawShader(); 2321 setupDrawBlending(mode); 2322 setupDrawProgram(); 2323 setupDrawModelViewIdentity(true); 2324 setupDrawColorUniforms(); 2325 setupDrawColorFilterUniforms(); 2326 setupDrawPointUniforms(); 2327 setupDrawShaderIdentityUniforms(); 2328 setupDrawMesh(vertex); 2329 2330 for (int i = 0; i < count; i += 2) { 2331 TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f); 2332 generatedVerticesCount++; 2333 2334 float left = points[i] - halfWidth; 2335 float right = points[i] + halfWidth; 2336 float top = points[i + 1] - halfWidth; 2337 float bottom = points [i + 1] + halfWidth; 2338 2339 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 2340 } 2341 2342 glDrawArrays(GL_POINTS, 0, generatedVerticesCount); 2343 2344 return DrawGlInfo::kStatusDrew; 2345} 2346 2347status_t OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 2348 // No need to check against the clip, we fill the clip region 2349 if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone; 2350 2351 Rect& clip(*mSnapshot->clipRect); 2352 clip.snapToPixelBoundaries(); 2353 2354 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true); 2355 2356 return DrawGlInfo::kStatusDrew; 2357} 2358 2359status_t OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, 2360 SkPaint* paint) { 2361 if (!texture) return DrawGlInfo::kStatusDone; 2362 const AutoTexture autoCleanup(texture); 2363 2364 const float x = left + texture->left - texture->offset; 2365 const float y = top + texture->top - texture->offset; 2366 2367 drawPathTexture(texture, x, y, paint); 2368 2369 return DrawGlInfo::kStatusDrew; 2370} 2371 2372status_t OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom, 2373 float rx, float ry, SkPaint* p) { 2374 if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) { 2375 return DrawGlInfo::kStatusDone; 2376 } 2377 2378 if (p->getPathEffect() != 0) { 2379 mCaches.activeTexture(0); 2380 const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect( 2381 right - left, bottom - top, rx, ry, p); 2382 return drawShape(left, top, texture, p); 2383 } 2384 2385 SkPath path; 2386 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2387 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2388 float outset = p->getStrokeWidth() / 2; 2389 rect.outset(outset, outset); 2390 rx += outset; 2391 ry += outset; 2392 } 2393 path.addRoundRect(rect, rx, ry); 2394 drawConvexPath(path, p); 2395 2396 return DrawGlInfo::kStatusDrew; 2397} 2398 2399status_t OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* p) { 2400 if (mSnapshot->isIgnored() || quickRejectPreStroke(x - radius, y - radius, 2401 x + radius, y + radius, p)) { 2402 return DrawGlInfo::kStatusDone; 2403 } 2404 if (p->getPathEffect() != 0) { 2405 mCaches.activeTexture(0); 2406 const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, p); 2407 return drawShape(x - radius, y - radius, texture, p); 2408 } 2409 2410 SkPath path; 2411 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2412 path.addCircle(x, y, radius + p->getStrokeWidth() / 2); 2413 } else { 2414 path.addCircle(x, y, radius); 2415 } 2416 drawConvexPath(path, p); 2417 2418 return DrawGlInfo::kStatusDrew; 2419} 2420 2421status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom, 2422 SkPaint* p) { 2423 if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) { 2424 return DrawGlInfo::kStatusDone; 2425 } 2426 2427 if (p->getPathEffect() != 0) { 2428 mCaches.activeTexture(0); 2429 const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, p); 2430 return drawShape(left, top, texture, p); 2431 } 2432 2433 SkPath path; 2434 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2435 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2436 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2437 } 2438 path.addOval(rect); 2439 drawConvexPath(path, p); 2440 2441 return DrawGlInfo::kStatusDrew; 2442} 2443 2444status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom, 2445 float startAngle, float sweepAngle, bool useCenter, SkPaint* p) { 2446 if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) { 2447 return DrawGlInfo::kStatusDone; 2448 } 2449 2450 if (fabs(sweepAngle) >= 360.0f) { 2451 return drawOval(left, top, right, bottom, p); 2452 } 2453 2454 // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180) 2455 if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || p->getStrokeCap() != SkPaint::kButt_Cap || useCenter) { 2456 mCaches.activeTexture(0); 2457 const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top, 2458 startAngle, sweepAngle, useCenter, p); 2459 return drawShape(left, top, texture, p); 2460 } 2461 2462 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2463 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2464 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2465 } 2466 2467 SkPath path; 2468 if (useCenter) { 2469 path.moveTo(rect.centerX(), rect.centerY()); 2470 } 2471 path.arcTo(rect, startAngle, sweepAngle, !useCenter); 2472 if (useCenter) { 2473 path.close(); 2474 } 2475 drawConvexPath(path, p); 2476 2477 return DrawGlInfo::kStatusDrew; 2478} 2479 2480// See SkPaintDefaults.h 2481#define SkPaintDefaults_MiterLimit SkIntToScalar(4) 2482 2483status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) { 2484 if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) { 2485 return DrawGlInfo::kStatusDone; 2486 } 2487 2488 if (p->getStyle() != SkPaint::kFill_Style) { 2489 // only fill style is supported by drawConvexPath, since others have to handle joins 2490 if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join || 2491 p->getStrokeMiter() != SkPaintDefaults_MiterLimit) { 2492 mCaches.activeTexture(0); 2493 const PathTexture* texture = 2494 mCaches.rectShapeCache.getRect(right - left, bottom - top, p); 2495 return drawShape(left, top, texture, p); 2496 } 2497 2498 SkPath path; 2499 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2500 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2501 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2502 } 2503 path.addRect(rect); 2504 drawConvexPath(path, p); 2505 2506 return DrawGlInfo::kStatusDrew; 2507 } 2508 2509 if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) { 2510 SkPath path; 2511 path.addRect(left, top, right, bottom); 2512 drawConvexPath(path, p); 2513 } else { 2514 drawColorRect(left, top, right, bottom, p->getColor(), getXfermode(p->getXfermode())); 2515 } 2516 2517 return DrawGlInfo::kStatusDrew; 2518} 2519 2520void OpenGLRenderer::drawTextShadow(SkPaint* paint, const char* text, int bytesCount, int count, 2521 const float* positions, FontRenderer& fontRenderer, int alpha, SkXfermode::Mode mode, 2522 float x, float y) { 2523 mCaches.activeTexture(0); 2524 2525 // NOTE: The drop shadow will not perform gamma correction 2526 // if shader-based correction is enabled 2527 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 2528 const ShadowTexture* shadow = mCaches.dropShadowCache.get( 2529 paint, text, bytesCount, count, mShadowRadius, positions); 2530 const AutoTexture autoCleanup(shadow); 2531 2532 const float sx = x - shadow->left + mShadowDx; 2533 const float sy = y - shadow->top + mShadowDy; 2534 2535 const int shadowAlpha = ((mShadowColor >> 24) & 0xFF) * mSnapshot->alpha; 2536 int shadowColor = mShadowColor; 2537 if (mShader) { 2538 shadowColor = 0xffffffff; 2539 } 2540 2541 setupDraw(); 2542 setupDrawWithTexture(true); 2543 setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha); 2544 setupDrawColorFilter(); 2545 setupDrawShader(); 2546 setupDrawBlending(true, mode); 2547 setupDrawProgram(); 2548 setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height); 2549 setupDrawTexture(shadow->id); 2550 setupDrawPureColorUniforms(); 2551 setupDrawColorFilterUniforms(); 2552 setupDrawShaderUniforms(); 2553 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 2554 2555 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 2556} 2557 2558status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count, 2559 const float* positions, SkPaint* paint) { 2560 if (text == NULL || count == 0 || mSnapshot->isIgnored() || 2561 (paint->getAlpha() * mSnapshot->alpha == 0 && paint->getXfermode() == NULL)) { 2562 return DrawGlInfo::kStatusDone; 2563 } 2564 2565 // NOTE: Skia does not support perspective transform on drawPosText yet 2566 if (!mSnapshot->transform->isSimple()) { 2567 return DrawGlInfo::kStatusDone; 2568 } 2569 2570 float x = 0.0f; 2571 float y = 0.0f; 2572 const bool pureTranslate = mSnapshot->transform->isPureTranslate(); 2573 if (pureTranslate) { 2574 x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f); 2575 y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f); 2576 } 2577 2578 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2579 fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), 2580 paint->getTextSize()); 2581 2582 int alpha; 2583 SkXfermode::Mode mode; 2584 getAlphaAndMode(paint, &alpha, &mode); 2585 2586 if (CC_UNLIKELY(mHasShadow)) { 2587 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, alpha, mode, 2588 0.0f, 0.0f); 2589 } 2590 2591 // Pick the appropriate texture filtering 2592 bool linearFilter = mSnapshot->transform->changesBounds(); 2593 if (pureTranslate && !linearFilter) { 2594 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2595 } 2596 2597 mCaches.activeTexture(0); 2598 setupDraw(); 2599 setupDrawTextGamma(paint); 2600 setupDrawDirtyRegionsDisabled(); 2601 setupDrawWithTexture(true); 2602 setupDrawAlpha8Color(paint->getColor(), alpha); 2603 setupDrawColorFilter(); 2604 setupDrawShader(); 2605 setupDrawBlending(true, mode); 2606 setupDrawProgram(); 2607 setupDrawModelView(x, y, x, y, pureTranslate, true); 2608 setupDrawTexture(fontRenderer.getTexture(linearFilter)); 2609 setupDrawPureColorUniforms(); 2610 setupDrawColorFilterUniforms(); 2611 setupDrawShaderUniforms(pureTranslate); 2612 setupDrawTextGammaUniforms(); 2613 2614 const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip(); 2615 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2616 2617 const bool hasActiveLayer = hasLayer(); 2618 2619 if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y, 2620 positions, hasActiveLayer ? &bounds : NULL)) { 2621 if (hasActiveLayer) { 2622 if (!pureTranslate) { 2623 mSnapshot->transform->mapRect(bounds); 2624 } 2625 dirtyLayerUnchecked(bounds, getRegion()); 2626 } 2627 } 2628 2629 return DrawGlInfo::kStatusDrew; 2630} 2631 2632status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count, 2633 float x, float y, const float* positions, SkPaint* paint, float length) { 2634 if (text == NULL || count == 0 || mSnapshot->isIgnored() || 2635 (paint->getAlpha() * mSnapshot->alpha == 0 && paint->getXfermode() == NULL)) { 2636 return DrawGlInfo::kStatusDone; 2637 } 2638 2639 if (length < 0.0f) length = paint->measureText(text, bytesCount); 2640 switch (paint->getTextAlign()) { 2641 case SkPaint::kCenter_Align: 2642 x -= length / 2.0f; 2643 break; 2644 case SkPaint::kRight_Align: 2645 x -= length; 2646 break; 2647 default: 2648 break; 2649 } 2650 2651 SkPaint::FontMetrics metrics; 2652 paint->getFontMetrics(&metrics, 0.0f); 2653 if (quickReject(x, y + metrics.fTop, x + length, y + metrics.fBottom)) { 2654 return DrawGlInfo::kStatusDone; 2655 } 2656 2657 const float oldX = x; 2658 const float oldY = y; 2659 const bool pureTranslate = mSnapshot->transform->isPureTranslate(); 2660 if (CC_LIKELY(pureTranslate)) { 2661 x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f); 2662 y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f); 2663 } 2664 2665#if DEBUG_GLYPHS 2666 ALOGD("OpenGLRenderer drawText() with FontID=%d", 2667 SkTypeface::UniqueID(paint->getTypeface())); 2668#endif 2669 2670 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2671 fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), 2672 paint->getTextSize()); 2673 2674 int alpha; 2675 SkXfermode::Mode mode; 2676 getAlphaAndMode(paint, &alpha, &mode); 2677 2678 if (CC_UNLIKELY(mHasShadow)) { 2679 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, alpha, mode, 2680 oldX, oldY); 2681 } 2682 2683 // Pick the appropriate texture filtering 2684 bool linearFilter = mSnapshot->transform->changesBounds(); 2685 if (pureTranslate && !linearFilter) { 2686 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2687 } 2688 2689 // The font renderer will always use texture unit 0 2690 mCaches.activeTexture(0); 2691 setupDraw(); 2692 setupDrawTextGamma(paint); 2693 setupDrawDirtyRegionsDisabled(); 2694 setupDrawWithTexture(true); 2695 setupDrawAlpha8Color(paint->getColor(), alpha); 2696 setupDrawColorFilter(); 2697 setupDrawShader(); 2698 setupDrawBlending(true, mode); 2699 setupDrawProgram(); 2700 setupDrawModelView(x, y, x, y, pureTranslate, true); 2701 // See comment above; the font renderer must use texture unit 0 2702 // assert(mTextureUnit == 0) 2703 setupDrawTexture(fontRenderer.getTexture(linearFilter)); 2704 setupDrawPureColorUniforms(); 2705 setupDrawColorFilterUniforms(); 2706 setupDrawShaderUniforms(pureTranslate); 2707 setupDrawTextGammaUniforms(); 2708 2709 const Rect* clip = pureTranslate ? mSnapshot->clipRect : 2710 (mSnapshot->hasPerspectiveTransform() ? NULL : &mSnapshot->getLocalClip()); 2711 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2712 2713 const bool hasActiveLayer = hasLayer(); 2714 2715 bool status; 2716 if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) { 2717 SkPaint paintCopy(*paint); 2718 paintCopy.setTextAlign(SkPaint::kLeft_Align); 2719 status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y, 2720 positions, hasActiveLayer ? &bounds : NULL); 2721 } else { 2722 status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y, 2723 positions, hasActiveLayer ? &bounds : NULL); 2724 } 2725 2726 if (status && hasActiveLayer) { 2727 if (!pureTranslate) { 2728 mSnapshot->transform->mapRect(bounds); 2729 } 2730 dirtyLayerUnchecked(bounds, getRegion()); 2731 } 2732 2733 drawTextDecorations(text, bytesCount, length, oldX, oldY, paint); 2734 2735 return DrawGlInfo::kStatusDrew; 2736} 2737 2738status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, SkPath* path, 2739 float hOffset, float vOffset, SkPaint* paint) { 2740 if (text == NULL || count == 0 || mSnapshot->isIgnored() || 2741 (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) { 2742 return DrawGlInfo::kStatusDone; 2743 } 2744 2745 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2746 fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), 2747 paint->getTextSize()); 2748 2749 int alpha; 2750 SkXfermode::Mode mode; 2751 getAlphaAndMode(paint, &alpha, &mode); 2752 2753 mCaches.activeTexture(0); 2754 setupDraw(); 2755 setupDrawTextGamma(paint); 2756 setupDrawDirtyRegionsDisabled(); 2757 setupDrawWithTexture(true); 2758 setupDrawAlpha8Color(paint->getColor(), alpha); 2759 setupDrawColorFilter(); 2760 setupDrawShader(); 2761 setupDrawBlending(true, mode); 2762 setupDrawProgram(); 2763 setupDrawModelView(0.0f, 0.0f, 0.0f, 0.0f, false, true); 2764 setupDrawTexture(fontRenderer.getTexture(true)); 2765 setupDrawPureColorUniforms(); 2766 setupDrawColorFilterUniforms(); 2767 setupDrawShaderUniforms(false); 2768 setupDrawTextGammaUniforms(); 2769 2770 const Rect* clip = &mSnapshot->getLocalClip(); 2771 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2772 2773 const bool hasActiveLayer = hasLayer(); 2774 2775 if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path, 2776 hOffset, vOffset, hasActiveLayer ? &bounds : NULL)) { 2777 if (hasActiveLayer) { 2778 mSnapshot->transform->mapRect(bounds); 2779 dirtyLayerUnchecked(bounds, getRegion()); 2780 } 2781 } 2782 2783 return DrawGlInfo::kStatusDrew; 2784} 2785 2786status_t OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) { 2787 if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone; 2788 2789 mCaches.activeTexture(0); 2790 2791 // TODO: Perform early clip test before we rasterize the path 2792 const PathTexture* texture = mCaches.pathCache.get(path, paint); 2793 if (!texture) return DrawGlInfo::kStatusDone; 2794 const AutoTexture autoCleanup(texture); 2795 2796 const float x = texture->left - texture->offset; 2797 const float y = texture->top - texture->offset; 2798 2799 drawPathTexture(texture, x, y, paint); 2800 2801 return DrawGlInfo::kStatusDrew; 2802} 2803 2804status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) { 2805 if (!layer) { 2806 return DrawGlInfo::kStatusDone; 2807 } 2808 2809 mat4* transform = NULL; 2810 if (layer->isTextureLayer()) { 2811 transform = &layer->getTransform(); 2812 if (!transform->isIdentity()) { 2813 save(0); 2814 mSnapshot->transform->multiply(*transform); 2815 } 2816 } 2817 2818 Rect transformed; 2819 Rect clip; 2820 const bool rejected = quickRejectNoScissor(x, y, 2821 x + layer->layer.getWidth(), y + layer->layer.getHeight(), transformed, clip); 2822 2823 if (rejected) { 2824 if (transform && !transform->isIdentity()) { 2825 restore(); 2826 } 2827 return DrawGlInfo::kStatusDone; 2828 } 2829 2830 updateLayer(layer, true); 2831 2832 mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clip.contains(transformed)); 2833 mCaches.activeTexture(0); 2834 2835 if (CC_LIKELY(!layer->region.isEmpty())) { 2836 SkiaColorFilter* oldFilter = mColorFilter; 2837 mColorFilter = layer->getColorFilter(); 2838 2839 if (layer->region.isRect()) { 2840 composeLayerRect(layer, layer->regionRect); 2841 } else if (layer->mesh) { 2842 const float a = layer->getAlpha() / 255.0f; 2843 setupDraw(); 2844 setupDrawWithTexture(); 2845 setupDrawColor(a, a, a, a); 2846 setupDrawColorFilter(); 2847 setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false); 2848 setupDrawProgram(); 2849 setupDrawPureColorUniforms(); 2850 setupDrawColorFilterUniforms(); 2851 setupDrawTexture(layer->getTexture()); 2852 if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) { 2853 int tx = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f); 2854 int ty = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f); 2855 2856 layer->setFilter(GL_NEAREST); 2857 setupDrawModelViewTranslate(tx, ty, 2858 tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true); 2859 } else { 2860 layer->setFilter(GL_LINEAR); 2861 setupDrawModelViewTranslate(x, y, 2862 x + layer->layer.getWidth(), y + layer->layer.getHeight()); 2863 } 2864 setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]); 2865 2866 glDrawElements(GL_TRIANGLES, layer->meshElementCount, 2867 GL_UNSIGNED_SHORT, layer->meshIndices); 2868 2869 finishDrawTexture(); 2870 2871#if DEBUG_LAYERS_AS_REGIONS 2872 drawRegionRects(layer->region); 2873#endif 2874 } 2875 2876 mColorFilter = oldFilter; 2877 2878 if (layer->debugDrawUpdate) { 2879 layer->debugDrawUpdate = false; 2880 drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), 2881 0x7f00ff00, SkXfermode::kSrcOver_Mode); 2882 } 2883 } 2884 2885 if (transform && !transform->isIdentity()) { 2886 restore(); 2887 } 2888 2889 return DrawGlInfo::kStatusDrew; 2890} 2891 2892/////////////////////////////////////////////////////////////////////////////// 2893// Shaders 2894/////////////////////////////////////////////////////////////////////////////// 2895 2896void OpenGLRenderer::resetShader() { 2897 mShader = NULL; 2898} 2899 2900void OpenGLRenderer::setupShader(SkiaShader* shader) { 2901 mShader = shader; 2902 if (mShader) { 2903 mShader->set(&mCaches.textureCache, &mCaches.gradientCache); 2904 } 2905} 2906 2907/////////////////////////////////////////////////////////////////////////////// 2908// Color filters 2909/////////////////////////////////////////////////////////////////////////////// 2910 2911void OpenGLRenderer::resetColorFilter() { 2912 mColorFilter = NULL; 2913} 2914 2915void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) { 2916 mColorFilter = filter; 2917} 2918 2919/////////////////////////////////////////////////////////////////////////////// 2920// Drop shadow 2921/////////////////////////////////////////////////////////////////////////////// 2922 2923void OpenGLRenderer::resetShadow() { 2924 mHasShadow = false; 2925} 2926 2927void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) { 2928 mHasShadow = true; 2929 mShadowRadius = radius; 2930 mShadowDx = dx; 2931 mShadowDy = dy; 2932 mShadowColor = color; 2933} 2934 2935/////////////////////////////////////////////////////////////////////////////// 2936// Draw filters 2937/////////////////////////////////////////////////////////////////////////////// 2938 2939void OpenGLRenderer::resetPaintFilter() { 2940 mHasDrawFilter = false; 2941} 2942 2943void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) { 2944 mHasDrawFilter = true; 2945 mPaintFilterClearBits = clearBits & SkPaint::kAllFlags; 2946 mPaintFilterSetBits = setBits & SkPaint::kAllFlags; 2947} 2948 2949SkPaint* OpenGLRenderer::filterPaint(SkPaint* paint) { 2950 if (CC_LIKELY(!mHasDrawFilter || !paint)) return paint; 2951 2952 uint32_t flags = paint->getFlags(); 2953 2954 mFilteredPaint = *paint; 2955 mFilteredPaint.setFlags((flags & ~mPaintFilterClearBits) | mPaintFilterSetBits); 2956 2957 return &mFilteredPaint; 2958} 2959 2960/////////////////////////////////////////////////////////////////////////////// 2961// Drawing implementation 2962/////////////////////////////////////////////////////////////////////////////// 2963 2964void OpenGLRenderer::drawPathTexture(const PathTexture* texture, 2965 float x, float y, SkPaint* paint) { 2966 if (quickReject(x, y, x + texture->width, y + texture->height)) { 2967 return; 2968 } 2969 2970 int alpha; 2971 SkXfermode::Mode mode; 2972 getAlphaAndMode(paint, &alpha, &mode); 2973 2974 setupDraw(); 2975 setupDrawWithTexture(true); 2976 setupDrawAlpha8Color(paint->getColor(), alpha); 2977 setupDrawColorFilter(); 2978 setupDrawShader(); 2979 setupDrawBlending(true, mode); 2980 setupDrawProgram(); 2981 setupDrawModelView(x, y, x + texture->width, y + texture->height); 2982 setupDrawTexture(texture->id); 2983 setupDrawPureColorUniforms(); 2984 setupDrawColorFilterUniforms(); 2985 setupDrawShaderUniforms(); 2986 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 2987 2988 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 2989 2990 finishDrawTexture(); 2991} 2992 2993// Same values used by Skia 2994#define kStdStrikeThru_Offset (-6.0f / 21.0f) 2995#define kStdUnderline_Offset (1.0f / 9.0f) 2996#define kStdUnderline_Thickness (1.0f / 18.0f) 2997 2998void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length, 2999 float x, float y, SkPaint* paint) { 3000 // Handle underline and strike-through 3001 uint32_t flags = paint->getFlags(); 3002 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) { 3003 SkPaint paintCopy(*paint); 3004 float underlineWidth = length; 3005 // If length is > 0.0f, we already measured the text for the text alignment 3006 if (length <= 0.0f) { 3007 underlineWidth = paintCopy.measureText(text, bytesCount); 3008 } 3009 3010 if (CC_LIKELY(underlineWidth > 0.0f)) { 3011 const float textSize = paintCopy.getTextSize(); 3012 const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f); 3013 3014 const float left = x; 3015 float top = 0.0f; 3016 3017 int linesCount = 0; 3018 if (flags & SkPaint::kUnderlineText_Flag) linesCount++; 3019 if (flags & SkPaint::kStrikeThruText_Flag) linesCount++; 3020 3021 const int pointsCount = 4 * linesCount; 3022 float points[pointsCount]; 3023 int currentPoint = 0; 3024 3025 if (flags & SkPaint::kUnderlineText_Flag) { 3026 top = y + textSize * kStdUnderline_Offset; 3027 points[currentPoint++] = left; 3028 points[currentPoint++] = top; 3029 points[currentPoint++] = left + underlineWidth; 3030 points[currentPoint++] = top; 3031 } 3032 3033 if (flags & SkPaint::kStrikeThruText_Flag) { 3034 top = y + textSize * kStdStrikeThru_Offset; 3035 points[currentPoint++] = left; 3036 points[currentPoint++] = top; 3037 points[currentPoint++] = left + underlineWidth; 3038 points[currentPoint++] = top; 3039 } 3040 3041 paintCopy.setStrokeWidth(strokeWidth); 3042 3043 drawLines(&points[0], pointsCount, &paintCopy); 3044 } 3045 } 3046} 3047 3048void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 3049 int color, SkXfermode::Mode mode, bool ignoreTransform) { 3050 // If a shader is set, preserve only the alpha 3051 if (mShader) { 3052 color |= 0x00ffffff; 3053 } 3054 3055 setupDraw(); 3056 setupDrawNoTexture(); 3057 setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha); 3058 setupDrawShader(); 3059 setupDrawColorFilter(); 3060 setupDrawBlending(mode); 3061 setupDrawProgram(); 3062 setupDrawModelView(left, top, right, bottom, ignoreTransform); 3063 setupDrawColorUniforms(); 3064 setupDrawShaderUniforms(ignoreTransform); 3065 setupDrawColorFilterUniforms(); 3066 setupDrawSimpleMesh(); 3067 3068 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 3069} 3070 3071void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 3072 Texture* texture, SkPaint* paint) { 3073 int alpha; 3074 SkXfermode::Mode mode; 3075 getAlphaAndMode(paint, &alpha, &mode); 3076 3077 texture->setWrap(GL_CLAMP_TO_EDGE, true); 3078 3079 if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) { 3080 const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f); 3081 const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f); 3082 3083 texture->setFilter(GL_NEAREST, true); 3084 drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 3085 alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL, 3086 (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true); 3087 } else { 3088 texture->setFilter(FILTER(paint), true); 3089 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, 3090 texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, 3091 GL_TRIANGLE_STRIP, gMeshCount); 3092 } 3093} 3094 3095void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 3096 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) { 3097 drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend, 3098 (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount); 3099} 3100 3101void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom, 3102 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend, 3103 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3104 bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) { 3105 3106 setupDraw(); 3107 setupDrawWithTexture(); 3108 setupDrawColor(alpha, alpha, alpha, alpha); 3109 setupDrawColorFilter(); 3110 setupDrawBlending(blend, mode, swapSrcDst); 3111 setupDrawProgram(); 3112 if (!dirty) setupDrawDirtyRegionsDisabled(); 3113 if (!ignoreScale) { 3114 setupDrawModelView(left, top, right, bottom, ignoreTransform); 3115 } else { 3116 setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform); 3117 } 3118 setupDrawTexture(texture); 3119 setupDrawPureColorUniforms(); 3120 setupDrawColorFilterUniforms(); 3121 setupDrawMesh(vertices, texCoords, vbo); 3122 3123 glDrawArrays(drawMode, 0, elementsCount); 3124 3125 finishDrawTexture(); 3126} 3127 3128void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom, 3129 GLuint texture, bool hasColor, int color, int alpha, SkXfermode::Mode mode, 3130 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3131 bool ignoreTransform, bool dirty) { 3132 3133 setupDraw(); 3134 setupDrawWithTexture(true); 3135 if (hasColor) { 3136 setupDrawAlpha8Color(color, alpha); 3137 } 3138 setupDrawColorFilter(); 3139 setupDrawShader(); 3140 setupDrawBlending(true, mode); 3141 setupDrawProgram(); 3142 if (!dirty) setupDrawDirtyRegionsDisabled(); 3143 setupDrawModelView(left, top, right, bottom, ignoreTransform); 3144 setupDrawTexture(texture); 3145 setupDrawPureColorUniforms(); 3146 setupDrawColorFilterUniforms(); 3147 setupDrawShaderUniforms(); 3148 setupDrawMesh(vertices, texCoords); 3149 3150 glDrawArrays(drawMode, 0, elementsCount); 3151 3152 finishDrawTexture(); 3153} 3154 3155void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, 3156 ProgramDescription& description, bool swapSrcDst) { 3157 blend = blend || mode != SkXfermode::kSrcOver_Mode; 3158 3159 if (blend) { 3160 // These blend modes are not supported by OpenGL directly and have 3161 // to be implemented using shaders. Since the shader will perform 3162 // the blending, turn blending off here 3163 // If the blend mode cannot be implemented using shaders, fall 3164 // back to the default SrcOver blend mode instead 3165 if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) { 3166 if (CC_UNLIKELY(mCaches.extensions.hasFramebufferFetch())) { 3167 description.framebufferMode = mode; 3168 description.swapSrcDst = swapSrcDst; 3169 3170 if (mCaches.blend) { 3171 glDisable(GL_BLEND); 3172 mCaches.blend = false; 3173 } 3174 3175 return; 3176 } else { 3177 mode = SkXfermode::kSrcOver_Mode; 3178 } 3179 } 3180 3181 if (!mCaches.blend) { 3182 glEnable(GL_BLEND); 3183 } 3184 3185 GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src; 3186 GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst; 3187 3188 if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) { 3189 glBlendFunc(sourceMode, destMode); 3190 mCaches.lastSrcMode = sourceMode; 3191 mCaches.lastDstMode = destMode; 3192 } 3193 } else if (mCaches.blend) { 3194 glDisable(GL_BLEND); 3195 } 3196 mCaches.blend = blend; 3197} 3198 3199bool OpenGLRenderer::useProgram(Program* program) { 3200 if (!program->isInUse()) { 3201 if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove(); 3202 program->use(); 3203 mCaches.currentProgram = program; 3204 return false; 3205 } 3206 return true; 3207} 3208 3209void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) { 3210 TextureVertex* v = &mMeshVertices[0]; 3211 TextureVertex::setUV(v++, u1, v1); 3212 TextureVertex::setUV(v++, u2, v1); 3213 TextureVertex::setUV(v++, u1, v2); 3214 TextureVertex::setUV(v++, u2, v2); 3215} 3216 3217void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) { 3218 getAlphaAndModeDirect(paint, alpha, mode); 3219 *alpha *= mSnapshot->alpha; 3220} 3221 3222}; // namespace uirenderer 3223}; // namespace android 3224