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