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