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