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