blob: c997b79bde5c2ea741b39524bb285dcd6dee73b4 [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
509 // SkShader::asNewEffect() may do offscreen rendering. Setup default drawing state
510 // Also require shader to set the render target .
511 GrContext::AutoWideOpenIdentityDraw awo(dev->context(), NULL);
512 GrContext::AutoRenderTarget(dev->context(), NULL);
513
514 // setup the shader as the first color effect on the paint
515 SkAutoTUnref<GrEffectRef> effect(shader->asNewEffect(dev->context(), skPaint));
516 if (NULL != effect.get()) {
517 grPaint->addColorEffect(effect);
518 // Now setup the rest of the paint.
519 return skPaint2GrPaintNoShader(dev, skPaint, true, false, grPaint);
520 } else {
521 // We still don't have SkColorShader::asNewEffect() implemented.
522 SkShader::GradientInfo info;
523 SkColor color;
524
525 info.fColors = &color;
526 info.fColorOffsets = NULL;
527 info.fColorCount = 1;
528 if (SkShader::kColor_GradientType == shader->asAGradient(&info)) {
529 SkPaint copy(skPaint);
530 copy.setShader(NULL);
531 // modulate the paint alpha by the shader's solid color alpha
532 U8CPU newA = SkMulDiv255Round(SkColorGetA(color), copy.getAlpha());
533 copy.setColor(SkColorSetA(color, newA));
534 return skPaint2GrPaintNoShader(dev, copy, false, constantColor, grPaint);
535 } else {
536 return false;
537 }
538 }
539}
540}
541
542///////////////////////////////////////////////////////////////////////////////
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000543
544SkBitmap::Config SkGpuDevice::config() const {
545 if (NULL == fRenderTarget) {
546 return SkBitmap::kNo_Config;
547 }
548
549 bool isOpaque;
550 return grConfig2skConfig(fRenderTarget->config(), &isOpaque);
551}
552
553void SkGpuDevice::clear(SkColor color) {
554 SkIRect rect = SkIRect::MakeWH(this->width(), this->height());
555 fContext->clear(&rect, SkColor2GrColor(color), true, fRenderTarget);
556 fNeedClear = false;
557}
558
559void SkGpuDevice::drawPaint(const SkDraw& draw, const SkPaint& paint) {
560 CHECK_SHOULD_DRAW(draw, false);
561
562 GrPaint grPaint;
563 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
564 return;
565 }
566
567 fContext->drawPaint(grPaint);
568}
569
570// must be in SkCanvas::PointMode order
571static const GrPrimitiveType gPointMode2PrimtiveType[] = {
572 kPoints_GrPrimitiveType,
573 kLines_GrPrimitiveType,
574 kLineStrip_GrPrimitiveType
575};
576
577void SkGpuDevice::drawPoints(const SkDraw& draw, SkCanvas::PointMode mode,
578 size_t count, const SkPoint pts[], const SkPaint& paint) {
579 CHECK_FOR_ANNOTATION(paint);
580 CHECK_SHOULD_DRAW(draw, false);
581
582 SkScalar width = paint.getStrokeWidth();
583 if (width < 0) {
584 return;
585 }
586
587 // we only handle hairlines and paints without path effects or mask filters,
588 // else we let the SkDraw call our drawPath()
589 if (width > 0 || paint.getPathEffect() || paint.getMaskFilter()) {
590 draw.drawPoints(mode, count, pts, paint, true);
591 return;
592 }
593
594 GrPaint grPaint;
595 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
596 return;
597 }
598
599 fContext->drawVertices(grPaint,
600 gPointMode2PrimtiveType[mode],
robertphillips@google.coma4662862013-11-21 14:24:16 +0000601 SkToS32(count),
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000602 (GrPoint*)pts,
603 NULL,
604 NULL,
605 NULL,
606 0);
607}
608
609///////////////////////////////////////////////////////////////////////////////
610
611void SkGpuDevice::drawRect(const SkDraw& draw, const SkRect& rect,
612 const SkPaint& paint) {
613 CHECK_FOR_ANNOTATION(paint);
614 CHECK_SHOULD_DRAW(draw, false);
615
616 bool doStroke = paint.getStyle() != SkPaint::kFill_Style;
617 SkScalar width = paint.getStrokeWidth();
618
619 /*
620 We have special code for hairline strokes, miter-strokes, bevel-stroke
621 and fills. Anything else we just call our path code.
622 */
623 bool usePath = doStroke && width > 0 &&
624 (paint.getStrokeJoin() == SkPaint::kRound_Join ||
625 (paint.getStrokeJoin() == SkPaint::kBevel_Join && rect.isEmpty()));
626 // another two reasons we might need to call drawPath...
627 if (paint.getMaskFilter() || paint.getPathEffect()) {
628 usePath = true;
629 }
630 if (!usePath && paint.isAntiAlias() && !fContext->getMatrix().rectStaysRect()) {
631#if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
632 if (doStroke) {
633#endif
634 usePath = true;
635#if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
636 } else {
637 usePath = !fContext->getMatrix().preservesRightAngles();
638 }
639#endif
640 }
641 // until we can both stroke and fill rectangles
642 if (paint.getStyle() == SkPaint::kStrokeAndFill_Style) {
643 usePath = true;
644 }
645
646 if (usePath) {
647 SkPath path;
648 path.addRect(rect);
649 this->drawPath(draw, path, paint, NULL, true);
650 return;
651 }
652
653 GrPaint grPaint;
654 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
655 return;
656 }
657
658 if (!doStroke) {
659 fContext->drawRect(grPaint, rect);
660 } else {
661 SkStrokeRec stroke(paint);
662 fContext->drawRect(grPaint, rect, &stroke);
663 }
664}
665
666///////////////////////////////////////////////////////////////////////////////
667
668void SkGpuDevice::drawRRect(const SkDraw& draw, const SkRRect& rect,
669 const SkPaint& paint) {
670 CHECK_FOR_ANNOTATION(paint);
671 CHECK_SHOULD_DRAW(draw, false);
672
673 bool usePath = !rect.isSimple();
674 // another two reasons we might need to call drawPath...
675 if (paint.getMaskFilter() || paint.getPathEffect()) {
676 usePath = true;
677 }
678 // until we can rotate rrects...
679 if (!usePath && !fContext->getMatrix().rectStaysRect()) {
680 usePath = true;
681 }
682
683 if (usePath) {
684 SkPath path;
685 path.addRRect(rect);
686 this->drawPath(draw, path, paint, NULL, true);
687 return;
688 }
689
690 GrPaint grPaint;
691 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
692 return;
693 }
694
695 SkStrokeRec stroke(paint);
696 fContext->drawRRect(grPaint, rect, stroke);
697}
698
699///////////////////////////////////////////////////////////////////////////////
700
701void SkGpuDevice::drawOval(const SkDraw& draw, const SkRect& oval,
702 const SkPaint& paint) {
703 CHECK_FOR_ANNOTATION(paint);
704 CHECK_SHOULD_DRAW(draw, false);
705
706 bool usePath = false;
707 // some basic reasons we might need to call drawPath...
708 if (paint.getMaskFilter() || paint.getPathEffect()) {
709 usePath = true;
710 }
711
712 if (usePath) {
713 SkPath path;
714 path.addOval(oval);
715 this->drawPath(draw, path, paint, NULL, true);
716 return;
717 }
718
719 GrPaint grPaint;
720 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
721 return;
722 }
723 SkStrokeRec stroke(paint);
724
725 fContext->drawOval(grPaint, oval, stroke);
726}
727
728#include "SkMaskFilter.h"
729#include "SkBounder.h"
730
731///////////////////////////////////////////////////////////////////////////////
732
733// helpers for applying mask filters
734namespace {
735
736// Draw a mask using the supplied paint. Since the coverage/geometry
737// is already burnt into the mask this boils down to a rect draw.
738// Return true if the mask was successfully drawn.
739bool draw_mask(GrContext* context, const SkRect& maskRect,
740 GrPaint* grp, GrTexture* mask) {
741 GrContext::AutoMatrix am;
742 if (!am.setIdentity(context, grp)) {
743 return false;
744 }
745
746 SkMatrix matrix;
747 matrix.setTranslate(-maskRect.fLeft, -maskRect.fTop);
748 matrix.postIDiv(mask->width(), mask->height());
749
750 grp->addCoverageEffect(GrSimpleTextureEffect::Create(mask, matrix))->unref();
751 context->drawRect(*grp, maskRect);
752 return true;
753}
754
755bool draw_with_mask_filter(GrContext* context, const SkPath& devPath,
756 SkMaskFilter* filter, const SkRegion& clip, SkBounder* bounder,
757 GrPaint* grp, SkPaint::Style style) {
758 SkMask srcM, dstM;
759
760 if (!SkDraw::DrawToMask(devPath, &clip.getBounds(), filter, &context->getMatrix(), &srcM,
761 SkMask::kComputeBoundsAndRenderImage_CreateMode, style)) {
762 return false;
763 }
764 SkAutoMaskFreeImage autoSrc(srcM.fImage);
765
766 if (!filter->filterMask(&dstM, srcM, context->getMatrix(), NULL)) {
767 return false;
768 }
769 // this will free-up dstM when we're done (allocated in filterMask())
770 SkAutoMaskFreeImage autoDst(dstM.fImage);
771
772 if (clip.quickReject(dstM.fBounds)) {
773 return false;
774 }
775 if (bounder && !bounder->doIRect(dstM.fBounds)) {
776 return false;
777 }
778
779 // we now have a device-aligned 8bit mask in dstM, ready to be drawn using
780 // the current clip (and identity matrix) and GrPaint settings
781 GrTextureDesc desc;
782 desc.fWidth = dstM.fBounds.width();
783 desc.fHeight = dstM.fBounds.height();
784 desc.fConfig = kAlpha_8_GrPixelConfig;
785
786 GrAutoScratchTexture ast(context, desc);
787 GrTexture* texture = ast.texture();
788
789 if (NULL == texture) {
790 return false;
791 }
792 texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig,
793 dstM.fImage, dstM.fRowBytes);
794
795 SkRect maskRect = SkRect::Make(dstM.fBounds);
796
797 return draw_mask(context, maskRect, grp, texture);
798}
799
800// Create a mask of 'devPath' and place the result in 'mask'. Return true on
801// success; false otherwise.
802bool create_mask_GPU(GrContext* context,
803 const SkRect& maskRect,
804 const SkPath& devPath,
805 const SkStrokeRec& stroke,
806 bool doAA,
807 GrAutoScratchTexture* mask) {
808 GrTextureDesc desc;
809 desc.fFlags = kRenderTarget_GrTextureFlagBit;
810 desc.fWidth = SkScalarCeilToInt(maskRect.width());
811 desc.fHeight = SkScalarCeilToInt(maskRect.height());
812 // We actually only need A8, but it often isn't supported as a
813 // render target so default to RGBA_8888
814 desc.fConfig = kRGBA_8888_GrPixelConfig;
815 if (context->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
816 desc.fConfig = kAlpha_8_GrPixelConfig;
817 }
818
819 mask->set(context, desc);
820 if (NULL == mask->texture()) {
821 return false;
822 }
823
824 GrTexture* maskTexture = mask->texture();
825 SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height());
826
827 GrContext::AutoRenderTarget art(context, maskTexture->asRenderTarget());
828 GrContext::AutoClip ac(context, clipRect);
829
830 context->clear(NULL, 0x0, true);
831
832 GrPaint tempPaint;
833 if (doAA) {
834 tempPaint.setAntiAlias(true);
835 // AA uses the "coverage" stages on GrDrawTarget. Coverage with a dst
836 // blend coeff of zero requires dual source blending support in order
837 // to properly blend partially covered pixels. This means the AA
838 // code path may not be taken. So we use a dst blend coeff of ISA. We
839 // could special case AA draws to a dst surface with known alpha=0 to
840 // use a zero dst coeff when dual source blending isn't available.
841 tempPaint.setBlendFunc(kOne_GrBlendCoeff, kISC_GrBlendCoeff);
842 }
843
844 GrContext::AutoMatrix am;
845
846 // Draw the mask into maskTexture with the path's top-left at the origin using tempPaint.
847 SkMatrix translate;
848 translate.setTranslate(-maskRect.fLeft, -maskRect.fTop);
849 am.set(context, translate);
850 context->drawPath(tempPaint, devPath, stroke);
851 return true;
852}
853
854SkBitmap wrap_texture(GrTexture* texture) {
reed@google.combf790232013-12-13 19:45:58 +0000855 SkImageInfo info;
856 texture->asImageInfo(&info);
857
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000858 SkBitmap result;
reed@google.combf790232013-12-13 19:45:58 +0000859 result.setConfig(info);
860 result.setPixelRef(SkNEW_ARGS(SkGrPixelRef, (info, texture)))->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000861 return result;
862}
863
864};
865
866void SkGpuDevice::drawPath(const SkDraw& draw, const SkPath& origSrcPath,
867 const SkPaint& paint, const SkMatrix* prePathMatrix,
868 bool pathIsMutable) {
869 CHECK_FOR_ANNOTATION(paint);
870 CHECK_SHOULD_DRAW(draw, false);
871
872 GrPaint grPaint;
873 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
874 return;
875 }
876
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000877 // If we have a prematrix, apply it to the path, optimizing for the case
878 // where the original path can in fact be modified in place (even though
879 // its parameter type is const).
880 SkPath* pathPtr = const_cast<SkPath*>(&origSrcPath);
881 SkPath tmpPath, effectPath;
882
883 if (prePathMatrix) {
884 SkPath* result = pathPtr;
885
886 if (!pathIsMutable) {
887 result = &tmpPath;
888 pathIsMutable = true;
889 }
890 // should I push prePathMatrix on our MV stack temporarily, instead
891 // of applying it here? See SkDraw.cpp
892 pathPtr->transform(*prePathMatrix, result);
893 pathPtr = result;
894 }
895 // at this point we're done with prePathMatrix
896 SkDEBUGCODE(prePathMatrix = (const SkMatrix*)0x50FF8001;)
897
898 SkStrokeRec stroke(paint);
899 SkPathEffect* pathEffect = paint.getPathEffect();
900 const SkRect* cullRect = NULL; // TODO: what is our bounds?
901 if (pathEffect && pathEffect->filterPath(&effectPath, *pathPtr, &stroke,
902 cullRect)) {
903 pathPtr = &effectPath;
904 }
905
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000906 if (paint.getMaskFilter()) {
907 if (!stroke.isHairlineStyle()) {
908 if (stroke.applyToPath(&tmpPath, *pathPtr)) {
909 pathPtr = &tmpPath;
910 pathIsMutable = true;
911 stroke.setFillStyle();
912 }
913 }
914
915 // avoid possibly allocating a new path in transform if we can
916 SkPath* devPathPtr = pathIsMutable ? pathPtr : &tmpPath;
917
918 // transform the path into device space
919 pathPtr->transform(fContext->getMatrix(), devPathPtr);
920
921 SkRect maskRect;
922 if (paint.getMaskFilter()->canFilterMaskGPU(devPathPtr->getBounds(),
923 draw.fClip->getBounds(),
924 fContext->getMatrix(),
925 &maskRect)) {
926 SkIRect finalIRect;
927 maskRect.roundOut(&finalIRect);
928 if (draw.fClip->quickReject(finalIRect)) {
929 // clipped out
930 return;
931 }
932 if (NULL != draw.fBounder && !draw.fBounder->doIRect(finalIRect)) {
933 // nothing to draw
934 return;
935 }
936
937 GrAutoScratchTexture mask;
938
939 if (create_mask_GPU(fContext, maskRect, *devPathPtr, stroke,
940 grPaint.isAntiAlias(), &mask)) {
941 GrTexture* filtered;
942
commit-bot@chromium.org41bf9302014-01-08 22:25:53 +0000943 if (paint.getMaskFilter()->filterMaskGPU(mask.texture(),
944 fContext->getMatrix(), maskRect,
945 &filtered, true)) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000946 // filterMaskGPU gives us ownership of a ref to the result
947 SkAutoTUnref<GrTexture> atu(filtered);
948
949 // If the scratch texture that we used as the filter src also holds the filter
950 // result then we must detach so that this texture isn't recycled for a later
951 // draw.
952 if (filtered == mask.texture()) {
953 mask.detach();
954 filtered->unref(); // detach transfers GrAutoScratchTexture's ref to us.
955 }
956
957 if (draw_mask(fContext, maskRect, &grPaint, filtered)) {
958 // This path is completely drawn
959 return;
960 }
961 }
962 }
963 }
964
965 // draw the mask on the CPU - this is a fallthrough path in case the
966 // GPU path fails
967 SkPaint::Style style = stroke.isHairlineStyle() ? SkPaint::kStroke_Style :
968 SkPaint::kFill_Style;
969 draw_with_mask_filter(fContext, *devPathPtr, paint.getMaskFilter(),
970 *draw.fClip, draw.fBounder, &grPaint, style);
971 return;
972 }
973
974 fContext->drawPath(grPaint, *pathPtr, stroke);
975}
976
977static const int kBmpSmallTileSize = 1 << 10;
978
979static inline int get_tile_count(const SkIRect& srcRect, int tileSize) {
980 int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1;
981 int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1;
982 return tilesX * tilesY;
983}
984
985static int determine_tile_size(const SkBitmap& bitmap, const SkIRect& src, int maxTileSize) {
986 if (maxTileSize <= kBmpSmallTileSize) {
987 return maxTileSize;
988 }
989
990 size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize);
991 size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize);
992
993 maxTileTotalTileSize *= maxTileSize * maxTileSize;
994 smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize;
995
996 if (maxTileTotalTileSize > 2 * smallTotalTileSize) {
997 return kBmpSmallTileSize;
998 } else {
999 return maxTileSize;
1000 }
1001}
1002
1003// Given a bitmap, an optional src rect, and a context with a clip and matrix determine what
1004// pixels from the bitmap are necessary.
1005static void determine_clipped_src_rect(const GrContext* context,
1006 const SkBitmap& bitmap,
1007 const SkRect* srcRectPtr,
1008 SkIRect* clippedSrcIRect) {
1009 const GrClipData* clip = context->getClip();
1010 clip->getConservativeBounds(context->getRenderTarget(), clippedSrcIRect, NULL);
1011 SkMatrix inv;
1012 if (!context->getMatrix().invert(&inv)) {
1013 clippedSrcIRect->setEmpty();
1014 return;
1015 }
1016 SkRect clippedSrcRect = SkRect::Make(*clippedSrcIRect);
1017 inv.mapRect(&clippedSrcRect);
1018 if (NULL != srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001019 // we've setup src space 0,0 to map to the top left of the src rect.
1020 clippedSrcRect.offset(srcRectPtr->fLeft, srcRectPtr->fTop);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001021 if (!clippedSrcRect.intersect(*srcRectPtr)) {
1022 clippedSrcIRect->setEmpty();
1023 return;
1024 }
1025 }
1026 clippedSrcRect.roundOut(clippedSrcIRect);
1027 SkIRect bmpBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1028 if (!clippedSrcIRect->intersect(bmpBounds)) {
1029 clippedSrcIRect->setEmpty();
1030 }
1031}
1032
1033bool SkGpuDevice::shouldTileBitmap(const SkBitmap& bitmap,
1034 const GrTextureParams& params,
1035 const SkRect* srcRectPtr,
1036 int maxTileSize,
1037 int* tileSize,
1038 SkIRect* clippedSrcRect) const {
1039 // if bitmap is explictly texture backed then just use the texture
1040 if (NULL != bitmap.getTexture()) {
1041 return false;
1042 }
1043
1044 // if it's larger than the max tile size, then we have no choice but tiling.
1045 if (bitmap.width() > maxTileSize || bitmap.height() > maxTileSize) {
1046 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1047 *tileSize = determine_tile_size(bitmap, *clippedSrcRect, maxTileSize);
1048 return true;
1049 }
1050
1051 if (bitmap.width() * bitmap.height() < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
1052 return false;
1053 }
1054
1055 // if the entire texture is already in our cache then no reason to tile it
1056 if (GrIsBitmapInCache(fContext, bitmap, &params)) {
1057 return false;
1058 }
1059
1060 // At this point we know we could do the draw by uploading the entire bitmap
1061 // as a texture. However, if the texture would be large compared to the
1062 // cache size and we don't require most of it for this draw then tile to
1063 // reduce the amount of upload and cache spill.
1064
1065 // assumption here is that sw bitmap size is a good proxy for its size as
1066 // a texture
1067 size_t bmpSize = bitmap.getSize();
1068 size_t cacheSize;
1069 fContext->getTextureCacheLimits(NULL, &cacheSize);
1070 if (bmpSize < cacheSize / 2) {
1071 return false;
1072 }
1073
1074 // Figure out how much of the src we will need based on the src rect and clipping.
1075 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1076 *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
1077 size_t usedTileBytes = get_tile_count(*clippedSrcRect, kBmpSmallTileSize) *
1078 kBmpSmallTileSize * kBmpSmallTileSize;
1079
1080 return usedTileBytes < 2 * bmpSize;
1081}
1082
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001083void SkGpuDevice::drawBitmap(const SkDraw& origDraw,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001084 const SkBitmap& bitmap,
1085 const SkMatrix& m,
1086 const SkPaint& paint) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001087 SkMatrix concat;
1088 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1089 if (!m.isIdentity()) {
1090 concat.setConcat(*draw->fMatrix, m);
1091 draw.writable()->fMatrix = &concat;
1092 }
1093 this->drawBitmapCommon(*draw, bitmap, NULL, NULL, paint, SkCanvas::kNone_DrawBitmapRectFlag);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001094}
1095
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001096// This method outsets 'iRect' by 'outset' all around and then clamps its extents to
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001097// 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
1098// of 'iRect' for all possible outsets/clamps.
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001099static inline void clamped_outset_with_offset(SkIRect* iRect,
1100 int outset,
1101 SkPoint* offset,
1102 const SkIRect& clamp) {
1103 iRect->outset(outset, outset);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001104
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001105 int leftClampDelta = clamp.fLeft - iRect->fLeft;
1106 if (leftClampDelta > 0) {
1107 offset->fX -= outset - leftClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001108 iRect->fLeft = clamp.fLeft;
1109 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001110 offset->fX -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001111 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001112
1113 int topClampDelta = clamp.fTop - iRect->fTop;
1114 if (topClampDelta > 0) {
1115 offset->fY -= outset - topClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001116 iRect->fTop = clamp.fTop;
1117 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001118 offset->fY -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001119 }
1120
1121 if (iRect->fRight > clamp.fRight) {
1122 iRect->fRight = clamp.fRight;
1123 }
1124 if (iRect->fBottom > clamp.fBottom) {
1125 iRect->fBottom = clamp.fBottom;
1126 }
1127}
1128
1129void SkGpuDevice::drawBitmapCommon(const SkDraw& draw,
1130 const SkBitmap& bitmap,
1131 const SkRect* srcRectPtr,
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001132 const SkSize* dstSizePtr,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001133 const SkPaint& paint,
1134 SkCanvas::DrawBitmapRectFlags flags) {
1135 CHECK_SHOULD_DRAW(draw, false);
1136
1137 SkRect srcRect;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001138 SkSize dstSize;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001139 // If there is no src rect, or the src rect contains the entire bitmap then we're effectively
1140 // in the (easier) bleed case, so update flags.
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001141 if (NULL == srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001142 SkScalar w = SkIntToScalar(bitmap.width());
1143 SkScalar h = SkIntToScalar(bitmap.height());
1144 dstSize.fWidth = w;
1145 dstSize.fHeight = h;
1146 srcRect.set(0, 0, w, h);
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001147 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001148 } else {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001149 SkASSERT(NULL != dstSizePtr);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001150 srcRect = *srcRectPtr;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001151 dstSize = *dstSizePtr;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001152 if (srcRect.fLeft <= 0 && srcRect.fTop <= 0 &&
1153 srcRect.fRight >= bitmap.width() && srcRect.fBottom >= bitmap.height()) {
1154 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1155 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001156 }
1157
1158 if (paint.getMaskFilter()){
1159 // Convert the bitmap to a shader so that the rect can be drawn
1160 // through drawRect, which supports mask filters.
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001161 SkBitmap tmp; // subset of bitmap, if necessary
1162 const SkBitmap* bitmapPtr = &bitmap;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001163 SkMatrix localM;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001164 if (NULL != srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001165 localM.setTranslate(-srcRectPtr->fLeft, -srcRectPtr->fTop);
1166 localM.postScale(dstSize.fWidth / srcRectPtr->width(),
1167 dstSize.fHeight / srcRectPtr->height());
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001168 // In bleed mode we position and trim the bitmap based on the src rect which is
1169 // already accounted for in 'm' and 'srcRect'. In clamp mode we need to chop out
1170 // the desired portion of the bitmap and then update 'm' and 'srcRect' to
1171 // compensate.
1172 if (!(SkCanvas::kBleed_DrawBitmapRectFlag & flags)) {
1173 SkIRect iSrc;
1174 srcRect.roundOut(&iSrc);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001175
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001176 SkPoint offset = SkPoint::Make(SkIntToScalar(iSrc.fLeft),
1177 SkIntToScalar(iSrc.fTop));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001178
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001179 if (!bitmap.extractSubset(&tmp, iSrc)) {
1180 return; // extraction failed
1181 }
1182 bitmapPtr = &tmp;
1183 srcRect.offset(-offset.fX, -offset.fY);
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001184
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001185 // The source rect has changed so update the matrix
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001186 localM.preTranslate(offset.fX, offset.fY);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001187 }
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001188 } else {
1189 localM.reset();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001190 }
1191
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001192 SkPaint paintWithShader(paint);
1193 paintWithShader.setShader(SkShader::CreateBitmapShader(*bitmapPtr,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001194 SkShader::kClamp_TileMode, SkShader::kClamp_TileMode))->unref();
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001195 paintWithShader.getShader()->setLocalMatrix(localM);
1196 SkRect dstRect = {0, 0, dstSize.fWidth, dstSize.fHeight};
1197 this->drawRect(draw, dstRect, paintWithShader);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001198
1199 return;
1200 }
1201
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001202 // If there is no mask filter than it is OK to handle the src rect -> dst rect scaling using
1203 // the view matrix rather than a local matrix.
1204 SkMatrix m;
1205 m.setScale(dstSize.fWidth / srcRect.width(),
1206 dstSize.fHeight / srcRect.height());
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001207 fContext->concatMatrix(m);
1208
1209 GrTextureParams params;
1210 SkPaint::FilterLevel paintFilterLevel = paint.getFilterLevel();
1211 GrTextureParams::FilterMode textureFilterMode;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001212
1213 int tileFilterPad;
1214 bool doBicubic = false;
1215
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001216 switch(paintFilterLevel) {
1217 case SkPaint::kNone_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001218 tileFilterPad = 0;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001219 textureFilterMode = GrTextureParams::kNone_FilterMode;
1220 break;
1221 case SkPaint::kLow_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001222 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001223 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1224 break;
1225 case SkPaint::kMedium_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001226 tileFilterPad = 1;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001227 if (fContext->getMatrix().getMinStretch() < SK_Scalar1) {
1228 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1229 } else {
1230 // Don't trigger MIP level generation unnecessarily.
1231 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1232 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001233 break;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001234 case SkPaint::kHigh_FilterLevel:
commit-bot@chromium.orgcea9abb2013-12-09 19:15:37 +00001235 // Minification can look bad with the bicubic effect.
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001236 if (fContext->getMatrix().getMinStretch() >= SK_Scalar1) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001237 // We will install an effect that does the filtering in the shader.
1238 textureFilterMode = GrTextureParams::kNone_FilterMode;
1239 tileFilterPad = GrBicubicEffect::kFilterTexelPad;
1240 doBicubic = true;
1241 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001242 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1243 tileFilterPad = 1;
1244 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001245 break;
1246 default:
1247 SkErrorInternals::SetError( kInvalidPaint_SkError,
1248 "Sorry, I don't understand the filtering "
1249 "mode you asked for. Falling back to "
1250 "MIPMaps.");
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001251 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001252 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1253 break;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001254 }
1255
1256 params.setFilterMode(textureFilterMode);
1257
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001258 int maxTileSize = fContext->getMaxTextureSize() - 2 * tileFilterPad;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001259 int tileSize;
1260
1261 SkIRect clippedSrcRect;
1262 if (this->shouldTileBitmap(bitmap, params, srcRectPtr, maxTileSize, &tileSize,
1263 &clippedSrcRect)) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001264 this->drawTiledBitmap(bitmap, srcRect, clippedSrcRect, params, paint, flags, tileSize,
1265 doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001266 } else {
1267 // take the simple case
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001268 this->internalDrawBitmap(bitmap, srcRect, params, paint, flags, doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001269 }
1270}
1271
1272// Break 'bitmap' into several tiles to draw it since it has already
1273// been determined to be too large to fit in VRAM
1274void SkGpuDevice::drawTiledBitmap(const SkBitmap& bitmap,
1275 const SkRect& srcRect,
1276 const SkIRect& clippedSrcIRect,
1277 const GrTextureParams& params,
1278 const SkPaint& paint,
1279 SkCanvas::DrawBitmapRectFlags flags,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001280 int tileSize,
1281 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001282 SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
1283
1284 int nx = bitmap.width() / tileSize;
1285 int ny = bitmap.height() / tileSize;
1286 for (int x = 0; x <= nx; x++) {
1287 for (int y = 0; y <= ny; y++) {
1288 SkRect tileR;
1289 tileR.set(SkIntToScalar(x * tileSize),
1290 SkIntToScalar(y * tileSize),
1291 SkIntToScalar((x + 1) * tileSize),
1292 SkIntToScalar((y + 1) * tileSize));
1293
1294 if (!SkRect::Intersects(tileR, clippedSrcRect)) {
1295 continue;
1296 }
1297
1298 if (!tileR.intersect(srcRect)) {
1299 continue;
1300 }
1301
1302 SkBitmap tmpB;
1303 SkIRect iTileR;
1304 tileR.roundOut(&iTileR);
1305 SkPoint offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
1306 SkIntToScalar(iTileR.fTop));
1307
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001308 // Adjust the context matrix to draw at the right x,y in device space
1309 SkMatrix tmpM;
1310 GrContext::AutoMatrix am;
1311 tmpM.setTranslate(offset.fX - srcRect.fLeft, offset.fY - srcRect.fTop);
1312 am.setPreConcat(fContext, tmpM);
1313
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001314 if (SkPaint::kNone_FilterLevel != paint.getFilterLevel() || bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001315 SkIRect iClampRect;
1316
1317 if (SkCanvas::kBleed_DrawBitmapRectFlag & flags) {
1318 // In bleed mode we want to always expand the tile on all edges
1319 // but stay within the bitmap bounds
1320 iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1321 } else {
1322 // In texture-domain/clamp mode we only want to expand the
1323 // tile on edges interior to "srcRect" (i.e., we want to
1324 // not bleed across the original clamped edges)
1325 srcRect.roundOut(&iClampRect);
1326 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001327 int outset = bicubic ? GrBicubicEffect::kFilterTexelPad : 1;
1328 clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001329 }
1330
1331 if (bitmap.extractSubset(&tmpB, iTileR)) {
1332 // now offset it to make it "local" to our tmp bitmap
1333 tileR.offset(-offset.fX, -offset.fY);
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001334
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001335 this->internalDrawBitmap(tmpB, tileR, params, paint, flags, bicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001336 }
1337 }
1338 }
1339}
1340
1341static bool has_aligned_samples(const SkRect& srcRect,
1342 const SkRect& transformedRect) {
1343 // detect pixel disalignment
1344 if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) -
1345 transformedRect.left()) < COLOR_BLEED_TOLERANCE &&
1346 SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) -
1347 transformedRect.top()) < COLOR_BLEED_TOLERANCE &&
1348 SkScalarAbs(transformedRect.width() - srcRect.width()) <
1349 COLOR_BLEED_TOLERANCE &&
1350 SkScalarAbs(transformedRect.height() - srcRect.height()) <
1351 COLOR_BLEED_TOLERANCE) {
1352 return true;
1353 }
1354 return false;
1355}
1356
1357static bool may_color_bleed(const SkRect& srcRect,
1358 const SkRect& transformedRect,
1359 const SkMatrix& m) {
1360 // Only gets called if has_aligned_samples returned false.
1361 // So we can assume that sampling is axis aligned but not texel aligned.
1362 SkASSERT(!has_aligned_samples(srcRect, transformedRect));
1363 SkRect innerSrcRect(srcRect), innerTransformedRect,
1364 outerTransformedRect(transformedRect);
1365 innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
1366 m.mapRect(&innerTransformedRect, innerSrcRect);
1367
1368 // The gap between outerTransformedRect and innerTransformedRect
1369 // represents the projection of the source border area, which is
1370 // problematic for color bleeding. We must check whether any
1371 // destination pixels sample the border area.
1372 outerTransformedRect.inset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1373 innerTransformedRect.outset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1374 SkIRect outer, inner;
1375 outerTransformedRect.round(&outer);
1376 innerTransformedRect.round(&inner);
1377 // If the inner and outer rects round to the same result, it means the
1378 // border does not overlap any pixel centers. Yay!
1379 return inner != outer;
1380}
1381
1382
1383/*
1384 * This is called by drawBitmap(), which has to handle images that may be too
1385 * large to be represented by a single texture.
1386 *
1387 * internalDrawBitmap assumes that the specified bitmap will fit in a texture
1388 * and that non-texture portion of the GrPaint has already been setup.
1389 */
1390void SkGpuDevice::internalDrawBitmap(const SkBitmap& bitmap,
1391 const SkRect& srcRect,
1392 const GrTextureParams& params,
1393 const SkPaint& paint,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001394 SkCanvas::DrawBitmapRectFlags flags,
1395 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001396 SkASSERT(bitmap.width() <= fContext->getMaxTextureSize() &&
1397 bitmap.height() <= fContext->getMaxTextureSize());
1398
1399 GrTexture* texture;
1400 SkAutoCachedTexture act(this, bitmap, &params, &texture);
1401 if (NULL == texture) {
1402 return;
1403 }
1404
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001405 SkRect dstRect = {0, 0, srcRect.width(), srcRect.height() };
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001406 SkRect paintRect;
1407 SkScalar wInv = SkScalarInvert(SkIntToScalar(texture->width()));
1408 SkScalar hInv = SkScalarInvert(SkIntToScalar(texture->height()));
1409 paintRect.setLTRB(SkScalarMul(srcRect.fLeft, wInv),
1410 SkScalarMul(srcRect.fTop, hInv),
1411 SkScalarMul(srcRect.fRight, wInv),
1412 SkScalarMul(srcRect.fBottom, hInv));
1413
1414 bool needsTextureDomain = false;
1415 if (!(flags & SkCanvas::kBleed_DrawBitmapRectFlag) &&
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001416 (bicubic || params.filterMode() != GrTextureParams::kNone_FilterMode)) {
1417 // Need texture domain if drawing a sub rect
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001418 needsTextureDomain = srcRect.width() < bitmap.width() ||
1419 srcRect.height() < bitmap.height();
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001420 if (!bicubic && needsTextureDomain && fContext->getMatrix().rectStaysRect()) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001421 const SkMatrix& matrix = fContext->getMatrix();
1422 // sampling is axis-aligned
1423 SkRect transformedRect;
1424 matrix.mapRect(&transformedRect, srcRect);
1425
1426 if (has_aligned_samples(srcRect, transformedRect)) {
1427 // We could also turn off filtering here (but we already did a cache lookup with
1428 // params).
1429 needsTextureDomain = false;
1430 } else {
1431 needsTextureDomain = may_color_bleed(srcRect, transformedRect, matrix);
1432 }
1433 }
1434 }
1435
1436 SkRect textureDomain = SkRect::MakeEmpty();
1437 SkAutoTUnref<GrEffectRef> effect;
1438 if (needsTextureDomain) {
1439 // Use a constrained texture domain to avoid color bleeding
1440 SkScalar left, top, right, bottom;
1441 if (srcRect.width() > SK_Scalar1) {
1442 SkScalar border = SK_ScalarHalf / texture->width();
1443 left = paintRect.left() + border;
1444 right = paintRect.right() - border;
1445 } else {
1446 left = right = SkScalarHalf(paintRect.left() + paintRect.right());
1447 }
1448 if (srcRect.height() > SK_Scalar1) {
1449 SkScalar border = SK_ScalarHalf / texture->height();
1450 top = paintRect.top() + border;
1451 bottom = paintRect.bottom() - border;
1452 } else {
1453 top = bottom = SkScalarHalf(paintRect.top() + paintRect.bottom());
1454 }
1455 textureDomain.setLTRB(left, top, right, bottom);
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001456 if (bicubic) {
1457 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), textureDomain));
1458 } else {
1459 effect.reset(GrTextureDomainEffect::Create(texture,
1460 SkMatrix::I(),
1461 textureDomain,
1462 GrTextureDomain::kClamp_Mode,
1463 params.filterMode()));
1464 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001465 } else if (bicubic) {
commit-bot@chromium.orgbc91fd72013-12-10 12:53:39 +00001466 SkASSERT(GrTextureParams::kNone_FilterMode == params.filterMode());
1467 SkShader::TileMode tileModes[2] = { params.getTileModeX(), params.getTileModeY() };
1468 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), tileModes));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001469 } else {
1470 effect.reset(GrSimpleTextureEffect::Create(texture, SkMatrix::I(), params));
1471 }
1472
1473 // Construct a GrPaint by setting the bitmap texture as the first effect and then configuring
1474 // the rest from the SkPaint.
1475 GrPaint grPaint;
1476 grPaint.addColorEffect(effect);
1477 bool alphaOnly = !(SkBitmap::kA8_Config == bitmap.config());
1478 if (!skPaint2GrPaintNoShader(this, paint, alphaOnly, false, &grPaint)) {
1479 return;
1480 }
1481
1482 fContext->drawRectToRect(grPaint, dstRect, paintRect, NULL);
1483}
1484
1485static bool filter_texture(SkBaseDevice* device, GrContext* context,
1486 GrTexture* texture, SkImageFilter* filter,
1487 int w, int h, const SkMatrix& ctm, SkBitmap* result,
1488 SkIPoint* offset) {
1489 SkASSERT(filter);
1490 SkDeviceImageFilterProxy proxy(device);
1491
1492 if (filter->canFilterImageGPU()) {
1493 // Save the render target and set it to NULL, so we don't accidentally draw to it in the
1494 // filter. Also set the clip wide open and the matrix to identity.
1495 GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
1496 return filter->filterImageGPU(&proxy, wrap_texture(texture), ctm, result, offset);
1497 } else {
1498 return false;
1499 }
1500}
1501
1502void SkGpuDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap,
1503 int left, int top, const SkPaint& paint) {
1504 // drawSprite is defined to be in device coords.
1505 CHECK_SHOULD_DRAW(draw, true);
1506
1507 SkAutoLockPixels alp(bitmap, !bitmap.getTexture());
1508 if (!bitmap.getTexture() && !bitmap.readyToDraw()) {
1509 return;
1510 }
1511
1512 int w = bitmap.width();
1513 int h = bitmap.height();
1514
1515 GrTexture* texture;
1516 // draw sprite uses the default texture params
1517 SkAutoCachedTexture act(this, bitmap, NULL, &texture);
1518
1519 SkImageFilter* filter = paint.getImageFilter();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001520 // This bitmap will own the filtered result as a texture.
1521 SkBitmap filteredBitmap;
1522
1523 if (NULL != filter) {
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001524 SkIPoint offset = SkIPoint::Make(0, 0);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001525 SkMatrix matrix(*draw.fMatrix);
1526 matrix.postTranslate(SkIntToScalar(-left), SkIntToScalar(-top));
1527 if (filter_texture(this, fContext, texture, filter, w, h, matrix, &filteredBitmap,
1528 &offset)) {
1529 texture = (GrTexture*) filteredBitmap.getTexture();
1530 w = filteredBitmap.width();
1531 h = filteredBitmap.height();
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001532 left += offset.x();
1533 top += offset.y();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001534 } else {
1535 return;
1536 }
1537 }
1538
1539 GrPaint grPaint;
1540 grPaint.addColorTextureEffect(texture, SkMatrix::I());
1541
1542 if(!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1543 return;
1544 }
1545
1546 fContext->drawRectToRect(grPaint,
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001547 SkRect::MakeXYWH(SkIntToScalar(left),
1548 SkIntToScalar(top),
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001549 SkIntToScalar(w),
1550 SkIntToScalar(h)),
1551 SkRect::MakeXYWH(0,
1552 0,
1553 SK_Scalar1 * w / texture->width(),
1554 SK_Scalar1 * h / texture->height()));
1555}
1556
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001557void SkGpuDevice::drawBitmapRect(const SkDraw& origDraw, const SkBitmap& bitmap,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001558 const SkRect* src, const SkRect& dst,
1559 const SkPaint& paint,
1560 SkCanvas::DrawBitmapRectFlags flags) {
1561 SkMatrix matrix;
1562 SkRect bitmapBounds, tmpSrc;
1563
1564 bitmapBounds.set(0, 0,
1565 SkIntToScalar(bitmap.width()),
1566 SkIntToScalar(bitmap.height()));
1567
1568 // Compute matrix from the two rectangles
1569 if (NULL != src) {
1570 tmpSrc = *src;
1571 } else {
1572 tmpSrc = bitmapBounds;
1573 }
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001574
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001575 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1576
1577 // clip the tmpSrc to the bounds of the bitmap. No check needed if src==null.
1578 if (NULL != src) {
1579 if (!bitmapBounds.contains(tmpSrc)) {
1580 if (!tmpSrc.intersect(bitmapBounds)) {
1581 return; // nothing to draw
1582 }
1583 }
1584 }
1585
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001586 SkRect tmpDst;
1587 matrix.mapRect(&tmpDst, tmpSrc);
1588
1589 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1590 if (0 != tmpDst.fLeft || 0 != tmpDst.fTop) {
1591 // Translate so that tempDst's top left is at the origin.
1592 matrix = *origDraw.fMatrix;
1593 matrix.preTranslate(tmpDst.fLeft, tmpDst.fTop);
1594 draw.writable()->fMatrix = &matrix;
1595 }
1596 SkSize dstSize;
1597 dstSize.fWidth = tmpDst.width();
1598 dstSize.fHeight = tmpDst.height();
1599
1600 this->drawBitmapCommon(*draw, bitmap, &tmpSrc, &dstSize, paint, flags);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001601}
1602
1603void SkGpuDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device,
1604 int x, int y, const SkPaint& paint) {
1605 // clear of the source device must occur before CHECK_SHOULD_DRAW
1606 SkGpuDevice* dev = static_cast<SkGpuDevice*>(device);
1607 if (dev->fNeedClear) {
1608 // TODO: could check here whether we really need to draw at all
1609 dev->clear(0x0);
1610 }
1611
1612 // drawDevice is defined to be in device coords.
1613 CHECK_SHOULD_DRAW(draw, true);
1614
1615 GrRenderTarget* devRT = dev->accessRenderTarget();
1616 GrTexture* devTex;
1617 if (NULL == (devTex = devRT->asTexture())) {
1618 return;
1619 }
1620
1621 const SkBitmap& bm = dev->accessBitmap(false);
1622 int w = bm.width();
1623 int h = bm.height();
1624
1625 SkImageFilter* filter = paint.getImageFilter();
1626 // This bitmap will own the filtered result as a texture.
1627 SkBitmap filteredBitmap;
1628
1629 if (NULL != filter) {
1630 SkIPoint offset = SkIPoint::Make(0, 0);
1631 SkMatrix matrix(*draw.fMatrix);
1632 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
1633 if (filter_texture(this, fContext, devTex, filter, w, h, matrix, &filteredBitmap,
1634 &offset)) {
1635 devTex = filteredBitmap.getTexture();
1636 w = filteredBitmap.width();
1637 h = filteredBitmap.height();
1638 x += offset.fX;
1639 y += offset.fY;
1640 } else {
1641 return;
1642 }
1643 }
1644
1645 GrPaint grPaint;
1646 grPaint.addColorTextureEffect(devTex, SkMatrix::I());
1647
1648 if (!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1649 return;
1650 }
1651
1652 SkRect dstRect = SkRect::MakeXYWH(SkIntToScalar(x),
1653 SkIntToScalar(y),
1654 SkIntToScalar(w),
1655 SkIntToScalar(h));
1656
1657 // The device being drawn may not fill up its texture (e.g. saveLayer uses approximate
1658 // scratch texture).
1659 SkRect srcRect = SkRect::MakeWH(SK_Scalar1 * w / devTex->width(),
1660 SK_Scalar1 * h / devTex->height());
1661
1662 fContext->drawRectToRect(grPaint, dstRect, srcRect);
1663}
1664
1665bool SkGpuDevice::canHandleImageFilter(SkImageFilter* filter) {
1666 return filter->canFilterImageGPU();
1667}
1668
1669bool SkGpuDevice::filterImage(SkImageFilter* filter, const SkBitmap& src,
1670 const SkMatrix& ctm,
1671 SkBitmap* result, SkIPoint* offset) {
1672 // want explicitly our impl, so guard against a subclass of us overriding it
1673 if (!this->SkGpuDevice::canHandleImageFilter(filter)) {
1674 return false;
1675 }
1676
1677 SkAutoLockPixels alp(src, !src.getTexture());
1678 if (!src.getTexture() && !src.readyToDraw()) {
1679 return false;
1680 }
1681
1682 GrTexture* texture;
1683 // We assume here that the filter will not attempt to tile the src. Otherwise, this cache lookup
1684 // must be pushed upstack.
1685 SkAutoCachedTexture act(this, src, NULL, &texture);
1686
1687 return filter_texture(this, fContext, texture, filter, src.width(), src.height(), ctm, result,
1688 offset);
1689}
1690
1691///////////////////////////////////////////////////////////////////////////////
1692
1693// must be in SkCanvas::VertexMode order
1694static const GrPrimitiveType gVertexMode2PrimitiveType[] = {
1695 kTriangles_GrPrimitiveType,
1696 kTriangleStrip_GrPrimitiveType,
1697 kTriangleFan_GrPrimitiveType,
1698};
1699
1700void SkGpuDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
1701 int vertexCount, const SkPoint vertices[],
1702 const SkPoint texs[], const SkColor colors[],
1703 SkXfermode* xmode,
1704 const uint16_t indices[], int indexCount,
1705 const SkPaint& paint) {
1706 CHECK_SHOULD_DRAW(draw, false);
1707
1708 GrPaint grPaint;
1709 // we ignore the shader if texs is null.
1710 if (NULL == texs) {
1711 if (!skPaint2GrPaintNoShader(this, paint, false, NULL == colors, &grPaint)) {
1712 return;
1713 }
1714 } else {
1715 if (!skPaint2GrPaintShader(this, paint, NULL == colors, &grPaint)) {
1716 return;
1717 }
1718 }
1719
1720 if (NULL != xmode && NULL != texs && NULL != colors) {
1721 if (!SkXfermode::IsMode(xmode, SkXfermode::kModulate_Mode)) {
1722 SkDebugf("Unsupported vertex-color/texture xfer mode.\n");
1723#if 0
1724 return
1725#endif
1726 }
1727 }
1728
1729 SkAutoSTMalloc<128, GrColor> convertedColors(0);
1730 if (NULL != colors) {
1731 // need to convert byte order and from non-PM to PM
1732 convertedColors.reset(vertexCount);
1733 for (int i = 0; i < vertexCount; ++i) {
1734 convertedColors[i] = SkColor2GrColor(colors[i]);
1735 }
1736 colors = convertedColors.get();
1737 }
1738 fContext->drawVertices(grPaint,
1739 gVertexMode2PrimitiveType[vmode],
1740 vertexCount,
1741 (GrPoint*) vertices,
1742 (GrPoint*) texs,
1743 colors,
1744 indices,
1745 indexCount);
1746}
1747
1748///////////////////////////////////////////////////////////////////////////////
1749
1750static void GlyphCacheAuxProc(void* data) {
1751 GrFontScaler* scaler = (GrFontScaler*)data;
1752 SkSafeUnref(scaler);
1753}
1754
1755static GrFontScaler* get_gr_font_scaler(SkGlyphCache* cache) {
1756 void* auxData;
1757 GrFontScaler* scaler = NULL;
1758 if (cache->getAuxProcData(GlyphCacheAuxProc, &auxData)) {
1759 scaler = (GrFontScaler*)auxData;
1760 }
1761 if (NULL == scaler) {
1762 scaler = SkNEW_ARGS(SkGrFontScaler, (cache));
1763 cache->setAuxProc(GlyphCacheAuxProc, scaler);
1764 }
1765 return scaler;
1766}
1767
1768static void SkGPU_Draw1Glyph(const SkDraw1Glyph& state,
1769 SkFixed fx, SkFixed fy,
1770 const SkGlyph& glyph) {
1771 SkASSERT(glyph.fWidth > 0 && glyph.fHeight > 0);
1772
1773 GrSkDrawProcs* procs = static_cast<GrSkDrawProcs*>(state.fDraw->fProcs);
1774
1775 if (NULL == procs->fFontScaler) {
1776 procs->fFontScaler = get_gr_font_scaler(state.fCache);
1777 }
1778
1779 procs->fTextContext->drawPackedGlyph(GrGlyph::Pack(glyph.getGlyphID(),
1780 glyph.getSubXFixed(),
1781 glyph.getSubYFixed()),
1782 SkFixedFloorToFixed(fx),
1783 SkFixedFloorToFixed(fy),
1784 procs->fFontScaler);
1785}
1786
1787SkDrawProcs* SkGpuDevice::initDrawForText(GrTextContext* context) {
1788
1789 // deferred allocation
1790 if (NULL == fDrawProcs) {
1791 fDrawProcs = SkNEW(GrSkDrawProcs);
1792 fDrawProcs->fD1GProc = SkGPU_Draw1Glyph;
1793 fDrawProcs->fContext = fContext;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001794 }
1795
1796 // init our (and GL's) state
1797 fDrawProcs->fTextContext = context;
1798 fDrawProcs->fFontScaler = NULL;
1799 return fDrawProcs;
1800}
1801
1802void SkGpuDevice::drawText(const SkDraw& draw, const void* text,
1803 size_t byteLength, SkScalar x, SkScalar y,
1804 const SkPaint& paint) {
1805 CHECK_SHOULD_DRAW(draw, false);
1806
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001807 if (SkDraw::ShouldDrawTextAsPaths(paint, fContext->getMatrix())) {
1808 draw.drawText_asPaths((const char*)text, byteLength, x, y, paint);
1809#if SK_DISTANCEFIELD_FONTS
1810 } else if (!paint.getRasterizer()) {
1811 GrPaint grPaint;
1812 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1813 return;
1814 }
1815
1816 SkDEBUGCODE(this->validate();)
1817
1818 GrDistanceFieldTextContext context(fContext, grPaint, paint);
1819
1820 SkAutoGlyphCache autoCache(context.getSkPaint(), &this->fLeakyProperties, NULL);
1821 SkGlyphCache* cache = autoCache.getCache();
1822 GrFontScaler* fontScaler = get_gr_font_scaler(cache);
1823
1824 context.drawText((const char *)text, byteLength, x, y, cache, fontScaler);
1825#endif
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001826 } else {
1827 SkDraw myDraw(draw);
1828
1829 GrPaint grPaint;
1830 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1831 return;
1832 }
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001833
1834 GrBitmapTextContext context(fContext, grPaint, paint.getColor());
1835 myDraw.fProcs = this->initDrawForText(&context);
1836 this->INHERITED::drawText(myDraw, text, byteLength, x, y, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001837 }
1838}
1839
1840void SkGpuDevice::drawPosText(const SkDraw& draw, const void* text,
1841 size_t byteLength, const SkScalar pos[],
1842 SkScalar constY, int scalarsPerPos,
1843 const SkPaint& paint) {
1844 CHECK_SHOULD_DRAW(draw, false);
1845
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001846 if (SkDraw::ShouldDrawTextAsPaths(paint, fContext->getMatrix())) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001847 // this guy will just call our drawPath()
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001848 draw.drawPosText_asPaths((const char*)text, byteLength, pos, constY,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001849 scalarsPerPos, paint);
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001850#if SK_DISTANCEFIELD_FONTS
1851 } else if (!paint.getRasterizer()) {
1852 GrPaint grPaint;
1853 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1854 return;
1855 }
1856
1857 SkDEBUGCODE(this->validate();)
1858
1859 GrDistanceFieldTextContext context(fContext, grPaint, paint);
1860
1861 SkAutoGlyphCache autoCache(context.getSkPaint(), &this->fLeakyProperties, NULL);
1862 SkGlyphCache* cache = autoCache.getCache();
1863 GrFontScaler* fontScaler = get_gr_font_scaler(cache);
skia.committer@gmail.com22e96722013-12-20 07:01:36 +00001864
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001865 context.drawPosText((const char *)text, byteLength, pos, constY, scalarsPerPos,
1866 cache, fontScaler);
1867#endif
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001868 } else {
1869 SkDraw myDraw(draw);
1870
1871 GrPaint grPaint;
1872 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1873 return;
1874 }
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001875 GrBitmapTextContext context(fContext, grPaint, paint.getColor());
1876 myDraw.fProcs = this->initDrawForText(&context);
1877 this->INHERITED::drawPosText(myDraw, text, byteLength, pos, constY,
1878 scalarsPerPos, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001879 }
1880}
1881
1882void SkGpuDevice::drawTextOnPath(const SkDraw& draw, const void* text,
1883 size_t len, const SkPath& path,
1884 const SkMatrix* m, const SkPaint& paint) {
1885 CHECK_SHOULD_DRAW(draw, false);
1886
1887 SkASSERT(draw.fDevice == this);
1888 draw.drawTextOnPath((const char*)text, len, path, m, paint);
1889}
1890
1891///////////////////////////////////////////////////////////////////////////////
1892
1893bool SkGpuDevice::filterTextFlags(const SkPaint& paint, TextFlags* flags) {
1894 if (!paint.isLCDRenderText()) {
1895 // we're cool with the paint as is
1896 return false;
1897 }
1898
1899 if (paint.getShader() ||
1900 paint.getXfermode() || // unless its srcover
1901 paint.getMaskFilter() ||
1902 paint.getRasterizer() ||
1903 paint.getColorFilter() ||
1904 paint.getPathEffect() ||
1905 paint.isFakeBoldText() ||
1906 paint.getStyle() != SkPaint::kFill_Style) {
1907 // turn off lcd
1908 flags->fFlags = paint.getFlags() & ~SkPaint::kLCDRenderText_Flag;
1909 flags->fHinting = paint.getHinting();
1910 return true;
1911 }
1912 // we're cool with the paint as is
1913 return false;
1914}
1915
1916void SkGpuDevice::flush() {
1917 DO_DEFERRED_CLEAR();
1918 fContext->resolveRenderTarget(fRenderTarget);
1919}
1920
1921///////////////////////////////////////////////////////////////////////////////
1922
1923SkBaseDevice* SkGpuDevice::onCreateCompatibleDevice(SkBitmap::Config config,
1924 int width, int height,
1925 bool isOpaque,
1926 Usage usage) {
1927 GrTextureDesc desc;
1928 desc.fConfig = fRenderTarget->config();
1929 desc.fFlags = kRenderTarget_GrTextureFlagBit;
1930 desc.fWidth = width;
1931 desc.fHeight = height;
1932 desc.fSampleCnt = fRenderTarget->numSamples();
1933
1934 SkAutoTUnref<GrTexture> texture;
1935 // Skia's convention is to only clear a device if it is non-opaque.
1936 bool needClear = !isOpaque;
1937
1938#if CACHE_COMPATIBLE_DEVICE_TEXTURES
1939 // layers are never draw in repeat modes, so we can request an approx
1940 // match and ignore any padding.
1941 const GrContext::ScratchTexMatch match = (kSaveLayer_Usage == usage) ?
1942 GrContext::kApprox_ScratchTexMatch :
1943 GrContext::kExact_ScratchTexMatch;
1944 texture.reset(fContext->lockAndRefScratchTexture(desc, match));
1945#else
1946 texture.reset(fContext->createUncachedTexture(desc, NULL, 0));
1947#endif
1948 if (NULL != texture.get()) {
1949 return SkNEW_ARGS(SkGpuDevice,(fContext, texture, needClear));
1950 } else {
1951 GrPrintf("---- failed to create compatible device texture [%d %d]\n", width, height);
1952 return NULL;
1953 }
1954}
1955
1956SkGpuDevice::SkGpuDevice(GrContext* context,
1957 GrTexture* texture,
1958 bool needClear)
1959 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
1960
1961 SkASSERT(texture && texture->asRenderTarget());
1962 // This constructor is called from onCreateCompatibleDevice. It has locked the RT in the texture
1963 // cache. We pass true for the third argument so that it will get unlocked.
1964 this->initFromRenderTarget(context, texture->asRenderTarget(), true);
1965 fNeedClear = needClear;
1966}