SkGpuDevice.cpp revision a3264e53ee3f3c5d6a2c813df7e44b5b96d207f2
1/* 2 * Copyright 2011 Google Inc. 3 * 4 * Use of this source code is governed by a BSD-style license that can be 5 * found in the LICENSE file. 6 */ 7 8#include "SkGpuDevice.h" 9 10#include "effects/GrBicubicEffect.h" 11#include "effects/GrDashingEffect.h" 12#include "effects/GrTextureDomain.h" 13#include "effects/GrSimpleTextureEffect.h" 14 15#include "GrContext.h" 16#include "GrBitmapTextContext.h" 17#include "GrDistanceFieldTextContext.h" 18#include "GrLayerCache.h" 19#include "GrPictureUtils.h" 20 21#include "SkGrTexturePixelRef.h" 22 23#include "SkBounder.h" 24#include "SkDeviceImageFilterProxy.h" 25#include "SkDrawProcs.h" 26#include "SkGlyphCache.h" 27#include "SkImageFilter.h" 28#include "SkMaskFilter.h" 29#include "SkPathEffect.h" 30#include "SkPicture.h" 31#include "SkPicturePlayback.h" 32#include "SkRRect.h" 33#include "SkStroke.h" 34#include "SkSurface.h" 35#include "SkTLazy.h" 36#include "SkUtils.h" 37#include "SkVertState.h" 38#include "SkErrorInternals.h" 39 40#define CACHE_COMPATIBLE_DEVICE_TEXTURES 1 41 42#if 0 43 extern bool (*gShouldDrawProc)(); 44 #define CHECK_SHOULD_DRAW(draw, forceI) \ 45 do { \ 46 if (gShouldDrawProc && !gShouldDrawProc()) return; \ 47 this->prepareDraw(draw, forceI); \ 48 } while (0) 49#else 50 #define CHECK_SHOULD_DRAW(draw, forceI) this->prepareDraw(draw, forceI) 51#endif 52 53// This constant represents the screen alignment criterion in texels for 54// requiring texture domain clamping to prevent color bleeding when drawing 55// a sub region of a larger source image. 56#define COLOR_BLEED_TOLERANCE 0.001f 57 58#define DO_DEFERRED_CLEAR() \ 59 do { \ 60 if (fNeedClear) { \ 61 this->clear(SK_ColorTRANSPARENT); \ 62 } \ 63 } while (false) \ 64 65/////////////////////////////////////////////////////////////////////////////// 66 67#define CHECK_FOR_ANNOTATION(paint) \ 68 do { if (paint.getAnnotation()) { return; } } while (0) 69 70/////////////////////////////////////////////////////////////////////////////// 71 72 73class SkGpuDevice::SkAutoCachedTexture : public ::SkNoncopyable { 74public: 75 SkAutoCachedTexture() 76 : fDevice(NULL) 77 , fTexture(NULL) { 78 } 79 80 SkAutoCachedTexture(SkGpuDevice* device, 81 const SkBitmap& bitmap, 82 const GrTextureParams* params, 83 GrTexture** texture) 84 : fDevice(NULL) 85 , fTexture(NULL) { 86 SkASSERT(NULL != texture); 87 *texture = this->set(device, bitmap, params); 88 } 89 90 ~SkAutoCachedTexture() { 91 if (NULL != fTexture) { 92 GrUnlockAndUnrefCachedBitmapTexture(fTexture); 93 } 94 } 95 96 GrTexture* set(SkGpuDevice* device, 97 const SkBitmap& bitmap, 98 const GrTextureParams* params) { 99 if (NULL != fTexture) { 100 GrUnlockAndUnrefCachedBitmapTexture(fTexture); 101 fTexture = NULL; 102 } 103 fDevice = device; 104 GrTexture* result = (GrTexture*)bitmap.getTexture(); 105 if (NULL == result) { 106 // Cannot return the native texture so look it up in our cache 107 fTexture = GrLockAndRefCachedBitmapTexture(device->context(), bitmap, params); 108 result = fTexture; 109 } 110 return result; 111 } 112 113private: 114 SkGpuDevice* fDevice; 115 GrTexture* fTexture; 116}; 117 118/////////////////////////////////////////////////////////////////////////////// 119 120struct GrSkDrawProcs : public SkDrawProcs { 121public: 122 GrContext* fContext; 123 GrTextContext* fTextContext; 124 GrFontScaler* fFontScaler; // cached in the skia glyphcache 125}; 126 127/////////////////////////////////////////////////////////////////////////////// 128 129static SkBitmap::Config grConfig2skConfig(GrPixelConfig config, bool* isOpaque) { 130 switch (config) { 131 case kAlpha_8_GrPixelConfig: 132 *isOpaque = false; 133 return SkBitmap::kA8_Config; 134 case kRGB_565_GrPixelConfig: 135 *isOpaque = true; 136 return SkBitmap::kRGB_565_Config; 137 case kRGBA_4444_GrPixelConfig: 138 *isOpaque = false; 139 return SkBitmap::kARGB_4444_Config; 140 case kSkia8888_GrPixelConfig: 141 // we don't currently have a way of knowing whether 142 // a 8888 is opaque based on the config. 143 *isOpaque = false; 144 return SkBitmap::kARGB_8888_Config; 145 default: 146 *isOpaque = false; 147 return SkBitmap::kNo_Config; 148 } 149} 150 151/* 152 * GrRenderTarget does not know its opaqueness, only its config, so we have 153 * to make conservative guesses when we return an "equivalent" bitmap. 154 */ 155static SkBitmap make_bitmap(GrContext* context, GrRenderTarget* renderTarget) { 156 bool isOpaque; 157 SkBitmap::Config config = grConfig2skConfig(renderTarget->config(), &isOpaque); 158 159 SkBitmap bitmap; 160 bitmap.setConfig(config, renderTarget->width(), renderTarget->height(), 0, 161 isOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType); 162 return bitmap; 163} 164 165SkGpuDevice* SkGpuDevice::Create(GrSurface* surface, unsigned flags) { 166 SkASSERT(NULL != surface); 167 if (NULL == surface->asRenderTarget() || NULL == surface->getContext()) { 168 return NULL; 169 } 170 if (surface->asTexture()) { 171 return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asTexture(), flags)); 172 } else { 173 return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asRenderTarget(), flags)); 174 } 175} 176 177SkGpuDevice::SkGpuDevice(GrContext* context, GrTexture* texture, unsigned flags) 178 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) { 179 this->initFromRenderTarget(context, texture->asRenderTarget(), flags); 180} 181 182SkGpuDevice::SkGpuDevice(GrContext* context, GrRenderTarget* renderTarget, unsigned flags) 183 : SkBitmapDevice(make_bitmap(context, renderTarget)) { 184 this->initFromRenderTarget(context, renderTarget, flags); 185} 186 187void SkGpuDevice::initFromRenderTarget(GrContext* context, 188 GrRenderTarget* renderTarget, 189 unsigned flags) { 190 fDrawProcs = NULL; 191 192 fContext = context; 193 fContext->ref(); 194 195 bool useDFFonts = !!(flags & kDFFonts_Flag); 196 fMainTextContext = SkNEW_ARGS(GrDistanceFieldTextContext, (fContext, fLeakyProperties, 197 useDFFonts)); 198 fFallbackTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties)); 199 200 fRenderTarget = NULL; 201 fNeedClear = flags & kNeedClear_Flag; 202 203 SkASSERT(NULL != renderTarget); 204 fRenderTarget = renderTarget; 205 fRenderTarget->ref(); 206 207 // Hold onto to the texture in the pixel ref (if there is one) because the texture holds a ref 208 // on the RT but not vice-versa. 209 // TODO: Remove this trickery once we figure out how to make SkGrPixelRef do this without 210 // busting chrome (for a currently unknown reason). 211 GrSurface* surface = fRenderTarget->asTexture(); 212 if (NULL == surface) { 213 surface = fRenderTarget; 214 } 215 216 SkImageInfo info; 217 surface->asImageInfo(&info); 218 SkPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, surface, SkToBool(flags & kCached_Flag))); 219 220 this->setPixelRef(pr)->unref(); 221} 222 223SkGpuDevice* SkGpuDevice::Create(GrContext* context, const SkImageInfo& origInfo, 224 int sampleCount) { 225 if (kUnknown_SkColorType == origInfo.colorType() || 226 origInfo.width() < 0 || origInfo.height() < 0) { 227 return NULL; 228 } 229 230 SkImageInfo info = origInfo; 231 // TODO: perhas we can loosen this check now that colortype is more detailed 232 // e.g. can we support both RGBA and BGRA here? 233 if (kRGB_565_SkColorType == info.colorType()) { 234 info.fAlphaType = kOpaque_SkAlphaType; // force this setting 235 } else { 236 info.fColorType = kN32_SkColorType; 237 if (kOpaque_SkAlphaType != info.alphaType()) { 238 info.fAlphaType = kPremul_SkAlphaType; // force this setting 239 } 240 } 241 242 GrTextureDesc desc; 243 desc.fFlags = kRenderTarget_GrTextureFlagBit; 244 desc.fWidth = info.width(); 245 desc.fHeight = info.height(); 246 desc.fConfig = SkImageInfo2GrPixelConfig(info); 247 desc.fSampleCnt = sampleCount; 248 249 SkAutoTUnref<GrTexture> texture(context->createUncachedTexture(desc, NULL, 0)); 250 if (!texture.get()) { 251 return NULL; 252 } 253 254 return SkNEW_ARGS(SkGpuDevice, (context, texture.get())); 255} 256 257SkGpuDevice::~SkGpuDevice() { 258 if (fDrawProcs) { 259 delete fDrawProcs; 260 } 261 262 delete fMainTextContext; 263 delete fFallbackTextContext; 264 265 // The GrContext takes a ref on the target. We don't want to cause the render 266 // target to be unnecessarily kept alive. 267 if (fContext->getRenderTarget() == fRenderTarget) { 268 fContext->setRenderTarget(NULL); 269 } 270 271 if (fContext->getClip() == &fClipData) { 272 fContext->setClip(NULL); 273 } 274 275 SkSafeUnref(fRenderTarget); 276 fContext->unref(); 277} 278 279/////////////////////////////////////////////////////////////////////////////// 280 281void SkGpuDevice::makeRenderTargetCurrent() { 282 DO_DEFERRED_CLEAR(); 283 fContext->setRenderTarget(fRenderTarget); 284} 285 286/////////////////////////////////////////////////////////////////////////////// 287 288bool SkGpuDevice::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes, 289 int x, int y) { 290 DO_DEFERRED_CLEAR(); 291 292 // TODO: teach fRenderTarget to take ImageInfo directly to specify the src pixels 293 GrPixelConfig config = SkImageInfo2GrPixelConfig(dstInfo); 294 if (kUnknown_GrPixelConfig == config) { 295 return false; 296 } 297 298 uint32_t flags = 0; 299 if (kUnpremul_SkAlphaType == dstInfo.alphaType()) { 300 flags = GrContext::kUnpremul_PixelOpsFlag; 301 } 302 return fContext->readRenderTargetPixels(fRenderTarget, x, y, dstInfo.width(), dstInfo.height(), 303 config, dstPixels, dstRowBytes, flags); 304} 305 306bool SkGpuDevice::onWritePixels(const SkImageInfo& info, const void* pixels, size_t rowBytes, 307 int x, int y) { 308 // TODO: teach fRenderTarget to take ImageInfo directly to specify the src pixels 309 GrPixelConfig config = SkImageInfo2GrPixelConfig(info); 310 if (kUnknown_GrPixelConfig == config) { 311 return false; 312 } 313 uint32_t flags = 0; 314 if (kUnpremul_SkAlphaType == info.alphaType()) { 315 flags = GrContext::kUnpremul_PixelOpsFlag; 316 } 317 fRenderTarget->writePixels(x, y, info.width(), info.height(), config, pixels, rowBytes, flags); 318 319 // need to bump our genID for compatibility with clients that "know" we have a bitmap 320 this->onAccessBitmap().notifyPixelsChanged(); 321 322 return true; 323} 324 325const SkBitmap& SkGpuDevice::onAccessBitmap() { 326 DO_DEFERRED_CLEAR(); 327 return INHERITED::onAccessBitmap(); 328} 329 330void SkGpuDevice::onAttachToCanvas(SkCanvas* canvas) { 331 INHERITED::onAttachToCanvas(canvas); 332 333 // Canvas promises that this ptr is valid until onDetachFromCanvas is called 334 fClipData.fClipStack = canvas->getClipStack(); 335} 336 337void SkGpuDevice::onDetachFromCanvas() { 338 INHERITED::onDetachFromCanvas(); 339 fClipData.fClipStack = NULL; 340} 341 342// call this every draw call, to ensure that the context reflects our state, 343// and not the state from some other canvas/device 344void SkGpuDevice::prepareDraw(const SkDraw& draw, bool forceIdentity) { 345 SkASSERT(NULL != fClipData.fClipStack); 346 347 fContext->setRenderTarget(fRenderTarget); 348 349 SkASSERT(draw.fClipStack && draw.fClipStack == fClipData.fClipStack); 350 351 if (forceIdentity) { 352 fContext->setIdentityMatrix(); 353 } else { 354 fContext->setMatrix(*draw.fMatrix); 355 } 356 fClipData.fOrigin = this->getOrigin(); 357 358 fContext->setClip(&fClipData); 359 360 DO_DEFERRED_CLEAR(); 361} 362 363GrRenderTarget* SkGpuDevice::accessRenderTarget() { 364 DO_DEFERRED_CLEAR(); 365 return fRenderTarget; 366} 367 368/////////////////////////////////////////////////////////////////////////////// 369 370SK_COMPILE_ASSERT(SkShader::kNone_BitmapType == 0, shader_type_mismatch); 371SK_COMPILE_ASSERT(SkShader::kDefault_BitmapType == 1, shader_type_mismatch); 372SK_COMPILE_ASSERT(SkShader::kRadial_BitmapType == 2, shader_type_mismatch); 373SK_COMPILE_ASSERT(SkShader::kSweep_BitmapType == 3, shader_type_mismatch); 374SK_COMPILE_ASSERT(SkShader::kTwoPointRadial_BitmapType == 4, 375 shader_type_mismatch); 376SK_COMPILE_ASSERT(SkShader::kTwoPointConical_BitmapType == 5, 377 shader_type_mismatch); 378SK_COMPILE_ASSERT(SkShader::kLinear_BitmapType == 6, shader_type_mismatch); 379SK_COMPILE_ASSERT(SkShader::kLast_BitmapType == 6, shader_type_mismatch); 380 381/////////////////////////////////////////////////////////////////////////////// 382 383SkBitmap::Config SkGpuDevice::config() const { 384 if (NULL == fRenderTarget) { 385 return SkBitmap::kNo_Config; 386 } 387 388 bool isOpaque; 389 return grConfig2skConfig(fRenderTarget->config(), &isOpaque); 390} 391 392void SkGpuDevice::clear(SkColor color) { 393 SkIRect rect = SkIRect::MakeWH(this->width(), this->height()); 394 fContext->clear(&rect, SkColor2GrColor(color), true, fRenderTarget); 395 fNeedClear = false; 396} 397 398void SkGpuDevice::drawPaint(const SkDraw& draw, const SkPaint& paint) { 399 CHECK_SHOULD_DRAW(draw, false); 400 401 GrPaint grPaint; 402 SkPaint2GrPaintShader(this->context(), paint, true, &grPaint); 403 404 fContext->drawPaint(grPaint); 405} 406 407// must be in SkCanvas::PointMode order 408static const GrPrimitiveType gPointMode2PrimtiveType[] = { 409 kPoints_GrPrimitiveType, 410 kLines_GrPrimitiveType, 411 kLineStrip_GrPrimitiveType 412}; 413 414void SkGpuDevice::drawPoints(const SkDraw& draw, SkCanvas::PointMode mode, 415 size_t count, const SkPoint pts[], const SkPaint& paint) { 416 CHECK_FOR_ANNOTATION(paint); 417 CHECK_SHOULD_DRAW(draw, false); 418 419 SkScalar width = paint.getStrokeWidth(); 420 if (width < 0) { 421 return; 422 } 423 424 if (paint.getPathEffect() && 2 == count && SkCanvas::kLines_PointMode == mode) { 425 if (GrDashingEffect::DrawDashLine(pts, paint, this->context())) { 426 return; 427 } 428 } 429 430 // we only handle hairlines and paints without path effects or mask filters, 431 // else we let the SkDraw call our drawPath() 432 if (width > 0 || paint.getPathEffect() || paint.getMaskFilter()) { 433 draw.drawPoints(mode, count, pts, paint, true); 434 return; 435 } 436 437 GrPaint grPaint; 438 SkPaint2GrPaintShader(this->context(), paint, true, &grPaint); 439 440 fContext->drawVertices(grPaint, 441 gPointMode2PrimtiveType[mode], 442 SkToS32(count), 443 (SkPoint*)pts, 444 NULL, 445 NULL, 446 NULL, 447 0); 448} 449 450/////////////////////////////////////////////////////////////////////////////// 451 452void SkGpuDevice::drawRect(const SkDraw& draw, const SkRect& rect, 453 const SkPaint& paint) { 454 CHECK_FOR_ANNOTATION(paint); 455 CHECK_SHOULD_DRAW(draw, false); 456 457 bool doStroke = paint.getStyle() != SkPaint::kFill_Style; 458 SkScalar width = paint.getStrokeWidth(); 459 460 /* 461 We have special code for hairline strokes, miter-strokes, bevel-stroke 462 and fills. Anything else we just call our path code. 463 */ 464 bool usePath = doStroke && width > 0 && 465 (paint.getStrokeJoin() == SkPaint::kRound_Join || 466 (paint.getStrokeJoin() == SkPaint::kBevel_Join && rect.isEmpty())); 467 // another two reasons we might need to call drawPath... 468 if (paint.getMaskFilter() || paint.getPathEffect()) { 469 usePath = true; 470 } 471 if (!usePath && paint.isAntiAlias() && !fContext->getMatrix().rectStaysRect()) { 472#if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT) 473 if (doStroke) { 474#endif 475 usePath = true; 476#if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT) 477 } else { 478 usePath = !fContext->getMatrix().preservesRightAngles(); 479 } 480#endif 481 } 482 // until we can both stroke and fill rectangles 483 if (paint.getStyle() == SkPaint::kStrokeAndFill_Style) { 484 usePath = true; 485 } 486 487 if (usePath) { 488 SkPath path; 489 path.addRect(rect); 490 this->drawPath(draw, path, paint, NULL, true); 491 return; 492 } 493 494 GrPaint grPaint; 495 SkPaint2GrPaintShader(this->context(), paint, true, &grPaint); 496 497 if (!doStroke) { 498 fContext->drawRect(grPaint, rect); 499 } else { 500 SkStrokeRec stroke(paint); 501 fContext->drawRect(grPaint, rect, &stroke); 502 } 503} 504 505/////////////////////////////////////////////////////////////////////////////// 506 507void SkGpuDevice::drawRRect(const SkDraw& draw, const SkRRect& rect, 508 const SkPaint& paint) { 509 CHECK_FOR_ANNOTATION(paint); 510 CHECK_SHOULD_DRAW(draw, false); 511 512 GrPaint grPaint; 513 SkPaint2GrPaintShader(this->context(), paint, true, &grPaint); 514 515 SkStrokeRec stroke(paint); 516 if (paint.getMaskFilter()) { 517 // try to hit the fast path for drawing filtered round rects 518 519 SkRRect devRRect; 520 if (rect.transform(fContext->getMatrix(), &devRRect)) { 521 if (devRRect.allCornersCircular()) { 522 SkRect maskRect; 523 if (paint.getMaskFilter()->canFilterMaskGPU(devRRect.rect(), 524 draw.fClip->getBounds(), 525 fContext->getMatrix(), 526 &maskRect)) { 527 SkIRect finalIRect; 528 maskRect.roundOut(&finalIRect); 529 if (draw.fClip->quickReject(finalIRect)) { 530 // clipped out 531 return; 532 } 533 if (NULL != draw.fBounder && !draw.fBounder->doIRect(finalIRect)) { 534 // nothing to draw 535 return; 536 } 537 if (paint.getMaskFilter()->directFilterRRectMaskGPU(fContext, &grPaint, 538 stroke, devRRect)) { 539 return; 540 } 541 } 542 543 } 544 } 545 546 } 547 548 if (paint.getMaskFilter() || paint.getPathEffect()) { 549 SkPath path; 550 path.addRRect(rect); 551 this->drawPath(draw, path, paint, NULL, true); 552 return; 553 } 554 555 fContext->drawRRect(grPaint, rect, stroke); 556} 557 558void SkGpuDevice::drawDRRect(const SkDraw& draw, const SkRRect& outer, 559 const SkRRect& inner, const SkPaint& paint) { 560 SkStrokeRec stroke(paint); 561 if (stroke.isFillStyle()) { 562 563 CHECK_FOR_ANNOTATION(paint); 564 CHECK_SHOULD_DRAW(draw, false); 565 566 GrPaint grPaint; 567 SkPaint2GrPaintShader(this->context(), paint, true, &grPaint); 568 569 if (NULL == paint.getMaskFilter() && NULL == paint.getPathEffect()) { 570 fContext->drawDRRect(grPaint, outer, inner); 571 return; 572 } 573 } 574 575 SkPath path; 576 path.addRRect(outer); 577 path.addRRect(inner); 578 path.setFillType(SkPath::kEvenOdd_FillType); 579 580 this->drawPath(draw, path, paint, NULL, true); 581} 582 583 584///////////////////////////////////////////////////////////////////////////// 585 586void SkGpuDevice::drawOval(const SkDraw& draw, const SkRect& oval, 587 const SkPaint& paint) { 588 CHECK_FOR_ANNOTATION(paint); 589 CHECK_SHOULD_DRAW(draw, false); 590 591 bool usePath = false; 592 // some basic reasons we might need to call drawPath... 593 if (paint.getMaskFilter() || paint.getPathEffect()) { 594 usePath = true; 595 } 596 597 if (usePath) { 598 SkPath path; 599 path.addOval(oval); 600 this->drawPath(draw, path, paint, NULL, true); 601 return; 602 } 603 604 GrPaint grPaint; 605 SkPaint2GrPaintShader(this->context(), paint, true, &grPaint); 606 SkStrokeRec stroke(paint); 607 608 fContext->drawOval(grPaint, oval, stroke); 609} 610 611#include "SkMaskFilter.h" 612#include "SkBounder.h" 613 614/////////////////////////////////////////////////////////////////////////////// 615 616// helpers for applying mask filters 617namespace { 618 619// Draw a mask using the supplied paint. Since the coverage/geometry 620// is already burnt into the mask this boils down to a rect draw. 621// Return true if the mask was successfully drawn. 622bool draw_mask(GrContext* context, const SkRect& maskRect, 623 GrPaint* grp, GrTexture* mask) { 624 GrContext::AutoMatrix am; 625 if (!am.setIdentity(context, grp)) { 626 return false; 627 } 628 629 SkMatrix matrix; 630 matrix.setTranslate(-maskRect.fLeft, -maskRect.fTop); 631 matrix.postIDiv(mask->width(), mask->height()); 632 633 grp->addCoverageEffect(GrSimpleTextureEffect::Create(mask, matrix))->unref(); 634 context->drawRect(*grp, maskRect); 635 return true; 636} 637 638bool draw_with_mask_filter(GrContext* context, const SkPath& devPath, 639 SkMaskFilter* filter, const SkRegion& clip, SkBounder* bounder, 640 GrPaint* grp, SkPaint::Style style) { 641 SkMask srcM, dstM; 642 643 if (!SkDraw::DrawToMask(devPath, &clip.getBounds(), filter, &context->getMatrix(), &srcM, 644 SkMask::kComputeBoundsAndRenderImage_CreateMode, style)) { 645 return false; 646 } 647 SkAutoMaskFreeImage autoSrc(srcM.fImage); 648 649 if (!filter->filterMask(&dstM, srcM, context->getMatrix(), NULL)) { 650 return false; 651 } 652 // this will free-up dstM when we're done (allocated in filterMask()) 653 SkAutoMaskFreeImage autoDst(dstM.fImage); 654 655 if (clip.quickReject(dstM.fBounds)) { 656 return false; 657 } 658 if (bounder && !bounder->doIRect(dstM.fBounds)) { 659 return false; 660 } 661 662 // we now have a device-aligned 8bit mask in dstM, ready to be drawn using 663 // the current clip (and identity matrix) and GrPaint settings 664 GrTextureDesc desc; 665 desc.fWidth = dstM.fBounds.width(); 666 desc.fHeight = dstM.fBounds.height(); 667 desc.fConfig = kAlpha_8_GrPixelConfig; 668 669 GrAutoScratchTexture ast(context, desc); 670 GrTexture* texture = ast.texture(); 671 672 if (NULL == texture) { 673 return false; 674 } 675 texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig, 676 dstM.fImage, dstM.fRowBytes); 677 678 SkRect maskRect = SkRect::Make(dstM.fBounds); 679 680 return draw_mask(context, maskRect, grp, texture); 681} 682 683// Create a mask of 'devPath' and place the result in 'mask'. Return true on 684// success; false otherwise. 685bool create_mask_GPU(GrContext* context, 686 const SkRect& maskRect, 687 const SkPath& devPath, 688 const SkStrokeRec& stroke, 689 bool doAA, 690 GrAutoScratchTexture* mask) { 691 GrTextureDesc desc; 692 desc.fFlags = kRenderTarget_GrTextureFlagBit; 693 desc.fWidth = SkScalarCeilToInt(maskRect.width()); 694 desc.fHeight = SkScalarCeilToInt(maskRect.height()); 695 // We actually only need A8, but it often isn't supported as a 696 // render target so default to RGBA_8888 697 desc.fConfig = kRGBA_8888_GrPixelConfig; 698 if (context->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) { 699 desc.fConfig = kAlpha_8_GrPixelConfig; 700 } 701 702 mask->set(context, desc); 703 if (NULL == mask->texture()) { 704 return false; 705 } 706 707 GrTexture* maskTexture = mask->texture(); 708 SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height()); 709 710 GrContext::AutoRenderTarget art(context, maskTexture->asRenderTarget()); 711 GrContext::AutoClip ac(context, clipRect); 712 713 context->clear(NULL, 0x0, true); 714 715 GrPaint tempPaint; 716 if (doAA) { 717 tempPaint.setAntiAlias(true); 718 // AA uses the "coverage" stages on GrDrawTarget. Coverage with a dst 719 // blend coeff of zero requires dual source blending support in order 720 // to properly blend partially covered pixels. This means the AA 721 // code path may not be taken. So we use a dst blend coeff of ISA. We 722 // could special case AA draws to a dst surface with known alpha=0 to 723 // use a zero dst coeff when dual source blending isn't available. 724 tempPaint.setBlendFunc(kOne_GrBlendCoeff, kISC_GrBlendCoeff); 725 } 726 727 GrContext::AutoMatrix am; 728 729 // Draw the mask into maskTexture with the path's top-left at the origin using tempPaint. 730 SkMatrix translate; 731 translate.setTranslate(-maskRect.fLeft, -maskRect.fTop); 732 am.set(context, translate); 733 context->drawPath(tempPaint, devPath, stroke); 734 return true; 735} 736 737SkBitmap wrap_texture(GrTexture* texture) { 738 SkImageInfo info; 739 texture->asImageInfo(&info); 740 741 SkBitmap result; 742 result.setInfo(info); 743 result.setPixelRef(SkNEW_ARGS(SkGrPixelRef, (info, texture)))->unref(); 744 return result; 745} 746 747}; 748 749void SkGpuDevice::drawPath(const SkDraw& draw, const SkPath& origSrcPath, 750 const SkPaint& paint, const SkMatrix* prePathMatrix, 751 bool pathIsMutable) { 752 CHECK_FOR_ANNOTATION(paint); 753 CHECK_SHOULD_DRAW(draw, false); 754 755 GrPaint grPaint; 756 SkPaint2GrPaintShader(this->context(), paint, true, &grPaint); 757 758 // If we have a prematrix, apply it to the path, optimizing for the case 759 // where the original path can in fact be modified in place (even though 760 // its parameter type is const). 761 SkPath* pathPtr = const_cast<SkPath*>(&origSrcPath); 762 SkTLazy<SkPath> tmpPath; 763 SkTLazy<SkPath> effectPath; 764 765 if (prePathMatrix) { 766 SkPath* result = pathPtr; 767 768 if (!pathIsMutable) { 769 result = tmpPath.init(); 770 pathIsMutable = true; 771 } 772 // should I push prePathMatrix on our MV stack temporarily, instead 773 // of applying it here? See SkDraw.cpp 774 pathPtr->transform(*prePathMatrix, result); 775 pathPtr = result; 776 } 777 // at this point we're done with prePathMatrix 778 SkDEBUGCODE(prePathMatrix = (const SkMatrix*)0x50FF8001;) 779 780 SkStrokeRec stroke(paint); 781 SkPathEffect* pathEffect = paint.getPathEffect(); 782 const SkRect* cullRect = NULL; // TODO: what is our bounds? 783 if (pathEffect && pathEffect->filterPath(effectPath.init(), *pathPtr, &stroke, 784 cullRect)) { 785 pathPtr = effectPath.get(); 786 pathIsMutable = true; 787 } 788 789 if (paint.getMaskFilter()) { 790 if (!stroke.isHairlineStyle()) { 791 SkPath* strokedPath = pathIsMutable ? pathPtr : tmpPath.init(); 792 if (stroke.applyToPath(strokedPath, *pathPtr)) { 793 pathPtr = strokedPath; 794 pathIsMutable = true; 795 stroke.setFillStyle(); 796 } 797 } 798 799 // avoid possibly allocating a new path in transform if we can 800 SkPath* devPathPtr = pathIsMutable ? pathPtr : tmpPath.init(); 801 802 // transform the path into device space 803 pathPtr->transform(fContext->getMatrix(), devPathPtr); 804 805 SkRect maskRect; 806 if (paint.getMaskFilter()->canFilterMaskGPU(devPathPtr->getBounds(), 807 draw.fClip->getBounds(), 808 fContext->getMatrix(), 809 &maskRect)) { 810 // The context's matrix may change while creating the mask, so save the CTM here to 811 // pass to filterMaskGPU. 812 const SkMatrix ctm = fContext->getMatrix(); 813 814 SkIRect finalIRect; 815 maskRect.roundOut(&finalIRect); 816 if (draw.fClip->quickReject(finalIRect)) { 817 // clipped out 818 return; 819 } 820 if (NULL != draw.fBounder && !draw.fBounder->doIRect(finalIRect)) { 821 // nothing to draw 822 return; 823 } 824 825 if (paint.getMaskFilter()->directFilterMaskGPU(fContext, &grPaint, 826 stroke, *devPathPtr)) { 827 // the mask filter was able to draw itself directly, so there's nothing 828 // left to do. 829 return; 830 } 831 832 GrAutoScratchTexture mask; 833 834 if (create_mask_GPU(fContext, maskRect, *devPathPtr, stroke, 835 grPaint.isAntiAlias(), &mask)) { 836 GrTexture* filtered; 837 838 if (paint.getMaskFilter()->filterMaskGPU(mask.texture(), 839 ctm, maskRect, &filtered, true)) { 840 // filterMaskGPU gives us ownership of a ref to the result 841 SkAutoTUnref<GrTexture> atu(filtered); 842 843 // If the scratch texture that we used as the filter src also holds the filter 844 // result then we must detach so that this texture isn't recycled for a later 845 // draw. 846 if (filtered == mask.texture()) { 847 mask.detach(); 848 filtered->unref(); // detach transfers GrAutoScratchTexture's ref to us. 849 } 850 851 if (draw_mask(fContext, maskRect, &grPaint, filtered)) { 852 // This path is completely drawn 853 return; 854 } 855 } 856 } 857 } 858 859 // draw the mask on the CPU - this is a fallthrough path in case the 860 // GPU path fails 861 SkPaint::Style style = stroke.isHairlineStyle() ? SkPaint::kStroke_Style : 862 SkPaint::kFill_Style; 863 draw_with_mask_filter(fContext, *devPathPtr, paint.getMaskFilter(), 864 *draw.fClip, draw.fBounder, &grPaint, style); 865 return; 866 } 867 868 fContext->drawPath(grPaint, *pathPtr, stroke); 869} 870 871static const int kBmpSmallTileSize = 1 << 10; 872 873static inline int get_tile_count(const SkIRect& srcRect, int tileSize) { 874 int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1; 875 int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1; 876 return tilesX * tilesY; 877} 878 879static int determine_tile_size(const SkBitmap& bitmap, const SkIRect& src, int maxTileSize) { 880 if (maxTileSize <= kBmpSmallTileSize) { 881 return maxTileSize; 882 } 883 884 size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize); 885 size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize); 886 887 maxTileTotalTileSize *= maxTileSize * maxTileSize; 888 smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize; 889 890 if (maxTileTotalTileSize > 2 * smallTotalTileSize) { 891 return kBmpSmallTileSize; 892 } else { 893 return maxTileSize; 894 } 895} 896 897// Given a bitmap, an optional src rect, and a context with a clip and matrix determine what 898// pixels from the bitmap are necessary. 899static void determine_clipped_src_rect(const GrContext* context, 900 const SkBitmap& bitmap, 901 const SkRect* srcRectPtr, 902 SkIRect* clippedSrcIRect) { 903 const GrClipData* clip = context->getClip(); 904 clip->getConservativeBounds(context->getRenderTarget(), clippedSrcIRect, NULL); 905 SkMatrix inv; 906 if (!context->getMatrix().invert(&inv)) { 907 clippedSrcIRect->setEmpty(); 908 return; 909 } 910 SkRect clippedSrcRect = SkRect::Make(*clippedSrcIRect); 911 inv.mapRect(&clippedSrcRect); 912 if (NULL != srcRectPtr) { 913 // we've setup src space 0,0 to map to the top left of the src rect. 914 clippedSrcRect.offset(srcRectPtr->fLeft, srcRectPtr->fTop); 915 if (!clippedSrcRect.intersect(*srcRectPtr)) { 916 clippedSrcIRect->setEmpty(); 917 return; 918 } 919 } 920 clippedSrcRect.roundOut(clippedSrcIRect); 921 SkIRect bmpBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height()); 922 if (!clippedSrcIRect->intersect(bmpBounds)) { 923 clippedSrcIRect->setEmpty(); 924 } 925} 926 927bool SkGpuDevice::shouldTileBitmap(const SkBitmap& bitmap, 928 const GrTextureParams& params, 929 const SkRect* srcRectPtr, 930 int maxTileSize, 931 int* tileSize, 932 SkIRect* clippedSrcRect) const { 933 // if bitmap is explictly texture backed then just use the texture 934 if (NULL != bitmap.getTexture()) { 935 return false; 936 } 937 938 // if it's larger than the max tile size, then we have no choice but tiling. 939 if (bitmap.width() > maxTileSize || bitmap.height() > maxTileSize) { 940 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect); 941 *tileSize = determine_tile_size(bitmap, *clippedSrcRect, maxTileSize); 942 return true; 943 } 944 945 if (bitmap.width() * bitmap.height() < 4 * kBmpSmallTileSize * kBmpSmallTileSize) { 946 return false; 947 } 948 949 // if the entire texture is already in our cache then no reason to tile it 950 if (GrIsBitmapInCache(fContext, bitmap, ¶ms)) { 951 return false; 952 } 953 954 // At this point we know we could do the draw by uploading the entire bitmap 955 // as a texture. However, if the texture would be large compared to the 956 // cache size and we don't require most of it for this draw then tile to 957 // reduce the amount of upload and cache spill. 958 959 // assumption here is that sw bitmap size is a good proxy for its size as 960 // a texture 961 size_t bmpSize = bitmap.getSize(); 962 size_t cacheSize; 963 fContext->getResourceCacheLimits(NULL, &cacheSize); 964 if (bmpSize < cacheSize / 2) { 965 return false; 966 } 967 968 // Figure out how much of the src we will need based on the src rect and clipping. 969 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect); 970 *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile. 971 size_t usedTileBytes = get_tile_count(*clippedSrcRect, kBmpSmallTileSize) * 972 kBmpSmallTileSize * kBmpSmallTileSize; 973 974 return usedTileBytes < 2 * bmpSize; 975} 976 977void SkGpuDevice::drawBitmap(const SkDraw& origDraw, 978 const SkBitmap& bitmap, 979 const SkMatrix& m, 980 const SkPaint& paint) { 981 SkMatrix concat; 982 SkTCopyOnFirstWrite<SkDraw> draw(origDraw); 983 if (!m.isIdentity()) { 984 concat.setConcat(*draw->fMatrix, m); 985 draw.writable()->fMatrix = &concat; 986 } 987 this->drawBitmapCommon(*draw, bitmap, NULL, NULL, paint, SkCanvas::kNone_DrawBitmapRectFlag); 988} 989 990// This method outsets 'iRect' by 'outset' all around and then clamps its extents to 991// 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner 992// of 'iRect' for all possible outsets/clamps. 993static inline void clamped_outset_with_offset(SkIRect* iRect, 994 int outset, 995 SkPoint* offset, 996 const SkIRect& clamp) { 997 iRect->outset(outset, outset); 998 999 int leftClampDelta = clamp.fLeft - iRect->fLeft; 1000 if (leftClampDelta > 0) { 1001 offset->fX -= outset - leftClampDelta; 1002 iRect->fLeft = clamp.fLeft; 1003 } else { 1004 offset->fX -= outset; 1005 } 1006 1007 int topClampDelta = clamp.fTop - iRect->fTop; 1008 if (topClampDelta > 0) { 1009 offset->fY -= outset - topClampDelta; 1010 iRect->fTop = clamp.fTop; 1011 } else { 1012 offset->fY -= outset; 1013 } 1014 1015 if (iRect->fRight > clamp.fRight) { 1016 iRect->fRight = clamp.fRight; 1017 } 1018 if (iRect->fBottom > clamp.fBottom) { 1019 iRect->fBottom = clamp.fBottom; 1020 } 1021} 1022 1023static bool has_aligned_samples(const SkRect& srcRect, 1024 const SkRect& transformedRect) { 1025 // detect pixel disalignment 1026 if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) - 1027 transformedRect.left()) < COLOR_BLEED_TOLERANCE && 1028 SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) - 1029 transformedRect.top()) < COLOR_BLEED_TOLERANCE && 1030 SkScalarAbs(transformedRect.width() - srcRect.width()) < 1031 COLOR_BLEED_TOLERANCE && 1032 SkScalarAbs(transformedRect.height() - srcRect.height()) < 1033 COLOR_BLEED_TOLERANCE) { 1034 return true; 1035 } 1036 return false; 1037} 1038 1039static bool may_color_bleed(const SkRect& srcRect, 1040 const SkRect& transformedRect, 1041 const SkMatrix& m) { 1042 // Only gets called if has_aligned_samples returned false. 1043 // So we can assume that sampling is axis aligned but not texel aligned. 1044 SkASSERT(!has_aligned_samples(srcRect, transformedRect)); 1045 SkRect innerSrcRect(srcRect), innerTransformedRect, 1046 outerTransformedRect(transformedRect); 1047 innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf); 1048 m.mapRect(&innerTransformedRect, innerSrcRect); 1049 1050 // The gap between outerTransformedRect and innerTransformedRect 1051 // represents the projection of the source border area, which is 1052 // problematic for color bleeding. We must check whether any 1053 // destination pixels sample the border area. 1054 outerTransformedRect.inset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE); 1055 innerTransformedRect.outset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE); 1056 SkIRect outer, inner; 1057 outerTransformedRect.round(&outer); 1058 innerTransformedRect.round(&inner); 1059 // If the inner and outer rects round to the same result, it means the 1060 // border does not overlap any pixel centers. Yay! 1061 return inner != outer; 1062} 1063 1064static bool needs_texture_domain(const SkBitmap& bitmap, 1065 const SkRect& srcRect, 1066 GrTextureParams ¶ms, 1067 const SkMatrix& contextMatrix, 1068 bool bicubic) { 1069 bool needsTextureDomain = false; 1070 1071 if (bicubic || params.filterMode() != GrTextureParams::kNone_FilterMode) { 1072 // Need texture domain if drawing a sub rect 1073 needsTextureDomain = srcRect.width() < bitmap.width() || 1074 srcRect.height() < bitmap.height(); 1075 if (!bicubic && needsTextureDomain && contextMatrix.rectStaysRect()) { 1076 // sampling is axis-aligned 1077 SkRect transformedRect; 1078 contextMatrix.mapRect(&transformedRect, srcRect); 1079 1080 if (has_aligned_samples(srcRect, transformedRect)) { 1081 params.setFilterMode(GrTextureParams::kNone_FilterMode); 1082 needsTextureDomain = false; 1083 } else { 1084 needsTextureDomain = may_color_bleed(srcRect, transformedRect, contextMatrix); 1085 } 1086 } 1087 } 1088 return needsTextureDomain; 1089} 1090 1091void SkGpuDevice::drawBitmapCommon(const SkDraw& draw, 1092 const SkBitmap& bitmap, 1093 const SkRect* srcRectPtr, 1094 const SkSize* dstSizePtr, 1095 const SkPaint& paint, 1096 SkCanvas::DrawBitmapRectFlags flags) { 1097 CHECK_SHOULD_DRAW(draw, false); 1098 1099 SkRect srcRect; 1100 SkSize dstSize; 1101 // If there is no src rect, or the src rect contains the entire bitmap then we're effectively 1102 // in the (easier) bleed case, so update flags. 1103 if (NULL == srcRectPtr) { 1104 SkScalar w = SkIntToScalar(bitmap.width()); 1105 SkScalar h = SkIntToScalar(bitmap.height()); 1106 dstSize.fWidth = w; 1107 dstSize.fHeight = h; 1108 srcRect.set(0, 0, w, h); 1109 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag); 1110 } else { 1111 SkASSERT(NULL != dstSizePtr); 1112 srcRect = *srcRectPtr; 1113 dstSize = *dstSizePtr; 1114 if (srcRect.fLeft <= 0 && srcRect.fTop <= 0 && 1115 srcRect.fRight >= bitmap.width() && srcRect.fBottom >= bitmap.height()) { 1116 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag); 1117 } 1118 } 1119 1120 if (paint.getMaskFilter()){ 1121 // Convert the bitmap to a shader so that the rect can be drawn 1122 // through drawRect, which supports mask filters. 1123 SkBitmap tmp; // subset of bitmap, if necessary 1124 const SkBitmap* bitmapPtr = &bitmap; 1125 SkMatrix localM; 1126 if (NULL != srcRectPtr) { 1127 localM.setTranslate(-srcRectPtr->fLeft, -srcRectPtr->fTop); 1128 localM.postScale(dstSize.fWidth / srcRectPtr->width(), 1129 dstSize.fHeight / srcRectPtr->height()); 1130 // In bleed mode we position and trim the bitmap based on the src rect which is 1131 // already accounted for in 'm' and 'srcRect'. In clamp mode we need to chop out 1132 // the desired portion of the bitmap and then update 'm' and 'srcRect' to 1133 // compensate. 1134 if (!(SkCanvas::kBleed_DrawBitmapRectFlag & flags)) { 1135 SkIRect iSrc; 1136 srcRect.roundOut(&iSrc); 1137 1138 SkPoint offset = SkPoint::Make(SkIntToScalar(iSrc.fLeft), 1139 SkIntToScalar(iSrc.fTop)); 1140 1141 if (!bitmap.extractSubset(&tmp, iSrc)) { 1142 return; // extraction failed 1143 } 1144 bitmapPtr = &tmp; 1145 srcRect.offset(-offset.fX, -offset.fY); 1146 1147 // The source rect has changed so update the matrix 1148 localM.preTranslate(offset.fX, offset.fY); 1149 } 1150 } else { 1151 localM.reset(); 1152 } 1153 1154 SkPaint paintWithShader(paint); 1155 paintWithShader.setShader(SkShader::CreateBitmapShader(*bitmapPtr, 1156 SkShader::kClamp_TileMode, SkShader::kClamp_TileMode, &localM))->unref(); 1157 SkRect dstRect = {0, 0, dstSize.fWidth, dstSize.fHeight}; 1158 this->drawRect(draw, dstRect, paintWithShader); 1159 1160 return; 1161 } 1162 1163 // If there is no mask filter than it is OK to handle the src rect -> dst rect scaling using 1164 // the view matrix rather than a local matrix. 1165 SkMatrix m; 1166 m.setScale(dstSize.fWidth / srcRect.width(), 1167 dstSize.fHeight / srcRect.height()); 1168 fContext->concatMatrix(m); 1169 1170 GrTextureParams params; 1171 SkPaint::FilterLevel paintFilterLevel = paint.getFilterLevel(); 1172 GrTextureParams::FilterMode textureFilterMode; 1173 1174 bool doBicubic = false; 1175 1176 switch(paintFilterLevel) { 1177 case SkPaint::kNone_FilterLevel: 1178 textureFilterMode = GrTextureParams::kNone_FilterMode; 1179 break; 1180 case SkPaint::kLow_FilterLevel: 1181 textureFilterMode = GrTextureParams::kBilerp_FilterMode; 1182 break; 1183 case SkPaint::kMedium_FilterLevel: 1184 if (fContext->getMatrix().getMinScale() < SK_Scalar1) { 1185 textureFilterMode = GrTextureParams::kMipMap_FilterMode; 1186 } else { 1187 // Don't trigger MIP level generation unnecessarily. 1188 textureFilterMode = GrTextureParams::kBilerp_FilterMode; 1189 } 1190 break; 1191 case SkPaint::kHigh_FilterLevel: 1192 // Minification can look bad with the bicubic effect. 1193 doBicubic = 1194 GrBicubicEffect::ShouldUseBicubic(fContext->getMatrix(), &textureFilterMode); 1195 break; 1196 default: 1197 SkErrorInternals::SetError( kInvalidPaint_SkError, 1198 "Sorry, I don't understand the filtering " 1199 "mode you asked for. Falling back to " 1200 "MIPMaps."); 1201 textureFilterMode = GrTextureParams::kMipMap_FilterMode; 1202 break; 1203 } 1204 1205 int tileFilterPad; 1206 if (doBicubic) { 1207 tileFilterPad = GrBicubicEffect::kFilterTexelPad; 1208 } else if (GrTextureParams::kNone_FilterMode == textureFilterMode) { 1209 tileFilterPad = 0; 1210 } else { 1211 tileFilterPad = 1; 1212 } 1213 params.setFilterMode(textureFilterMode); 1214 1215 int maxTileSize = fContext->getMaxTextureSize() - 2 * tileFilterPad; 1216 int tileSize; 1217 1218 SkIRect clippedSrcRect; 1219 if (this->shouldTileBitmap(bitmap, params, srcRectPtr, maxTileSize, &tileSize, 1220 &clippedSrcRect)) { 1221 this->drawTiledBitmap(bitmap, srcRect, clippedSrcRect, params, paint, flags, tileSize, 1222 doBicubic); 1223 } else { 1224 // take the simple case 1225 bool needsTextureDomain = needs_texture_domain(bitmap, 1226 srcRect, 1227 params, 1228 fContext->getMatrix(), 1229 doBicubic); 1230 this->internalDrawBitmap(bitmap, 1231 srcRect, 1232 params, 1233 paint, 1234 flags, 1235 doBicubic, 1236 needsTextureDomain); 1237 } 1238} 1239 1240// Break 'bitmap' into several tiles to draw it since it has already 1241// been determined to be too large to fit in VRAM 1242void SkGpuDevice::drawTiledBitmap(const SkBitmap& bitmap, 1243 const SkRect& srcRect, 1244 const SkIRect& clippedSrcIRect, 1245 const GrTextureParams& params, 1246 const SkPaint& paint, 1247 SkCanvas::DrawBitmapRectFlags flags, 1248 int tileSize, 1249 bool bicubic) { 1250 // The following pixel lock is technically redundant, but it is desirable 1251 // to lock outside of the tile loop to prevent redecoding the whole image 1252 // at each tile in cases where 'bitmap' holds an SkDiscardablePixelRef that 1253 // is larger than the limit of the discardable memory pool. 1254 SkAutoLockPixels alp(bitmap); 1255 SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect); 1256 1257 int nx = bitmap.width() / tileSize; 1258 int ny = bitmap.height() / tileSize; 1259 for (int x = 0; x <= nx; x++) { 1260 for (int y = 0; y <= ny; y++) { 1261 SkRect tileR; 1262 tileR.set(SkIntToScalar(x * tileSize), 1263 SkIntToScalar(y * tileSize), 1264 SkIntToScalar((x + 1) * tileSize), 1265 SkIntToScalar((y + 1) * tileSize)); 1266 1267 if (!SkRect::Intersects(tileR, clippedSrcRect)) { 1268 continue; 1269 } 1270 1271 if (!tileR.intersect(srcRect)) { 1272 continue; 1273 } 1274 1275 SkBitmap tmpB; 1276 SkIRect iTileR; 1277 tileR.roundOut(&iTileR); 1278 SkPoint offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft), 1279 SkIntToScalar(iTileR.fTop)); 1280 1281 // Adjust the context matrix to draw at the right x,y in device space 1282 SkMatrix tmpM; 1283 GrContext::AutoMatrix am; 1284 tmpM.setTranslate(offset.fX - srcRect.fLeft, offset.fY - srcRect.fTop); 1285 am.setPreConcat(fContext, tmpM); 1286 1287 if (SkPaint::kNone_FilterLevel != paint.getFilterLevel() || bicubic) { 1288 SkIRect iClampRect; 1289 1290 if (SkCanvas::kBleed_DrawBitmapRectFlag & flags) { 1291 // In bleed mode we want to always expand the tile on all edges 1292 // but stay within the bitmap bounds 1293 iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height()); 1294 } else { 1295 // In texture-domain/clamp mode we only want to expand the 1296 // tile on edges interior to "srcRect" (i.e., we want to 1297 // not bleed across the original clamped edges) 1298 srcRect.roundOut(&iClampRect); 1299 } 1300 int outset = bicubic ? GrBicubicEffect::kFilterTexelPad : 1; 1301 clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect); 1302 } 1303 1304 if (bitmap.extractSubset(&tmpB, iTileR)) { 1305 // now offset it to make it "local" to our tmp bitmap 1306 tileR.offset(-offset.fX, -offset.fY); 1307 GrTextureParams paramsTemp = params; 1308 bool needsTextureDomain = needs_texture_domain(bitmap, 1309 srcRect, 1310 paramsTemp, 1311 fContext->getMatrix(), 1312 bicubic); 1313 this->internalDrawBitmap(tmpB, 1314 tileR, 1315 paramsTemp, 1316 paint, 1317 flags, 1318 bicubic, 1319 needsTextureDomain); 1320 } 1321 } 1322 } 1323} 1324 1325 1326/* 1327 * This is called by drawBitmap(), which has to handle images that may be too 1328 * large to be represented by a single texture. 1329 * 1330 * internalDrawBitmap assumes that the specified bitmap will fit in a texture 1331 * and that non-texture portion of the GrPaint has already been setup. 1332 */ 1333void SkGpuDevice::internalDrawBitmap(const SkBitmap& bitmap, 1334 const SkRect& srcRect, 1335 const GrTextureParams& params, 1336 const SkPaint& paint, 1337 SkCanvas::DrawBitmapRectFlags flags, 1338 bool bicubic, 1339 bool needsTextureDomain) { 1340 SkASSERT(bitmap.width() <= fContext->getMaxTextureSize() && 1341 bitmap.height() <= fContext->getMaxTextureSize()); 1342 1343 GrTexture* texture; 1344 SkAutoCachedTexture act(this, bitmap, ¶ms, &texture); 1345 if (NULL == texture) { 1346 return; 1347 } 1348 1349 SkRect dstRect = {0, 0, srcRect.width(), srcRect.height() }; 1350 SkRect paintRect; 1351 SkScalar wInv = SkScalarInvert(SkIntToScalar(texture->width())); 1352 SkScalar hInv = SkScalarInvert(SkIntToScalar(texture->height())); 1353 paintRect.setLTRB(SkScalarMul(srcRect.fLeft, wInv), 1354 SkScalarMul(srcRect.fTop, hInv), 1355 SkScalarMul(srcRect.fRight, wInv), 1356 SkScalarMul(srcRect.fBottom, hInv)); 1357 1358 SkRect textureDomain = SkRect::MakeEmpty(); 1359 SkAutoTUnref<GrEffectRef> effect; 1360 if (needsTextureDomain && !(flags & SkCanvas::kBleed_DrawBitmapRectFlag)) { 1361 // Use a constrained texture domain to avoid color bleeding 1362 SkScalar left, top, right, bottom; 1363 if (srcRect.width() > SK_Scalar1) { 1364 SkScalar border = SK_ScalarHalf / texture->width(); 1365 left = paintRect.left() + border; 1366 right = paintRect.right() - border; 1367 } else { 1368 left = right = SkScalarHalf(paintRect.left() + paintRect.right()); 1369 } 1370 if (srcRect.height() > SK_Scalar1) { 1371 SkScalar border = SK_ScalarHalf / texture->height(); 1372 top = paintRect.top() + border; 1373 bottom = paintRect.bottom() - border; 1374 } else { 1375 top = bottom = SkScalarHalf(paintRect.top() + paintRect.bottom()); 1376 } 1377 textureDomain.setLTRB(left, top, right, bottom); 1378 if (bicubic) { 1379 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), textureDomain)); 1380 } else { 1381 effect.reset(GrTextureDomainEffect::Create(texture, 1382 SkMatrix::I(), 1383 textureDomain, 1384 GrTextureDomain::kClamp_Mode, 1385 params.filterMode())); 1386 } 1387 } else if (bicubic) { 1388 SkASSERT(GrTextureParams::kNone_FilterMode == params.filterMode()); 1389 SkShader::TileMode tileModes[2] = { params.getTileModeX(), params.getTileModeY() }; 1390 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), tileModes)); 1391 } else { 1392 effect.reset(GrSimpleTextureEffect::Create(texture, SkMatrix::I(), params)); 1393 } 1394 1395 // Construct a GrPaint by setting the bitmap texture as the first effect and then configuring 1396 // the rest from the SkPaint. 1397 GrPaint grPaint; 1398 grPaint.addColorEffect(effect); 1399 bool alphaOnly = !(SkBitmap::kA8_Config == bitmap.config()); 1400 SkPaint2GrPaintNoShader(this->context(), paint, alphaOnly, false, &grPaint); 1401 1402 fContext->drawRectToRect(grPaint, dstRect, paintRect, NULL); 1403} 1404 1405static bool filter_texture(SkBaseDevice* device, GrContext* context, 1406 GrTexture* texture, const SkImageFilter* filter, 1407 int w, int h, const SkImageFilter::Context& ctx, 1408 SkBitmap* result, SkIPoint* offset) { 1409 SkASSERT(filter); 1410 SkDeviceImageFilterProxy proxy(device); 1411 1412 if (filter->canFilterImageGPU()) { 1413 // Save the render target and set it to NULL, so we don't accidentally draw to it in the 1414 // filter. Also set the clip wide open and the matrix to identity. 1415 GrContext::AutoWideOpenIdentityDraw awo(context, NULL); 1416 return filter->filterImageGPU(&proxy, wrap_texture(texture), ctx, result, offset); 1417 } else { 1418 return false; 1419 } 1420} 1421 1422void SkGpuDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap, 1423 int left, int top, const SkPaint& paint) { 1424 // drawSprite is defined to be in device coords. 1425 CHECK_SHOULD_DRAW(draw, true); 1426 1427 SkAutoLockPixels alp(bitmap, !bitmap.getTexture()); 1428 if (!bitmap.getTexture() && !bitmap.readyToDraw()) { 1429 return; 1430 } 1431 1432 int w = bitmap.width(); 1433 int h = bitmap.height(); 1434 1435 GrTexture* texture; 1436 // draw sprite uses the default texture params 1437 SkAutoCachedTexture act(this, bitmap, NULL, &texture); 1438 1439 SkImageFilter* filter = paint.getImageFilter(); 1440 // This bitmap will own the filtered result as a texture. 1441 SkBitmap filteredBitmap; 1442 1443 if (NULL != filter) { 1444 SkIPoint offset = SkIPoint::Make(0, 0); 1445 SkMatrix matrix(*draw.fMatrix); 1446 matrix.postTranslate(SkIntToScalar(-left), SkIntToScalar(-top)); 1447 SkIRect clipBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height()); 1448 SkImageFilter::Cache* cache = SkImageFilter::Cache::Create(); 1449 SkAutoUnref aur(cache); 1450 SkImageFilter::Context ctx(matrix, clipBounds, cache); 1451 if (filter_texture(this, fContext, texture, filter, w, h, ctx, &filteredBitmap, 1452 &offset)) { 1453 texture = (GrTexture*) filteredBitmap.getTexture(); 1454 w = filteredBitmap.width(); 1455 h = filteredBitmap.height(); 1456 left += offset.x(); 1457 top += offset.y(); 1458 } else { 1459 return; 1460 } 1461 } 1462 1463 GrPaint grPaint; 1464 grPaint.addColorTextureEffect(texture, SkMatrix::I()); 1465 1466 SkPaint2GrPaintNoShader(this->context(), paint, true, false, &grPaint); 1467 1468 fContext->drawRectToRect(grPaint, 1469 SkRect::MakeXYWH(SkIntToScalar(left), 1470 SkIntToScalar(top), 1471 SkIntToScalar(w), 1472 SkIntToScalar(h)), 1473 SkRect::MakeXYWH(0, 1474 0, 1475 SK_Scalar1 * w / texture->width(), 1476 SK_Scalar1 * h / texture->height())); 1477} 1478 1479void SkGpuDevice::drawBitmapRect(const SkDraw& origDraw, const SkBitmap& bitmap, 1480 const SkRect* src, const SkRect& dst, 1481 const SkPaint& paint, 1482 SkCanvas::DrawBitmapRectFlags flags) { 1483 SkMatrix matrix; 1484 SkRect bitmapBounds, tmpSrc; 1485 1486 bitmapBounds.set(0, 0, 1487 SkIntToScalar(bitmap.width()), 1488 SkIntToScalar(bitmap.height())); 1489 1490 // Compute matrix from the two rectangles 1491 if (NULL != src) { 1492 tmpSrc = *src; 1493 } else { 1494 tmpSrc = bitmapBounds; 1495 } 1496 1497 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit); 1498 1499 // clip the tmpSrc to the bounds of the bitmap. No check needed if src==null. 1500 if (NULL != src) { 1501 if (!bitmapBounds.contains(tmpSrc)) { 1502 if (!tmpSrc.intersect(bitmapBounds)) { 1503 return; // nothing to draw 1504 } 1505 } 1506 } 1507 1508 SkRect tmpDst; 1509 matrix.mapRect(&tmpDst, tmpSrc); 1510 1511 SkTCopyOnFirstWrite<SkDraw> draw(origDraw); 1512 if (0 != tmpDst.fLeft || 0 != tmpDst.fTop) { 1513 // Translate so that tempDst's top left is at the origin. 1514 matrix = *origDraw.fMatrix; 1515 matrix.preTranslate(tmpDst.fLeft, tmpDst.fTop); 1516 draw.writable()->fMatrix = &matrix; 1517 } 1518 SkSize dstSize; 1519 dstSize.fWidth = tmpDst.width(); 1520 dstSize.fHeight = tmpDst.height(); 1521 1522 this->drawBitmapCommon(*draw, bitmap, &tmpSrc, &dstSize, paint, flags); 1523} 1524 1525void SkGpuDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device, 1526 int x, int y, const SkPaint& paint) { 1527 // clear of the source device must occur before CHECK_SHOULD_DRAW 1528 SkGpuDevice* dev = static_cast<SkGpuDevice*>(device); 1529 if (dev->fNeedClear) { 1530 // TODO: could check here whether we really need to draw at all 1531 dev->clear(0x0); 1532 } 1533 1534 // drawDevice is defined to be in device coords. 1535 CHECK_SHOULD_DRAW(draw, true); 1536 1537 GrRenderTarget* devRT = dev->accessRenderTarget(); 1538 GrTexture* devTex; 1539 if (NULL == (devTex = devRT->asTexture())) { 1540 return; 1541 } 1542 1543 const SkBitmap& bm = dev->accessBitmap(false); 1544 int w = bm.width(); 1545 int h = bm.height(); 1546 1547 SkImageFilter* filter = paint.getImageFilter(); 1548 // This bitmap will own the filtered result as a texture. 1549 SkBitmap filteredBitmap; 1550 1551 if (NULL != filter) { 1552 SkIPoint offset = SkIPoint::Make(0, 0); 1553 SkMatrix matrix(*draw.fMatrix); 1554 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y)); 1555 SkIRect clipBounds = SkIRect::MakeWH(devTex->width(), devTex->height()); 1556 SkImageFilter::Cache* cache = SkImageFilter::Cache::Create(); 1557 SkAutoUnref aur(cache); 1558 SkImageFilter::Context ctx(matrix, clipBounds, cache); 1559 if (filter_texture(this, fContext, devTex, filter, w, h, ctx, &filteredBitmap, 1560 &offset)) { 1561 devTex = filteredBitmap.getTexture(); 1562 w = filteredBitmap.width(); 1563 h = filteredBitmap.height(); 1564 x += offset.fX; 1565 y += offset.fY; 1566 } else { 1567 return; 1568 } 1569 } 1570 1571 GrPaint grPaint; 1572 grPaint.addColorTextureEffect(devTex, SkMatrix::I()); 1573 1574 SkPaint2GrPaintNoShader(this->context(), paint, true, false, &grPaint); 1575 1576 SkRect dstRect = SkRect::MakeXYWH(SkIntToScalar(x), 1577 SkIntToScalar(y), 1578 SkIntToScalar(w), 1579 SkIntToScalar(h)); 1580 1581 // The device being drawn may not fill up its texture (e.g. saveLayer uses approximate 1582 // scratch texture). 1583 SkRect srcRect = SkRect::MakeWH(SK_Scalar1 * w / devTex->width(), 1584 SK_Scalar1 * h / devTex->height()); 1585 1586 fContext->drawRectToRect(grPaint, dstRect, srcRect); 1587} 1588 1589bool SkGpuDevice::canHandleImageFilter(const SkImageFilter* filter) { 1590 return filter->canFilterImageGPU(); 1591} 1592 1593bool SkGpuDevice::filterImage(const SkImageFilter* filter, const SkBitmap& src, 1594 const SkImageFilter::Context& ctx, 1595 SkBitmap* result, SkIPoint* offset) { 1596 // want explicitly our impl, so guard against a subclass of us overriding it 1597 if (!this->SkGpuDevice::canHandleImageFilter(filter)) { 1598 return false; 1599 } 1600 1601 SkAutoLockPixels alp(src, !src.getTexture()); 1602 if (!src.getTexture() && !src.readyToDraw()) { 1603 return false; 1604 } 1605 1606 GrTexture* texture; 1607 // We assume here that the filter will not attempt to tile the src. Otherwise, this cache lookup 1608 // must be pushed upstack. 1609 SkAutoCachedTexture act(this, src, NULL, &texture); 1610 1611 return filter_texture(this, fContext, texture, filter, src.width(), src.height(), ctx, 1612 result, offset); 1613} 1614 1615/////////////////////////////////////////////////////////////////////////////// 1616 1617// must be in SkCanvas::VertexMode order 1618static const GrPrimitiveType gVertexMode2PrimitiveType[] = { 1619 kTriangles_GrPrimitiveType, 1620 kTriangleStrip_GrPrimitiveType, 1621 kTriangleFan_GrPrimitiveType, 1622}; 1623 1624void SkGpuDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode, 1625 int vertexCount, const SkPoint vertices[], 1626 const SkPoint texs[], const SkColor colors[], 1627 SkXfermode* xmode, 1628 const uint16_t indices[], int indexCount, 1629 const SkPaint& paint) { 1630 CHECK_SHOULD_DRAW(draw, false); 1631 1632 // If both textures and vertex-colors are NULL, strokes hairlines with the paint's color. 1633 if ((NULL == texs || NULL == paint.getShader()) && NULL == colors) { 1634 texs = NULL; 1635 SkPaint copy(paint); 1636 copy.setStyle(SkPaint::kStroke_Style); 1637 copy.setStrokeWidth(0); 1638 1639 VertState state(vertexCount, indices, indexCount); 1640 VertState::Proc vertProc = state.chooseProc(vmode); 1641 1642 SkPoint* pts = new SkPoint[vertexCount * 6]; 1643 int i = 0; 1644 while (vertProc(&state)) { 1645 pts[i] = vertices[state.f0]; 1646 pts[i + 1] = vertices[state.f1]; 1647 pts[i + 2] = vertices[state.f1]; 1648 pts[i + 3] = vertices[state.f2]; 1649 pts[i + 4] = vertices[state.f2]; 1650 pts[i + 5] = vertices[state.f0]; 1651 i += 6; 1652 } 1653 draw.drawPoints(SkCanvas::kLines_PointMode, i, pts, copy, true); 1654 return; 1655 } 1656 1657 GrPaint grPaint; 1658 // we ignore the shader if texs is null. 1659 if (NULL == texs) { 1660 SkPaint2GrPaintNoShader(this->context(), paint, false, NULL == colors, &grPaint); 1661 } else { 1662 SkPaint2GrPaintShader(this->context(), paint, NULL == colors, &grPaint); 1663 } 1664 1665 if (NULL != xmode && NULL != texs && NULL != colors) { 1666 if (!SkXfermode::IsMode(xmode, SkXfermode::kModulate_Mode)) { 1667 SkDebugf("Unsupported vertex-color/texture xfer mode.\n"); 1668#if 0 1669 return 1670#endif 1671 } 1672 } 1673 1674 SkAutoSTMalloc<128, GrColor> convertedColors(0); 1675 if (NULL != colors) { 1676 // need to convert byte order and from non-PM to PM 1677 convertedColors.reset(vertexCount); 1678 SkColor color; 1679 for (int i = 0; i < vertexCount; ++i) { 1680 color = colors[i]; 1681 if (paint.getAlpha() != 255) { 1682 color = SkColorSetA(color, SkMulDiv255Round(SkColorGetA(color), paint.getAlpha())); 1683 } 1684 convertedColors[i] = SkColor2GrColor(color); 1685 } 1686 colors = convertedColors.get(); 1687 } 1688 fContext->drawVertices(grPaint, 1689 gVertexMode2PrimitiveType[vmode], 1690 vertexCount, 1691 vertices, 1692 texs, 1693 colors, 1694 indices, 1695 indexCount); 1696} 1697 1698/////////////////////////////////////////////////////////////////////////////// 1699 1700void SkGpuDevice::drawText(const SkDraw& draw, const void* text, 1701 size_t byteLength, SkScalar x, SkScalar y, 1702 const SkPaint& paint) { 1703 CHECK_SHOULD_DRAW(draw, false); 1704 1705 if (fMainTextContext->canDraw(paint)) { 1706 GrPaint grPaint; 1707 SkPaint2GrPaintShader(this->context(), paint, true, &grPaint); 1708 1709 SkDEBUGCODE(this->validate();) 1710 1711 fMainTextContext->drawText(grPaint, paint, (const char *)text, byteLength, x, y); 1712 } else if (fFallbackTextContext && fFallbackTextContext->canDraw(paint)) { 1713 GrPaint grPaint; 1714 SkPaint2GrPaintShader(this->context(), paint, true, &grPaint); 1715 1716 SkDEBUGCODE(this->validate();) 1717 1718 fFallbackTextContext->drawText(grPaint, paint, (const char *)text, byteLength, x, y); 1719 } else { 1720 // this guy will just call our drawPath() 1721 draw.drawText_asPaths((const char*)text, byteLength, x, y, paint); 1722 } 1723} 1724 1725void SkGpuDevice::drawPosText(const SkDraw& draw, const void* text, 1726 size_t byteLength, const SkScalar pos[], 1727 SkScalar constY, int scalarsPerPos, 1728 const SkPaint& paint) { 1729 CHECK_SHOULD_DRAW(draw, false); 1730 1731 if (fMainTextContext->canDraw(paint)) { 1732 GrPaint grPaint; 1733 SkPaint2GrPaintShader(this->context(), paint, true, &grPaint); 1734 1735 SkDEBUGCODE(this->validate();) 1736 1737 fMainTextContext->drawPosText(grPaint, paint, (const char *)text, byteLength, pos, 1738 constY, scalarsPerPos); 1739 } else if (fFallbackTextContext && fFallbackTextContext->canDraw(paint)) { 1740 GrPaint grPaint; 1741 SkPaint2GrPaintShader(this->context(), paint, true, &grPaint); 1742 1743 SkDEBUGCODE(this->validate();) 1744 1745 fFallbackTextContext->drawPosText(grPaint, paint, (const char *)text, byteLength, pos, 1746 constY, scalarsPerPos); 1747 } else { 1748 draw.drawPosText_asPaths((const char*)text, byteLength, pos, constY, 1749 scalarsPerPos, paint); 1750 } 1751} 1752 1753void SkGpuDevice::drawTextOnPath(const SkDraw& draw, const void* text, 1754 size_t len, const SkPath& path, 1755 const SkMatrix* m, const SkPaint& paint) { 1756 CHECK_SHOULD_DRAW(draw, false); 1757 1758 SkASSERT(draw.fDevice == this); 1759 draw.drawTextOnPath((const char*)text, len, path, m, paint); 1760} 1761 1762/////////////////////////////////////////////////////////////////////////////// 1763 1764bool SkGpuDevice::filterTextFlags(const SkPaint& paint, TextFlags* flags) { 1765 if (!paint.isLCDRenderText()) { 1766 // we're cool with the paint as is 1767 return false; 1768 } 1769 1770 if (paint.getShader() || 1771 paint.getXfermode() || // unless its srcover 1772 paint.getMaskFilter() || 1773 paint.getRasterizer() || 1774 paint.getColorFilter() || 1775 paint.getPathEffect() || 1776 paint.isFakeBoldText() || 1777 paint.getStyle() != SkPaint::kFill_Style) { 1778 // turn off lcd 1779 flags->fFlags = paint.getFlags() & ~SkPaint::kLCDRenderText_Flag; 1780 flags->fHinting = paint.getHinting(); 1781 return true; 1782 } 1783 // we're cool with the paint as is 1784 return false; 1785} 1786 1787void SkGpuDevice::flush() { 1788 DO_DEFERRED_CLEAR(); 1789 fContext->resolveRenderTarget(fRenderTarget); 1790} 1791 1792/////////////////////////////////////////////////////////////////////////////// 1793 1794SkBaseDevice* SkGpuDevice::onCreateDevice(const SkImageInfo& info, Usage usage) { 1795 GrTextureDesc desc; 1796 desc.fConfig = fRenderTarget->config(); 1797 desc.fFlags = kRenderTarget_GrTextureFlagBit; 1798 desc.fWidth = info.width(); 1799 desc.fHeight = info.height(); 1800 desc.fSampleCnt = fRenderTarget->numSamples(); 1801 1802 SkAutoTUnref<GrTexture> texture; 1803 // Skia's convention is to only clear a device if it is non-opaque. 1804 unsigned flags = info.isOpaque() ? 0 : kNeedClear_Flag; 1805 1806#if CACHE_COMPATIBLE_DEVICE_TEXTURES 1807 // layers are never draw in repeat modes, so we can request an approx 1808 // match and ignore any padding. 1809 flags |= kCached_Flag; 1810 const GrContext::ScratchTexMatch match = (kSaveLayer_Usage == usage) ? 1811 GrContext::kApprox_ScratchTexMatch : 1812 GrContext::kExact_ScratchTexMatch; 1813 texture.reset(fContext->lockAndRefScratchTexture(desc, match)); 1814#else 1815 texture.reset(fContext->createUncachedTexture(desc, NULL, 0)); 1816#endif 1817 if (NULL != texture.get()) { 1818 return SkGpuDevice::Create(texture, flags); 1819 } else { 1820 GrPrintf("---- failed to create compatible device texture [%d %d]\n", 1821 info.width(), info.height()); 1822 return NULL; 1823 } 1824} 1825 1826SkSurface* SkGpuDevice::newSurface(const SkImageInfo& info) { 1827 return SkSurface::NewRenderTarget(fContext, info, fRenderTarget->numSamples()); 1828} 1829 1830void SkGpuDevice::EXPERIMENTAL_optimize(SkPicture* picture) { 1831 SkPicture::AccelData::Key key = GPUAccelData::ComputeAccelDataKey(); 1832 1833 const SkPicture::AccelData* existing = picture->EXPERIMENTAL_getAccelData(key); 1834 if (NULL != existing) { 1835 return; 1836 } 1837 1838 SkAutoTUnref<GPUAccelData> data(SkNEW_ARGS(GPUAccelData, (key))); 1839 1840 picture->EXPERIMENTAL_addAccelData(data); 1841 1842 GatherGPUInfo(picture, data); 1843} 1844 1845static void wrap_texture(GrTexture* texture, int width, int height, SkBitmap* result) { 1846 SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); 1847 result->setInfo(info); 1848 result->setPixelRef(SkNEW_ARGS(SkGrPixelRef, (info, texture)))->unref(); 1849} 1850 1851void SkGpuDevice::EXPERIMENTAL_purge(SkPicture* picture) { 1852 1853} 1854 1855bool SkGpuDevice::EXPERIMENTAL_drawPicture(SkCanvas* canvas, SkPicture* picture) { 1856 1857 SkPicture::AccelData::Key key = GPUAccelData::ComputeAccelDataKey(); 1858 1859 const SkPicture::AccelData* data = picture->EXPERIMENTAL_getAccelData(key); 1860 if (NULL == data) { 1861 return false; 1862 } 1863 1864 const GPUAccelData *gpuData = static_cast<const GPUAccelData*>(data); 1865 1866 if (0 == gpuData->numSaveLayers()) { 1867 return false; 1868 } 1869 1870 SkAutoTArray<bool> pullForward(gpuData->numSaveLayers()); 1871 for (int i = 0; i < gpuData->numSaveLayers(); ++i) { 1872 pullForward[i] = false; 1873 } 1874 1875 SkRect clipBounds; 1876 if (!canvas->getClipBounds(&clipBounds)) { 1877 return true; 1878 } 1879 SkIRect query; 1880 clipBounds.roundOut(&query); 1881 1882 const SkPicture::OperationList& ops = picture->EXPERIMENTAL_getActiveOps(query); 1883 1884 // This code pre-renders the entire layer since it will be cached and potentially 1885 // reused with different clips (e.g., in different tiles). Because of this the 1886 // clip will not be limiting the size of the pre-rendered layer. kSaveLayerMaxSize 1887 // is used to limit which clips are pre-rendered. 1888 static const int kSaveLayerMaxSize = 256; 1889 1890 if (ops.valid()) { 1891 // In this case the picture has been generated with a BBH so we use 1892 // the BBH to limit the pre-rendering to just the layers needed to cover 1893 // the region being drawn 1894 for (int i = 0; i < ops.numOps(); ++i) { 1895 uint32_t offset = ops.offset(i); 1896 1897 // For now we're saving all the layers in the GPUAccelData so they 1898 // can be nested. Additionally, the nested layers appear before 1899 // their parent in the list. 1900 for (int j = 0 ; j < gpuData->numSaveLayers(); ++j) { 1901 const GPUAccelData::SaveLayerInfo& info = gpuData->saveLayerInfo(j); 1902 1903 if (pullForward[j]) { 1904 continue; // already pulling forward 1905 } 1906 1907 if (offset < info.fSaveLayerOpID || offset > info.fRestoreOpID) { 1908 continue; // the op isn't in this range 1909 } 1910 1911 // TODO: once this code is more stable unsuitable layers can 1912 // just be omitted during the optimization stage 1913 if (!info.fValid || 1914 kSaveLayerMaxSize < info.fSize.fWidth || 1915 kSaveLayerMaxSize < info.fSize.fHeight || 1916 info.fIsNested) { 1917 continue; // this layer is unsuitable 1918 } 1919 1920 pullForward[j] = true; 1921 } 1922 } 1923 } else { 1924 // In this case there is no BBH associated with the picture. Pre-render 1925 // all the layers that intersect the drawn region 1926 for (int j = 0; j < gpuData->numSaveLayers(); ++j) { 1927 const GPUAccelData::SaveLayerInfo& info = gpuData->saveLayerInfo(j); 1928 1929 SkIRect layerRect = SkIRect::MakeXYWH(info.fOffset.fX, 1930 info.fOffset.fY, 1931 info.fSize.fWidth, 1932 info.fSize.fHeight); 1933 1934 if (!SkIRect::Intersects(query, layerRect)) { 1935 continue; 1936 } 1937 1938 // TODO: once this code is more stable unsuitable layers can 1939 // just be omitted during the optimization stage 1940 if (!info.fValid || 1941 kSaveLayerMaxSize < info.fSize.fWidth || 1942 kSaveLayerMaxSize < info.fSize.fHeight || 1943 info.fIsNested) { 1944 continue; 1945 } 1946 1947 pullForward[j] = true; 1948 } 1949 } 1950 1951 SkPicturePlayback::PlaybackReplacements replacements; 1952 1953 for (int i = 0; i < gpuData->numSaveLayers(); ++i) { 1954 if (pullForward[i]) { 1955 GrCachedLayer* layer = fContext->getLayerCache()->findLayerOrCreate(picture, i); 1956 1957 const GPUAccelData::SaveLayerInfo& info = gpuData->saveLayerInfo(i); 1958 1959 if (NULL != picture->fPlayback) { 1960 SkPicturePlayback::PlaybackReplacements::ReplacementInfo* layerInfo = 1961 replacements.push(); 1962 layerInfo->fStart = info.fSaveLayerOpID; 1963 layerInfo->fStop = info.fRestoreOpID; 1964 layerInfo->fPos = info.fOffset; 1965 1966 GrTextureDesc desc; 1967 desc.fFlags = kRenderTarget_GrTextureFlagBit; 1968 desc.fWidth = info.fSize.fWidth; 1969 desc.fHeight = info.fSize.fHeight; 1970 desc.fConfig = kSkia8888_GrPixelConfig; 1971 // TODO: need to deal with sample count 1972 1973 bool bNeedsRendering = true; 1974 1975 // This just uses scratch textures and doesn't cache the texture. 1976 // This can yield a lot of re-rendering 1977 if (NULL == layer->getTexture()) { 1978 layer->setTexture(fContext->lockAndRefScratchTexture(desc, 1979 GrContext::kApprox_ScratchTexMatch)); 1980 if (NULL == layer->getTexture()) { 1981 continue; 1982 } 1983 } else { 1984 bNeedsRendering = false; 1985 } 1986 1987 layerInfo->fBM = SkNEW(SkBitmap); 1988 wrap_texture(layer->getTexture(), desc.fWidth, desc.fHeight, layerInfo->fBM); 1989 1990 SkASSERT(info.fPaint); 1991 layerInfo->fPaint = info.fPaint; 1992 1993 if (bNeedsRendering) { 1994 SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTargetDirect( 1995 layer->getTexture()->asRenderTarget())); 1996 1997 SkCanvas* canvas = surface->getCanvas(); 1998 1999 canvas->setMatrix(info.fCTM); 2000 canvas->clear(SK_ColorTRANSPARENT); 2001 2002 picture->fPlayback->setDrawLimits(info.fSaveLayerOpID, info.fRestoreOpID); 2003 picture->fPlayback->draw(*canvas, NULL); 2004 picture->fPlayback->setDrawLimits(0, 0); 2005 canvas->flush(); 2006 } 2007 } 2008 } 2009 } 2010 2011 // Playback using new layers 2012 picture->fPlayback->setReplacements(&replacements); 2013 picture->fPlayback->draw(*canvas, NULL); 2014 picture->fPlayback->setReplacements(NULL); 2015 2016 for (int i = 0; i < gpuData->numSaveLayers(); ++i) { 2017 GrCachedLayer* layer = fContext->getLayerCache()->findLayerOrCreate(picture, i); 2018 2019 if (NULL != layer->getTexture()) { 2020 fContext->unlockScratchTexture(layer->getTexture()); 2021 layer->setTexture(NULL); 2022 } 2023 } 2024 2025 return true; 2026} 2027