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