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