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