OpenGLRenderer.cpp revision 8f3b8e32993d190a26c70c839a63d8ce4c3b16d9
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 } 682 683 dirtyClip(); 684 685 // Failing to add the layer to the cache should happen only if the layer is too large 686 if (!mCaches.layerCache.put(layer)) { 687 LAYER_LOGD("Deleting layer"); 688 layer->deleteTexture(); 689 delete layer; 690 } 691} 692 693void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) { 694 float alpha = layer->getAlpha() / 255.0f; 695 696 mat4& transform = layer->getTransform(); 697 if (!transform.isIdentity()) { 698 save(0); 699 mSnapshot->transform->multiply(transform); 700 } 701 702 setupDraw(); 703 if (layer->getRenderTarget() == GL_TEXTURE_2D) { 704 setupDrawWithTexture(); 705 } else { 706 setupDrawWithExternalTexture(); 707 } 708 setupDrawTextureTransform(); 709 setupDrawColor(alpha, alpha, alpha, alpha); 710 setupDrawColorFilter(); 711 setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode()); 712 setupDrawProgram(); 713 setupDrawPureColorUniforms(); 714 setupDrawColorFilterUniforms(); 715 if (layer->getRenderTarget() == GL_TEXTURE_2D) { 716 setupDrawTexture(layer->getTexture()); 717 } else { 718 setupDrawExternalTexture(layer->getTexture()); 719 } 720 if (mSnapshot->transform->isPureTranslate() && 721 layer->getWidth() == (uint32_t) rect.getWidth() && 722 layer->getHeight() == (uint32_t) rect.getHeight()) { 723 const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f); 724 const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f); 725 726 layer->setFilter(GL_NEAREST); 727 setupDrawModelView(x, y, x + rect.getWidth(), y + rect.getHeight(), true); 728 } else { 729 layer->setFilter(GL_LINEAR); 730 setupDrawModelView(rect.left, rect.top, rect.right, rect.bottom); 731 } 732 setupDrawTextureTransformUniforms(layer->getTexTransform()); 733 setupDrawMesh(&mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]); 734 735 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 736 737 finishDrawTexture(); 738 739 if (!transform.isIdentity()) { 740 restore(); 741 } 742} 743 744void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) { 745 if (!layer->isTextureLayer()) { 746 const Rect& texCoords = layer->texCoords; 747 resetDrawTextureTexCoords(texCoords.left, texCoords.top, 748 texCoords.right, texCoords.bottom); 749 750 float x = rect.left; 751 float y = rect.top; 752 bool simpleTransform = mSnapshot->transform->isPureTranslate() && 753 layer->getWidth() == (uint32_t) rect.getWidth() && 754 layer->getHeight() == (uint32_t) rect.getHeight(); 755 756 if (simpleTransform) { 757 // When we're swapping, the layer is already in screen coordinates 758 if (!swap) { 759 x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f); 760 y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f); 761 } 762 763 layer->setFilter(GL_NEAREST, true); 764 } else { 765 layer->setFilter(GL_LINEAR, true); 766 } 767 768 drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(), 769 layer->getTexture(), layer->getAlpha() / 255.0f, 770 layer->getMode(), layer->isBlend(), 771 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], 772 GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform); 773 774 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 775 } else { 776 resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f); 777 drawTextureLayer(layer, rect); 778 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 779 } 780} 781 782void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) { 783#if RENDER_LAYERS_AS_REGIONS 784 if (layer->region.isRect()) { 785 layer->setRegionAsRect(); 786 787 composeLayerRect(layer, layer->regionRect); 788 789 layer->region.clear(); 790 return; 791 } 792 793 // TODO: See LayerRenderer.cpp::generateMesh() for important 794 // information about this implementation 795 if (CC_LIKELY(!layer->region.isEmpty())) { 796 size_t count; 797 const android::Rect* rects = layer->region.getArray(&count); 798 799 const float alpha = layer->getAlpha() / 255.0f; 800 const float texX = 1.0f / float(layer->getWidth()); 801 const float texY = 1.0f / float(layer->getHeight()); 802 const float height = rect.getHeight(); 803 804 TextureVertex* mesh = mCaches.getRegionMesh(); 805 GLsizei numQuads = 0; 806 807 setupDraw(); 808 setupDrawWithTexture(); 809 setupDrawColor(alpha, alpha, alpha, alpha); 810 setupDrawColorFilter(); 811 setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode(), false); 812 setupDrawProgram(); 813 setupDrawDirtyRegionsDisabled(); 814 setupDrawPureColorUniforms(); 815 setupDrawColorFilterUniforms(); 816 setupDrawTexture(layer->getTexture()); 817 if (mSnapshot->transform->isPureTranslate()) { 818 const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f); 819 const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f); 820 821 layer->setFilter(GL_NEAREST); 822 setupDrawModelViewTranslate(x, y, x + rect.getWidth(), y + rect.getHeight(), true); 823 } else { 824 layer->setFilter(GL_LINEAR); 825 setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom); 826 } 827 setupDrawMeshIndices(&mesh[0].position[0], &mesh[0].texture[0]); 828 829 for (size_t i = 0; i < count; i++) { 830 const android::Rect* r = &rects[i]; 831 832 const float u1 = r->left * texX; 833 const float v1 = (height - r->top) * texY; 834 const float u2 = r->right * texX; 835 const float v2 = (height - r->bottom) * texY; 836 837 // TODO: Reject quads outside of the clip 838 TextureVertex::set(mesh++, r->left, r->top, u1, v1); 839 TextureVertex::set(mesh++, r->right, r->top, u2, v1); 840 TextureVertex::set(mesh++, r->left, r->bottom, u1, v2); 841 TextureVertex::set(mesh++, r->right, r->bottom, u2, v2); 842 843 numQuads++; 844 845 if (numQuads >= REGION_MESH_QUAD_COUNT) { 846 glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL); 847 numQuads = 0; 848 mesh = mCaches.getRegionMesh(); 849 } 850 } 851 852 if (numQuads > 0) { 853 glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL); 854 } 855 856 finishDrawTexture(); 857 858#if DEBUG_LAYERS_AS_REGIONS 859 drawRegionRects(layer->region); 860#endif 861 862 layer->region.clear(); 863 } 864#else 865 composeLayerRect(layer, rect); 866#endif 867} 868 869void OpenGLRenderer::drawRegionRects(const Region& region) { 870#if DEBUG_LAYERS_AS_REGIONS 871 size_t count; 872 const android::Rect* rects = region.getArray(&count); 873 874 uint32_t colors[] = { 875 0x7fff0000, 0x7f00ff00, 876 0x7f0000ff, 0x7fff00ff, 877 }; 878 879 int offset = 0; 880 int32_t top = rects[0].top; 881 882 for (size_t i = 0; i < count; i++) { 883 if (top != rects[i].top) { 884 offset ^= 0x2; 885 top = rects[i].top; 886 } 887 888 Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom); 889 drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)], 890 SkXfermode::kSrcOver_Mode); 891 } 892#endif 893} 894 895void OpenGLRenderer::dirtyLayer(const float left, const float top, 896 const float right, const float bottom, const mat4 transform) { 897#if RENDER_LAYERS_AS_REGIONS 898 if (hasLayer()) { 899 Rect bounds(left, top, right, bottom); 900 transform.mapRect(bounds); 901 dirtyLayerUnchecked(bounds, getRegion()); 902 } 903#endif 904} 905 906void OpenGLRenderer::dirtyLayer(const float left, const float top, 907 const float right, const float bottom) { 908#if RENDER_LAYERS_AS_REGIONS 909 if (hasLayer()) { 910 Rect bounds(left, top, right, bottom); 911 dirtyLayerUnchecked(bounds, getRegion()); 912 } 913#endif 914} 915 916void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) { 917#if RENDER_LAYERS_AS_REGIONS 918 if (bounds.intersect(*mSnapshot->clipRect)) { 919 bounds.snapToPixelBoundaries(); 920 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom); 921 if (!dirty.isEmpty()) { 922 region->orSelf(dirty); 923 } 924 } 925#endif 926} 927 928void OpenGLRenderer::clearLayerRegions() { 929 const size_t count = mLayers.size(); 930 if (count == 0) return; 931 932 if (!mSnapshot->isIgnored()) { 933 // Doing several glScissor/glClear here can negatively impact 934 // GPUs with a tiler architecture, instead we draw quads with 935 // the Clear blending mode 936 937 // The list contains bounds that have already been clipped 938 // against their initial clip rect, and the current clip 939 // is likely different so we need to disable clipping here 940 glDisable(GL_SCISSOR_TEST); 941 942 Vertex mesh[count * 6]; 943 Vertex* vertex = mesh; 944 945 for (uint32_t i = 0; i < count; i++) { 946 Rect* bounds = mLayers.itemAt(i); 947 948 Vertex::set(vertex++, bounds->left, bounds->bottom); 949 Vertex::set(vertex++, bounds->left, bounds->top); 950 Vertex::set(vertex++, bounds->right, bounds->top); 951 Vertex::set(vertex++, bounds->left, bounds->bottom); 952 Vertex::set(vertex++, bounds->right, bounds->top); 953 Vertex::set(vertex++, bounds->right, bounds->bottom); 954 955 delete bounds; 956 } 957 958 setupDraw(false); 959 setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f); 960 setupDrawBlending(true, SkXfermode::kClear_Mode); 961 setupDrawProgram(); 962 setupDrawPureColorUniforms(); 963 setupDrawModelViewTranslate(0.0f, 0.0f, 0.0f, 0.0f, true); 964 setupDrawVertices(&mesh[0].position[0]); 965 966 glDrawArrays(GL_TRIANGLES, 0, count * 6); 967 968 glEnable(GL_SCISSOR_TEST); 969 } else { 970 for (uint32_t i = 0; i < count; i++) { 971 delete mLayers.itemAt(i); 972 } 973 } 974 975 mLayers.clear(); 976} 977 978/////////////////////////////////////////////////////////////////////////////// 979// Transforms 980/////////////////////////////////////////////////////////////////////////////// 981 982void OpenGLRenderer::translate(float dx, float dy) { 983 mSnapshot->transform->translate(dx, dy, 0.0f); 984} 985 986void OpenGLRenderer::rotate(float degrees) { 987 mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f); 988} 989 990void OpenGLRenderer::scale(float sx, float sy) { 991 mSnapshot->transform->scale(sx, sy, 1.0f); 992} 993 994void OpenGLRenderer::skew(float sx, float sy) { 995 mSnapshot->transform->skew(sx, sy); 996} 997 998void OpenGLRenderer::setMatrix(SkMatrix* matrix) { 999 if (matrix) { 1000 mSnapshot->transform->load(*matrix); 1001 } else { 1002 mSnapshot->transform->loadIdentity(); 1003 } 1004} 1005 1006void OpenGLRenderer::getMatrix(SkMatrix* matrix) { 1007 mSnapshot->transform->copyTo(*matrix); 1008} 1009 1010void OpenGLRenderer::concatMatrix(SkMatrix* matrix) { 1011 SkMatrix transform; 1012 mSnapshot->transform->copyTo(transform); 1013 transform.preConcat(*matrix); 1014 mSnapshot->transform->load(transform); 1015} 1016 1017/////////////////////////////////////////////////////////////////////////////// 1018// Clipping 1019/////////////////////////////////////////////////////////////////////////////// 1020 1021void OpenGLRenderer::setScissorFromClip() { 1022 Rect clip(*mSnapshot->clipRect); 1023 clip.snapToPixelBoundaries(); 1024 1025 mCaches.setScissor(clip.left, mSnapshot->height - clip.bottom, 1026 clip.getWidth(), clip.getHeight()); 1027 1028 mDirtyClip = false; 1029} 1030 1031const Rect& OpenGLRenderer::getClipBounds() { 1032 return mSnapshot->getLocalClip(); 1033} 1034 1035bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) { 1036 if (mSnapshot->isIgnored()) { 1037 return true; 1038 } 1039 1040 Rect r(left, top, right, bottom); 1041 mSnapshot->transform->mapRect(r); 1042 r.snapToPixelBoundaries(); 1043 1044 Rect clipRect(*mSnapshot->clipRect); 1045 clipRect.snapToPixelBoundaries(); 1046 1047 return !clipRect.intersects(r); 1048} 1049 1050bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) { 1051 bool clipped = mSnapshot->clip(left, top, right, bottom, op); 1052 if (clipped) { 1053 dirtyClip(); 1054 } 1055 return !mSnapshot->clipRect->isEmpty(); 1056} 1057 1058/////////////////////////////////////////////////////////////////////////////// 1059// Drawing commands 1060/////////////////////////////////////////////////////////////////////////////// 1061 1062void OpenGLRenderer::setupDraw(bool clear) { 1063 if (clear) clearLayerRegions(); 1064 if (mDirtyClip) { 1065 setScissorFromClip(); 1066 } 1067 mDescription.reset(); 1068 mSetShaderColor = false; 1069 mColorSet = false; 1070 mColorA = mColorR = mColorG = mColorB = 0.0f; 1071 mTextureUnit = 0; 1072 mTrackDirtyRegions = true; 1073} 1074 1075void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) { 1076 mDescription.hasTexture = true; 1077 mDescription.hasAlpha8Texture = isAlpha8; 1078} 1079 1080void OpenGLRenderer::setupDrawWithExternalTexture() { 1081 mDescription.hasExternalTexture = true; 1082} 1083 1084void OpenGLRenderer::setupDrawNoTexture() { 1085 mCaches.disbaleTexCoordsVertexArray(); 1086} 1087 1088void OpenGLRenderer::setupDrawAALine() { 1089 mDescription.isAA = true; 1090} 1091 1092void OpenGLRenderer::setupDrawPoint(float pointSize) { 1093 mDescription.isPoint = true; 1094 mDescription.pointSize = pointSize; 1095} 1096 1097void OpenGLRenderer::setupDrawColor(int color) { 1098 setupDrawColor(color, (color >> 24) & 0xFF); 1099} 1100 1101void OpenGLRenderer::setupDrawColor(int color, int alpha) { 1102 mColorA = alpha / 255.0f; 1103 // Second divide of a by 255 is an optimization, allowing us to simply multiply 1104 // the rgb values by a instead of also dividing by 255 1105 const float a = mColorA / 255.0f; 1106 mColorR = a * ((color >> 16) & 0xFF); 1107 mColorG = a * ((color >> 8) & 0xFF); 1108 mColorB = a * ((color ) & 0xFF); 1109 mColorSet = true; 1110 mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA); 1111} 1112 1113void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) { 1114 mColorA = alpha / 255.0f; 1115 // Double-divide of a by 255 is an optimization, allowing us to simply multiply 1116 // the rgb values by a instead of also dividing by 255 1117 const float a = mColorA / 255.0f; 1118 mColorR = a * ((color >> 16) & 0xFF); 1119 mColorG = a * ((color >> 8) & 0xFF); 1120 mColorB = a * ((color ) & 0xFF); 1121 mColorSet = true; 1122 mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA); 1123} 1124 1125void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) { 1126 mColorA = a; 1127 mColorR = r; 1128 mColorG = g; 1129 mColorB = b; 1130 mColorSet = true; 1131 mSetShaderColor = mDescription.setColor(r, g, b, a); 1132} 1133 1134void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) { 1135 mColorA = a; 1136 mColorR = r; 1137 mColorG = g; 1138 mColorB = b; 1139 mColorSet = true; 1140 mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a); 1141} 1142 1143void OpenGLRenderer::setupDrawShader() { 1144 if (mShader) { 1145 mShader->describe(mDescription, mCaches.extensions); 1146 } 1147} 1148 1149void OpenGLRenderer::setupDrawColorFilter() { 1150 if (mColorFilter) { 1151 mColorFilter->describe(mDescription, mCaches.extensions); 1152 } 1153} 1154 1155void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) { 1156 if (mColorSet && mode == SkXfermode::kClear_Mode) { 1157 mColorA = 1.0f; 1158 mColorR = mColorG = mColorB = 0.0f; 1159 mSetShaderColor = mDescription.modulate = true; 1160 } 1161} 1162 1163void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) { 1164 // When the blending mode is kClear_Mode, we need to use a modulate color 1165 // argb=1,0,0,0 1166 accountForClear(mode); 1167 chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode, 1168 mDescription, swapSrcDst); 1169} 1170 1171void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) { 1172 // When the blending mode is kClear_Mode, we need to use a modulate color 1173 // argb=1,0,0,0 1174 accountForClear(mode); 1175 chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode, 1176 mDescription, swapSrcDst); 1177} 1178 1179void OpenGLRenderer::setupDrawProgram() { 1180 useProgram(mCaches.programCache.get(mDescription)); 1181} 1182 1183void OpenGLRenderer::setupDrawDirtyRegionsDisabled() { 1184 mTrackDirtyRegions = false; 1185} 1186 1187void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom, 1188 bool ignoreTransform) { 1189 mModelView.loadTranslate(left, top, 0.0f); 1190 if (!ignoreTransform) { 1191 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 1192 if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1193 } else { 1194 mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity); 1195 if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom); 1196 } 1197} 1198 1199void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) { 1200 mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset); 1201} 1202 1203void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom, 1204 bool ignoreTransform, bool ignoreModelView) { 1205 if (!ignoreModelView) { 1206 mModelView.loadTranslate(left, top, 0.0f); 1207 mModelView.scale(right - left, bottom - top, 1.0f); 1208 } else { 1209 mModelView.loadIdentity(); 1210 } 1211 bool dirty = right - left > 0.0f && bottom - top > 0.0f; 1212 if (!ignoreTransform) { 1213 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 1214 if (mTrackDirtyRegions && dirty) { 1215 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1216 } 1217 } else { 1218 mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity); 1219 if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom); 1220 } 1221} 1222 1223void OpenGLRenderer::setupDrawPointUniforms() { 1224 int slot = mCaches.currentProgram->getUniform("pointSize"); 1225 glUniform1f(slot, mDescription.pointSize); 1226} 1227 1228void OpenGLRenderer::setupDrawColorUniforms() { 1229 if ((mColorSet && !mShader) || (mShader && mSetShaderColor)) { 1230 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1231 } 1232} 1233 1234void OpenGLRenderer::setupDrawPureColorUniforms() { 1235 if (mSetShaderColor) { 1236 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1237 } 1238} 1239 1240void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) { 1241 if (mShader) { 1242 if (ignoreTransform) { 1243 mModelView.loadInverse(*mSnapshot->transform); 1244 } 1245 mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit); 1246 } 1247} 1248 1249void OpenGLRenderer::setupDrawShaderIdentityUniforms() { 1250 if (mShader) { 1251 mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit); 1252 } 1253} 1254 1255void OpenGLRenderer::setupDrawColorFilterUniforms() { 1256 if (mColorFilter) { 1257 mColorFilter->setupProgram(mCaches.currentProgram); 1258 } 1259} 1260 1261void OpenGLRenderer::setupDrawSimpleMesh() { 1262 bool force = mCaches.bindMeshBuffer(); 1263 mCaches.bindPositionVertexPointer(force, mCaches.currentProgram->position, 0); 1264 mCaches.unbindIndicesBuffer(); 1265} 1266 1267void OpenGLRenderer::setupDrawTexture(GLuint texture) { 1268 bindTexture(texture); 1269 mTextureUnit++; 1270 mCaches.enableTexCoordsVertexArray(); 1271} 1272 1273void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) { 1274 bindExternalTexture(texture); 1275 mTextureUnit++; 1276 mCaches.enableTexCoordsVertexArray(); 1277} 1278 1279void OpenGLRenderer::setupDrawTextureTransform() { 1280 mDescription.hasTextureTransform = true; 1281} 1282 1283void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) { 1284 glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1, 1285 GL_FALSE, &transform.data[0]); 1286} 1287 1288void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) { 1289 bool force = false; 1290 if (!vertices) { 1291 force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo); 1292 } else { 1293 force = mCaches.unbindMeshBuffer(); 1294 } 1295 1296 mCaches.bindPositionVertexPointer(force, mCaches.currentProgram->position, vertices); 1297 if (mCaches.currentProgram->texCoords >= 0) { 1298 mCaches.bindTexCoordsVertexPointer(force, mCaches.currentProgram->texCoords, texCoords); 1299 } 1300 1301 mCaches.unbindIndicesBuffer(); 1302} 1303 1304void OpenGLRenderer::setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords) { 1305 bool force = mCaches.unbindMeshBuffer(); 1306 mCaches.bindPositionVertexPointer(force, mCaches.currentProgram->position, vertices); 1307 if (mCaches.currentProgram->texCoords >= 0) { 1308 mCaches.bindTexCoordsVertexPointer(force, mCaches.currentProgram->texCoords, texCoords); 1309 } 1310} 1311 1312void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) { 1313 bool force = mCaches.unbindMeshBuffer(); 1314 mCaches.bindPositionVertexPointer(force, mCaches.currentProgram->position, 1315 vertices, gVertexStride); 1316 mCaches.unbindIndicesBuffer(); 1317} 1318 1319/** 1320 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an 1321 * outer boundary that fades out to 0. The variables set in the shader define the proportion of 1322 * the width and length of the primitive occupied by the AA region. The vtxWidth and vtxLength 1323 * attributes (one per vertex) are values from zero to one that tells the fragment 1324 * shader where the fragment is in relation to the line width/length overall; these values are 1325 * then used to compute the proper color, based on whether the fragment lies in the fading AA 1326 * region of the line. 1327 * Note that we only pass down the width values in this setup function. The length coordinates 1328 * are set up for each individual segment. 1329 */ 1330void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* widthCoords, 1331 GLvoid* lengthCoords, float boundaryWidthProportion) { 1332 bool force = mCaches.unbindMeshBuffer(); 1333 mCaches.bindPositionVertexPointer(force, mCaches.currentProgram->position, 1334 vertices, gAAVertexStride); 1335 mCaches.resetTexCoordsVertexPointer(); 1336 mCaches.unbindIndicesBuffer(); 1337 1338 int widthSlot = mCaches.currentProgram->getAttrib("vtxWidth"); 1339 glEnableVertexAttribArray(widthSlot); 1340 glVertexAttribPointer(widthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, widthCoords); 1341 1342 int lengthSlot = mCaches.currentProgram->getAttrib("vtxLength"); 1343 glEnableVertexAttribArray(lengthSlot); 1344 glVertexAttribPointer(lengthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, lengthCoords); 1345 1346 int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth"); 1347 glUniform1f(boundaryWidthSlot, boundaryWidthProportion); 1348 1349 // Setting the inverse value saves computations per-fragment in the shader 1350 int inverseBoundaryWidthSlot = mCaches.currentProgram->getUniform("inverseBoundaryWidth"); 1351 glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion)); 1352} 1353 1354void OpenGLRenderer::finishDrawTexture() { 1355} 1356 1357/////////////////////////////////////////////////////////////////////////////// 1358// Drawing 1359/////////////////////////////////////////////////////////////////////////////// 1360 1361status_t OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t width, uint32_t height, 1362 Rect& dirty, int32_t flags, uint32_t level) { 1363 1364 if (!USE_DISPLAY_LIST_PROPERTIES && quickReject(0, 0, width, height)) { 1365 return false; 1366 } 1367 1368 // All the usual checks and setup operations (quickReject, setupDraw, etc.) 1369 // will be performed by the display list itself 1370 if (displayList && displayList->isRenderable()) { 1371 return displayList->replay(*this, width, height, dirty, flags, level); 1372 } 1373 1374 return DrawGlInfo::kStatusDone; 1375} 1376 1377void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) { 1378 if (displayList) { 1379 displayList->output(*this, level); 1380 } 1381} 1382 1383void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) { 1384 int alpha; 1385 SkXfermode::Mode mode; 1386 getAlphaAndMode(paint, &alpha, &mode); 1387 1388 float x = left; 1389 float y = top; 1390 1391 GLenum filter = GL_LINEAR; 1392 bool ignoreTransform = false; 1393 if (mSnapshot->transform->isPureTranslate()) { 1394 x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f); 1395 y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f); 1396 ignoreTransform = true; 1397 filter = GL_NEAREST; 1398 } else { 1399 filter = FILTER(paint); 1400 } 1401 1402 setupDraw(); 1403 setupDrawWithTexture(true); 1404 if (paint) { 1405 setupDrawAlpha8Color(paint->getColor(), alpha); 1406 } 1407 setupDrawColorFilter(); 1408 setupDrawShader(); 1409 setupDrawBlending(true, mode); 1410 setupDrawProgram(); 1411 setupDrawModelView(x, y, x + texture->width, y + texture->height, ignoreTransform); 1412 1413 setupDrawTexture(texture->id); 1414 texture->setWrap(GL_CLAMP_TO_EDGE); 1415 texture->setFilter(filter); 1416 1417 setupDrawPureColorUniforms(); 1418 setupDrawColorFilterUniforms(); 1419 setupDrawShaderUniforms(); 1420 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 1421 1422 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 1423 1424 finishDrawTexture(); 1425} 1426 1427void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) { 1428 const float right = left + bitmap->width(); 1429 const float bottom = top + bitmap->height(); 1430 1431 if (quickReject(left, top, right, bottom)) { 1432 return; 1433 } 1434 1435 mCaches.activeTexture(0); 1436 Texture* texture = mCaches.textureCache.get(bitmap); 1437 if (!texture) return; 1438 const AutoTexture autoCleanup(texture); 1439 1440 if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) { 1441 drawAlphaBitmap(texture, left, top, paint); 1442 } else { 1443 drawTextureRect(left, top, right, bottom, texture, paint); 1444 } 1445} 1446 1447void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) { 1448 Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height()); 1449 const mat4 transform(*matrix); 1450 transform.mapRect(r); 1451 1452 if (quickReject(r.left, r.top, r.right, r.bottom)) { 1453 return; 1454 } 1455 1456 mCaches.activeTexture(0); 1457 Texture* texture = mCaches.textureCache.get(bitmap); 1458 if (!texture) return; 1459 const AutoTexture autoCleanup(texture); 1460 1461 // This could be done in a cheaper way, all we need is pass the matrix 1462 // to the vertex shader. The save/restore is a bit overkill. 1463 save(SkCanvas::kMatrix_SaveFlag); 1464 concatMatrix(matrix); 1465 drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint); 1466 restore(); 1467} 1468 1469void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight, 1470 float* vertices, int* colors, SkPaint* paint) { 1471 // TODO: Do a quickReject 1472 if (!vertices || mSnapshot->isIgnored()) { 1473 return; 1474 } 1475 1476 mCaches.activeTexture(0); 1477 Texture* texture = mCaches.textureCache.get(bitmap); 1478 if (!texture) return; 1479 const AutoTexture autoCleanup(texture); 1480 1481 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1482 texture->setFilter(FILTER(paint), true); 1483 1484 int alpha; 1485 SkXfermode::Mode mode; 1486 getAlphaAndMode(paint, &alpha, &mode); 1487 1488 const uint32_t count = meshWidth * meshHeight * 6; 1489 1490 float left = FLT_MAX; 1491 float top = FLT_MAX; 1492 float right = FLT_MIN; 1493 float bottom = FLT_MIN; 1494 1495#if RENDER_LAYERS_AS_REGIONS 1496 const bool hasActiveLayer = hasLayer(); 1497#else 1498 const bool hasActiveLayer = false; 1499#endif 1500 1501 // TODO: Support the colors array 1502 TextureVertex mesh[count]; 1503 TextureVertex* vertex = mesh; 1504 for (int32_t y = 0; y < meshHeight; y++) { 1505 for (int32_t x = 0; x < meshWidth; x++) { 1506 uint32_t i = (y * (meshWidth + 1) + x) * 2; 1507 1508 float u1 = float(x) / meshWidth; 1509 float u2 = float(x + 1) / meshWidth; 1510 float v1 = float(y) / meshHeight; 1511 float v2 = float(y + 1) / meshHeight; 1512 1513 int ax = i + (meshWidth + 1) * 2; 1514 int ay = ax + 1; 1515 int bx = i; 1516 int by = bx + 1; 1517 int cx = i + 2; 1518 int cy = cx + 1; 1519 int dx = i + (meshWidth + 1) * 2 + 2; 1520 int dy = dx + 1; 1521 1522 TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2); 1523 TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1); 1524 TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1); 1525 1526 TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2); 1527 TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1); 1528 TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2); 1529 1530#if RENDER_LAYERS_AS_REGIONS 1531 if (hasActiveLayer) { 1532 // TODO: This could be optimized to avoid unnecessary ops 1533 left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx]))); 1534 top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy]))); 1535 right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx]))); 1536 bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy]))); 1537 } 1538#endif 1539 } 1540 } 1541 1542#if RENDER_LAYERS_AS_REGIONS 1543 if (hasActiveLayer) { 1544 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1545 } 1546#endif 1547 1548 drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f, 1549 mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0], 1550 GL_TRIANGLES, count, false, false, 0, false, false); 1551} 1552 1553void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, 1554 float srcLeft, float srcTop, float srcRight, float srcBottom, 1555 float dstLeft, float dstTop, float dstRight, float dstBottom, 1556 SkPaint* paint) { 1557 if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) { 1558 return; 1559 } 1560 1561 mCaches.activeTexture(0); 1562 Texture* texture = mCaches.textureCache.get(bitmap); 1563 if (!texture) return; 1564 const AutoTexture autoCleanup(texture); 1565 1566 const float width = texture->width; 1567 const float height = texture->height; 1568 1569 const float u1 = fmax(0.0f, srcLeft / width); 1570 const float v1 = fmax(0.0f, srcTop / height); 1571 const float u2 = fmin(1.0f, srcRight / width); 1572 const float v2 = fmin(1.0f, srcBottom / height); 1573 1574 mCaches.unbindMeshBuffer(); 1575 resetDrawTextureTexCoords(u1, v1, u2, v2); 1576 1577 int alpha; 1578 SkXfermode::Mode mode; 1579 getAlphaAndMode(paint, &alpha, &mode); 1580 1581 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1582 1583 if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) { 1584 const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f); 1585 const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f); 1586 1587 GLenum filter = GL_NEAREST; 1588 // Enable linear filtering if the source rectangle is scaled 1589 if (srcRight - srcLeft != dstRight - dstLeft || srcBottom - srcTop != dstBottom - dstTop) { 1590 filter = FILTER(paint); 1591 } 1592 1593 texture->setFilter(filter, true); 1594 drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop), 1595 texture->id, alpha / 255.0f, mode, texture->blend, 1596 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], 1597 GL_TRIANGLE_STRIP, gMeshCount, false, true); 1598 } else { 1599 texture->setFilter(FILTER(paint), true); 1600 drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f, 1601 mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], 1602 GL_TRIANGLE_STRIP, gMeshCount); 1603 } 1604 1605 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 1606} 1607 1608void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs, 1609 const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors, 1610 float left, float top, float right, float bottom, SkPaint* paint) { 1611 if (quickReject(left, top, right, bottom)) { 1612 return; 1613 } 1614 1615 mCaches.activeTexture(0); 1616 Texture* texture = mCaches.textureCache.get(bitmap); 1617 if (!texture) return; 1618 const AutoTexture autoCleanup(texture); 1619 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1620 texture->setFilter(GL_LINEAR, true); 1621 1622 int alpha; 1623 SkXfermode::Mode mode; 1624 getAlphaAndMode(paint, &alpha, &mode); 1625 1626 const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(), 1627 right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors); 1628 1629 if (CC_LIKELY(mesh && mesh->verticesCount > 0)) { 1630 const bool pureTranslate = mSnapshot->transform->isPureTranslate(); 1631#if RENDER_LAYERS_AS_REGIONS 1632 // Mark the current layer dirty where we are going to draw the patch 1633 if (hasLayer() && mesh->hasEmptyQuads) { 1634 const float offsetX = left + mSnapshot->transform->getTranslateX(); 1635 const float offsetY = top + mSnapshot->transform->getTranslateY(); 1636 const size_t count = mesh->quads.size(); 1637 for (size_t i = 0; i < count; i++) { 1638 const Rect& bounds = mesh->quads.itemAt(i); 1639 if (CC_LIKELY(pureTranslate)) { 1640 const float x = (int) floorf(bounds.left + offsetX + 0.5f); 1641 const float y = (int) floorf(bounds.top + offsetY + 0.5f); 1642 dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight()); 1643 } else { 1644 dirtyLayer(left + bounds.left, top + bounds.top, 1645 left + bounds.right, top + bounds.bottom, *mSnapshot->transform); 1646 } 1647 } 1648 } 1649#endif 1650 1651 if (CC_LIKELY(pureTranslate)) { 1652 const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f); 1653 const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f); 1654 1655 drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f, 1656 mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset, 1657 GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer, 1658 true, !mesh->hasEmptyQuads); 1659 } else { 1660 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, 1661 mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset, 1662 GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer, 1663 true, !mesh->hasEmptyQuads); 1664 } 1665 } 1666} 1667 1668/** 1669 * This function uses a similar approach to that of AA lines in the drawLines() function. 1670 * We expand the rectangle by a half pixel in screen space on all sides, and use a fragment 1671 * shader to compute the translucency of the color, determined by whether a given pixel is 1672 * within that boundary region and how far into the region it is. 1673 */ 1674void OpenGLRenderer::drawAARect(float left, float top, float right, float bottom, 1675 int color, SkXfermode::Mode mode) { 1676 float inverseScaleX = 1.0f; 1677 float inverseScaleY = 1.0f; 1678 // The quad that we use needs to account for scaling. 1679 if (CC_UNLIKELY(!mSnapshot->transform->isPureTranslate())) { 1680 Matrix4 *mat = mSnapshot->transform; 1681 float m00 = mat->data[Matrix4::kScaleX]; 1682 float m01 = mat->data[Matrix4::kSkewY]; 1683 float m02 = mat->data[2]; 1684 float m10 = mat->data[Matrix4::kSkewX]; 1685 float m11 = mat->data[Matrix4::kScaleX]; 1686 float m12 = mat->data[6]; 1687 float scaleX = sqrt(m00 * m00 + m01 * m01); 1688 float scaleY = sqrt(m10 * m10 + m11 * m11); 1689 inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0; 1690 inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0; 1691 } 1692 1693 setupDraw(); 1694 setupDrawNoTexture(); 1695 setupDrawAALine(); 1696 setupDrawColor(color); 1697 setupDrawColorFilter(); 1698 setupDrawShader(); 1699 setupDrawBlending(true, mode); 1700 setupDrawProgram(); 1701 setupDrawModelViewIdentity(true); 1702 setupDrawColorUniforms(); 1703 setupDrawColorFilterUniforms(); 1704 setupDrawShaderIdentityUniforms(); 1705 1706 AAVertex rects[4]; 1707 AAVertex* aaVertices = &rects[0]; 1708 void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset; 1709 void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset; 1710 1711 float boundarySizeX = .5 * inverseScaleX; 1712 float boundarySizeY = .5 * inverseScaleY; 1713 1714 // Adjust the rect by the AA boundary padding 1715 left -= boundarySizeX; 1716 right += boundarySizeX; 1717 top -= boundarySizeY; 1718 bottom += boundarySizeY; 1719 1720 float width = right - left; 1721 float height = bottom - top; 1722 1723 float boundaryWidthProportion = (width != 0) ? (2 * boundarySizeX) / width : 0; 1724 float boundaryHeightProportion = (height != 0) ? (2 * boundarySizeY) / height : 0; 1725 setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion); 1726 int boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength"); 1727 int inverseBoundaryLengthSlot = mCaches.currentProgram->getUniform("inverseBoundaryLength"); 1728 glUniform1f(boundaryLengthSlot, boundaryHeightProportion); 1729 glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryHeightProportion)); 1730 1731 if (!quickReject(left, top, right, bottom)) { 1732 AAVertex::set(aaVertices++, left, bottom, 1, 1); 1733 AAVertex::set(aaVertices++, left, top, 1, 0); 1734 AAVertex::set(aaVertices++, right, bottom, 0, 1); 1735 AAVertex::set(aaVertices++, right, top, 0, 0); 1736 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1737 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); 1738 } 1739} 1740 1741/** 1742 * We draw lines as quads (tristrips). Using GL_LINES can be difficult because the rasterization 1743 * rules for those lines produces some unexpected results, and may vary between hardware devices. 1744 * The basics of lines-as-quads is easy; we simply find the normal to the line and position the 1745 * corners of the quads on either side of each line endpoint, separated by the strokeWidth 1746 * of the line. Hairlines are more involved because we need to account for transform scaling 1747 * to end up with a one-pixel-wide line in screen space.. 1748 * Anti-aliased lines add another factor to the approach. We use a specialized fragment shader 1749 * in combination with values that we calculate and pass down in this method. The basic approach 1750 * is that the quad we create contains both the core line area plus a bounding area in which 1751 * the translucent/AA pixels are drawn. The values we calculate tell the shader what 1752 * proportion of the width and the length of a given segment is represented by the boundary 1753 * region. The quad ends up being exactly .5 pixel larger in all directions than the non-AA quad. 1754 * The bounding region is actually 1 pixel wide on all sides (half pixel on the outside, half pixel 1755 * on the inside). This ends up giving the result we want, with pixels that are completely 1756 * 'inside' the line area being filled opaquely and the other pixels being filled according to 1757 * how far into the boundary region they are, which is determined by shader interpolation. 1758 */ 1759void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) { 1760 if (mSnapshot->isIgnored()) return; 1761 1762 const bool isAA = paint->isAntiAlias(); 1763 // We use half the stroke width here because we're going to position the quad 1764 // corner vertices half of the width away from the line endpoints 1765 float halfStrokeWidth = paint->getStrokeWidth() * 0.5f; 1766 // A stroke width of 0 has a special meaning in Skia: 1767 // it draws a line 1 px wide regardless of current transform 1768 bool isHairLine = paint->getStrokeWidth() == 0.0f; 1769 float inverseScaleX = 1.0f; 1770 float inverseScaleY = 1.0f; 1771 bool scaled = false; 1772 int alpha; 1773 SkXfermode::Mode mode; 1774 int generatedVerticesCount = 0; 1775 int verticesCount = count; 1776 if (count > 4) { 1777 // Polyline: account for extra vertices needed for continuous tri-strip 1778 verticesCount += (count - 4); 1779 } 1780 1781 if (isHairLine || isAA) { 1782 // The quad that we use for AA and hairlines needs to account for scaling. For hairlines 1783 // the line on the screen should always be one pixel wide regardless of scale. For 1784 // AA lines, we only want one pixel of translucent boundary around the quad. 1785 if (CC_UNLIKELY(!mSnapshot->transform->isPureTranslate())) { 1786 Matrix4 *mat = mSnapshot->transform; 1787 float m00 = mat->data[Matrix4::kScaleX]; 1788 float m01 = mat->data[Matrix4::kSkewY]; 1789 float m02 = mat->data[2]; 1790 float m10 = mat->data[Matrix4::kSkewX]; 1791 float m11 = mat->data[Matrix4::kScaleX]; 1792 float m12 = mat->data[6]; 1793 float scaleX = sqrtf(m00 * m00 + m01 * m01); 1794 float scaleY = sqrtf(m10 * m10 + m11 * m11); 1795 inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0; 1796 inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0; 1797 if (inverseScaleX != 1.0f || inverseScaleY != 1.0f) { 1798 scaled = true; 1799 } 1800 } 1801 } 1802 1803 getAlphaAndMode(paint, &alpha, &mode); 1804 setupDraw(); 1805 setupDrawNoTexture(); 1806 if (isAA) { 1807 setupDrawAALine(); 1808 } 1809 setupDrawColor(paint->getColor(), alpha); 1810 setupDrawColorFilter(); 1811 setupDrawShader(); 1812 setupDrawBlending(isAA, mode); 1813 setupDrawProgram(); 1814 setupDrawModelViewIdentity(true); 1815 setupDrawColorUniforms(); 1816 setupDrawColorFilterUniforms(); 1817 setupDrawShaderIdentityUniforms(); 1818 1819 if (isHairLine) { 1820 // Set a real stroke width to be used in quad construction 1821 halfStrokeWidth = isAA? 1 : .5; 1822 } else if (isAA && !scaled) { 1823 // Expand boundary to enable AA calculations on the quad border 1824 halfStrokeWidth += .5f; 1825 } 1826 Vertex lines[verticesCount]; 1827 Vertex* vertices = &lines[0]; 1828 AAVertex wLines[verticesCount]; 1829 AAVertex* aaVertices = &wLines[0]; 1830 if (CC_UNLIKELY(!isAA)) { 1831 setupDrawVertices(vertices); 1832 } else { 1833 void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset; 1834 void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset; 1835 // innerProportion is the ratio of the inner (non-AA) part of the line to the total 1836 // AA stroke width (the base stroke width expanded by a half pixel on either side). 1837 // This value is used in the fragment shader to determine how to fill fragments. 1838 // We will need to calculate the actual width proportion on each segment for 1839 // scaled non-hairlines, since the boundary proportion may differ per-axis when scaled. 1840 float boundaryWidthProportion = 1 / (2 * halfStrokeWidth); 1841 setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion); 1842 } 1843 1844 AAVertex* prevAAVertex = NULL; 1845 Vertex* prevVertex = NULL; 1846 1847 int boundaryLengthSlot = -1; 1848 int inverseBoundaryLengthSlot = -1; 1849 int boundaryWidthSlot = -1; 1850 int inverseBoundaryWidthSlot = -1; 1851 for (int i = 0; i < count; i += 4) { 1852 // a = start point, b = end point 1853 vec2 a(points[i], points[i + 1]); 1854 vec2 b(points[i + 2], points[i + 3]); 1855 float length = 0; 1856 float boundaryLengthProportion = 0; 1857 float boundaryWidthProportion = 0; 1858 1859 // Find the normal to the line 1860 vec2 n = (b - a).copyNormalized() * halfStrokeWidth; 1861 if (isHairLine) { 1862 if (isAA) { 1863 float wideningFactor; 1864 if (fabs(n.x) >= fabs(n.y)) { 1865 wideningFactor = fabs(1.0f / n.x); 1866 } else { 1867 wideningFactor = fabs(1.0f / n.y); 1868 } 1869 n *= wideningFactor; 1870 } 1871 if (scaled) { 1872 n.x *= inverseScaleX; 1873 n.y *= inverseScaleY; 1874 } 1875 } else if (scaled) { 1876 // Extend n by .5 pixel on each side, post-transform 1877 vec2 extendedN = n.copyNormalized(); 1878 extendedN /= 2; 1879 extendedN.x *= inverseScaleX; 1880 extendedN.y *= inverseScaleY; 1881 float extendedNLength = extendedN.length(); 1882 // We need to set this value on the shader prior to drawing 1883 boundaryWidthProportion = extendedNLength / (halfStrokeWidth + extendedNLength); 1884 n += extendedN; 1885 } 1886 float x = n.x; 1887 n.x = -n.y; 1888 n.y = x; 1889 1890 // aa lines expand the endpoint vertices to encompass the AA boundary 1891 if (isAA) { 1892 vec2 abVector = (b - a); 1893 length = abVector.length(); 1894 abVector.normalize(); 1895 if (scaled) { 1896 abVector.x *= inverseScaleX; 1897 abVector.y *= inverseScaleY; 1898 float abLength = abVector.length(); 1899 boundaryLengthProportion = abLength / (length + abLength); 1900 } else { 1901 boundaryLengthProportion = .5 / (length + 1); 1902 } 1903 abVector /= 2; 1904 a -= abVector; 1905 b += abVector; 1906 } 1907 1908 // Four corners of the rectangle defining a thick line 1909 vec2 p1 = a - n; 1910 vec2 p2 = a + n; 1911 vec2 p3 = b + n; 1912 vec2 p4 = b - n; 1913 1914 1915 const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x))); 1916 const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x))); 1917 const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y))); 1918 const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y))); 1919 1920 if (!quickReject(left, top, right, bottom)) { 1921 if (!isAA) { 1922 if (prevVertex != NULL) { 1923 // Issue two repeat vertices to create degenerate triangles to bridge 1924 // between the previous line and the new one. This is necessary because 1925 // we are creating a single triangle_strip which will contain 1926 // potentially discontinuous line segments. 1927 Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]); 1928 Vertex::set(vertices++, p1.x, p1.y); 1929 generatedVerticesCount += 2; 1930 } 1931 Vertex::set(vertices++, p1.x, p1.y); 1932 Vertex::set(vertices++, p2.x, p2.y); 1933 Vertex::set(vertices++, p4.x, p4.y); 1934 Vertex::set(vertices++, p3.x, p3.y); 1935 prevVertex = vertices - 1; 1936 generatedVerticesCount += 4; 1937 } else { 1938 if (!isHairLine && scaled) { 1939 // Must set width proportions per-segment for scaled non-hairlines to use the 1940 // correct AA boundary dimensions 1941 if (boundaryWidthSlot < 0) { 1942 boundaryWidthSlot = 1943 mCaches.currentProgram->getUniform("boundaryWidth"); 1944 inverseBoundaryWidthSlot = 1945 mCaches.currentProgram->getUniform("inverseBoundaryWidth"); 1946 } 1947 glUniform1f(boundaryWidthSlot, boundaryWidthProportion); 1948 glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion)); 1949 } 1950 if (boundaryLengthSlot < 0) { 1951 boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength"); 1952 inverseBoundaryLengthSlot = 1953 mCaches.currentProgram->getUniform("inverseBoundaryLength"); 1954 } 1955 glUniform1f(boundaryLengthSlot, boundaryLengthProportion); 1956 glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryLengthProportion)); 1957 1958 if (prevAAVertex != NULL) { 1959 // Issue two repeat vertices to create degenerate triangles to bridge 1960 // between the previous line and the new one. This is necessary because 1961 // we are creating a single triangle_strip which will contain 1962 // potentially discontinuous line segments. 1963 AAVertex::set(aaVertices++,prevAAVertex->position[0], 1964 prevAAVertex->position[1], prevAAVertex->width, prevAAVertex->length); 1965 AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1); 1966 generatedVerticesCount += 2; 1967 } 1968 AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1); 1969 AAVertex::set(aaVertices++, p1.x, p1.y, 1, 0); 1970 AAVertex::set(aaVertices++, p3.x, p3.y, 0, 1); 1971 AAVertex::set(aaVertices++, p2.x, p2.y, 0, 0); 1972 prevAAVertex = aaVertices - 1; 1973 generatedVerticesCount += 4; 1974 } 1975 dirtyLayer(a.x == b.x ? left - 1 : left, a.y == b.y ? top - 1 : top, 1976 a.x == b.x ? right: right, a.y == b.y ? bottom: bottom, 1977 *mSnapshot->transform); 1978 } 1979 } 1980 if (generatedVerticesCount > 0) { 1981 glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount); 1982 } 1983} 1984 1985void OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) { 1986 if (mSnapshot->isIgnored()) return; 1987 1988 // TODO: The paint's cap style defines whether the points are square or circular 1989 // TODO: Handle AA for round points 1990 1991 // A stroke width of 0 has a special meaning in Skia: 1992 // it draws an unscaled 1px point 1993 float strokeWidth = paint->getStrokeWidth(); 1994 const bool isHairLine = paint->getStrokeWidth() == 0.0f; 1995 if (isHairLine) { 1996 // Now that we know it's hairline, we can set the effective width, to be used later 1997 strokeWidth = 1.0f; 1998 } 1999 const float halfWidth = strokeWidth / 2; 2000 int alpha; 2001 SkXfermode::Mode mode; 2002 getAlphaAndMode(paint, &alpha, &mode); 2003 2004 int verticesCount = count >> 1; 2005 int generatedVerticesCount = 0; 2006 2007 TextureVertex pointsData[verticesCount]; 2008 TextureVertex* vertex = &pointsData[0]; 2009 2010 setupDraw(); 2011 setupDrawNoTexture(); 2012 setupDrawPoint(strokeWidth); 2013 setupDrawColor(paint->getColor(), alpha); 2014 setupDrawColorFilter(); 2015 setupDrawShader(); 2016 setupDrawBlending(mode); 2017 setupDrawProgram(); 2018 setupDrawModelViewIdentity(true); 2019 setupDrawColorUniforms(); 2020 setupDrawColorFilterUniforms(); 2021 setupDrawPointUniforms(); 2022 setupDrawShaderIdentityUniforms(); 2023 setupDrawMesh(vertex); 2024 2025 for (int i = 0; i < count; i += 2) { 2026 TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f); 2027 generatedVerticesCount++; 2028 float left = points[i] - halfWidth; 2029 float right = points[i] + halfWidth; 2030 float top = points[i + 1] - halfWidth; 2031 float bottom = points [i + 1] + halfWidth; 2032 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 2033 } 2034 2035 glDrawArrays(GL_POINTS, 0, generatedVerticesCount); 2036} 2037 2038void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 2039 // No need to check against the clip, we fill the clip region 2040 if (mSnapshot->isIgnored()) return; 2041 2042 Rect& clip(*mSnapshot->clipRect); 2043 clip.snapToPixelBoundaries(); 2044 2045 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true); 2046} 2047 2048void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) { 2049 if (!texture) return; 2050 const AutoTexture autoCleanup(texture); 2051 2052 const float x = left + texture->left - texture->offset; 2053 const float y = top + texture->top - texture->offset; 2054 2055 drawPathTexture(texture, x, y, paint); 2056} 2057 2058void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom, 2059 float rx, float ry, SkPaint* paint) { 2060 if (mSnapshot->isIgnored()) return; 2061 2062 mCaches.activeTexture(0); 2063 const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect( 2064 right - left, bottom - top, rx, ry, paint); 2065 drawShape(left, top, texture, paint); 2066} 2067 2068void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) { 2069 if (mSnapshot->isIgnored()) return; 2070 2071 mCaches.activeTexture(0); 2072 const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint); 2073 drawShape(x - radius, y - radius, texture, paint); 2074} 2075 2076void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) { 2077 if (mSnapshot->isIgnored()) return; 2078 2079 mCaches.activeTexture(0); 2080 const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint); 2081 drawShape(left, top, texture, paint); 2082} 2083 2084void OpenGLRenderer::drawArc(float left, float top, float right, float bottom, 2085 float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) { 2086 if (mSnapshot->isIgnored()) return; 2087 2088 if (fabs(sweepAngle) >= 360.0f) { 2089 drawOval(left, top, right, bottom, paint); 2090 return; 2091 } 2092 2093 mCaches.activeTexture(0); 2094 const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top, 2095 startAngle, sweepAngle, useCenter, paint); 2096 drawShape(left, top, texture, paint); 2097} 2098 2099void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom, 2100 SkPaint* paint) { 2101 if (mSnapshot->isIgnored()) return; 2102 2103 mCaches.activeTexture(0); 2104 const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint); 2105 drawShape(left, top, texture, paint); 2106} 2107 2108void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) { 2109 if (p->getStyle() != SkPaint::kFill_Style) { 2110 drawRectAsShape(left, top, right, bottom, p); 2111 return; 2112 } 2113 2114 if (quickReject(left, top, right, bottom)) { 2115 return; 2116 } 2117 2118 SkXfermode::Mode mode; 2119 if (!mCaches.extensions.hasFramebufferFetch()) { 2120 const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode); 2121 if (!isMode) { 2122 // Assume SRC_OVER 2123 mode = SkXfermode::kSrcOver_Mode; 2124 } 2125 } else { 2126 mode = getXfermode(p->getXfermode()); 2127 } 2128 2129 int color = p->getColor(); 2130 if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) { 2131 drawAARect(left, top, right, bottom, color, mode); 2132 } else { 2133 drawColorRect(left, top, right, bottom, color, mode); 2134 } 2135} 2136 2137void OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count, 2138 const float* positions, SkPaint* paint) { 2139 if (text == NULL || count == 0 || mSnapshot->isIgnored() || 2140 (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) { 2141 return; 2142 } 2143 2144 // NOTE: Skia does not support perspective transform on drawPosText yet 2145 if (!mSnapshot->transform->isSimple()) { 2146 return; 2147 } 2148 2149 float x = 0.0f; 2150 float y = 0.0f; 2151 const bool pureTranslate = mSnapshot->transform->isPureTranslate(); 2152 if (pureTranslate) { 2153 x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f); 2154 y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f); 2155 } 2156 2157 FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint); 2158 fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), 2159 paint->getTextSize()); 2160 2161 int alpha; 2162 SkXfermode::Mode mode; 2163 getAlphaAndMode(paint, &alpha, &mode); 2164 2165 // Pick the appropriate texture filtering 2166 bool linearFilter = mSnapshot->transform->changesBounds(); 2167 if (pureTranslate && !linearFilter) { 2168 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2169 } 2170 2171 mCaches.activeTexture(0); 2172 setupDraw(); 2173 setupDrawDirtyRegionsDisabled(); 2174 setupDrawWithTexture(true); 2175 setupDrawAlpha8Color(paint->getColor(), alpha); 2176 setupDrawColorFilter(); 2177 setupDrawShader(); 2178 setupDrawBlending(true, mode); 2179 setupDrawProgram(); 2180 setupDrawModelView(x, y, x, y, pureTranslate, true); 2181 setupDrawTexture(fontRenderer.getTexture(linearFilter)); 2182 setupDrawPureColorUniforms(); 2183 setupDrawColorFilterUniforms(); 2184 setupDrawShaderUniforms(pureTranslate); 2185 2186 const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip(); 2187 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2188 2189#if RENDER_LAYERS_AS_REGIONS 2190 const bool hasActiveLayer = hasLayer(); 2191#else 2192 const bool hasActiveLayer = false; 2193#endif 2194 2195 if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y, 2196 positions, hasActiveLayer ? &bounds : NULL)) { 2197#if RENDER_LAYERS_AS_REGIONS 2198 if (hasActiveLayer) { 2199 if (!pureTranslate) { 2200 mSnapshot->transform->mapRect(bounds); 2201 } 2202 dirtyLayerUnchecked(bounds, getRegion()); 2203 } 2204#endif 2205 } 2206} 2207 2208void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, 2209 float x, float y, SkPaint* paint, float length) { 2210 if (text == NULL || count == 0 || mSnapshot->isIgnored() || 2211 (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) { 2212 return; 2213 } 2214 2215 if (length < 0.0f) length = paint->measureText(text, bytesCount); 2216 switch (paint->getTextAlign()) { 2217 case SkPaint::kCenter_Align: 2218 x -= length / 2.0f; 2219 break; 2220 case SkPaint::kRight_Align: 2221 x -= length; 2222 break; 2223 default: 2224 break; 2225 } 2226 2227 SkPaint::FontMetrics metrics; 2228 paint->getFontMetrics(&metrics, 0.0f); 2229 if (quickReject(x, y + metrics.fTop, x + length, y + metrics.fBottom)) { 2230 return; 2231 } 2232 2233 const float oldX = x; 2234 const float oldY = y; 2235 const bool pureTranslate = mSnapshot->transform->isPureTranslate(); 2236 if (CC_LIKELY(pureTranslate)) { 2237 x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f); 2238 y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f); 2239 } 2240 2241#if DEBUG_GLYPHS 2242 ALOGD("OpenGLRenderer drawText() with FontID=%d", SkTypeface::UniqueID(paint->getTypeface())); 2243#endif 2244 2245 FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint); 2246 fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), 2247 paint->getTextSize()); 2248 2249 int alpha; 2250 SkXfermode::Mode mode; 2251 getAlphaAndMode(paint, &alpha, &mode); 2252 2253 if (CC_UNLIKELY(mHasShadow)) { 2254 mCaches.activeTexture(0); 2255 2256 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 2257 const ShadowTexture* shadow = mCaches.dropShadowCache.get( 2258 paint, text, bytesCount, count, mShadowRadius); 2259 const AutoTexture autoCleanup(shadow); 2260 2261 const float sx = oldX - shadow->left + mShadowDx; 2262 const float sy = oldY - shadow->top + mShadowDy; 2263 2264 const int shadowAlpha = ((mShadowColor >> 24) & 0xFF); 2265 int shadowColor = mShadowColor; 2266 if (mShader) { 2267 shadowColor = 0xffffffff; 2268 } 2269 2270 setupDraw(); 2271 setupDrawWithTexture(true); 2272 setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha); 2273 setupDrawColorFilter(); 2274 setupDrawShader(); 2275 setupDrawBlending(true, mode); 2276 setupDrawProgram(); 2277 setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height); 2278 setupDrawTexture(shadow->id); 2279 setupDrawPureColorUniforms(); 2280 setupDrawColorFilterUniforms(); 2281 setupDrawShaderUniforms(); 2282 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 2283 2284 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 2285 } 2286 2287 // Pick the appropriate texture filtering 2288 bool linearFilter = mSnapshot->transform->changesBounds(); 2289 if (pureTranslate && !linearFilter) { 2290 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2291 } 2292 2293 mCaches.activeTexture(0); 2294 setupDraw(); 2295 setupDrawDirtyRegionsDisabled(); 2296 setupDrawWithTexture(true); 2297 setupDrawAlpha8Color(paint->getColor(), alpha); 2298 setupDrawColorFilter(); 2299 setupDrawShader(); 2300 setupDrawBlending(true, mode); 2301 setupDrawProgram(); 2302 setupDrawModelView(x, y, x, y, pureTranslate, true); 2303 setupDrawTexture(fontRenderer.getTexture(linearFilter)); 2304 setupDrawPureColorUniforms(); 2305 setupDrawColorFilterUniforms(); 2306 setupDrawShaderUniforms(pureTranslate); 2307 2308 const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip(); 2309 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2310 2311#if RENDER_LAYERS_AS_REGIONS 2312 const bool hasActiveLayer = hasLayer(); 2313#else 2314 const bool hasActiveLayer = false; 2315#endif 2316 2317 if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y, 2318 hasActiveLayer ? &bounds : NULL)) { 2319#if RENDER_LAYERS_AS_REGIONS 2320 if (hasActiveLayer) { 2321 if (!pureTranslate) { 2322 mSnapshot->transform->mapRect(bounds); 2323 } 2324 dirtyLayerUnchecked(bounds, getRegion()); 2325 } 2326#endif 2327 } 2328 2329 drawTextDecorations(text, bytesCount, length, oldX, oldY, paint); 2330} 2331 2332void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, SkPath* path, 2333 float hOffset, float vOffset, SkPaint* paint) { 2334 if (text == NULL || count == 0 || mSnapshot->isIgnored() || 2335 (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) { 2336 return; 2337 } 2338 2339 FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint); 2340 fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), 2341 paint->getTextSize()); 2342 2343 int alpha; 2344 SkXfermode::Mode mode; 2345 getAlphaAndMode(paint, &alpha, &mode); 2346 2347 mCaches.activeTexture(0); 2348 setupDraw(); 2349 setupDrawDirtyRegionsDisabled(); 2350 setupDrawWithTexture(true); 2351 setupDrawAlpha8Color(paint->getColor(), alpha); 2352 setupDrawColorFilter(); 2353 setupDrawShader(); 2354 setupDrawBlending(true, mode); 2355 setupDrawProgram(); 2356 setupDrawModelView(0.0f, 0.0f, 0.0f, 0.0f, false, true); 2357 setupDrawTexture(fontRenderer.getTexture(true)); 2358 setupDrawPureColorUniforms(); 2359 setupDrawColorFilterUniforms(); 2360 setupDrawShaderUniforms(false); 2361 2362 const Rect* clip = &mSnapshot->getLocalClip(); 2363 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2364 2365#if RENDER_LAYERS_AS_REGIONS 2366 const bool hasActiveLayer = hasLayer(); 2367#else 2368 const bool hasActiveLayer = false; 2369#endif 2370 2371 if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path, 2372 hOffset, vOffset, hasActiveLayer ? &bounds : NULL)) { 2373#if RENDER_LAYERS_AS_REGIONS 2374 if (hasActiveLayer) { 2375 mSnapshot->transform->mapRect(bounds); 2376 dirtyLayerUnchecked(bounds, getRegion()); 2377 } 2378#endif 2379 } 2380} 2381 2382void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) { 2383 if (mSnapshot->isIgnored()) return; 2384 2385 mCaches.activeTexture(0); 2386 2387 // TODO: Perform early clip test before we rasterize the path 2388 const PathTexture* texture = mCaches.pathCache.get(path, paint); 2389 if (!texture) return; 2390 const AutoTexture autoCleanup(texture); 2391 2392 const float x = texture->left - texture->offset; 2393 const float y = texture->top - texture->offset; 2394 2395 drawPathTexture(texture, x, y, paint); 2396} 2397 2398void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) { 2399 if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) { 2400 return; 2401 } 2402 2403 if (layer->deferredUpdateScheduled && layer->renderer && layer->displayList) { 2404 OpenGLRenderer* renderer = layer->renderer; 2405 Rect& dirty = layer->dirtyRect; 2406 2407 interrupt(); 2408 renderer->setViewport(layer->layer.getWidth(), layer->layer.getHeight()); 2409 renderer->prepareDirty(dirty.left, dirty.top, dirty.right, dirty.bottom, !layer->isBlend()); 2410 renderer->drawDisplayList(layer->displayList, layer->getWidth(), layer->getHeight(), 2411 dirty, DisplayList::kReplayFlag_ClipChildren); 2412 renderer->finish(); 2413 resume(); 2414 2415 dirty.setEmpty(); 2416 layer->deferredUpdateScheduled = false; 2417 layer->renderer = NULL; 2418 layer->displayList = NULL; 2419 } 2420 2421 mCaches.activeTexture(0); 2422 2423 int alpha; 2424 SkXfermode::Mode mode; 2425 getAlphaAndMode(paint, &alpha, &mode); 2426 2427 layer->setAlpha(alpha, mode); 2428 2429#if RENDER_LAYERS_AS_REGIONS 2430 if (CC_LIKELY(!layer->region.isEmpty())) { 2431 if (layer->region.isRect()) { 2432 composeLayerRect(layer, layer->regionRect); 2433 } else if (layer->mesh) { 2434 const float a = alpha / 255.0f; 2435 const Rect& rect = layer->layer; 2436 2437 setupDraw(); 2438 setupDrawWithTexture(); 2439 setupDrawColor(a, a, a, a); 2440 setupDrawColorFilter(); 2441 setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false); 2442 setupDrawProgram(); 2443 setupDrawPureColorUniforms(); 2444 setupDrawColorFilterUniforms(); 2445 setupDrawTexture(layer->getTexture()); 2446 if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) { 2447 x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f); 2448 y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f); 2449 2450 layer->setFilter(GL_NEAREST); 2451 setupDrawModelViewTranslate(x, y, 2452 x + layer->layer.getWidth(), y + layer->layer.getHeight(), true); 2453 } else { 2454 layer->setFilter(GL_LINEAR); 2455 setupDrawModelViewTranslate(x, y, 2456 x + layer->layer.getWidth(), y + layer->layer.getHeight()); 2457 } 2458 setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]); 2459 2460 glDrawElements(GL_TRIANGLES, layer->meshElementCount, 2461 GL_UNSIGNED_SHORT, layer->meshIndices); 2462 2463 finishDrawTexture(); 2464 2465#if DEBUG_LAYERS_AS_REGIONS 2466 drawRegionRects(layer->region); 2467#endif 2468 } 2469 } 2470#else 2471 const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight()); 2472 composeLayerRect(layer, r); 2473#endif 2474} 2475 2476/////////////////////////////////////////////////////////////////////////////// 2477// Shaders 2478/////////////////////////////////////////////////////////////////////////////// 2479 2480void OpenGLRenderer::resetShader() { 2481 mShader = NULL; 2482} 2483 2484void OpenGLRenderer::setupShader(SkiaShader* shader) { 2485 mShader = shader; 2486 if (mShader) { 2487 mShader->set(&mCaches.textureCache, &mCaches.gradientCache); 2488 } 2489} 2490 2491/////////////////////////////////////////////////////////////////////////////// 2492// Color filters 2493/////////////////////////////////////////////////////////////////////////////// 2494 2495void OpenGLRenderer::resetColorFilter() { 2496 mColorFilter = NULL; 2497} 2498 2499void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) { 2500 mColorFilter = filter; 2501} 2502 2503/////////////////////////////////////////////////////////////////////////////// 2504// Drop shadow 2505/////////////////////////////////////////////////////////////////////////////// 2506 2507void OpenGLRenderer::resetShadow() { 2508 mHasShadow = false; 2509} 2510 2511void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) { 2512 mHasShadow = true; 2513 mShadowRadius = radius; 2514 mShadowDx = dx; 2515 mShadowDy = dy; 2516 mShadowColor = color; 2517} 2518 2519/////////////////////////////////////////////////////////////////////////////// 2520// Draw filters 2521/////////////////////////////////////////////////////////////////////////////// 2522 2523void OpenGLRenderer::resetPaintFilter() { 2524 mHasDrawFilter = false; 2525} 2526 2527void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) { 2528 mHasDrawFilter = true; 2529 mPaintFilterClearBits = clearBits & SkPaint::kAllFlags; 2530 mPaintFilterSetBits = setBits & SkPaint::kAllFlags; 2531} 2532 2533SkPaint* OpenGLRenderer::filterPaint(SkPaint* paint) { 2534 if (CC_LIKELY(!mHasDrawFilter || !paint)) return paint; 2535 2536 uint32_t flags = paint->getFlags(); 2537 2538 mFilteredPaint = *paint; 2539 mFilteredPaint.setFlags((flags & ~mPaintFilterClearBits) | mPaintFilterSetBits); 2540 2541 return &mFilteredPaint; 2542} 2543 2544/////////////////////////////////////////////////////////////////////////////// 2545// Drawing implementation 2546/////////////////////////////////////////////////////////////////////////////// 2547 2548void OpenGLRenderer::drawPathTexture(const PathTexture* texture, 2549 float x, float y, SkPaint* paint) { 2550 if (quickReject(x, y, x + texture->width, y + texture->height)) { 2551 return; 2552 } 2553 2554 int alpha; 2555 SkXfermode::Mode mode; 2556 getAlphaAndMode(paint, &alpha, &mode); 2557 2558 setupDraw(); 2559 setupDrawWithTexture(true); 2560 setupDrawAlpha8Color(paint->getColor(), alpha); 2561 setupDrawColorFilter(); 2562 setupDrawShader(); 2563 setupDrawBlending(true, mode); 2564 setupDrawProgram(); 2565 setupDrawModelView(x, y, x + texture->width, y + texture->height); 2566 setupDrawTexture(texture->id); 2567 setupDrawPureColorUniforms(); 2568 setupDrawColorFilterUniforms(); 2569 setupDrawShaderUniforms(); 2570 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 2571 2572 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 2573 2574 finishDrawTexture(); 2575} 2576 2577// Same values used by Skia 2578#define kStdStrikeThru_Offset (-6.0f / 21.0f) 2579#define kStdUnderline_Offset (1.0f / 9.0f) 2580#define kStdUnderline_Thickness (1.0f / 18.0f) 2581 2582void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length, 2583 float x, float y, SkPaint* paint) { 2584 // Handle underline and strike-through 2585 uint32_t flags = paint->getFlags(); 2586 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) { 2587 SkPaint paintCopy(*paint); 2588 float underlineWidth = length; 2589 // If length is > 0.0f, we already measured the text for the text alignment 2590 if (length <= 0.0f) { 2591 underlineWidth = paintCopy.measureText(text, bytesCount); 2592 } 2593 2594 float offsetX = 0; 2595 switch (paintCopy.getTextAlign()) { 2596 case SkPaint::kCenter_Align: 2597 offsetX = underlineWidth * 0.5f; 2598 break; 2599 case SkPaint::kRight_Align: 2600 offsetX = underlineWidth; 2601 break; 2602 default: 2603 break; 2604 } 2605 2606 if (CC_LIKELY(underlineWidth > 0.0f)) { 2607 const float textSize = paintCopy.getTextSize(); 2608 const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f); 2609 2610 const float left = x - offsetX; 2611 float top = 0.0f; 2612 2613 int linesCount = 0; 2614 if (flags & SkPaint::kUnderlineText_Flag) linesCount++; 2615 if (flags & SkPaint::kStrikeThruText_Flag) linesCount++; 2616 2617 const int pointsCount = 4 * linesCount; 2618 float points[pointsCount]; 2619 int currentPoint = 0; 2620 2621 if (flags & SkPaint::kUnderlineText_Flag) { 2622 top = y + textSize * kStdUnderline_Offset; 2623 points[currentPoint++] = left; 2624 points[currentPoint++] = top; 2625 points[currentPoint++] = left + underlineWidth; 2626 points[currentPoint++] = top; 2627 } 2628 2629 if (flags & SkPaint::kStrikeThruText_Flag) { 2630 top = y + textSize * kStdStrikeThru_Offset; 2631 points[currentPoint++] = left; 2632 points[currentPoint++] = top; 2633 points[currentPoint++] = left + underlineWidth; 2634 points[currentPoint++] = top; 2635 } 2636 2637 paintCopy.setStrokeWidth(strokeWidth); 2638 2639 drawLines(&points[0], pointsCount, &paintCopy); 2640 } 2641 } 2642} 2643 2644void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 2645 int color, SkXfermode::Mode mode, bool ignoreTransform) { 2646 // If a shader is set, preserve only the alpha 2647 if (mShader) { 2648 color |= 0x00ffffff; 2649 } 2650 2651 setupDraw(); 2652 setupDrawNoTexture(); 2653 setupDrawColor(color); 2654 setupDrawShader(); 2655 setupDrawColorFilter(); 2656 setupDrawBlending(mode); 2657 setupDrawProgram(); 2658 setupDrawModelView(left, top, right, bottom, ignoreTransform); 2659 setupDrawColorUniforms(); 2660 setupDrawShaderUniforms(ignoreTransform); 2661 setupDrawColorFilterUniforms(); 2662 setupDrawSimpleMesh(); 2663 2664 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 2665} 2666 2667void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 2668 Texture* texture, SkPaint* paint) { 2669 int alpha; 2670 SkXfermode::Mode mode; 2671 getAlphaAndMode(paint, &alpha, &mode); 2672 2673 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2674 2675 if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) { 2676 const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f); 2677 const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f); 2678 2679 texture->setFilter(GL_NEAREST, true); 2680 drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 2681 alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL, 2682 (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true); 2683 } else { 2684 texture->setFilter(FILTER(paint), true); 2685 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, 2686 texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, 2687 GL_TRIANGLE_STRIP, gMeshCount); 2688 } 2689} 2690 2691void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 2692 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) { 2693 drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend, 2694 (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount); 2695} 2696 2697void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom, 2698 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend, 2699 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 2700 bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) { 2701 2702 setupDraw(); 2703 setupDrawWithTexture(); 2704 setupDrawColor(alpha, alpha, alpha, alpha); 2705 setupDrawColorFilter(); 2706 setupDrawBlending(blend, mode, swapSrcDst); 2707 setupDrawProgram(); 2708 if (!dirty) { 2709 setupDrawDirtyRegionsDisabled(); 2710 } 2711 if (!ignoreScale) { 2712 setupDrawModelView(left, top, right, bottom, ignoreTransform); 2713 } else { 2714 setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform); 2715 } 2716 setupDrawPureColorUniforms(); 2717 setupDrawColorFilterUniforms(); 2718 setupDrawTexture(texture); 2719 setupDrawMesh(vertices, texCoords, vbo); 2720 2721 glDrawArrays(drawMode, 0, elementsCount); 2722 2723 finishDrawTexture(); 2724} 2725 2726void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, 2727 ProgramDescription& description, bool swapSrcDst) { 2728 blend = blend || mode != SkXfermode::kSrcOver_Mode; 2729 if (blend) { 2730 // These blend modes are not supported by OpenGL directly and have 2731 // to be implemented using shaders. Since the shader will perform 2732 // the blending, turn blending off here 2733 // If the blend mode cannot be implemented using shaders, fall 2734 // back to the default SrcOver blend mode instead 2735 if CC_UNLIKELY((mode > SkXfermode::kScreen_Mode)) { 2736 if (CC_UNLIKELY(mCaches.extensions.hasFramebufferFetch())) { 2737 description.framebufferMode = mode; 2738 description.swapSrcDst = swapSrcDst; 2739 2740 if (mCaches.blend) { 2741 glDisable(GL_BLEND); 2742 mCaches.blend = false; 2743 } 2744 2745 return; 2746 } else { 2747 mode = SkXfermode::kSrcOver_Mode; 2748 } 2749 } 2750 2751 if (!mCaches.blend) { 2752 glEnable(GL_BLEND); 2753 } 2754 2755 GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src; 2756 GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst; 2757 2758 if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) { 2759 glBlendFunc(sourceMode, destMode); 2760 mCaches.lastSrcMode = sourceMode; 2761 mCaches.lastDstMode = destMode; 2762 } 2763 } else if (mCaches.blend) { 2764 glDisable(GL_BLEND); 2765 } 2766 mCaches.blend = blend; 2767} 2768 2769bool OpenGLRenderer::useProgram(Program* program) { 2770 if (!program->isInUse()) { 2771 if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove(); 2772 program->use(); 2773 mCaches.currentProgram = program; 2774 return false; 2775 } 2776 return true; 2777} 2778 2779void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) { 2780 TextureVertex* v = &mMeshVertices[0]; 2781 TextureVertex::setUV(v++, u1, v1); 2782 TextureVertex::setUV(v++, u2, v1); 2783 TextureVertex::setUV(v++, u1, v2); 2784 TextureVertex::setUV(v++, u2, v2); 2785} 2786 2787void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) { 2788 if (paint) { 2789 *mode = getXfermode(paint->getXfermode()); 2790 2791 // Skia draws using the color's alpha channel if < 255 2792 // Otherwise, it uses the paint's alpha 2793 int color = paint->getColor(); 2794 *alpha = (color >> 24) & 0xFF; 2795 if (*alpha == 255) { 2796 *alpha = paint->getAlpha(); 2797 } 2798 } else { 2799 *mode = SkXfermode::kSrcOver_Mode; 2800 *alpha = 255; 2801 } 2802} 2803 2804SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) { 2805 SkXfermode::Mode resultMode; 2806 if (!SkXfermode::AsMode(mode, &resultMode)) { 2807 resultMode = SkXfermode::kSrcOver_Mode; 2808 } 2809 return resultMode; 2810} 2811 2812}; // namespace uirenderer 2813}; // namespace android 2814