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 #if SK_DISTANCEFIELD_FONTS
17 #include "GrDistanceFieldTextContext.h"
20 #include "SkGrTexturePixelRef.h"
22 #include "SkColorFilter.h"
23 #include "SkDeviceImageFilterProxy.h"
24 #include "SkDrawProcs.h"
25 #include "SkGlyphCache.h"
26 #include "SkImageFilter.h"
27 #include "SkPathEffect.h"
30 #include "SkSurface.h"
33 #include "SkErrorInternals.h"
35 #define CACHE_COMPATIBLE_DEVICE_TEXTURES 1
38 extern bool (*gShouldDrawProc)();
39 #define CHECK_SHOULD_DRAW(draw, forceI) \
41 if (gShouldDrawProc && !gShouldDrawProc()) return; \
42 this->prepareDraw(draw, forceI); \
45 #define CHECK_SHOULD_DRAW(draw, forceI) this->prepareDraw(draw, forceI)
48 // This constant represents the screen alignment criterion in texels for
49 // requiring texture domain clamping to prevent color bleeding when drawing
50 // a sub region of a larger source image.
51 #define COLOR_BLEED_TOLERANCE 0.001f
53 #define DO_DEFERRED_CLEAR() \
56 this->clear(SK_ColorTRANSPARENT); \
60 ///////////////////////////////////////////////////////////////////////////////
62 #define CHECK_FOR_ANNOTATION(paint) \
63 do { if (paint.getAnnotation()) { return; } } while (0)
65 ///////////////////////////////////////////////////////////////////////////////
68 class SkGpuDevice::SkAutoCachedTexture : public ::SkNoncopyable {
75 SkAutoCachedTexture(SkGpuDevice* device,
76 const SkBitmap& bitmap,
77 const GrTextureParams* params,
81 SkASSERT(NULL != texture);
82 *texture = this->set(device, bitmap, params);
85 ~SkAutoCachedTexture() {
86 if (NULL != fTexture) {
87 GrUnlockAndUnrefCachedBitmapTexture(fTexture);
91 GrTexture* set(SkGpuDevice* device,
92 const SkBitmap& bitmap,
93 const GrTextureParams* params) {
94 if (NULL != fTexture) {
95 GrUnlockAndUnrefCachedBitmapTexture(fTexture);
99 GrTexture* result = (GrTexture*)bitmap.getTexture();
100 if (NULL == result) {
101 // Cannot return the native texture so look it up in our cache
102 fTexture = GrLockAndRefCachedBitmapTexture(device->context(), bitmap, params);
109 SkGpuDevice* fDevice;
113 ///////////////////////////////////////////////////////////////////////////////
115 struct GrSkDrawProcs : public SkDrawProcs {
118 GrTextContext* fTextContext;
119 GrFontScaler* fFontScaler; // cached in the skia glyphcache
122 ///////////////////////////////////////////////////////////////////////////////
124 static SkBitmap::Config grConfig2skConfig(GrPixelConfig config, bool* isOpaque) {
126 case kAlpha_8_GrPixelConfig:
128 return SkBitmap::kA8_Config;
129 case kRGB_565_GrPixelConfig:
131 return SkBitmap::kRGB_565_Config;
132 case kRGBA_4444_GrPixelConfig:
134 return SkBitmap::kARGB_4444_Config;
135 case kSkia8888_GrPixelConfig:
136 // we don't currently have a way of knowing whether
137 // a 8888 is opaque based on the config.
139 return SkBitmap::kARGB_8888_Config;
142 return SkBitmap::kNo_Config;
147 * GrRenderTarget does not know its opaqueness, only its config, so we have
148 * to make conservative guesses when we return an "equivalent" bitmap.
150 static SkBitmap make_bitmap(GrContext* context, GrRenderTarget* renderTarget) {
152 SkBitmap::Config config = grConfig2skConfig(renderTarget->config(), &isOpaque);
155 bitmap.setConfig(config, renderTarget->width(), renderTarget->height(), 0,
156 isOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
161 * Calling SkBitmapDevice with individual params asks it to allocate pixel memory.
162 * We never want that, so we always need to call it with a bitmap argument
163 * (which says take my allocate (or lack thereof)).
165 * This is a REALLY good reason to finish the clean-up of SkBaseDevice, and have
166 * SkGpuDevice inherit from that instead of SkBitmapDevice.
168 static SkBitmap make_bitmap(SkBitmap::Config config, int width, int height, bool isOpaque) {
170 bm.setConfig(config, width, height, isOpaque);
174 SkGpuDevice* SkGpuDevice::Create(GrSurface* surface) {
175 SkASSERT(NULL != surface);
176 if (NULL == surface->asRenderTarget() || NULL == surface->getContext()) {
179 if (surface->asTexture()) {
180 return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asTexture()));
182 return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asRenderTarget()));
186 SkGpuDevice::SkGpuDevice(GrContext* context, GrTexture* texture)
187 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
188 this->initFromRenderTarget(context, texture->asRenderTarget(), false);
191 SkGpuDevice::SkGpuDevice(GrContext* context, GrRenderTarget* renderTarget)
192 : SkBitmapDevice(make_bitmap(context, renderTarget)) {
193 this->initFromRenderTarget(context, renderTarget, false);
196 void SkGpuDevice::initFromRenderTarget(GrContext* context,
197 GrRenderTarget* renderTarget,
204 #if SK_DISTANCEFIELD_FONTS
205 fMainTextContext = SkNEW_ARGS(GrDistanceFieldTextContext, (fContext, fLeakyProperties));
206 fFallbackTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
208 fMainTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
209 fFallbackTextContext = NULL;
212 fRenderTarget = NULL;
215 SkASSERT(NULL != renderTarget);
216 fRenderTarget = renderTarget;
217 fRenderTarget->ref();
219 // Hold onto to the texture in the pixel ref (if there is one) because the texture holds a ref
220 // on the RT but not vice-versa.
221 // TODO: Remove this trickery once we figure out how to make SkGrPixelRef do this without
222 // busting chrome (for a currently unknown reason).
223 GrSurface* surface = fRenderTarget->asTexture();
224 if (NULL == surface) {
225 surface = fRenderTarget;
229 surface->asImageInfo(&info);
230 SkPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, surface, cached));
232 this->setPixelRef(pr)->unref();
235 SkGpuDevice::SkGpuDevice(GrContext* context,
236 SkBitmap::Config config,
240 : SkBitmapDevice(make_bitmap(config, width, height, false /*isOpaque*/))
247 #if SK_DISTANCEFIELD_FONTS
248 fMainTextContext = SkNEW_ARGS(GrDistanceFieldTextContext, (fContext, fLeakyProperties));
249 fFallbackTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
251 fMainTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
252 fFallbackTextContext = NULL;
255 fRenderTarget = NULL;
258 if (config != SkBitmap::kRGB_565_Config) {
259 config = SkBitmap::kARGB_8888_Config;
263 desc.fFlags = kRenderTarget_GrTextureFlagBit;
265 desc.fHeight = height;
266 desc.fConfig = SkBitmapConfig2GrPixelConfig(config);
267 desc.fSampleCnt = sampleCount;
270 if (!GrPixelConfig2ColorType(desc.fConfig, &info.fColorType)) {
274 info.fHeight = height;
275 info.fAlphaType = kPremul_SkAlphaType;
277 SkAutoTUnref<GrTexture> texture(fContext->createUncachedTexture(desc, NULL, 0));
279 if (NULL != texture) {
280 fRenderTarget = texture->asRenderTarget();
281 fRenderTarget->ref();
283 SkASSERT(NULL != fRenderTarget);
285 // wrap the bitmap with a pixelref to expose our texture
286 SkGrPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, texture));
287 this->setPixelRef(pr)->unref();
289 GrPrintf("--- failed to create gpu-offscreen [%d %d]\n",
295 SkGpuDevice::~SkGpuDevice() {
300 delete fMainTextContext;
301 delete fFallbackTextContext;
303 // The GrContext takes a ref on the target. We don't want to cause the render
304 // target to be unnecessarily kept alive.
305 if (fContext->getRenderTarget() == fRenderTarget) {
306 fContext->setRenderTarget(NULL);
309 if (fContext->getClip() == &fClipData) {
310 fContext->setClip(NULL);
313 SkSafeUnref(fRenderTarget);
317 ///////////////////////////////////////////////////////////////////////////////
319 void SkGpuDevice::makeRenderTargetCurrent() {
321 fContext->setRenderTarget(fRenderTarget);
324 ///////////////////////////////////////////////////////////////////////////////
327 GrPixelConfig config8888_to_grconfig_and_flags(SkCanvas::Config8888 config8888, uint32_t* flags) {
328 switch (config8888) {
329 case SkCanvas::kNative_Premul_Config8888:
331 return kSkia8888_GrPixelConfig;
332 case SkCanvas::kNative_Unpremul_Config8888:
333 *flags = GrContext::kUnpremul_PixelOpsFlag;
334 return kSkia8888_GrPixelConfig;
335 case SkCanvas::kBGRA_Premul_Config8888:
337 return kBGRA_8888_GrPixelConfig;
338 case SkCanvas::kBGRA_Unpremul_Config8888:
339 *flags = GrContext::kUnpremul_PixelOpsFlag;
340 return kBGRA_8888_GrPixelConfig;
341 case SkCanvas::kRGBA_Premul_Config8888:
343 return kRGBA_8888_GrPixelConfig;
344 case SkCanvas::kRGBA_Unpremul_Config8888:
345 *flags = GrContext::kUnpremul_PixelOpsFlag;
346 return kRGBA_8888_GrPixelConfig;
348 GrCrash("Unexpected Config8888.");
349 *flags = 0; // suppress warning
350 return kSkia8888_GrPixelConfig;
355 bool SkGpuDevice::onReadPixels(const SkBitmap& bitmap,
357 SkCanvas::Config8888 config8888) {
359 SkASSERT(SkBitmap::kARGB_8888_Config == bitmap.config());
360 SkASSERT(!bitmap.isNull());
361 SkASSERT(SkIRect::MakeWH(this->width(), this->height()).contains(SkIRect::MakeXYWH(x, y, bitmap.width(), bitmap.height())));
363 SkAutoLockPixels alp(bitmap);
364 GrPixelConfig config;
366 config = config8888_to_grconfig_and_flags(config8888, &flags);
367 return fContext->readRenderTargetPixels(fRenderTarget,
377 void SkGpuDevice::writePixels(const SkBitmap& bitmap, int x, int y,
378 SkCanvas::Config8888 config8888) {
379 SkAutoLockPixels alp(bitmap);
380 if (!bitmap.readyToDraw()) {
384 GrPixelConfig config;
386 if (SkBitmap::kARGB_8888_Config == bitmap.config()) {
387 config = config8888_to_grconfig_and_flags(config8888, &flags);
390 config= SkBitmapConfig2GrPixelConfig(bitmap.config());
393 fRenderTarget->writePixels(x, y, bitmap.width(), bitmap.height(),
394 config, bitmap.getPixels(), bitmap.rowBytes(), flags);
397 void SkGpuDevice::onAttachToCanvas(SkCanvas* canvas) {
398 INHERITED::onAttachToCanvas(canvas);
400 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
401 fClipData.fClipStack = canvas->getClipStack();
404 void SkGpuDevice::onDetachFromCanvas() {
405 INHERITED::onDetachFromCanvas();
406 fClipData.fClipStack = NULL;
409 // call this every draw call, to ensure that the context reflects our state,
410 // and not the state from some other canvas/device
411 void SkGpuDevice::prepareDraw(const SkDraw& draw, bool forceIdentity) {
412 SkASSERT(NULL != fClipData.fClipStack);
414 fContext->setRenderTarget(fRenderTarget);
416 SkASSERT(draw.fClipStack && draw.fClipStack == fClipData.fClipStack);
419 fContext->setIdentityMatrix();
421 fContext->setMatrix(*draw.fMatrix);
423 fClipData.fOrigin = this->getOrigin();
425 fContext->setClip(&fClipData);
430 GrRenderTarget* SkGpuDevice::accessRenderTarget() {
432 return fRenderTarget;
435 ///////////////////////////////////////////////////////////////////////////////
437 SK_COMPILE_ASSERT(SkShader::kNone_BitmapType == 0, shader_type_mismatch);
438 SK_COMPILE_ASSERT(SkShader::kDefault_BitmapType == 1, shader_type_mismatch);
439 SK_COMPILE_ASSERT(SkShader::kRadial_BitmapType == 2, shader_type_mismatch);
440 SK_COMPILE_ASSERT(SkShader::kSweep_BitmapType == 3, shader_type_mismatch);
441 SK_COMPILE_ASSERT(SkShader::kTwoPointRadial_BitmapType == 4,
442 shader_type_mismatch);
443 SK_COMPILE_ASSERT(SkShader::kTwoPointConical_BitmapType == 5,
444 shader_type_mismatch);
445 SK_COMPILE_ASSERT(SkShader::kLinear_BitmapType == 6, shader_type_mismatch);
446 SK_COMPILE_ASSERT(SkShader::kLast_BitmapType == 6, shader_type_mismatch);
450 // converts a SkPaint to a GrPaint, ignoring the skPaint's shader
451 // justAlpha indicates that skPaint's alpha should be used rather than the color
452 // Callers may subsequently modify the GrPaint. Setting constantColor indicates
453 // that the final paint will draw the same color at every pixel. This allows
454 // an optimization where the the color filter can be applied to the skPaint's
455 // color once while converting to GrPaint and then ignored.
456 inline bool skPaint2GrPaintNoShader(SkGpuDevice* dev,
457 const SkPaint& skPaint,
462 grPaint->setDither(skPaint.isDither());
463 grPaint->setAntiAlias(skPaint.isAntiAlias());
465 SkXfermode::Coeff sm;
466 SkXfermode::Coeff dm;
468 SkXfermode* mode = skPaint.getXfermode();
469 GrEffectRef* xferEffect = NULL;
470 if (SkXfermode::AsNewEffectOrCoeff(mode, &xferEffect, &sm, &dm)) {
471 if (NULL != xferEffect) {
472 grPaint->addColorEffect(xferEffect)->unref();
473 sm = SkXfermode::kOne_Coeff;
474 dm = SkXfermode::kZero_Coeff;
477 //SkDEBUGCODE(SkDebugf("Unsupported xfer mode.\n");)
481 // Fall back to src-over
482 sm = SkXfermode::kOne_Coeff;
483 dm = SkXfermode::kISA_Coeff;
486 grPaint->setBlendFunc(sk_blend_to_grblend(sm), sk_blend_to_grblend(dm));
489 uint8_t alpha = skPaint.getAlpha();
490 grPaint->setColor(GrColorPackRGBA(alpha, alpha, alpha, alpha));
491 // justAlpha is currently set to true only if there is a texture,
492 // so constantColor should not also be true.
493 SkASSERT(!constantColor);
495 grPaint->setColor(SkColor2GrColor(skPaint.getColor()));
498 SkColorFilter* colorFilter = skPaint.getColorFilter();
499 if (NULL != colorFilter) {
500 // if the source color is a constant then apply the filter here once rather than per pixel
503 SkColor filtered = colorFilter->filterColor(skPaint.getColor());
504 grPaint->setColor(SkColor2GrColor(filtered));
506 SkAutoTUnref<GrEffectRef> effect(colorFilter->asNewEffect(dev->context()));
507 if (NULL != effect.get()) {
508 grPaint->addColorEffect(effect);
516 // This function is similar to skPaint2GrPaintNoShader but also converts
517 // skPaint's shader to a GrTexture/GrEffectStage if possible. The texture to
518 // be used is set on grPaint and returned in param act. constantColor has the
519 // same meaning as in skPaint2GrPaintNoShader.
520 inline bool skPaint2GrPaintShader(SkGpuDevice* dev,
521 const SkPaint& skPaint,
524 SkShader* shader = skPaint.getShader();
525 if (NULL == shader) {
526 return skPaint2GrPaintNoShader(dev, skPaint, false, constantColor, grPaint);
529 // SkShader::asNewEffect() may do offscreen rendering. Setup default drawing state and require
530 // the shader to set a render target .
531 GrContext::AutoWideOpenIdentityDraw awo(dev->context(), NULL);
533 // setup the shader as the first color effect on the paint
534 SkAutoTUnref<GrEffectRef> effect(shader->asNewEffect(dev->context(), skPaint));
535 if (NULL != effect.get()) {
536 grPaint->addColorEffect(effect);
537 // Now setup the rest of the paint.
538 return skPaint2GrPaintNoShader(dev, skPaint, true, false, grPaint);
540 // We still don't have SkColorShader::asNewEffect() implemented.
541 SkShader::GradientInfo info;
544 info.fColors = &color;
545 info.fColorOffsets = NULL;
546 info.fColorCount = 1;
547 if (SkShader::kColor_GradientType == shader->asAGradient(&info)) {
548 SkPaint copy(skPaint);
549 copy.setShader(NULL);
550 // modulate the paint alpha by the shader's solid color alpha
551 U8CPU newA = SkMulDiv255Round(SkColorGetA(color), copy.getAlpha());
552 copy.setColor(SkColorSetA(color, newA));
553 return skPaint2GrPaintNoShader(dev, copy, false, constantColor, grPaint);
561 ///////////////////////////////////////////////////////////////////////////////
563 SkBitmap::Config SkGpuDevice::config() const {
564 if (NULL == fRenderTarget) {
565 return SkBitmap::kNo_Config;
569 return grConfig2skConfig(fRenderTarget->config(), &isOpaque);
572 void SkGpuDevice::clear(SkColor color) {
573 SkIRect rect = SkIRect::MakeWH(this->width(), this->height());
574 fContext->clear(&rect, SkColor2GrColor(color), true, fRenderTarget);
578 void SkGpuDevice::drawPaint(const SkDraw& draw, const SkPaint& paint) {
579 CHECK_SHOULD_DRAW(draw, false);
582 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
586 fContext->drawPaint(grPaint);
589 // must be in SkCanvas::PointMode order
590 static const GrPrimitiveType gPointMode2PrimtiveType[] = {
591 kPoints_GrPrimitiveType,
592 kLines_GrPrimitiveType,
593 kLineStrip_GrPrimitiveType
596 void SkGpuDevice::drawPoints(const SkDraw& draw, SkCanvas::PointMode mode,
597 size_t count, const SkPoint pts[], const SkPaint& paint) {
598 CHECK_FOR_ANNOTATION(paint);
599 CHECK_SHOULD_DRAW(draw, false);
601 SkScalar width = paint.getStrokeWidth();
606 // we only handle hairlines and paints without path effects or mask filters,
607 // else we let the SkDraw call our drawPath()
608 if (width > 0 || paint.getPathEffect() || paint.getMaskFilter()) {
609 draw.drawPoints(mode, count, pts, paint, true);
614 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
618 fContext->drawVertices(grPaint,
619 gPointMode2PrimtiveType[mode],
628 ///////////////////////////////////////////////////////////////////////////////
630 void SkGpuDevice::drawRect(const SkDraw& draw, const SkRect& rect,
631 const SkPaint& paint) {
632 CHECK_FOR_ANNOTATION(paint);
633 CHECK_SHOULD_DRAW(draw, false);
635 bool doStroke = paint.getStyle() != SkPaint::kFill_Style;
636 SkScalar width = paint.getStrokeWidth();
639 We have special code for hairline strokes, miter-strokes, bevel-stroke
640 and fills. Anything else we just call our path code.
642 bool usePath = doStroke && width > 0 &&
643 (paint.getStrokeJoin() == SkPaint::kRound_Join ||
644 (paint.getStrokeJoin() == SkPaint::kBevel_Join && rect.isEmpty()));
645 // another two reasons we might need to call drawPath...
646 if (paint.getMaskFilter() || paint.getPathEffect()) {
649 if (!usePath && paint.isAntiAlias() && !fContext->getMatrix().rectStaysRect()) {
650 #if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
654 #if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
656 usePath = !fContext->getMatrix().preservesRightAngles();
660 // until we can both stroke and fill rectangles
661 if (paint.getStyle() == SkPaint::kStrokeAndFill_Style) {
668 this->drawPath(draw, path, paint, NULL, true);
673 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
678 fContext->drawRect(grPaint, rect);
680 SkStrokeRec stroke(paint);
681 fContext->drawRect(grPaint, rect, &stroke);
685 ///////////////////////////////////////////////////////////////////////////////
687 void SkGpuDevice::drawRRect(const SkDraw& draw, const SkRRect& rect,
688 const SkPaint& paint) {
689 CHECK_FOR_ANNOTATION(paint);
690 CHECK_SHOULD_DRAW(draw, false);
692 bool usePath = !rect.isSimple();
693 // another two reasons we might need to call drawPath...
694 if (paint.getMaskFilter() || paint.getPathEffect()) {
697 // until we can rotate rrects...
698 if (!usePath && !fContext->getMatrix().rectStaysRect()) {
705 this->drawPath(draw, path, paint, NULL, true);
710 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
714 SkStrokeRec stroke(paint);
715 fContext->drawRRect(grPaint, rect, stroke);
718 ///////////////////////////////////////////////////////////////////////////////
720 void SkGpuDevice::drawOval(const SkDraw& draw, const SkRect& oval,
721 const SkPaint& paint) {
722 CHECK_FOR_ANNOTATION(paint);
723 CHECK_SHOULD_DRAW(draw, false);
725 bool usePath = false;
726 // some basic reasons we might need to call drawPath...
727 if (paint.getMaskFilter() || paint.getPathEffect()) {
734 this->drawPath(draw, path, paint, NULL, true);
739 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
742 SkStrokeRec stroke(paint);
744 fContext->drawOval(grPaint, oval, stroke);
747 #include "SkMaskFilter.h"
748 #include "SkBounder.h"
750 ///////////////////////////////////////////////////////////////////////////////
752 // helpers for applying mask filters
755 // Draw a mask using the supplied paint. Since the coverage/geometry
756 // is already burnt into the mask this boils down to a rect draw.
757 // Return true if the mask was successfully drawn.
758 bool draw_mask(GrContext* context, const SkRect& maskRect,
759 GrPaint* grp, GrTexture* mask) {
760 GrContext::AutoMatrix am;
761 if (!am.setIdentity(context, grp)) {
766 matrix.setTranslate(-maskRect.fLeft, -maskRect.fTop);
767 matrix.postIDiv(mask->width(), mask->height());
769 grp->addCoverageEffect(GrSimpleTextureEffect::Create(mask, matrix))->unref();
770 context->drawRect(*grp, maskRect);
774 bool draw_with_mask_filter(GrContext* context, const SkPath& devPath,
775 SkMaskFilter* filter, const SkRegion& clip, SkBounder* bounder,
776 GrPaint* grp, SkPaint::Style style) {
779 if (!SkDraw::DrawToMask(devPath, &clip.getBounds(), filter, &context->getMatrix(), &srcM,
780 SkMask::kComputeBoundsAndRenderImage_CreateMode, style)) {
783 SkAutoMaskFreeImage autoSrc(srcM.fImage);
785 if (!filter->filterMask(&dstM, srcM, context->getMatrix(), NULL)) {
788 // this will free-up dstM when we're done (allocated in filterMask())
789 SkAutoMaskFreeImage autoDst(dstM.fImage);
791 if (clip.quickReject(dstM.fBounds)) {
794 if (bounder && !bounder->doIRect(dstM.fBounds)) {
798 // we now have a device-aligned 8bit mask in dstM, ready to be drawn using
799 // the current clip (and identity matrix) and GrPaint settings
801 desc.fWidth = dstM.fBounds.width();
802 desc.fHeight = dstM.fBounds.height();
803 desc.fConfig = kAlpha_8_GrPixelConfig;
805 GrAutoScratchTexture ast(context, desc);
806 GrTexture* texture = ast.texture();
808 if (NULL == texture) {
811 texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig,
812 dstM.fImage, dstM.fRowBytes);
814 SkRect maskRect = SkRect::Make(dstM.fBounds);
816 return draw_mask(context, maskRect, grp, texture);
819 // Create a mask of 'devPath' and place the result in 'mask'. Return true on
820 // success; false otherwise.
821 bool create_mask_GPU(GrContext* context,
822 const SkRect& maskRect,
823 const SkPath& devPath,
824 const SkStrokeRec& stroke,
826 GrAutoScratchTexture* mask) {
828 desc.fFlags = kRenderTarget_GrTextureFlagBit;
829 desc.fWidth = SkScalarCeilToInt(maskRect.width());
830 desc.fHeight = SkScalarCeilToInt(maskRect.height());
831 // We actually only need A8, but it often isn't supported as a
832 // render target so default to RGBA_8888
833 desc.fConfig = kRGBA_8888_GrPixelConfig;
834 if (context->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
835 desc.fConfig = kAlpha_8_GrPixelConfig;
838 mask->set(context, desc);
839 if (NULL == mask->texture()) {
843 GrTexture* maskTexture = mask->texture();
844 SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height());
846 GrContext::AutoRenderTarget art(context, maskTexture->asRenderTarget());
847 GrContext::AutoClip ac(context, clipRect);
849 context->clear(NULL, 0x0, true);
853 tempPaint.setAntiAlias(true);
854 // AA uses the "coverage" stages on GrDrawTarget. Coverage with a dst
855 // blend coeff of zero requires dual source blending support in order
856 // to properly blend partially covered pixels. This means the AA
857 // code path may not be taken. So we use a dst blend coeff of ISA. We
858 // could special case AA draws to a dst surface with known alpha=0 to
859 // use a zero dst coeff when dual source blending isn't available.
860 tempPaint.setBlendFunc(kOne_GrBlendCoeff, kISC_GrBlendCoeff);
863 GrContext::AutoMatrix am;
865 // Draw the mask into maskTexture with the path's top-left at the origin using tempPaint.
867 translate.setTranslate(-maskRect.fLeft, -maskRect.fTop);
868 am.set(context, translate);
869 context->drawPath(tempPaint, devPath, stroke);
873 SkBitmap wrap_texture(GrTexture* texture) {
875 texture->asImageInfo(&info);
878 result.setConfig(info);
879 result.setPixelRef(SkNEW_ARGS(SkGrPixelRef, (info, texture)))->unref();
885 void SkGpuDevice::drawPath(const SkDraw& draw, const SkPath& origSrcPath,
886 const SkPaint& paint, const SkMatrix* prePathMatrix,
887 bool pathIsMutable) {
888 CHECK_FOR_ANNOTATION(paint);
889 CHECK_SHOULD_DRAW(draw, false);
892 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
896 // If we have a prematrix, apply it to the path, optimizing for the case
897 // where the original path can in fact be modified in place (even though
898 // its parameter type is const).
899 SkPath* pathPtr = const_cast<SkPath*>(&origSrcPath);
900 SkTLazy<SkPath> tmpPath;
901 SkTLazy<SkPath> effectPath;
904 SkPath* result = pathPtr;
906 if (!pathIsMutable) {
907 result = tmpPath.init();
908 pathIsMutable = true;
910 // should I push prePathMatrix on our MV stack temporarily, instead
911 // of applying it here? See SkDraw.cpp
912 pathPtr->transform(*prePathMatrix, result);
915 // at this point we're done with prePathMatrix
916 SkDEBUGCODE(prePathMatrix = (const SkMatrix*)0x50FF8001;)
918 SkStrokeRec stroke(paint);
919 SkPathEffect* pathEffect = paint.getPathEffect();
920 const SkRect* cullRect = NULL; // TODO: what is our bounds?
921 if (pathEffect && pathEffect->filterPath(effectPath.init(), *pathPtr, &stroke,
923 pathPtr = effectPath.get();
924 pathIsMutable = true;
927 if (paint.getMaskFilter()) {
928 if (!stroke.isHairlineStyle()) {
929 SkPath* strokedPath = pathIsMutable ? pathPtr : tmpPath.init();
930 if (stroke.applyToPath(strokedPath, *pathPtr)) {
931 pathPtr = strokedPath;
932 pathIsMutable = true;
933 stroke.setFillStyle();
937 // avoid possibly allocating a new path in transform if we can
938 SkPath* devPathPtr = pathIsMutable ? pathPtr : tmpPath.init();
940 // transform the path into device space
941 pathPtr->transform(fContext->getMatrix(), devPathPtr);
944 if (paint.getMaskFilter()->canFilterMaskGPU(devPathPtr->getBounds(),
945 draw.fClip->getBounds(),
946 fContext->getMatrix(),
948 // The context's matrix may change while creating the mask, so save the CTM here to
949 // pass to filterMaskGPU.
950 const SkMatrix ctm = fContext->getMatrix();
953 maskRect.roundOut(&finalIRect);
954 if (draw.fClip->quickReject(finalIRect)) {
958 if (NULL != draw.fBounder && !draw.fBounder->doIRect(finalIRect)) {
963 if (paint.getMaskFilter()->directFilterMaskGPU(fContext, &grPaint,
964 SkStrokeRec(paint), *devPathPtr)) {
965 // the mask filter was able to draw itself directly, so there's nothing
970 GrAutoScratchTexture mask;
972 if (create_mask_GPU(fContext, maskRect, *devPathPtr, stroke,
973 grPaint.isAntiAlias(), &mask)) {
976 if (paint.getMaskFilter()->filterMaskGPU(mask.texture(),
977 ctm, maskRect, &filtered, true)) {
978 // filterMaskGPU gives us ownership of a ref to the result
979 SkAutoTUnref<GrTexture> atu(filtered);
981 // If the scratch texture that we used as the filter src also holds the filter
982 // result then we must detach so that this texture isn't recycled for a later
984 if (filtered == mask.texture()) {
986 filtered->unref(); // detach transfers GrAutoScratchTexture's ref to us.
989 if (draw_mask(fContext, maskRect, &grPaint, filtered)) {
990 // This path is completely drawn
997 // draw the mask on the CPU - this is a fallthrough path in case the
999 SkPaint::Style style = stroke.isHairlineStyle() ? SkPaint::kStroke_Style :
1000 SkPaint::kFill_Style;
1001 draw_with_mask_filter(fContext, *devPathPtr, paint.getMaskFilter(),
1002 *draw.fClip, draw.fBounder, &grPaint, style);
1006 fContext->drawPath(grPaint, *pathPtr, stroke);
1009 static const int kBmpSmallTileSize = 1 << 10;
1011 static inline int get_tile_count(const SkIRect& srcRect, int tileSize) {
1012 int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1;
1013 int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1;
1014 return tilesX * tilesY;
1017 static int determine_tile_size(const SkBitmap& bitmap, const SkIRect& src, int maxTileSize) {
1018 if (maxTileSize <= kBmpSmallTileSize) {
1022 size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize);
1023 size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize);
1025 maxTileTotalTileSize *= maxTileSize * maxTileSize;
1026 smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize;
1028 if (maxTileTotalTileSize > 2 * smallTotalTileSize) {
1029 return kBmpSmallTileSize;
1035 // Given a bitmap, an optional src rect, and a context with a clip and matrix determine what
1036 // pixels from the bitmap are necessary.
1037 static void determine_clipped_src_rect(const GrContext* context,
1038 const SkBitmap& bitmap,
1039 const SkRect* srcRectPtr,
1040 SkIRect* clippedSrcIRect) {
1041 const GrClipData* clip = context->getClip();
1042 clip->getConservativeBounds(context->getRenderTarget(), clippedSrcIRect, NULL);
1044 if (!context->getMatrix().invert(&inv)) {
1045 clippedSrcIRect->setEmpty();
1048 SkRect clippedSrcRect = SkRect::Make(*clippedSrcIRect);
1049 inv.mapRect(&clippedSrcRect);
1050 if (NULL != srcRectPtr) {
1051 // we've setup src space 0,0 to map to the top left of the src rect.
1052 clippedSrcRect.offset(srcRectPtr->fLeft, srcRectPtr->fTop);
1053 if (!clippedSrcRect.intersect(*srcRectPtr)) {
1054 clippedSrcIRect->setEmpty();
1058 clippedSrcRect.roundOut(clippedSrcIRect);
1059 SkIRect bmpBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1060 if (!clippedSrcIRect->intersect(bmpBounds)) {
1061 clippedSrcIRect->setEmpty();
1065 bool SkGpuDevice::shouldTileBitmap(const SkBitmap& bitmap,
1066 const GrTextureParams& params,
1067 const SkRect* srcRectPtr,
1070 SkIRect* clippedSrcRect) const {
1071 // if bitmap is explictly texture backed then just use the texture
1072 if (NULL != bitmap.getTexture()) {
1076 // if it's larger than the max tile size, then we have no choice but tiling.
1077 if (bitmap.width() > maxTileSize || bitmap.height() > maxTileSize) {
1078 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1079 *tileSize = determine_tile_size(bitmap, *clippedSrcRect, maxTileSize);
1083 if (bitmap.width() * bitmap.height() < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
1087 // if the entire texture is already in our cache then no reason to tile it
1088 if (GrIsBitmapInCache(fContext, bitmap, ¶ms)) {
1092 // At this point we know we could do the draw by uploading the entire bitmap
1093 // as a texture. However, if the texture would be large compared to the
1094 // cache size and we don't require most of it for this draw then tile to
1095 // reduce the amount of upload and cache spill.
1097 // assumption here is that sw bitmap size is a good proxy for its size as
1099 size_t bmpSize = bitmap.getSize();
1101 fContext->getTextureCacheLimits(NULL, &cacheSize);
1102 if (bmpSize < cacheSize / 2) {
1106 // Figure out how much of the src we will need based on the src rect and clipping.
1107 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1108 *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
1109 size_t usedTileBytes = get_tile_count(*clippedSrcRect, kBmpSmallTileSize) *
1110 kBmpSmallTileSize * kBmpSmallTileSize;
1112 return usedTileBytes < 2 * bmpSize;
1115 void SkGpuDevice::drawBitmap(const SkDraw& origDraw,
1116 const SkBitmap& bitmap,
1118 const SkPaint& paint) {
1120 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1121 if (!m.isIdentity()) {
1122 concat.setConcat(*draw->fMatrix, m);
1123 draw.writable()->fMatrix = &concat;
1125 this->drawBitmapCommon(*draw, bitmap, NULL, NULL, paint, SkCanvas::kNone_DrawBitmapRectFlag);
1128 // This method outsets 'iRect' by 'outset' all around and then clamps its extents to
1129 // 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
1130 // of 'iRect' for all possible outsets/clamps.
1131 static inline void clamped_outset_with_offset(SkIRect* iRect,
1134 const SkIRect& clamp) {
1135 iRect->outset(outset, outset);
1137 int leftClampDelta = clamp.fLeft - iRect->fLeft;
1138 if (leftClampDelta > 0) {
1139 offset->fX -= outset - leftClampDelta;
1140 iRect->fLeft = clamp.fLeft;
1142 offset->fX -= outset;
1145 int topClampDelta = clamp.fTop - iRect->fTop;
1146 if (topClampDelta > 0) {
1147 offset->fY -= outset - topClampDelta;
1148 iRect->fTop = clamp.fTop;
1150 offset->fY -= outset;
1153 if (iRect->fRight > clamp.fRight) {
1154 iRect->fRight = clamp.fRight;
1156 if (iRect->fBottom > clamp.fBottom) {
1157 iRect->fBottom = clamp.fBottom;
1161 void SkGpuDevice::drawBitmapCommon(const SkDraw& draw,
1162 const SkBitmap& bitmap,
1163 const SkRect* srcRectPtr,
1164 const SkSize* dstSizePtr,
1165 const SkPaint& paint,
1166 SkCanvas::DrawBitmapRectFlags flags) {
1167 CHECK_SHOULD_DRAW(draw, false);
1171 // If there is no src rect, or the src rect contains the entire bitmap then we're effectively
1172 // in the (easier) bleed case, so update flags.
1173 if (NULL == srcRectPtr) {
1174 SkScalar w = SkIntToScalar(bitmap.width());
1175 SkScalar h = SkIntToScalar(bitmap.height());
1177 dstSize.fHeight = h;
1178 srcRect.set(0, 0, w, h);
1179 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1181 SkASSERT(NULL != dstSizePtr);
1182 srcRect = *srcRectPtr;
1183 dstSize = *dstSizePtr;
1184 if (srcRect.fLeft <= 0 && srcRect.fTop <= 0 &&
1185 srcRect.fRight >= bitmap.width() && srcRect.fBottom >= bitmap.height()) {
1186 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1190 if (paint.getMaskFilter()){
1191 // Convert the bitmap to a shader so that the rect can be drawn
1192 // through drawRect, which supports mask filters.
1193 SkBitmap tmp; // subset of bitmap, if necessary
1194 const SkBitmap* bitmapPtr = &bitmap;
1196 if (NULL != srcRectPtr) {
1197 localM.setTranslate(-srcRectPtr->fLeft, -srcRectPtr->fTop);
1198 localM.postScale(dstSize.fWidth / srcRectPtr->width(),
1199 dstSize.fHeight / srcRectPtr->height());
1200 // In bleed mode we position and trim the bitmap based on the src rect which is
1201 // already accounted for in 'm' and 'srcRect'. In clamp mode we need to chop out
1202 // the desired portion of the bitmap and then update 'm' and 'srcRect' to
1204 if (!(SkCanvas::kBleed_DrawBitmapRectFlag & flags)) {
1206 srcRect.roundOut(&iSrc);
1208 SkPoint offset = SkPoint::Make(SkIntToScalar(iSrc.fLeft),
1209 SkIntToScalar(iSrc.fTop));
1211 if (!bitmap.extractSubset(&tmp, iSrc)) {
1212 return; // extraction failed
1215 srcRect.offset(-offset.fX, -offset.fY);
1217 // The source rect has changed so update the matrix
1218 localM.preTranslate(offset.fX, offset.fY);
1224 SkPaint paintWithShader(paint);
1225 paintWithShader.setShader(SkShader::CreateBitmapShader(*bitmapPtr,
1226 SkShader::kClamp_TileMode, SkShader::kClamp_TileMode))->unref();
1227 paintWithShader.getShader()->setLocalMatrix(localM);
1228 SkRect dstRect = {0, 0, dstSize.fWidth, dstSize.fHeight};
1229 this->drawRect(draw, dstRect, paintWithShader);
1234 // If there is no mask filter than it is OK to handle the src rect -> dst rect scaling using
1235 // the view matrix rather than a local matrix.
1237 m.setScale(dstSize.fWidth / srcRect.width(),
1238 dstSize.fHeight / srcRect.height());
1239 fContext->concatMatrix(m);
1241 GrTextureParams params;
1242 SkPaint::FilterLevel paintFilterLevel = paint.getFilterLevel();
1243 GrTextureParams::FilterMode textureFilterMode;
1246 bool doBicubic = false;
1248 switch(paintFilterLevel) {
1249 case SkPaint::kNone_FilterLevel:
1251 textureFilterMode = GrTextureParams::kNone_FilterMode;
1253 case SkPaint::kLow_FilterLevel:
1255 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1257 case SkPaint::kMedium_FilterLevel:
1259 if (fContext->getMatrix().getMinStretch() < SK_Scalar1) {
1260 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1262 // Don't trigger MIP level generation unnecessarily.
1263 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1266 case SkPaint::kHigh_FilterLevel:
1267 // Minification can look bad with the bicubic effect.
1268 if (fContext->getMatrix().getMinStretch() >= SK_Scalar1) {
1269 // We will install an effect that does the filtering in the shader.
1270 textureFilterMode = GrTextureParams::kNone_FilterMode;
1271 tileFilterPad = GrBicubicEffect::kFilterTexelPad;
1274 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1279 SkErrorInternals::SetError( kInvalidPaint_SkError,
1280 "Sorry, I don't understand the filtering "
1281 "mode you asked for. Falling back to "
1284 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1288 params.setFilterMode(textureFilterMode);
1290 int maxTileSize = fContext->getMaxTextureSize() - 2 * tileFilterPad;
1293 SkIRect clippedSrcRect;
1294 if (this->shouldTileBitmap(bitmap, params, srcRectPtr, maxTileSize, &tileSize,
1296 this->drawTiledBitmap(bitmap, srcRect, clippedSrcRect, params, paint, flags, tileSize,
1299 // take the simple case
1300 this->internalDrawBitmap(bitmap, srcRect, params, paint, flags, doBicubic);
1304 // Break 'bitmap' into several tiles to draw it since it has already
1305 // been determined to be too large to fit in VRAM
1306 void SkGpuDevice::drawTiledBitmap(const SkBitmap& bitmap,
1307 const SkRect& srcRect,
1308 const SkIRect& clippedSrcIRect,
1309 const GrTextureParams& params,
1310 const SkPaint& paint,
1311 SkCanvas::DrawBitmapRectFlags flags,
1314 SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
1316 int nx = bitmap.width() / tileSize;
1317 int ny = bitmap.height() / tileSize;
1318 for (int x = 0; x <= nx; x++) {
1319 for (int y = 0; y <= ny; y++) {
1321 tileR.set(SkIntToScalar(x * tileSize),
1322 SkIntToScalar(y * tileSize),
1323 SkIntToScalar((x + 1) * tileSize),
1324 SkIntToScalar((y + 1) * tileSize));
1326 if (!SkRect::Intersects(tileR, clippedSrcRect)) {
1330 if (!tileR.intersect(srcRect)) {
1336 tileR.roundOut(&iTileR);
1337 SkPoint offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
1338 SkIntToScalar(iTileR.fTop));
1340 // Adjust the context matrix to draw at the right x,y in device space
1342 GrContext::AutoMatrix am;
1343 tmpM.setTranslate(offset.fX - srcRect.fLeft, offset.fY - srcRect.fTop);
1344 am.setPreConcat(fContext, tmpM);
1346 if (SkPaint::kNone_FilterLevel != paint.getFilterLevel() || bicubic) {
1349 if (SkCanvas::kBleed_DrawBitmapRectFlag & flags) {
1350 // In bleed mode we want to always expand the tile on all edges
1351 // but stay within the bitmap bounds
1352 iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1354 // In texture-domain/clamp mode we only want to expand the
1355 // tile on edges interior to "srcRect" (i.e., we want to
1356 // not bleed across the original clamped edges)
1357 srcRect.roundOut(&iClampRect);
1359 int outset = bicubic ? GrBicubicEffect::kFilterTexelPad : 1;
1360 clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect);
1363 if (bitmap.extractSubset(&tmpB, iTileR)) {
1364 // now offset it to make it "local" to our tmp bitmap
1365 tileR.offset(-offset.fX, -offset.fY);
1367 this->internalDrawBitmap(tmpB, tileR, params, paint, flags, bicubic);
1373 static bool has_aligned_samples(const SkRect& srcRect,
1374 const SkRect& transformedRect) {
1375 // detect pixel disalignment
1376 if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) -
1377 transformedRect.left()) < COLOR_BLEED_TOLERANCE &&
1378 SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) -
1379 transformedRect.top()) < COLOR_BLEED_TOLERANCE &&
1380 SkScalarAbs(transformedRect.width() - srcRect.width()) <
1381 COLOR_BLEED_TOLERANCE &&
1382 SkScalarAbs(transformedRect.height() - srcRect.height()) <
1383 COLOR_BLEED_TOLERANCE) {
1389 static bool may_color_bleed(const SkRect& srcRect,
1390 const SkRect& transformedRect,
1391 const SkMatrix& m) {
1392 // Only gets called if has_aligned_samples returned false.
1393 // So we can assume that sampling is axis aligned but not texel aligned.
1394 SkASSERT(!has_aligned_samples(srcRect, transformedRect));
1395 SkRect innerSrcRect(srcRect), innerTransformedRect,
1396 outerTransformedRect(transformedRect);
1397 innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
1398 m.mapRect(&innerTransformedRect, innerSrcRect);
1400 // The gap between outerTransformedRect and innerTransformedRect
1401 // represents the projection of the source border area, which is
1402 // problematic for color bleeding. We must check whether any
1403 // destination pixels sample the border area.
1404 outerTransformedRect.inset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1405 innerTransformedRect.outset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1406 SkIRect outer, inner;
1407 outerTransformedRect.round(&outer);
1408 innerTransformedRect.round(&inner);
1409 // If the inner and outer rects round to the same result, it means the
1410 // border does not overlap any pixel centers. Yay!
1411 return inner != outer;
1416 * This is called by drawBitmap(), which has to handle images that may be too
1417 * large to be represented by a single texture.
1419 * internalDrawBitmap assumes that the specified bitmap will fit in a texture
1420 * and that non-texture portion of the GrPaint has already been setup.
1422 void SkGpuDevice::internalDrawBitmap(const SkBitmap& bitmap,
1423 const SkRect& srcRect,
1424 const GrTextureParams& params,
1425 const SkPaint& paint,
1426 SkCanvas::DrawBitmapRectFlags flags,
1428 SkASSERT(bitmap.width() <= fContext->getMaxTextureSize() &&
1429 bitmap.height() <= fContext->getMaxTextureSize());
1432 SkAutoCachedTexture act(this, bitmap, ¶ms, &texture);
1433 if (NULL == texture) {
1437 SkRect dstRect = {0, 0, srcRect.width(), srcRect.height() };
1439 SkScalar wInv = SkScalarInvert(SkIntToScalar(texture->width()));
1440 SkScalar hInv = SkScalarInvert(SkIntToScalar(texture->height()));
1441 paintRect.setLTRB(SkScalarMul(srcRect.fLeft, wInv),
1442 SkScalarMul(srcRect.fTop, hInv),
1443 SkScalarMul(srcRect.fRight, wInv),
1444 SkScalarMul(srcRect.fBottom, hInv));
1446 bool needsTextureDomain = false;
1447 if (!(flags & SkCanvas::kBleed_DrawBitmapRectFlag) &&
1448 (bicubic || params.filterMode() != GrTextureParams::kNone_FilterMode)) {
1449 // Need texture domain if drawing a sub rect
1450 needsTextureDomain = srcRect.width() < bitmap.width() ||
1451 srcRect.height() < bitmap.height();
1452 if (!bicubic && needsTextureDomain && fContext->getMatrix().rectStaysRect()) {
1453 const SkMatrix& matrix = fContext->getMatrix();
1454 // sampling is axis-aligned
1455 SkRect transformedRect;
1456 matrix.mapRect(&transformedRect, srcRect);
1458 if (has_aligned_samples(srcRect, transformedRect)) {
1459 // We could also turn off filtering here (but we already did a cache lookup with
1461 needsTextureDomain = false;
1463 needsTextureDomain = may_color_bleed(srcRect, transformedRect, matrix);
1468 SkRect textureDomain = SkRect::MakeEmpty();
1469 SkAutoTUnref<GrEffectRef> effect;
1470 if (needsTextureDomain) {
1471 // Use a constrained texture domain to avoid color bleeding
1472 SkScalar left, top, right, bottom;
1473 if (srcRect.width() > SK_Scalar1) {
1474 SkScalar border = SK_ScalarHalf / texture->width();
1475 left = paintRect.left() + border;
1476 right = paintRect.right() - border;
1478 left = right = SkScalarHalf(paintRect.left() + paintRect.right());
1480 if (srcRect.height() > SK_Scalar1) {
1481 SkScalar border = SK_ScalarHalf / texture->height();
1482 top = paintRect.top() + border;
1483 bottom = paintRect.bottom() - border;
1485 top = bottom = SkScalarHalf(paintRect.top() + paintRect.bottom());
1487 textureDomain.setLTRB(left, top, right, bottom);
1489 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), textureDomain));
1491 effect.reset(GrTextureDomainEffect::Create(texture,
1494 GrTextureDomain::kClamp_Mode,
1495 params.filterMode()));
1497 } else if (bicubic) {
1498 SkASSERT(GrTextureParams::kNone_FilterMode == params.filterMode());
1499 SkShader::TileMode tileModes[2] = { params.getTileModeX(), params.getTileModeY() };
1500 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), tileModes));
1502 effect.reset(GrSimpleTextureEffect::Create(texture, SkMatrix::I(), params));
1505 // Construct a GrPaint by setting the bitmap texture as the first effect and then configuring
1506 // the rest from the SkPaint.
1508 grPaint.addColorEffect(effect);
1509 bool alphaOnly = !(SkBitmap::kA8_Config == bitmap.config());
1510 if (!skPaint2GrPaintNoShader(this, paint, alphaOnly, false, &grPaint)) {
1514 fContext->drawRectToRect(grPaint, dstRect, paintRect, NULL);
1517 static bool filter_texture(SkBaseDevice* device, GrContext* context,
1518 GrTexture* texture, const SkImageFilter* filter,
1519 int w, int h, const SkMatrix& ctm, SkBitmap* result,
1522 SkDeviceImageFilterProxy proxy(device);
1524 if (filter->canFilterImageGPU()) {
1525 // Save the render target and set it to NULL, so we don't accidentally draw to it in the
1526 // filter. Also set the clip wide open and the matrix to identity.
1527 GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
1528 return filter->filterImageGPU(&proxy, wrap_texture(texture), ctm, result, offset);
1534 void SkGpuDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap,
1535 int left, int top, const SkPaint& paint) {
1536 // drawSprite is defined to be in device coords.
1537 CHECK_SHOULD_DRAW(draw, true);
1539 SkAutoLockPixels alp(bitmap, !bitmap.getTexture());
1540 if (!bitmap.getTexture() && !bitmap.readyToDraw()) {
1544 int w = bitmap.width();
1545 int h = bitmap.height();
1548 // draw sprite uses the default texture params
1549 SkAutoCachedTexture act(this, bitmap, NULL, &texture);
1551 SkImageFilter* filter = paint.getImageFilter();
1552 // This bitmap will own the filtered result as a texture.
1553 SkBitmap filteredBitmap;
1555 if (NULL != filter) {
1556 SkIPoint offset = SkIPoint::Make(0, 0);
1557 SkMatrix matrix(*draw.fMatrix);
1558 matrix.postTranslate(SkIntToScalar(-left), SkIntToScalar(-top));
1559 if (filter_texture(this, fContext, texture, filter, w, h, matrix, &filteredBitmap,
1561 texture = (GrTexture*) filteredBitmap.getTexture();
1562 w = filteredBitmap.width();
1563 h = filteredBitmap.height();
1572 grPaint.addColorTextureEffect(texture, SkMatrix::I());
1574 if(!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1578 fContext->drawRectToRect(grPaint,
1579 SkRect::MakeXYWH(SkIntToScalar(left),
1585 SK_Scalar1 * w / texture->width(),
1586 SK_Scalar1 * h / texture->height()));
1589 void SkGpuDevice::drawBitmapRect(const SkDraw& origDraw, const SkBitmap& bitmap,
1590 const SkRect* src, const SkRect& dst,
1591 const SkPaint& paint,
1592 SkCanvas::DrawBitmapRectFlags flags) {
1594 SkRect bitmapBounds, tmpSrc;
1596 bitmapBounds.set(0, 0,
1597 SkIntToScalar(bitmap.width()),
1598 SkIntToScalar(bitmap.height()));
1600 // Compute matrix from the two rectangles
1604 tmpSrc = bitmapBounds;
1607 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1609 // clip the tmpSrc to the bounds of the bitmap. No check needed if src==null.
1611 if (!bitmapBounds.contains(tmpSrc)) {
1612 if (!tmpSrc.intersect(bitmapBounds)) {
1613 return; // nothing to draw
1619 matrix.mapRect(&tmpDst, tmpSrc);
1621 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1622 if (0 != tmpDst.fLeft || 0 != tmpDst.fTop) {
1623 // Translate so that tempDst's top left is at the origin.
1624 matrix = *origDraw.fMatrix;
1625 matrix.preTranslate(tmpDst.fLeft, tmpDst.fTop);
1626 draw.writable()->fMatrix = &matrix;
1629 dstSize.fWidth = tmpDst.width();
1630 dstSize.fHeight = tmpDst.height();
1632 this->drawBitmapCommon(*draw, bitmap, &tmpSrc, &dstSize, paint, flags);
1635 void SkGpuDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device,
1636 int x, int y, const SkPaint& paint) {
1637 // clear of the source device must occur before CHECK_SHOULD_DRAW
1638 SkGpuDevice* dev = static_cast<SkGpuDevice*>(device);
1639 if (dev->fNeedClear) {
1640 // TODO: could check here whether we really need to draw at all
1644 // drawDevice is defined to be in device coords.
1645 CHECK_SHOULD_DRAW(draw, true);
1647 GrRenderTarget* devRT = dev->accessRenderTarget();
1649 if (NULL == (devTex = devRT->asTexture())) {
1653 const SkBitmap& bm = dev->accessBitmap(false);
1655 int h = bm.height();
1657 SkImageFilter* filter = paint.getImageFilter();
1658 // This bitmap will own the filtered result as a texture.
1659 SkBitmap filteredBitmap;
1661 if (NULL != filter) {
1662 SkIPoint offset = SkIPoint::Make(0, 0);
1663 SkMatrix matrix(*draw.fMatrix);
1664 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
1665 if (filter_texture(this, fContext, devTex, filter, w, h, matrix, &filteredBitmap,
1667 devTex = filteredBitmap.getTexture();
1668 w = filteredBitmap.width();
1669 h = filteredBitmap.height();
1678 grPaint.addColorTextureEffect(devTex, SkMatrix::I());
1680 if (!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1684 SkRect dstRect = SkRect::MakeXYWH(SkIntToScalar(x),
1689 // The device being drawn may not fill up its texture (e.g. saveLayer uses approximate
1690 // scratch texture).
1691 SkRect srcRect = SkRect::MakeWH(SK_Scalar1 * w / devTex->width(),
1692 SK_Scalar1 * h / devTex->height());
1694 fContext->drawRectToRect(grPaint, dstRect, srcRect);
1697 bool SkGpuDevice::canHandleImageFilter(const SkImageFilter* filter) {
1698 return filter->canFilterImageGPU();
1701 bool SkGpuDevice::filterImage(const SkImageFilter* filter, const SkBitmap& src,
1702 const SkMatrix& ctm,
1703 SkBitmap* result, SkIPoint* offset) {
1704 // want explicitly our impl, so guard against a subclass of us overriding it
1705 if (!this->SkGpuDevice::canHandleImageFilter(filter)) {
1709 SkAutoLockPixels alp(src, !src.getTexture());
1710 if (!src.getTexture() && !src.readyToDraw()) {
1715 // We assume here that the filter will not attempt to tile the src. Otherwise, this cache lookup
1716 // must be pushed upstack.
1717 SkAutoCachedTexture act(this, src, NULL, &texture);
1719 return filter_texture(this, fContext, texture, filter, src.width(), src.height(), ctm, result,
1723 ///////////////////////////////////////////////////////////////////////////////
1725 // must be in SkCanvas::VertexMode order
1726 static const GrPrimitiveType gVertexMode2PrimitiveType[] = {
1727 kTriangles_GrPrimitiveType,
1728 kTriangleStrip_GrPrimitiveType,
1729 kTriangleFan_GrPrimitiveType,
1732 void SkGpuDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
1733 int vertexCount, const SkPoint vertices[],
1734 const SkPoint texs[], const SkColor colors[],
1736 const uint16_t indices[], int indexCount,
1737 const SkPaint& paint) {
1738 CHECK_SHOULD_DRAW(draw, false);
1741 // we ignore the shader if texs is null.
1743 if (!skPaint2GrPaintNoShader(this, paint, false, NULL == colors, &grPaint)) {
1747 if (!skPaint2GrPaintShader(this, paint, NULL == colors, &grPaint)) {
1752 if (NULL != xmode && NULL != texs && NULL != colors) {
1753 if (!SkXfermode::IsMode(xmode, SkXfermode::kModulate_Mode)) {
1754 SkDebugf("Unsupported vertex-color/texture xfer mode.\n");
1761 SkAutoSTMalloc<128, GrColor> convertedColors(0);
1762 if (NULL != colors) {
1763 // need to convert byte order and from non-PM to PM
1764 convertedColors.reset(vertexCount);
1765 for (int i = 0; i < vertexCount; ++i) {
1766 convertedColors[i] = SkColor2GrColor(colors[i]);
1768 colors = convertedColors.get();
1770 fContext->drawVertices(grPaint,
1771 gVertexMode2PrimitiveType[vmode],
1773 (GrPoint*) vertices,
1780 ///////////////////////////////////////////////////////////////////////////////
1782 void SkGpuDevice::drawText(const SkDraw& draw, const void* text,
1783 size_t byteLength, SkScalar x, SkScalar y,
1784 const SkPaint& paint) {
1785 CHECK_SHOULD_DRAW(draw, false);
1787 if (fMainTextContext->canDraw(paint)) {
1789 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1793 SkDEBUGCODE(this->validate();)
1795 fMainTextContext->drawText(grPaint, paint, (const char *)text, byteLength, x, y);
1796 } else if (fFallbackTextContext && fFallbackTextContext->canDraw(paint)) {
1798 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1802 SkDEBUGCODE(this->validate();)
1804 fFallbackTextContext->drawText(grPaint, paint, (const char *)text, byteLength, x, y);
1806 // this guy will just call our drawPath()
1807 draw.drawText_asPaths((const char*)text, byteLength, x, y, paint);
1811 void SkGpuDevice::drawPosText(const SkDraw& draw, const void* text,
1812 size_t byteLength, const SkScalar pos[],
1813 SkScalar constY, int scalarsPerPos,
1814 const SkPaint& paint) {
1815 CHECK_SHOULD_DRAW(draw, false);
1817 if (fMainTextContext->canDraw(paint)) {
1819 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1823 SkDEBUGCODE(this->validate();)
1825 fMainTextContext->drawPosText(grPaint, paint, (const char *)text, byteLength, pos,
1826 constY, scalarsPerPos);
1827 } else if (fFallbackTextContext && fFallbackTextContext->canDraw(paint)) {
1829 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1833 SkDEBUGCODE(this->validate();)
1835 fFallbackTextContext->drawPosText(grPaint, paint, (const char *)text, byteLength, pos,
1836 constY, scalarsPerPos);
1838 draw.drawPosText_asPaths((const char*)text, byteLength, pos, constY,
1839 scalarsPerPos, paint);
1843 void SkGpuDevice::drawTextOnPath(const SkDraw& draw, const void* text,
1844 size_t len, const SkPath& path,
1845 const SkMatrix* m, const SkPaint& paint) {
1846 CHECK_SHOULD_DRAW(draw, false);
1848 SkASSERT(draw.fDevice == this);
1849 draw.drawTextOnPath((const char*)text, len, path, m, paint);
1852 ///////////////////////////////////////////////////////////////////////////////
1854 bool SkGpuDevice::filterTextFlags(const SkPaint& paint, TextFlags* flags) {
1855 if (!paint.isLCDRenderText()) {
1856 // we're cool with the paint as is
1860 if (paint.getShader() ||
1861 paint.getXfermode() || // unless its srcover
1862 paint.getMaskFilter() ||
1863 paint.getRasterizer() ||
1864 paint.getColorFilter() ||
1865 paint.getPathEffect() ||
1866 paint.isFakeBoldText() ||
1867 paint.getStyle() != SkPaint::kFill_Style) {
1869 flags->fFlags = paint.getFlags() & ~SkPaint::kLCDRenderText_Flag;
1870 flags->fHinting = paint.getHinting();
1873 // we're cool with the paint as is
1877 void SkGpuDevice::flush() {
1878 DO_DEFERRED_CLEAR();
1879 fContext->resolveRenderTarget(fRenderTarget);
1882 ///////////////////////////////////////////////////////////////////////////////
1884 SkBaseDevice* SkGpuDevice::onCreateCompatibleDevice(SkBitmap::Config config,
1885 int width, int height,
1889 desc.fConfig = fRenderTarget->config();
1890 desc.fFlags = kRenderTarget_GrTextureFlagBit;
1891 desc.fWidth = width;
1892 desc.fHeight = height;
1893 desc.fSampleCnt = fRenderTarget->numSamples();
1895 SkAutoTUnref<GrTexture> texture;
1896 // Skia's convention is to only clear a device if it is non-opaque.
1897 bool needClear = !isOpaque;
1899 #if CACHE_COMPATIBLE_DEVICE_TEXTURES
1900 // layers are never draw in repeat modes, so we can request an approx
1901 // match and ignore any padding.
1902 const GrContext::ScratchTexMatch match = (kSaveLayer_Usage == usage) ?
1903 GrContext::kApprox_ScratchTexMatch :
1904 GrContext::kExact_ScratchTexMatch;
1905 texture.reset(fContext->lockAndRefScratchTexture(desc, match));
1907 texture.reset(fContext->createUncachedTexture(desc, NULL, 0));
1909 if (NULL != texture.get()) {
1910 return SkNEW_ARGS(SkGpuDevice,(fContext, texture, needClear));
1912 GrPrintf("---- failed to create compatible device texture [%d %d]\n", width, height);
1917 SkSurface* SkGpuDevice::newSurface(const SkImageInfo& info) {
1918 return SkSurface::NewRenderTarget(fContext, info, fRenderTarget->numSamples());
1921 SkGpuDevice::SkGpuDevice(GrContext* context,
1924 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
1926 SkASSERT(texture && texture->asRenderTarget());
1927 // This constructor is called from onCreateCompatibleDevice. It has locked the RT in the texture
1928 // cache. We pass true for the third argument so that it will get unlocked.
1929 this->initFromRenderTarget(context, texture->asRenderTarget(), true);
1930 fNeedClear = needClear;