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