2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkGpuDevice.h"
10 #include "effects/GrBicubicEffect.h"
11 #include "effects/GrTextureDomain.h"
12 #include "effects/GrSimpleTextureEffect.h"
14 #include "GrContext.h"
15 #include "GrBitmapTextContext.h"
16 #include "GrDistanceFieldTextContext.h"
17 #include "GrLayerCache.h"
18 #include "GrPictureUtils.h"
20 #include "SkGrTexturePixelRef.h"
22 #include "SkBounder.h"
23 #include "SkColorFilter.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"
33 #include "SkSurface.h"
36 #include "SkErrorInternals.h"
38 #define CACHE_COMPATIBLE_DEVICE_TEXTURES 1
41 extern bool (*gShouldDrawProc)();
42 #define CHECK_SHOULD_DRAW(draw, forceI) \
44 if (gShouldDrawProc && !gShouldDrawProc()) return; \
45 this->prepareDraw(draw, forceI); \
48 #define CHECK_SHOULD_DRAW(draw, forceI) this->prepareDraw(draw, forceI)
51 // This constant represents the screen alignment criterion in texels for
52 // requiring texture domain clamping to prevent color bleeding when drawing
53 // a sub region of a larger source image.
54 #define COLOR_BLEED_TOLERANCE 0.001f
56 #define DO_DEFERRED_CLEAR() \
59 this->clear(SK_ColorTRANSPARENT); \
63 ///////////////////////////////////////////////////////////////////////////////
65 #define CHECK_FOR_ANNOTATION(paint) \
66 do { if (paint.getAnnotation()) { return; } } while (0)
68 ///////////////////////////////////////////////////////////////////////////////
71 class SkGpuDevice::SkAutoCachedTexture : public ::SkNoncopyable {
78 SkAutoCachedTexture(SkGpuDevice* device,
79 const SkBitmap& bitmap,
80 const GrTextureParams* params,
84 SkASSERT(NULL != texture);
85 *texture = this->set(device, bitmap, params);
88 ~SkAutoCachedTexture() {
89 if (NULL != fTexture) {
90 GrUnlockAndUnrefCachedBitmapTexture(fTexture);
94 GrTexture* set(SkGpuDevice* device,
95 const SkBitmap& bitmap,
96 const GrTextureParams* params) {
97 if (NULL != fTexture) {
98 GrUnlockAndUnrefCachedBitmapTexture(fTexture);
102 GrTexture* result = (GrTexture*)bitmap.getTexture();
103 if (NULL == result) {
104 // Cannot return the native texture so look it up in our cache
105 fTexture = GrLockAndRefCachedBitmapTexture(device->context(), bitmap, params);
112 SkGpuDevice* fDevice;
116 ///////////////////////////////////////////////////////////////////////////////
118 struct GrSkDrawProcs : public SkDrawProcs {
121 GrTextContext* fTextContext;
122 GrFontScaler* fFontScaler; // cached in the skia glyphcache
125 ///////////////////////////////////////////////////////////////////////////////
127 static SkBitmap::Config grConfig2skConfig(GrPixelConfig config, bool* isOpaque) {
129 case kAlpha_8_GrPixelConfig:
131 return SkBitmap::kA8_Config;
132 case kRGB_565_GrPixelConfig:
134 return SkBitmap::kRGB_565_Config;
135 case kRGBA_4444_GrPixelConfig:
137 return SkBitmap::kARGB_4444_Config;
138 case kSkia8888_GrPixelConfig:
139 // we don't currently have a way of knowing whether
140 // a 8888 is opaque based on the config.
142 return SkBitmap::kARGB_8888_Config;
145 return SkBitmap::kNo_Config;
150 * GrRenderTarget does not know its opaqueness, only its config, so we have
151 * to make conservative guesses when we return an "equivalent" bitmap.
153 static SkBitmap make_bitmap(GrContext* context, GrRenderTarget* renderTarget) {
155 SkBitmap::Config config = grConfig2skConfig(renderTarget->config(), &isOpaque);
158 bitmap.setConfig(config, renderTarget->width(), renderTarget->height(), 0,
159 isOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
163 SkGpuDevice* SkGpuDevice::Create(GrSurface* surface, unsigned flags) {
164 SkASSERT(NULL != surface);
165 if (NULL == surface->asRenderTarget() || NULL == surface->getContext()) {
168 if (surface->asTexture()) {
169 return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asTexture(), flags));
171 return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asRenderTarget(), flags));
175 SkGpuDevice::SkGpuDevice(GrContext* context, GrTexture* texture, unsigned flags)
176 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
177 this->initFromRenderTarget(context, texture->asRenderTarget(), flags);
180 SkGpuDevice::SkGpuDevice(GrContext* context, GrRenderTarget* renderTarget, unsigned flags)
181 : SkBitmapDevice(make_bitmap(context, renderTarget)) {
182 this->initFromRenderTarget(context, renderTarget, flags);
185 void SkGpuDevice::initFromRenderTarget(GrContext* context,
186 GrRenderTarget* renderTarget,
193 bool useDFFonts = !!(flags & kDFFonts_Flag);
194 fMainTextContext = SkNEW_ARGS(GrDistanceFieldTextContext, (fContext, fLeakyProperties,
196 fFallbackTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
198 fRenderTarget = NULL;
199 fNeedClear = flags & kNeedClear_Flag;
201 SkASSERT(NULL != renderTarget);
202 fRenderTarget = renderTarget;
203 fRenderTarget->ref();
205 // Hold onto to the texture in the pixel ref (if there is one) because the texture holds a ref
206 // on the RT but not vice-versa.
207 // TODO: Remove this trickery once we figure out how to make SkGrPixelRef do this without
208 // busting chrome (for a currently unknown reason).
209 GrSurface* surface = fRenderTarget->asTexture();
210 if (NULL == surface) {
211 surface = fRenderTarget;
215 surface->asImageInfo(&info);
216 SkPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, surface, SkToBool(flags & kCached_Flag)));
218 this->setPixelRef(pr)->unref();
221 SkGpuDevice* SkGpuDevice::Create(GrContext* context, const SkImageInfo& origInfo,
223 if (kUnknown_SkColorType == origInfo.colorType() ||
224 origInfo.width() < 0 || origInfo.height() < 0) {
228 SkImageInfo info = origInfo;
229 // TODO: perhas we can loosen this check now that colortype is more detailed
230 // e.g. can we support both RGBA and BGRA here?
231 if (kRGB_565_SkColorType == info.colorType()) {
232 info.fAlphaType = kOpaque_SkAlphaType; // force this setting
234 info.fColorType = kN32_SkColorType;
235 if (kOpaque_SkAlphaType != info.alphaType()) {
236 info.fAlphaType = kPremul_SkAlphaType; // force this setting
241 desc.fFlags = kRenderTarget_GrTextureFlagBit;
242 desc.fWidth = info.width();
243 desc.fHeight = info.height();
244 desc.fConfig = SkImageInfo2GrPixelConfig(info);
245 desc.fSampleCnt = sampleCount;
247 SkAutoTUnref<GrTexture> texture(context->createUncachedTexture(desc, NULL, 0));
248 if (!texture.get()) {
252 return SkNEW_ARGS(SkGpuDevice, (context, texture.get()));
255 SkGpuDevice::~SkGpuDevice() {
260 delete fMainTextContext;
261 delete fFallbackTextContext;
263 // The GrContext takes a ref on the target. We don't want to cause the render
264 // target to be unnecessarily kept alive.
265 if (fContext->getRenderTarget() == fRenderTarget) {
266 fContext->setRenderTarget(NULL);
269 if (fContext->getClip() == &fClipData) {
270 fContext->setClip(NULL);
273 SkSafeUnref(fRenderTarget);
277 ///////////////////////////////////////////////////////////////////////////////
279 void SkGpuDevice::makeRenderTargetCurrent() {
281 fContext->setRenderTarget(fRenderTarget);
284 ///////////////////////////////////////////////////////////////////////////////
286 bool SkGpuDevice::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
290 // TODO: teach fRenderTarget to take ImageInfo directly to specify the src pixels
291 GrPixelConfig config = SkImageInfo2GrPixelConfig(dstInfo);
292 if (kUnknown_GrPixelConfig == config) {
297 if (kUnpremul_SkAlphaType == dstInfo.alphaType()) {
298 flags = GrContext::kUnpremul_PixelOpsFlag;
300 return fContext->readRenderTargetPixels(fRenderTarget, x, y, dstInfo.width(), dstInfo.height(),
301 config, dstPixels, dstRowBytes, flags);
304 bool SkGpuDevice::onWritePixels(const SkImageInfo& info, const void* pixels, size_t rowBytes,
306 // TODO: teach fRenderTarget to take ImageInfo directly to specify the src pixels
307 GrPixelConfig config = SkImageInfo2GrPixelConfig(info);
308 if (kUnknown_GrPixelConfig == config) {
312 if (kUnpremul_SkAlphaType == info.alphaType()) {
313 flags = GrContext::kUnpremul_PixelOpsFlag;
315 fRenderTarget->writePixels(x, y, info.width(), info.height(), config, pixels, rowBytes, flags);
317 // need to bump our genID for compatibility with clients that "know" we have a bitmap
318 this->onAccessBitmap().notifyPixelsChanged();
323 const SkBitmap& SkGpuDevice::onAccessBitmap() {
325 return INHERITED::onAccessBitmap();
328 void SkGpuDevice::onAttachToCanvas(SkCanvas* canvas) {
329 INHERITED::onAttachToCanvas(canvas);
331 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
332 fClipData.fClipStack = canvas->getClipStack();
335 void SkGpuDevice::onDetachFromCanvas() {
336 INHERITED::onDetachFromCanvas();
337 fClipData.fClipStack = NULL;
340 // call this every draw call, to ensure that the context reflects our state,
341 // and not the state from some other canvas/device
342 void SkGpuDevice::prepareDraw(const SkDraw& draw, bool forceIdentity) {
343 SkASSERT(NULL != fClipData.fClipStack);
345 fContext->setRenderTarget(fRenderTarget);
347 SkASSERT(draw.fClipStack && draw.fClipStack == fClipData.fClipStack);
350 fContext->setIdentityMatrix();
352 fContext->setMatrix(*draw.fMatrix);
354 fClipData.fOrigin = this->getOrigin();
356 fContext->setClip(&fClipData);
361 GrRenderTarget* SkGpuDevice::accessRenderTarget() {
363 return fRenderTarget;
366 ///////////////////////////////////////////////////////////////////////////////
368 SK_COMPILE_ASSERT(SkShader::kNone_BitmapType == 0, shader_type_mismatch);
369 SK_COMPILE_ASSERT(SkShader::kDefault_BitmapType == 1, shader_type_mismatch);
370 SK_COMPILE_ASSERT(SkShader::kRadial_BitmapType == 2, shader_type_mismatch);
371 SK_COMPILE_ASSERT(SkShader::kSweep_BitmapType == 3, shader_type_mismatch);
372 SK_COMPILE_ASSERT(SkShader::kTwoPointRadial_BitmapType == 4,
373 shader_type_mismatch);
374 SK_COMPILE_ASSERT(SkShader::kTwoPointConical_BitmapType == 5,
375 shader_type_mismatch);
376 SK_COMPILE_ASSERT(SkShader::kLinear_BitmapType == 6, shader_type_mismatch);
377 SK_COMPILE_ASSERT(SkShader::kLast_BitmapType == 6, shader_type_mismatch);
381 // converts a SkPaint to a GrPaint, ignoring the skPaint's shader
382 // justAlpha indicates that skPaint's alpha should be used rather than the color
383 // Callers may subsequently modify the GrPaint. Setting constantColor indicates
384 // that the final paint will draw the same color at every pixel. This allows
385 // an optimization where the the color filter can be applied to the skPaint's
386 // color once while converting to GrPaint and then ignored.
387 inline bool skPaint2GrPaintNoShader(SkGpuDevice* dev,
388 const SkPaint& skPaint,
393 grPaint->setDither(skPaint.isDither());
394 grPaint->setAntiAlias(skPaint.isAntiAlias());
396 SkXfermode::Coeff sm;
397 SkXfermode::Coeff dm;
399 SkXfermode* mode = skPaint.getXfermode();
400 GrEffectRef* xferEffect = NULL;
401 if (SkXfermode::AsNewEffectOrCoeff(mode, &xferEffect, &sm, &dm)) {
402 if (NULL != xferEffect) {
403 grPaint->addColorEffect(xferEffect)->unref();
404 sm = SkXfermode::kOne_Coeff;
405 dm = SkXfermode::kZero_Coeff;
408 //SkDEBUGCODE(SkDebugf("Unsupported xfer mode.\n");)
412 // Fall back to src-over
413 sm = SkXfermode::kOne_Coeff;
414 dm = SkXfermode::kISA_Coeff;
417 grPaint->setBlendFunc(sk_blend_to_grblend(sm), sk_blend_to_grblend(dm));
420 uint8_t alpha = skPaint.getAlpha();
421 grPaint->setColor(GrColorPackRGBA(alpha, alpha, alpha, alpha));
422 // justAlpha is currently set to true only if there is a texture,
423 // so constantColor should not also be true.
424 SkASSERT(!constantColor);
426 grPaint->setColor(SkColor2GrColor(skPaint.getColor()));
429 SkColorFilter* colorFilter = skPaint.getColorFilter();
430 if (NULL != colorFilter) {
431 // if the source color is a constant then apply the filter here once rather than per pixel
434 SkColor filtered = colorFilter->filterColor(skPaint.getColor());
435 grPaint->setColor(SkColor2GrColor(filtered));
437 SkAutoTUnref<GrEffectRef> effect(colorFilter->asNewEffect(dev->context()));
438 if (NULL != effect.get()) {
439 grPaint->addColorEffect(effect);
447 // This function is similar to skPaint2GrPaintNoShader but also converts
448 // skPaint's shader to a GrTexture/GrEffectStage if possible. The texture to
449 // be used is set on grPaint and returned in param act. constantColor has the
450 // same meaning as in skPaint2GrPaintNoShader.
451 inline bool skPaint2GrPaintShader(SkGpuDevice* dev,
452 const SkPaint& skPaint,
455 SkShader* shader = skPaint.getShader();
456 if (NULL == shader) {
457 return skPaint2GrPaintNoShader(dev, skPaint, false, constantColor, grPaint);
460 // SkShader::asNewEffect() may do offscreen rendering. Setup default drawing state and require
461 // the shader to set a render target .
462 GrContext::AutoWideOpenIdentityDraw awo(dev->context(), NULL);
464 // setup the shader as the first color effect on the paint
465 SkAutoTUnref<GrEffectRef> effect(shader->asNewEffect(dev->context(), skPaint));
466 if (NULL != effect.get()) {
467 grPaint->addColorEffect(effect);
468 // Now setup the rest of the paint.
469 return skPaint2GrPaintNoShader(dev, skPaint, true, false, grPaint);
471 // We still don't have SkColorShader::asNewEffect() implemented.
472 SkShader::GradientInfo info;
475 info.fColors = &color;
476 info.fColorOffsets = NULL;
477 info.fColorCount = 1;
478 if (SkShader::kColor_GradientType == shader->asAGradient(&info)) {
479 SkPaint copy(skPaint);
480 copy.setShader(NULL);
481 // modulate the paint alpha by the shader's solid color alpha
482 U8CPU newA = SkMulDiv255Round(SkColorGetA(color), copy.getAlpha());
483 copy.setColor(SkColorSetA(color, newA));
484 return skPaint2GrPaintNoShader(dev, copy, false, constantColor, grPaint);
492 ///////////////////////////////////////////////////////////////////////////////
494 SkBitmap::Config SkGpuDevice::config() const {
495 if (NULL == fRenderTarget) {
496 return SkBitmap::kNo_Config;
500 return grConfig2skConfig(fRenderTarget->config(), &isOpaque);
503 void SkGpuDevice::clear(SkColor color) {
504 SkIRect rect = SkIRect::MakeWH(this->width(), this->height());
505 fContext->clear(&rect, SkColor2GrColor(color), true, fRenderTarget);
509 void SkGpuDevice::drawPaint(const SkDraw& draw, const SkPaint& paint) {
510 CHECK_SHOULD_DRAW(draw, false);
513 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
517 fContext->drawPaint(grPaint);
520 // must be in SkCanvas::PointMode order
521 static const GrPrimitiveType gPointMode2PrimtiveType[] = {
522 kPoints_GrPrimitiveType,
523 kLines_GrPrimitiveType,
524 kLineStrip_GrPrimitiveType
527 void SkGpuDevice::drawPoints(const SkDraw& draw, SkCanvas::PointMode mode,
528 size_t count, const SkPoint pts[], const SkPaint& paint) {
529 CHECK_FOR_ANNOTATION(paint);
530 CHECK_SHOULD_DRAW(draw, false);
532 SkScalar width = paint.getStrokeWidth();
537 // we only handle hairlines and paints without path effects or mask filters,
538 // else we let the SkDraw call our drawPath()
539 if (width > 0 || paint.getPathEffect() || paint.getMaskFilter()) {
540 draw.drawPoints(mode, count, pts, paint, true);
545 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
549 fContext->drawVertices(grPaint,
550 gPointMode2PrimtiveType[mode],
559 ///////////////////////////////////////////////////////////////////////////////
561 void SkGpuDevice::drawRect(const SkDraw& draw, const SkRect& rect,
562 const SkPaint& paint) {
563 CHECK_FOR_ANNOTATION(paint);
564 CHECK_SHOULD_DRAW(draw, false);
566 bool doStroke = paint.getStyle() != SkPaint::kFill_Style;
567 SkScalar width = paint.getStrokeWidth();
570 We have special code for hairline strokes, miter-strokes, bevel-stroke
571 and fills. Anything else we just call our path code.
573 bool usePath = doStroke && width > 0 &&
574 (paint.getStrokeJoin() == SkPaint::kRound_Join ||
575 (paint.getStrokeJoin() == SkPaint::kBevel_Join && rect.isEmpty()));
576 // another two reasons we might need to call drawPath...
577 if (paint.getMaskFilter() || paint.getPathEffect()) {
580 if (!usePath && paint.isAntiAlias() && !fContext->getMatrix().rectStaysRect()) {
581 #if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
585 #if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
587 usePath = !fContext->getMatrix().preservesRightAngles();
591 // until we can both stroke and fill rectangles
592 if (paint.getStyle() == SkPaint::kStrokeAndFill_Style) {
599 this->drawPath(draw, path, paint, NULL, true);
604 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
609 fContext->drawRect(grPaint, rect);
611 SkStrokeRec stroke(paint);
612 fContext->drawRect(grPaint, rect, &stroke);
616 ///////////////////////////////////////////////////////////////////////////////
618 void SkGpuDevice::drawRRect(const SkDraw& draw, const SkRRect& rect,
619 const SkPaint& paint) {
620 CHECK_FOR_ANNOTATION(paint);
621 CHECK_SHOULD_DRAW(draw, false);
624 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
628 SkStrokeRec stroke(paint);
629 if (paint.getMaskFilter()) {
630 // try to hit the fast path for drawing filtered round rects
633 if (rect.transform(fContext->getMatrix(), &devRRect)) {
634 if (devRRect.allCornersCircular()) {
636 if (paint.getMaskFilter()->canFilterMaskGPU(devRRect.rect(),
637 draw.fClip->getBounds(),
638 fContext->getMatrix(),
641 maskRect.roundOut(&finalIRect);
642 if (draw.fClip->quickReject(finalIRect)) {
646 if (NULL != draw.fBounder && !draw.fBounder->doIRect(finalIRect)) {
650 if (paint.getMaskFilter()->directFilterRRectMaskGPU(fContext, &grPaint,
661 if (paint.getMaskFilter() || paint.getPathEffect()) {
664 this->drawPath(draw, path, paint, NULL, true);
668 fContext->drawRRect(grPaint, rect, stroke);
671 void SkGpuDevice::drawDRRect(const SkDraw& draw, const SkRRect& outer,
672 const SkRRect& inner, const SkPaint& paint) {
673 SkStrokeRec stroke(paint);
674 if (stroke.isFillStyle()) {
676 CHECK_FOR_ANNOTATION(paint);
677 CHECK_SHOULD_DRAW(draw, false);
680 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
684 if (NULL == paint.getMaskFilter() && NULL == paint.getPathEffect()) {
685 fContext->drawDRRect(grPaint, outer, inner);
691 path.addRRect(outer);
692 path.addRRect(inner);
693 path.setFillType(SkPath::kEvenOdd_FillType);
695 this->drawPath(draw, path, paint, NULL, true);
699 /////////////////////////////////////////////////////////////////////////////
701 void SkGpuDevice::drawOval(const SkDraw& draw, const SkRect& oval,
702 const SkPaint& paint) {
703 CHECK_FOR_ANNOTATION(paint);
704 CHECK_SHOULD_DRAW(draw, false);
706 bool usePath = false;
707 // some basic reasons we might need to call drawPath...
708 if (paint.getMaskFilter() || paint.getPathEffect()) {
715 this->drawPath(draw, path, paint, NULL, true);
720 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
723 SkStrokeRec stroke(paint);
725 fContext->drawOval(grPaint, oval, stroke);
728 #include "SkMaskFilter.h"
729 #include "SkBounder.h"
731 ///////////////////////////////////////////////////////////////////////////////
733 // helpers for applying mask filters
736 // Draw a mask using the supplied paint. Since the coverage/geometry
737 // is already burnt into the mask this boils down to a rect draw.
738 // Return true if the mask was successfully drawn.
739 bool draw_mask(GrContext* context, const SkRect& maskRect,
740 GrPaint* grp, GrTexture* mask) {
741 GrContext::AutoMatrix am;
742 if (!am.setIdentity(context, grp)) {
747 matrix.setTranslate(-maskRect.fLeft, -maskRect.fTop);
748 matrix.postIDiv(mask->width(), mask->height());
750 grp->addCoverageEffect(GrSimpleTextureEffect::Create(mask, matrix))->unref();
751 context->drawRect(*grp, maskRect);
755 bool draw_with_mask_filter(GrContext* context, const SkPath& devPath,
756 SkMaskFilter* filter, const SkRegion& clip, SkBounder* bounder,
757 GrPaint* grp, SkPaint::Style style) {
760 if (!SkDraw::DrawToMask(devPath, &clip.getBounds(), filter, &context->getMatrix(), &srcM,
761 SkMask::kComputeBoundsAndRenderImage_CreateMode, style)) {
764 SkAutoMaskFreeImage autoSrc(srcM.fImage);
766 if (!filter->filterMask(&dstM, srcM, context->getMatrix(), NULL)) {
769 // this will free-up dstM when we're done (allocated in filterMask())
770 SkAutoMaskFreeImage autoDst(dstM.fImage);
772 if (clip.quickReject(dstM.fBounds)) {
775 if (bounder && !bounder->doIRect(dstM.fBounds)) {
779 // we now have a device-aligned 8bit mask in dstM, ready to be drawn using
780 // the current clip (and identity matrix) and GrPaint settings
782 desc.fWidth = dstM.fBounds.width();
783 desc.fHeight = dstM.fBounds.height();
784 desc.fConfig = kAlpha_8_GrPixelConfig;
786 GrAutoScratchTexture ast(context, desc);
787 GrTexture* texture = ast.texture();
789 if (NULL == texture) {
792 texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig,
793 dstM.fImage, dstM.fRowBytes);
795 SkRect maskRect = SkRect::Make(dstM.fBounds);
797 return draw_mask(context, maskRect, grp, texture);
800 // Create a mask of 'devPath' and place the result in 'mask'. Return true on
801 // success; false otherwise.
802 bool create_mask_GPU(GrContext* context,
803 const SkRect& maskRect,
804 const SkPath& devPath,
805 const SkStrokeRec& stroke,
807 GrAutoScratchTexture* mask) {
809 desc.fFlags = kRenderTarget_GrTextureFlagBit;
810 desc.fWidth = SkScalarCeilToInt(maskRect.width());
811 desc.fHeight = SkScalarCeilToInt(maskRect.height());
812 // We actually only need A8, but it often isn't supported as a
813 // render target so default to RGBA_8888
814 desc.fConfig = kRGBA_8888_GrPixelConfig;
815 if (context->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
816 desc.fConfig = kAlpha_8_GrPixelConfig;
819 mask->set(context, desc);
820 if (NULL == mask->texture()) {
824 GrTexture* maskTexture = mask->texture();
825 SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height());
827 GrContext::AutoRenderTarget art(context, maskTexture->asRenderTarget());
828 GrContext::AutoClip ac(context, clipRect);
830 context->clear(NULL, 0x0, true);
834 tempPaint.setAntiAlias(true);
835 // AA uses the "coverage" stages on GrDrawTarget. Coverage with a dst
836 // blend coeff of zero requires dual source blending support in order
837 // to properly blend partially covered pixels. This means the AA
838 // code path may not be taken. So we use a dst blend coeff of ISA. We
839 // could special case AA draws to a dst surface with known alpha=0 to
840 // use a zero dst coeff when dual source blending isn't available.
841 tempPaint.setBlendFunc(kOne_GrBlendCoeff, kISC_GrBlendCoeff);
844 GrContext::AutoMatrix am;
846 // Draw the mask into maskTexture with the path's top-left at the origin using tempPaint.
848 translate.setTranslate(-maskRect.fLeft, -maskRect.fTop);
849 am.set(context, translate);
850 context->drawPath(tempPaint, devPath, stroke);
854 SkBitmap wrap_texture(GrTexture* texture) {
856 texture->asImageInfo(&info);
859 result.setConfig(info);
860 result.setPixelRef(SkNEW_ARGS(SkGrPixelRef, (info, texture)))->unref();
866 void SkGpuDevice::drawPath(const SkDraw& draw, const SkPath& origSrcPath,
867 const SkPaint& paint, const SkMatrix* prePathMatrix,
868 bool pathIsMutable) {
869 CHECK_FOR_ANNOTATION(paint);
870 CHECK_SHOULD_DRAW(draw, false);
873 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
877 // If we have a prematrix, apply it to the path, optimizing for the case
878 // where the original path can in fact be modified in place (even though
879 // its parameter type is const).
880 SkPath* pathPtr = const_cast<SkPath*>(&origSrcPath);
881 SkTLazy<SkPath> tmpPath;
882 SkTLazy<SkPath> effectPath;
885 SkPath* result = pathPtr;
887 if (!pathIsMutable) {
888 result = tmpPath.init();
889 pathIsMutable = true;
891 // should I push prePathMatrix on our MV stack temporarily, instead
892 // of applying it here? See SkDraw.cpp
893 pathPtr->transform(*prePathMatrix, result);
896 // at this point we're done with prePathMatrix
897 SkDEBUGCODE(prePathMatrix = (const SkMatrix*)0x50FF8001;)
899 SkStrokeRec stroke(paint);
900 SkPathEffect* pathEffect = paint.getPathEffect();
901 const SkRect* cullRect = NULL; // TODO: what is our bounds?
902 if (pathEffect && pathEffect->filterPath(effectPath.init(), *pathPtr, &stroke,
904 pathPtr = effectPath.get();
905 pathIsMutable = true;
908 if (paint.getMaskFilter()) {
909 if (!stroke.isHairlineStyle()) {
910 SkPath* strokedPath = pathIsMutable ? pathPtr : tmpPath.init();
911 if (stroke.applyToPath(strokedPath, *pathPtr)) {
912 pathPtr = strokedPath;
913 pathIsMutable = true;
914 stroke.setFillStyle();
918 // avoid possibly allocating a new path in transform if we can
919 SkPath* devPathPtr = pathIsMutable ? pathPtr : tmpPath.init();
921 // transform the path into device space
922 pathPtr->transform(fContext->getMatrix(), devPathPtr);
925 if (paint.getMaskFilter()->canFilterMaskGPU(devPathPtr->getBounds(),
926 draw.fClip->getBounds(),
927 fContext->getMatrix(),
929 // The context's matrix may change while creating the mask, so save the CTM here to
930 // pass to filterMaskGPU.
931 const SkMatrix ctm = fContext->getMatrix();
934 maskRect.roundOut(&finalIRect);
935 if (draw.fClip->quickReject(finalIRect)) {
939 if (NULL != draw.fBounder && !draw.fBounder->doIRect(finalIRect)) {
944 if (paint.getMaskFilter()->directFilterMaskGPU(fContext, &grPaint,
945 stroke, *devPathPtr)) {
946 // the mask filter was able to draw itself directly, so there's nothing
951 GrAutoScratchTexture mask;
953 if (create_mask_GPU(fContext, maskRect, *devPathPtr, stroke,
954 grPaint.isAntiAlias(), &mask)) {
957 if (paint.getMaskFilter()->filterMaskGPU(mask.texture(),
958 ctm, maskRect, &filtered, true)) {
959 // filterMaskGPU gives us ownership of a ref to the result
960 SkAutoTUnref<GrTexture> atu(filtered);
962 // If the scratch texture that we used as the filter src also holds the filter
963 // result then we must detach so that this texture isn't recycled for a later
965 if (filtered == mask.texture()) {
967 filtered->unref(); // detach transfers GrAutoScratchTexture's ref to us.
970 if (draw_mask(fContext, maskRect, &grPaint, filtered)) {
971 // This path is completely drawn
978 // draw the mask on the CPU - this is a fallthrough path in case the
980 SkPaint::Style style = stroke.isHairlineStyle() ? SkPaint::kStroke_Style :
981 SkPaint::kFill_Style;
982 draw_with_mask_filter(fContext, *devPathPtr, paint.getMaskFilter(),
983 *draw.fClip, draw.fBounder, &grPaint, style);
987 fContext->drawPath(grPaint, *pathPtr, stroke);
990 static const int kBmpSmallTileSize = 1 << 10;
992 static inline int get_tile_count(const SkIRect& srcRect, int tileSize) {
993 int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1;
994 int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1;
995 return tilesX * tilesY;
998 static int determine_tile_size(const SkBitmap& bitmap, const SkIRect& src, int maxTileSize) {
999 if (maxTileSize <= kBmpSmallTileSize) {
1003 size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize);
1004 size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize);
1006 maxTileTotalTileSize *= maxTileSize * maxTileSize;
1007 smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize;
1009 if (maxTileTotalTileSize > 2 * smallTotalTileSize) {
1010 return kBmpSmallTileSize;
1016 // Given a bitmap, an optional src rect, and a context with a clip and matrix determine what
1017 // pixels from the bitmap are necessary.
1018 static void determine_clipped_src_rect(const GrContext* context,
1019 const SkBitmap& bitmap,
1020 const SkRect* srcRectPtr,
1021 SkIRect* clippedSrcIRect) {
1022 const GrClipData* clip = context->getClip();
1023 clip->getConservativeBounds(context->getRenderTarget(), clippedSrcIRect, NULL);
1025 if (!context->getMatrix().invert(&inv)) {
1026 clippedSrcIRect->setEmpty();
1029 SkRect clippedSrcRect = SkRect::Make(*clippedSrcIRect);
1030 inv.mapRect(&clippedSrcRect);
1031 if (NULL != srcRectPtr) {
1032 // we've setup src space 0,0 to map to the top left of the src rect.
1033 clippedSrcRect.offset(srcRectPtr->fLeft, srcRectPtr->fTop);
1034 if (!clippedSrcRect.intersect(*srcRectPtr)) {
1035 clippedSrcIRect->setEmpty();
1039 clippedSrcRect.roundOut(clippedSrcIRect);
1040 SkIRect bmpBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1041 if (!clippedSrcIRect->intersect(bmpBounds)) {
1042 clippedSrcIRect->setEmpty();
1046 bool SkGpuDevice::shouldTileBitmap(const SkBitmap& bitmap,
1047 const GrTextureParams& params,
1048 const SkRect* srcRectPtr,
1051 SkIRect* clippedSrcRect) const {
1052 // if bitmap is explictly texture backed then just use the texture
1053 if (NULL != bitmap.getTexture()) {
1057 // if it's larger than the max tile size, then we have no choice but tiling.
1058 if (bitmap.width() > maxTileSize || bitmap.height() > maxTileSize) {
1059 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1060 *tileSize = determine_tile_size(bitmap, *clippedSrcRect, maxTileSize);
1064 if (bitmap.width() * bitmap.height() < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
1068 // if the entire texture is already in our cache then no reason to tile it
1069 if (GrIsBitmapInCache(fContext, bitmap, ¶ms)) {
1073 // At this point we know we could do the draw by uploading the entire bitmap
1074 // as a texture. However, if the texture would be large compared to the
1075 // cache size and we don't require most of it for this draw then tile to
1076 // reduce the amount of upload and cache spill.
1078 // assumption here is that sw bitmap size is a good proxy for its size as
1080 size_t bmpSize = bitmap.getSize();
1082 fContext->getTextureCacheLimits(NULL, &cacheSize);
1083 if (bmpSize < cacheSize / 2) {
1087 // Figure out how much of the src we will need based on the src rect and clipping.
1088 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1089 *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
1090 size_t usedTileBytes = get_tile_count(*clippedSrcRect, kBmpSmallTileSize) *
1091 kBmpSmallTileSize * kBmpSmallTileSize;
1093 return usedTileBytes < 2 * bmpSize;
1096 void SkGpuDevice::drawBitmap(const SkDraw& origDraw,
1097 const SkBitmap& bitmap,
1099 const SkPaint& paint) {
1101 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1102 if (!m.isIdentity()) {
1103 concat.setConcat(*draw->fMatrix, m);
1104 draw.writable()->fMatrix = &concat;
1106 this->drawBitmapCommon(*draw, bitmap, NULL, NULL, paint, SkCanvas::kNone_DrawBitmapRectFlag);
1109 // This method outsets 'iRect' by 'outset' all around and then clamps its extents to
1110 // 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
1111 // of 'iRect' for all possible outsets/clamps.
1112 static inline void clamped_outset_with_offset(SkIRect* iRect,
1115 const SkIRect& clamp) {
1116 iRect->outset(outset, outset);
1118 int leftClampDelta = clamp.fLeft - iRect->fLeft;
1119 if (leftClampDelta > 0) {
1120 offset->fX -= outset - leftClampDelta;
1121 iRect->fLeft = clamp.fLeft;
1123 offset->fX -= outset;
1126 int topClampDelta = clamp.fTop - iRect->fTop;
1127 if (topClampDelta > 0) {
1128 offset->fY -= outset - topClampDelta;
1129 iRect->fTop = clamp.fTop;
1131 offset->fY -= outset;
1134 if (iRect->fRight > clamp.fRight) {
1135 iRect->fRight = clamp.fRight;
1137 if (iRect->fBottom > clamp.fBottom) {
1138 iRect->fBottom = clamp.fBottom;
1142 void SkGpuDevice::drawBitmapCommon(const SkDraw& draw,
1143 const SkBitmap& bitmap,
1144 const SkRect* srcRectPtr,
1145 const SkSize* dstSizePtr,
1146 const SkPaint& paint,
1147 SkCanvas::DrawBitmapRectFlags flags) {
1148 CHECK_SHOULD_DRAW(draw, false);
1152 // If there is no src rect, or the src rect contains the entire bitmap then we're effectively
1153 // in the (easier) bleed case, so update flags.
1154 if (NULL == srcRectPtr) {
1155 SkScalar w = SkIntToScalar(bitmap.width());
1156 SkScalar h = SkIntToScalar(bitmap.height());
1158 dstSize.fHeight = h;
1159 srcRect.set(0, 0, w, h);
1160 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1162 SkASSERT(NULL != dstSizePtr);
1163 srcRect = *srcRectPtr;
1164 dstSize = *dstSizePtr;
1165 if (srcRect.fLeft <= 0 && srcRect.fTop <= 0 &&
1166 srcRect.fRight >= bitmap.width() && srcRect.fBottom >= bitmap.height()) {
1167 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1171 if (paint.getMaskFilter()){
1172 // Convert the bitmap to a shader so that the rect can be drawn
1173 // through drawRect, which supports mask filters.
1174 SkBitmap tmp; // subset of bitmap, if necessary
1175 const SkBitmap* bitmapPtr = &bitmap;
1177 if (NULL != srcRectPtr) {
1178 localM.setTranslate(-srcRectPtr->fLeft, -srcRectPtr->fTop);
1179 localM.postScale(dstSize.fWidth / srcRectPtr->width(),
1180 dstSize.fHeight / srcRectPtr->height());
1181 // In bleed mode we position and trim the bitmap based on the src rect which is
1182 // already accounted for in 'm' and 'srcRect'. In clamp mode we need to chop out
1183 // the desired portion of the bitmap and then update 'm' and 'srcRect' to
1185 if (!(SkCanvas::kBleed_DrawBitmapRectFlag & flags)) {
1187 srcRect.roundOut(&iSrc);
1189 SkPoint offset = SkPoint::Make(SkIntToScalar(iSrc.fLeft),
1190 SkIntToScalar(iSrc.fTop));
1192 if (!bitmap.extractSubset(&tmp, iSrc)) {
1193 return; // extraction failed
1196 srcRect.offset(-offset.fX, -offset.fY);
1198 // The source rect has changed so update the matrix
1199 localM.preTranslate(offset.fX, offset.fY);
1205 SkPaint paintWithShader(paint);
1206 paintWithShader.setShader(SkShader::CreateBitmapShader(*bitmapPtr,
1207 SkShader::kClamp_TileMode, SkShader::kClamp_TileMode, &localM))->unref();
1208 SkRect dstRect = {0, 0, dstSize.fWidth, dstSize.fHeight};
1209 this->drawRect(draw, dstRect, paintWithShader);
1214 // If there is no mask filter than it is OK to handle the src rect -> dst rect scaling using
1215 // the view matrix rather than a local matrix.
1217 m.setScale(dstSize.fWidth / srcRect.width(),
1218 dstSize.fHeight / srcRect.height());
1219 fContext->concatMatrix(m);
1221 GrTextureParams params;
1222 SkPaint::FilterLevel paintFilterLevel = paint.getFilterLevel();
1223 GrTextureParams::FilterMode textureFilterMode;
1226 bool doBicubic = false;
1228 switch(paintFilterLevel) {
1229 case SkPaint::kNone_FilterLevel:
1231 textureFilterMode = GrTextureParams::kNone_FilterMode;
1233 case SkPaint::kLow_FilterLevel:
1235 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1237 case SkPaint::kMedium_FilterLevel:
1239 if (fContext->getMatrix().getMinStretch() < SK_Scalar1) {
1240 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1242 // Don't trigger MIP level generation unnecessarily.
1243 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1246 case SkPaint::kHigh_FilterLevel:
1247 // Minification can look bad with the bicubic effect.
1248 if (fContext->getMatrix().getMinStretch() >= SK_Scalar1) {
1249 // We will install an effect that does the filtering in the shader.
1250 textureFilterMode = GrTextureParams::kNone_FilterMode;
1251 tileFilterPad = GrBicubicEffect::kFilterTexelPad;
1254 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1259 SkErrorInternals::SetError( kInvalidPaint_SkError,
1260 "Sorry, I don't understand the filtering "
1261 "mode you asked for. Falling back to "
1264 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1268 params.setFilterMode(textureFilterMode);
1270 int maxTileSize = fContext->getMaxTextureSize() - 2 * tileFilterPad;
1273 SkIRect clippedSrcRect;
1274 if (this->shouldTileBitmap(bitmap, params, srcRectPtr, maxTileSize, &tileSize,
1276 this->drawTiledBitmap(bitmap, srcRect, clippedSrcRect, params, paint, flags, tileSize,
1279 // take the simple case
1280 this->internalDrawBitmap(bitmap, srcRect, params, paint, flags, doBicubic);
1284 // Break 'bitmap' into several tiles to draw it since it has already
1285 // been determined to be too large to fit in VRAM
1286 void SkGpuDevice::drawTiledBitmap(const SkBitmap& bitmap,
1287 const SkRect& srcRect,
1288 const SkIRect& clippedSrcIRect,
1289 const GrTextureParams& params,
1290 const SkPaint& paint,
1291 SkCanvas::DrawBitmapRectFlags flags,
1294 // The following pixel lock is technically redundant, but it is desirable
1295 // to lock outside of the tile loop to prevent redecoding the whole image
1296 // at each tile in cases where 'bitmap' holds an SkDiscardablePixelRef that
1297 // is larger than the limit of the discardable memory pool.
1298 SkAutoLockPixels alp(bitmap);
1299 SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
1301 int nx = bitmap.width() / tileSize;
1302 int ny = bitmap.height() / tileSize;
1303 for (int x = 0; x <= nx; x++) {
1304 for (int y = 0; y <= ny; y++) {
1306 tileR.set(SkIntToScalar(x * tileSize),
1307 SkIntToScalar(y * tileSize),
1308 SkIntToScalar((x + 1) * tileSize),
1309 SkIntToScalar((y + 1) * tileSize));
1311 if (!SkRect::Intersects(tileR, clippedSrcRect)) {
1315 if (!tileR.intersect(srcRect)) {
1321 tileR.roundOut(&iTileR);
1322 SkPoint offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
1323 SkIntToScalar(iTileR.fTop));
1325 // Adjust the context matrix to draw at the right x,y in device space
1327 GrContext::AutoMatrix am;
1328 tmpM.setTranslate(offset.fX - srcRect.fLeft, offset.fY - srcRect.fTop);
1329 am.setPreConcat(fContext, tmpM);
1331 if (SkPaint::kNone_FilterLevel != paint.getFilterLevel() || bicubic) {
1334 if (SkCanvas::kBleed_DrawBitmapRectFlag & flags) {
1335 // In bleed mode we want to always expand the tile on all edges
1336 // but stay within the bitmap bounds
1337 iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1339 // In texture-domain/clamp mode we only want to expand the
1340 // tile on edges interior to "srcRect" (i.e., we want to
1341 // not bleed across the original clamped edges)
1342 srcRect.roundOut(&iClampRect);
1344 int outset = bicubic ? GrBicubicEffect::kFilterTexelPad : 1;
1345 clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect);
1348 if (bitmap.extractSubset(&tmpB, iTileR)) {
1349 // now offset it to make it "local" to our tmp bitmap
1350 tileR.offset(-offset.fX, -offset.fY);
1352 this->internalDrawBitmap(tmpB, tileR, params, paint, flags, bicubic);
1358 static bool has_aligned_samples(const SkRect& srcRect,
1359 const SkRect& transformedRect) {
1360 // detect pixel disalignment
1361 if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) -
1362 transformedRect.left()) < COLOR_BLEED_TOLERANCE &&
1363 SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) -
1364 transformedRect.top()) < COLOR_BLEED_TOLERANCE &&
1365 SkScalarAbs(transformedRect.width() - srcRect.width()) <
1366 COLOR_BLEED_TOLERANCE &&
1367 SkScalarAbs(transformedRect.height() - srcRect.height()) <
1368 COLOR_BLEED_TOLERANCE) {
1374 static bool may_color_bleed(const SkRect& srcRect,
1375 const SkRect& transformedRect,
1376 const SkMatrix& m) {
1377 // Only gets called if has_aligned_samples returned false.
1378 // So we can assume that sampling is axis aligned but not texel aligned.
1379 SkASSERT(!has_aligned_samples(srcRect, transformedRect));
1380 SkRect innerSrcRect(srcRect), innerTransformedRect,
1381 outerTransformedRect(transformedRect);
1382 innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
1383 m.mapRect(&innerTransformedRect, innerSrcRect);
1385 // The gap between outerTransformedRect and innerTransformedRect
1386 // represents the projection of the source border area, which is
1387 // problematic for color bleeding. We must check whether any
1388 // destination pixels sample the border area.
1389 outerTransformedRect.inset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1390 innerTransformedRect.outset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1391 SkIRect outer, inner;
1392 outerTransformedRect.round(&outer);
1393 innerTransformedRect.round(&inner);
1394 // If the inner and outer rects round to the same result, it means the
1395 // border does not overlap any pixel centers. Yay!
1396 return inner != outer;
1401 * This is called by drawBitmap(), which has to handle images that may be too
1402 * large to be represented by a single texture.
1404 * internalDrawBitmap assumes that the specified bitmap will fit in a texture
1405 * and that non-texture portion of the GrPaint has already been setup.
1407 void SkGpuDevice::internalDrawBitmap(const SkBitmap& bitmap,
1408 const SkRect& srcRect,
1409 const GrTextureParams& params,
1410 const SkPaint& paint,
1411 SkCanvas::DrawBitmapRectFlags flags,
1413 SkASSERT(bitmap.width() <= fContext->getMaxTextureSize() &&
1414 bitmap.height() <= fContext->getMaxTextureSize());
1417 SkAutoCachedTexture act(this, bitmap, ¶ms, &texture);
1418 if (NULL == texture) {
1422 SkRect dstRect = {0, 0, srcRect.width(), srcRect.height() };
1424 SkScalar wInv = SkScalarInvert(SkIntToScalar(texture->width()));
1425 SkScalar hInv = SkScalarInvert(SkIntToScalar(texture->height()));
1426 paintRect.setLTRB(SkScalarMul(srcRect.fLeft, wInv),
1427 SkScalarMul(srcRect.fTop, hInv),
1428 SkScalarMul(srcRect.fRight, wInv),
1429 SkScalarMul(srcRect.fBottom, hInv));
1431 bool needsTextureDomain = false;
1432 if (!(flags & SkCanvas::kBleed_DrawBitmapRectFlag) &&
1433 (bicubic || params.filterMode() != GrTextureParams::kNone_FilterMode)) {
1434 // Need texture domain if drawing a sub rect
1435 needsTextureDomain = srcRect.width() < bitmap.width() ||
1436 srcRect.height() < bitmap.height();
1437 if (!bicubic && needsTextureDomain && fContext->getMatrix().rectStaysRect()) {
1438 const SkMatrix& matrix = fContext->getMatrix();
1439 // sampling is axis-aligned
1440 SkRect transformedRect;
1441 matrix.mapRect(&transformedRect, srcRect);
1443 if (has_aligned_samples(srcRect, transformedRect)) {
1444 // We could also turn off filtering here (but we already did a cache lookup with
1446 needsTextureDomain = false;
1448 needsTextureDomain = may_color_bleed(srcRect, transformedRect, matrix);
1453 SkRect textureDomain = SkRect::MakeEmpty();
1454 SkAutoTUnref<GrEffectRef> effect;
1455 if (needsTextureDomain) {
1456 // Use a constrained texture domain to avoid color bleeding
1457 SkScalar left, top, right, bottom;
1458 if (srcRect.width() > SK_Scalar1) {
1459 SkScalar border = SK_ScalarHalf / texture->width();
1460 left = paintRect.left() + border;
1461 right = paintRect.right() - border;
1463 left = right = SkScalarHalf(paintRect.left() + paintRect.right());
1465 if (srcRect.height() > SK_Scalar1) {
1466 SkScalar border = SK_ScalarHalf / texture->height();
1467 top = paintRect.top() + border;
1468 bottom = paintRect.bottom() - border;
1470 top = bottom = SkScalarHalf(paintRect.top() + paintRect.bottom());
1472 textureDomain.setLTRB(left, top, right, bottom);
1474 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), textureDomain));
1476 effect.reset(GrTextureDomainEffect::Create(texture,
1479 GrTextureDomain::kClamp_Mode,
1480 params.filterMode()));
1482 } else if (bicubic) {
1483 SkASSERT(GrTextureParams::kNone_FilterMode == params.filterMode());
1484 SkShader::TileMode tileModes[2] = { params.getTileModeX(), params.getTileModeY() };
1485 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), tileModes));
1487 effect.reset(GrSimpleTextureEffect::Create(texture, SkMatrix::I(), params));
1490 // Construct a GrPaint by setting the bitmap texture as the first effect and then configuring
1491 // the rest from the SkPaint.
1493 grPaint.addColorEffect(effect);
1494 bool alphaOnly = !(SkBitmap::kA8_Config == bitmap.config());
1495 if (!skPaint2GrPaintNoShader(this, paint, alphaOnly, false, &grPaint)) {
1499 fContext->drawRectToRect(grPaint, dstRect, paintRect, NULL);
1502 static bool filter_texture(SkBaseDevice* device, GrContext* context,
1503 GrTexture* texture, const SkImageFilter* filter,
1504 int w, int h, const SkImageFilter::Context& ctx,
1505 SkBitmap* result, SkIPoint* offset) {
1507 SkDeviceImageFilterProxy proxy(device);
1509 if (filter->canFilterImageGPU()) {
1510 // Save the render target and set it to NULL, so we don't accidentally draw to it in the
1511 // filter. Also set the clip wide open and the matrix to identity.
1512 GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
1513 return filter->filterImageGPU(&proxy, wrap_texture(texture), ctx, result, offset);
1519 void SkGpuDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap,
1520 int left, int top, const SkPaint& paint) {
1521 // drawSprite is defined to be in device coords.
1522 CHECK_SHOULD_DRAW(draw, true);
1524 SkAutoLockPixels alp(bitmap, !bitmap.getTexture());
1525 if (!bitmap.getTexture() && !bitmap.readyToDraw()) {
1529 int w = bitmap.width();
1530 int h = bitmap.height();
1533 // draw sprite uses the default texture params
1534 SkAutoCachedTexture act(this, bitmap, NULL, &texture);
1536 SkImageFilter* filter = paint.getImageFilter();
1537 // This bitmap will own the filtered result as a texture.
1538 SkBitmap filteredBitmap;
1540 if (NULL != filter) {
1541 SkIPoint offset = SkIPoint::Make(0, 0);
1542 SkMatrix matrix(*draw.fMatrix);
1543 matrix.postTranslate(SkIntToScalar(-left), SkIntToScalar(-top));
1544 SkIRect clipBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1545 SkImageFilter::Cache* cache = SkImageFilter::Cache::Create();
1546 SkAutoUnref aur(cache);
1547 SkImageFilter::Context ctx(matrix, clipBounds, cache);
1548 if (filter_texture(this, fContext, texture, filter, w, h, ctx, &filteredBitmap,
1550 texture = (GrTexture*) filteredBitmap.getTexture();
1551 w = filteredBitmap.width();
1552 h = filteredBitmap.height();
1561 grPaint.addColorTextureEffect(texture, SkMatrix::I());
1563 if(!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1567 fContext->drawRectToRect(grPaint,
1568 SkRect::MakeXYWH(SkIntToScalar(left),
1574 SK_Scalar1 * w / texture->width(),
1575 SK_Scalar1 * h / texture->height()));
1578 void SkGpuDevice::drawBitmapRect(const SkDraw& origDraw, const SkBitmap& bitmap,
1579 const SkRect* src, const SkRect& dst,
1580 const SkPaint& paint,
1581 SkCanvas::DrawBitmapRectFlags flags) {
1583 SkRect bitmapBounds, tmpSrc;
1585 bitmapBounds.set(0, 0,
1586 SkIntToScalar(bitmap.width()),
1587 SkIntToScalar(bitmap.height()));
1589 // Compute matrix from the two rectangles
1593 tmpSrc = bitmapBounds;
1596 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1598 // clip the tmpSrc to the bounds of the bitmap. No check needed if src==null.
1600 if (!bitmapBounds.contains(tmpSrc)) {
1601 if (!tmpSrc.intersect(bitmapBounds)) {
1602 return; // nothing to draw
1608 matrix.mapRect(&tmpDst, tmpSrc);
1610 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1611 if (0 != tmpDst.fLeft || 0 != tmpDst.fTop) {
1612 // Translate so that tempDst's top left is at the origin.
1613 matrix = *origDraw.fMatrix;
1614 matrix.preTranslate(tmpDst.fLeft, tmpDst.fTop);
1615 draw.writable()->fMatrix = &matrix;
1618 dstSize.fWidth = tmpDst.width();
1619 dstSize.fHeight = tmpDst.height();
1621 this->drawBitmapCommon(*draw, bitmap, &tmpSrc, &dstSize, paint, flags);
1624 void SkGpuDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device,
1625 int x, int y, const SkPaint& paint) {
1626 // clear of the source device must occur before CHECK_SHOULD_DRAW
1627 SkGpuDevice* dev = static_cast<SkGpuDevice*>(device);
1628 if (dev->fNeedClear) {
1629 // TODO: could check here whether we really need to draw at all
1633 // drawDevice is defined to be in device coords.
1634 CHECK_SHOULD_DRAW(draw, true);
1636 GrRenderTarget* devRT = dev->accessRenderTarget();
1638 if (NULL == (devTex = devRT->asTexture())) {
1642 const SkBitmap& bm = dev->accessBitmap(false);
1644 int h = bm.height();
1646 SkImageFilter* filter = paint.getImageFilter();
1647 // This bitmap will own the filtered result as a texture.
1648 SkBitmap filteredBitmap;
1650 if (NULL != filter) {
1651 SkIPoint offset = SkIPoint::Make(0, 0);
1652 SkMatrix matrix(*draw.fMatrix);
1653 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
1654 SkIRect clipBounds = SkIRect::MakeWH(devTex->width(), devTex->height());
1655 SkImageFilter::Cache* cache = SkImageFilter::Cache::Create();
1656 SkAutoUnref aur(cache);
1657 SkImageFilter::Context ctx(matrix, clipBounds, cache);
1658 if (filter_texture(this, fContext, devTex, filter, w, h, ctx, &filteredBitmap,
1660 devTex = filteredBitmap.getTexture();
1661 w = filteredBitmap.width();
1662 h = filteredBitmap.height();
1671 grPaint.addColorTextureEffect(devTex, SkMatrix::I());
1673 if (!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1677 SkRect dstRect = SkRect::MakeXYWH(SkIntToScalar(x),
1682 // The device being drawn may not fill up its texture (e.g. saveLayer uses approximate
1683 // scratch texture).
1684 SkRect srcRect = SkRect::MakeWH(SK_Scalar1 * w / devTex->width(),
1685 SK_Scalar1 * h / devTex->height());
1687 fContext->drawRectToRect(grPaint, dstRect, srcRect);
1690 bool SkGpuDevice::canHandleImageFilter(const SkImageFilter* filter) {
1691 return filter->canFilterImageGPU();
1694 bool SkGpuDevice::filterImage(const SkImageFilter* filter, const SkBitmap& src,
1695 const SkImageFilter::Context& ctx,
1696 SkBitmap* result, SkIPoint* offset) {
1697 // want explicitly our impl, so guard against a subclass of us overriding it
1698 if (!this->SkGpuDevice::canHandleImageFilter(filter)) {
1702 SkAutoLockPixels alp(src, !src.getTexture());
1703 if (!src.getTexture() && !src.readyToDraw()) {
1708 // We assume here that the filter will not attempt to tile the src. Otherwise, this cache lookup
1709 // must be pushed upstack.
1710 SkAutoCachedTexture act(this, src, NULL, &texture);
1712 return filter_texture(this, fContext, texture, filter, src.width(), src.height(), ctx,
1716 ///////////////////////////////////////////////////////////////////////////////
1718 // must be in SkCanvas::VertexMode order
1719 static const GrPrimitiveType gVertexMode2PrimitiveType[] = {
1720 kTriangles_GrPrimitiveType,
1721 kTriangleStrip_GrPrimitiveType,
1722 kTriangleFan_GrPrimitiveType,
1725 void SkGpuDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
1726 int vertexCount, const SkPoint vertices[],
1727 const SkPoint texs[], const SkColor colors[],
1729 const uint16_t indices[], int indexCount,
1730 const SkPaint& paint) {
1731 CHECK_SHOULD_DRAW(draw, false);
1734 // we ignore the shader if texs is null.
1736 if (!skPaint2GrPaintNoShader(this, paint, false, NULL == colors, &grPaint)) {
1740 if (!skPaint2GrPaintShader(this, paint, NULL == colors, &grPaint)) {
1745 if (NULL != xmode && NULL != texs && NULL != colors) {
1746 if (!SkXfermode::IsMode(xmode, SkXfermode::kModulate_Mode)) {
1747 SkDebugf("Unsupported vertex-color/texture xfer mode.\n");
1754 SkAutoSTMalloc<128, GrColor> convertedColors(0);
1755 if (NULL != colors) {
1756 // need to convert byte order and from non-PM to PM
1757 convertedColors.reset(vertexCount);
1758 for (int i = 0; i < vertexCount; ++i) {
1759 convertedColors[i] = SkColor2GrColor(colors[i]);
1761 colors = convertedColors.get();
1763 fContext->drawVertices(grPaint,
1764 gVertexMode2PrimitiveType[vmode],
1773 ///////////////////////////////////////////////////////////////////////////////
1775 void SkGpuDevice::drawText(const SkDraw& draw, const void* text,
1776 size_t byteLength, SkScalar x, SkScalar y,
1777 const SkPaint& paint) {
1778 CHECK_SHOULD_DRAW(draw, false);
1780 if (fMainTextContext->canDraw(paint)) {
1782 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1786 SkDEBUGCODE(this->validate();)
1788 fMainTextContext->drawText(grPaint, paint, (const char *)text, byteLength, x, y);
1789 } else if (fFallbackTextContext && fFallbackTextContext->canDraw(paint)) {
1791 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1795 SkDEBUGCODE(this->validate();)
1797 fFallbackTextContext->drawText(grPaint, paint, (const char *)text, byteLength, x, y);
1799 // this guy will just call our drawPath()
1800 draw.drawText_asPaths((const char*)text, byteLength, x, y, paint);
1804 void SkGpuDevice::drawPosText(const SkDraw& draw, const void* text,
1805 size_t byteLength, const SkScalar pos[],
1806 SkScalar constY, int scalarsPerPos,
1807 const SkPaint& paint) {
1808 CHECK_SHOULD_DRAW(draw, false);
1810 if (fMainTextContext->canDraw(paint)) {
1812 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1816 SkDEBUGCODE(this->validate();)
1818 fMainTextContext->drawPosText(grPaint, paint, (const char *)text, byteLength, pos,
1819 constY, scalarsPerPos);
1820 } else if (fFallbackTextContext && fFallbackTextContext->canDraw(paint)) {
1822 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1826 SkDEBUGCODE(this->validate();)
1828 fFallbackTextContext->drawPosText(grPaint, paint, (const char *)text, byteLength, pos,
1829 constY, scalarsPerPos);
1831 draw.drawPosText_asPaths((const char*)text, byteLength, pos, constY,
1832 scalarsPerPos, paint);
1836 void SkGpuDevice::drawTextOnPath(const SkDraw& draw, const void* text,
1837 size_t len, const SkPath& path,
1838 const SkMatrix* m, const SkPaint& paint) {
1839 CHECK_SHOULD_DRAW(draw, false);
1841 SkASSERT(draw.fDevice == this);
1842 draw.drawTextOnPath((const char*)text, len, path, m, paint);
1845 ///////////////////////////////////////////////////////////////////////////////
1847 bool SkGpuDevice::filterTextFlags(const SkPaint& paint, TextFlags* flags) {
1848 if (!paint.isLCDRenderText()) {
1849 // we're cool with the paint as is
1853 if (paint.getShader() ||
1854 paint.getXfermode() || // unless its srcover
1855 paint.getMaskFilter() ||
1856 paint.getRasterizer() ||
1857 paint.getColorFilter() ||
1858 paint.getPathEffect() ||
1859 paint.isFakeBoldText() ||
1860 paint.getStyle() != SkPaint::kFill_Style) {
1862 flags->fFlags = paint.getFlags() & ~SkPaint::kLCDRenderText_Flag;
1863 flags->fHinting = paint.getHinting();
1866 // we're cool with the paint as is
1870 void SkGpuDevice::flush() {
1871 DO_DEFERRED_CLEAR();
1872 fContext->resolveRenderTarget(fRenderTarget);
1875 ///////////////////////////////////////////////////////////////////////////////
1877 SkBaseDevice* SkGpuDevice::onCreateDevice(const SkImageInfo& info, Usage usage) {
1879 desc.fConfig = fRenderTarget->config();
1880 desc.fFlags = kRenderTarget_GrTextureFlagBit;
1881 desc.fWidth = info.width();
1882 desc.fHeight = info.height();
1883 desc.fSampleCnt = fRenderTarget->numSamples();
1885 SkAutoTUnref<GrTexture> texture;
1886 // Skia's convention is to only clear a device if it is non-opaque.
1887 unsigned flags = info.isOpaque() ? 0 : kNeedClear_Flag;
1889 #if CACHE_COMPATIBLE_DEVICE_TEXTURES
1890 // layers are never draw in repeat modes, so we can request an approx
1891 // match and ignore any padding.
1892 flags |= kCached_Flag;
1893 const GrContext::ScratchTexMatch match = (kSaveLayer_Usage == usage) ?
1894 GrContext::kApprox_ScratchTexMatch :
1895 GrContext::kExact_ScratchTexMatch;
1896 texture.reset(fContext->lockAndRefScratchTexture(desc, match));
1898 texture.reset(fContext->createUncachedTexture(desc, NULL, 0));
1900 if (NULL != texture.get()) {
1901 return SkGpuDevice::Create(texture, flags);
1903 GrPrintf("---- failed to create compatible device texture [%d %d]\n",
1904 info.width(), info.height());
1909 SkSurface* SkGpuDevice::newSurface(const SkImageInfo& info) {
1910 return SkSurface::NewRenderTarget(fContext, info, fRenderTarget->numSamples());
1913 void SkGpuDevice::EXPERIMENTAL_optimize(SkPicture* picture) {
1914 SkPicture::AccelData::Key key = GPUAccelData::ComputeAccelDataKey();
1916 SkAutoTUnref<GPUAccelData> data(SkNEW_ARGS(GPUAccelData, (key)));
1918 picture->EXPERIMENTAL_addAccelData(data);
1920 GatherGPUInfo(picture, data);
1923 void SkGpuDevice::EXPERIMENTAL_purge(SkPicture* picture) {
1927 bool SkGpuDevice::EXPERIMENTAL_drawPicture(SkCanvas* canvas, SkPicture* picture) {
1929 SkPicture::AccelData::Key key = GPUAccelData::ComputeAccelDataKey();
1931 const SkPicture::AccelData* data = picture->EXPERIMENTAL_getAccelData(key);
1936 const GPUAccelData *gpuData = static_cast<const GPUAccelData*>(data);
1938 SkAutoTArray<bool> pullForward(gpuData->numSaveLayers());
1939 for (int i = 0; i < gpuData->numSaveLayers(); ++i) {
1940 pullForward[i] = false;
1945 fClipData.getConservativeBounds(this->width(), this->height(), &clip, NULL);
1948 if (!fContext->getMatrix().invert(&inv)) {
1952 SkRect r = SkRect::Make(clip);
1956 const SkPicture::OperationList& ops = picture->EXPERIMENTAL_getActiveOps(clip);
1958 for (int i = 0; i < ops.numOps(); ++i) {
1959 for (int j = 0; j < gpuData->numSaveLayers(); ++j) {
1960 const GPUAccelData::SaveLayerInfo& info = gpuData->saveLayerInfo(j);
1962 if (ops.offset(i) > info.fSaveLayerOpID && ops.offset(i) < info.fRestoreOpID) {
1963 pullForward[j] = true;