blob: 86c8ba90f8a24c18f14eb20dc03256f341d50aeb [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"
30#include "SkUtils.h"
31#include "SkErrorInternals.h"
32
33#define CACHE_COMPATIBLE_DEVICE_TEXTURES 1
34
35#if 0
36 extern bool (*gShouldDrawProc)();
37 #define CHECK_SHOULD_DRAW(draw, forceI) \
38 do { \
39 if (gShouldDrawProc && !gShouldDrawProc()) return; \
40 this->prepareDraw(draw, forceI); \
41 } while (0)
42#else
43 #define CHECK_SHOULD_DRAW(draw, forceI) this->prepareDraw(draw, forceI)
44#endif
45
46// This constant represents the screen alignment criterion in texels for
47// requiring texture domain clamping to prevent color bleeding when drawing
48// a sub region of a larger source image.
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +000049#define COLOR_BLEED_TOLERANCE 0.001f
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +000050
51#define DO_DEFERRED_CLEAR() \
52 do { \
53 if (fNeedClear) { \
54 this->clear(SK_ColorTRANSPARENT); \
55 } \
56 } while (false) \
57
58///////////////////////////////////////////////////////////////////////////////
59
60#define CHECK_FOR_ANNOTATION(paint) \
61 do { if (paint.getAnnotation()) { return; } } while (0)
62
63///////////////////////////////////////////////////////////////////////////////
64
65
66class SkGpuDevice::SkAutoCachedTexture : public ::SkNoncopyable {
67public:
68 SkAutoCachedTexture()
69 : fDevice(NULL)
70 , fTexture(NULL) {
71 }
72
73 SkAutoCachedTexture(SkGpuDevice* device,
74 const SkBitmap& bitmap,
75 const GrTextureParams* params,
76 GrTexture** texture)
77 : fDevice(NULL)
78 , fTexture(NULL) {
79 SkASSERT(NULL != texture);
80 *texture = this->set(device, bitmap, params);
81 }
82
83 ~SkAutoCachedTexture() {
84 if (NULL != fTexture) {
85 GrUnlockAndUnrefCachedBitmapTexture(fTexture);
86 }
87 }
88
89 GrTexture* set(SkGpuDevice* device,
90 const SkBitmap& bitmap,
91 const GrTextureParams* params) {
92 if (NULL != fTexture) {
93 GrUnlockAndUnrefCachedBitmapTexture(fTexture);
94 fTexture = NULL;
95 }
96 fDevice = device;
97 GrTexture* result = (GrTexture*)bitmap.getTexture();
98 if (NULL == result) {
99 // Cannot return the native texture so look it up in our cache
100 fTexture = GrLockAndRefCachedBitmapTexture(device->context(), bitmap, params);
101 result = fTexture;
102 }
103 return result;
104 }
105
106private:
107 SkGpuDevice* fDevice;
108 GrTexture* fTexture;
109};
110
111///////////////////////////////////////////////////////////////////////////////
112
113struct GrSkDrawProcs : public SkDrawProcs {
114public:
115 GrContext* fContext;
116 GrTextContext* fTextContext;
117 GrFontScaler* fFontScaler; // cached in the skia glyphcache
118};
119
120///////////////////////////////////////////////////////////////////////////////
121
122static SkBitmap::Config grConfig2skConfig(GrPixelConfig config, bool* isOpaque) {
123 switch (config) {
124 case kAlpha_8_GrPixelConfig:
125 *isOpaque = false;
126 return SkBitmap::kA8_Config;
127 case kRGB_565_GrPixelConfig:
128 *isOpaque = true;
129 return SkBitmap::kRGB_565_Config;
130 case kRGBA_4444_GrPixelConfig:
131 *isOpaque = false;
132 return SkBitmap::kARGB_4444_Config;
133 case kSkia8888_GrPixelConfig:
134 // we don't currently have a way of knowing whether
135 // a 8888 is opaque based on the config.
136 *isOpaque = false;
137 return SkBitmap::kARGB_8888_Config;
138 default:
139 *isOpaque = false;
140 return SkBitmap::kNo_Config;
141 }
142}
143
144/*
145 * GrRenderTarget does not know its opaqueness, only its config, so we have
146 * to make conservative guesses when we return an "equivalent" bitmap.
147 */
148static SkBitmap make_bitmap(GrContext* context, GrRenderTarget* renderTarget) {
149 bool isOpaque;
150 SkBitmap::Config config = grConfig2skConfig(renderTarget->config(), &isOpaque);
151
152 SkBitmap bitmap;
153 bitmap.setConfig(config, renderTarget->width(), renderTarget->height(), 0,
154 isOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
155 return bitmap;
156}
157
commit-bot@chromium.org3e7f3852013-12-06 22:59:02 +0000158/*
159 * Calling SkBitmapDevice with individual params asks it to allocate pixel memory.
160 * We never want that, so we always need to call it with a bitmap argument
161 * (which says take my allocate (or lack thereof)).
162 *
163 * This is a REALLY good reason to finish the clean-up of SkBaseDevice, and have
164 * SkGpuDevice inherit from that instead of SkBitmapDevice.
165 */
166static SkBitmap make_bitmap(SkBitmap::Config config, int width, int height, bool isOpaque) {
167 SkBitmap bm;
168 bm.setConfig(config, width, height, isOpaque);
169 return bm;
170}
171
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000172SkGpuDevice* SkGpuDevice::Create(GrSurface* surface) {
173 SkASSERT(NULL != surface);
174 if (NULL == surface->asRenderTarget() || NULL == surface->getContext()) {
175 return NULL;
176 }
177 if (surface->asTexture()) {
178 return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asTexture()));
179 } else {
180 return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asRenderTarget()));
181 }
182}
183
184SkGpuDevice::SkGpuDevice(GrContext* context, GrTexture* texture)
185 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
186 this->initFromRenderTarget(context, texture->asRenderTarget(), false);
187}
188
189SkGpuDevice::SkGpuDevice(GrContext* context, GrRenderTarget* renderTarget)
190 : SkBitmapDevice(make_bitmap(context, renderTarget)) {
191 this->initFromRenderTarget(context, renderTarget, false);
192}
193
194void SkGpuDevice::initFromRenderTarget(GrContext* context,
195 GrRenderTarget* renderTarget,
196 bool cached) {
197 fDrawProcs = NULL;
198
199 fContext = context;
200 fContext->ref();
201
202 fRenderTarget = NULL;
203 fNeedClear = false;
204
205 SkASSERT(NULL != renderTarget);
206 fRenderTarget = renderTarget;
207 fRenderTarget->ref();
208
209 // Hold onto to the texture in the pixel ref (if there is one) because the texture holds a ref
210 // on the RT but not vice-versa.
211 // TODO: Remove this trickery once we figure out how to make SkGrPixelRef do this without
212 // busting chrome (for a currently unknown reason).
213 GrSurface* surface = fRenderTarget->asTexture();
214 if (NULL == surface) {
215 surface = fRenderTarget;
216 }
reed@google.combf790232013-12-13 19:45:58 +0000217
218 SkImageInfo info;
219 surface->asImageInfo(&info);
220 SkPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, surface, cached));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000221
reed@google.com672588b2014-01-08 15:42:01 +0000222 this->setPixelRef(pr)->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000223}
224
225SkGpuDevice::SkGpuDevice(GrContext* context,
226 SkBitmap::Config config,
227 int width,
228 int height,
229 int sampleCount)
reed@google.combf790232013-12-13 19:45:58 +0000230 : SkBitmapDevice(make_bitmap(config, width, height, false /*isOpaque*/))
231{
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000232 fDrawProcs = NULL;
233
234 fContext = context;
235 fContext->ref();
236
237 fRenderTarget = NULL;
238 fNeedClear = false;
239
240 if (config != SkBitmap::kRGB_565_Config) {
241 config = SkBitmap::kARGB_8888_Config;
242 }
243
244 GrTextureDesc desc;
245 desc.fFlags = kRenderTarget_GrTextureFlagBit;
246 desc.fWidth = width;
247 desc.fHeight = height;
248 desc.fConfig = SkBitmapConfig2GrPixelConfig(config);
249 desc.fSampleCnt = sampleCount;
250
reed@google.combf790232013-12-13 19:45:58 +0000251 SkImageInfo info;
252 if (!GrPixelConfig2ColorType(desc.fConfig, &info.fColorType)) {
253 sk_throw();
254 }
255 info.fWidth = width;
256 info.fHeight = height;
257 info.fAlphaType = kPremul_SkAlphaType;
skia.committer@gmail.com96f5fa02013-12-16 07:01:40 +0000258
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000259 SkAutoTUnref<GrTexture> texture(fContext->createUncachedTexture(desc, NULL, 0));
260
261 if (NULL != texture) {
262 fRenderTarget = texture->asRenderTarget();
263 fRenderTarget->ref();
264
265 SkASSERT(NULL != fRenderTarget);
266
267 // wrap the bitmap with a pixelref to expose our texture
reed@google.combf790232013-12-13 19:45:58 +0000268 SkGrPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, texture));
reed@google.com672588b2014-01-08 15:42:01 +0000269 this->setPixelRef(pr)->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000270 } else {
271 GrPrintf("--- failed to create gpu-offscreen [%d %d]\n",
272 width, height);
273 SkASSERT(false);
274 }
275}
276
277SkGpuDevice::~SkGpuDevice() {
278 if (fDrawProcs) {
279 delete fDrawProcs;
280 }
281
282 // The GrContext takes a ref on the target. We don't want to cause the render
283 // target to be unnecessarily kept alive.
284 if (fContext->getRenderTarget() == fRenderTarget) {
285 fContext->setRenderTarget(NULL);
286 }
287
288 if (fContext->getClip() == &fClipData) {
289 fContext->setClip(NULL);
290 }
291
292 SkSafeUnref(fRenderTarget);
293 fContext->unref();
294}
295
296///////////////////////////////////////////////////////////////////////////////
297
298void SkGpuDevice::makeRenderTargetCurrent() {
299 DO_DEFERRED_CLEAR();
300 fContext->setRenderTarget(fRenderTarget);
301}
302
303///////////////////////////////////////////////////////////////////////////////
304
305namespace {
306GrPixelConfig config8888_to_grconfig_and_flags(SkCanvas::Config8888 config8888, uint32_t* flags) {
307 switch (config8888) {
308 case SkCanvas::kNative_Premul_Config8888:
309 *flags = 0;
310 return kSkia8888_GrPixelConfig;
311 case SkCanvas::kNative_Unpremul_Config8888:
312 *flags = GrContext::kUnpremul_PixelOpsFlag;
313 return kSkia8888_GrPixelConfig;
314 case SkCanvas::kBGRA_Premul_Config8888:
315 *flags = 0;
316 return kBGRA_8888_GrPixelConfig;
317 case SkCanvas::kBGRA_Unpremul_Config8888:
318 *flags = GrContext::kUnpremul_PixelOpsFlag;
319 return kBGRA_8888_GrPixelConfig;
320 case SkCanvas::kRGBA_Premul_Config8888:
321 *flags = 0;
322 return kRGBA_8888_GrPixelConfig;
323 case SkCanvas::kRGBA_Unpremul_Config8888:
324 *flags = GrContext::kUnpremul_PixelOpsFlag;
325 return kRGBA_8888_GrPixelConfig;
326 default:
327 GrCrash("Unexpected Config8888.");
328 *flags = 0; // suppress warning
329 return kSkia8888_GrPixelConfig;
330 }
331}
332}
333
334bool SkGpuDevice::onReadPixels(const SkBitmap& bitmap,
335 int x, int y,
336 SkCanvas::Config8888 config8888) {
337 DO_DEFERRED_CLEAR();
338 SkASSERT(SkBitmap::kARGB_8888_Config == bitmap.config());
339 SkASSERT(!bitmap.isNull());
340 SkASSERT(SkIRect::MakeWH(this->width(), this->height()).contains(SkIRect::MakeXYWH(x, y, bitmap.width(), bitmap.height())));
341
342 SkAutoLockPixels alp(bitmap);
343 GrPixelConfig config;
344 uint32_t flags;
345 config = config8888_to_grconfig_and_flags(config8888, &flags);
346 return fContext->readRenderTargetPixels(fRenderTarget,
347 x, y,
348 bitmap.width(),
349 bitmap.height(),
350 config,
351 bitmap.getPixels(),
352 bitmap.rowBytes(),
353 flags);
354}
355
356void SkGpuDevice::writePixels(const SkBitmap& bitmap, int x, int y,
357 SkCanvas::Config8888 config8888) {
358 SkAutoLockPixels alp(bitmap);
359 if (!bitmap.readyToDraw()) {
360 return;
361 }
362
363 GrPixelConfig config;
364 uint32_t flags;
365 if (SkBitmap::kARGB_8888_Config == bitmap.config()) {
366 config = config8888_to_grconfig_and_flags(config8888, &flags);
367 } else {
368 flags = 0;
369 config= SkBitmapConfig2GrPixelConfig(bitmap.config());
370 }
371
372 fRenderTarget->writePixels(x, y, bitmap.width(), bitmap.height(),
373 config, bitmap.getPixels(), bitmap.rowBytes(), flags);
374}
375
376void SkGpuDevice::onAttachToCanvas(SkCanvas* canvas) {
377 INHERITED::onAttachToCanvas(canvas);
378
379 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
380 fClipData.fClipStack = canvas->getClipStack();
381}
382
383void SkGpuDevice::onDetachFromCanvas() {
384 INHERITED::onDetachFromCanvas();
385 fClipData.fClipStack = NULL;
386}
387
388// call this every draw call, to ensure that the context reflects our state,
389// and not the state from some other canvas/device
390void SkGpuDevice::prepareDraw(const SkDraw& draw, bool forceIdentity) {
391 SkASSERT(NULL != fClipData.fClipStack);
392
393 fContext->setRenderTarget(fRenderTarget);
394
395 SkASSERT(draw.fClipStack && draw.fClipStack == fClipData.fClipStack);
396
397 if (forceIdentity) {
398 fContext->setIdentityMatrix();
399 } else {
400 fContext->setMatrix(*draw.fMatrix);
401 }
402 fClipData.fOrigin = this->getOrigin();
403
404 fContext->setClip(&fClipData);
405
406 DO_DEFERRED_CLEAR();
407}
408
409GrRenderTarget* SkGpuDevice::accessRenderTarget() {
410 DO_DEFERRED_CLEAR();
411 return fRenderTarget;
412}
413
414///////////////////////////////////////////////////////////////////////////////
415
416SK_COMPILE_ASSERT(SkShader::kNone_BitmapType == 0, shader_type_mismatch);
417SK_COMPILE_ASSERT(SkShader::kDefault_BitmapType == 1, shader_type_mismatch);
418SK_COMPILE_ASSERT(SkShader::kRadial_BitmapType == 2, shader_type_mismatch);
419SK_COMPILE_ASSERT(SkShader::kSweep_BitmapType == 3, shader_type_mismatch);
420SK_COMPILE_ASSERT(SkShader::kTwoPointRadial_BitmapType == 4,
421 shader_type_mismatch);
422SK_COMPILE_ASSERT(SkShader::kTwoPointConical_BitmapType == 5,
423 shader_type_mismatch);
424SK_COMPILE_ASSERT(SkShader::kLinear_BitmapType == 6, shader_type_mismatch);
425SK_COMPILE_ASSERT(SkShader::kLast_BitmapType == 6, shader_type_mismatch);
426
427namespace {
428
429// converts a SkPaint to a GrPaint, ignoring the skPaint's shader
430// justAlpha indicates that skPaint's alpha should be used rather than the color
431// Callers may subsequently modify the GrPaint. Setting constantColor indicates
432// that the final paint will draw the same color at every pixel. This allows
433// an optimization where the the color filter can be applied to the skPaint's
434// color once while converting to GrPaint and then ignored.
435inline bool skPaint2GrPaintNoShader(SkGpuDevice* dev,
436 const SkPaint& skPaint,
437 bool justAlpha,
438 bool constantColor,
439 GrPaint* grPaint) {
440
441 grPaint->setDither(skPaint.isDither());
442 grPaint->setAntiAlias(skPaint.isAntiAlias());
443
444 SkXfermode::Coeff sm;
445 SkXfermode::Coeff dm;
446
447 SkXfermode* mode = skPaint.getXfermode();
448 GrEffectRef* xferEffect = NULL;
449 if (SkXfermode::AsNewEffectOrCoeff(mode, &xferEffect, &sm, &dm)) {
450 if (NULL != xferEffect) {
451 grPaint->addColorEffect(xferEffect)->unref();
452 sm = SkXfermode::kOne_Coeff;
453 dm = SkXfermode::kZero_Coeff;
454 }
455 } else {
456 //SkDEBUGCODE(SkDebugf("Unsupported xfer mode.\n");)
457#if 0
458 return false;
459#else
460 // Fall back to src-over
461 sm = SkXfermode::kOne_Coeff;
462 dm = SkXfermode::kISA_Coeff;
463#endif
464 }
465 grPaint->setBlendFunc(sk_blend_to_grblend(sm), sk_blend_to_grblend(dm));
466
467 if (justAlpha) {
468 uint8_t alpha = skPaint.getAlpha();
469 grPaint->setColor(GrColorPackRGBA(alpha, alpha, alpha, alpha));
470 // justAlpha is currently set to true only if there is a texture,
471 // so constantColor should not also be true.
472 SkASSERT(!constantColor);
473 } else {
474 grPaint->setColor(SkColor2GrColor(skPaint.getColor()));
475 }
476
477 SkColorFilter* colorFilter = skPaint.getColorFilter();
478 if (NULL != colorFilter) {
479 // if the source color is a constant then apply the filter here once rather than per pixel
480 // in a shader.
481 if (constantColor) {
482 SkColor filtered = colorFilter->filterColor(skPaint.getColor());
483 grPaint->setColor(SkColor2GrColor(filtered));
484 } else {
485 SkAutoTUnref<GrEffectRef> effect(colorFilter->asNewEffect(dev->context()));
486 if (NULL != effect.get()) {
487 grPaint->addColorEffect(effect);
488 }
489 }
490 }
491
492 return true;
493}
494
495// This function is similar to skPaint2GrPaintNoShader but also converts
496// skPaint's shader to a GrTexture/GrEffectStage if possible. The texture to
497// be used is set on grPaint and returned in param act. constantColor has the
498// same meaning as in skPaint2GrPaintNoShader.
499inline bool skPaint2GrPaintShader(SkGpuDevice* dev,
500 const SkPaint& skPaint,
501 bool constantColor,
502 GrPaint* grPaint) {
503 SkShader* shader = skPaint.getShader();
504 if (NULL == shader) {
505 return skPaint2GrPaintNoShader(dev, skPaint, false, constantColor, grPaint);
506 }
507
508 // SkShader::asNewEffect() may do offscreen rendering. Setup default drawing state
509 // Also require shader to set the render target .
510 GrContext::AutoWideOpenIdentityDraw awo(dev->context(), NULL);
511 GrContext::AutoRenderTarget(dev->context(), NULL);
512
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) {
1018 if (!clippedSrcRect.intersect(*srcRectPtr)) {
1019 clippedSrcIRect->setEmpty();
1020 return;
1021 }
1022 }
1023 clippedSrcRect.roundOut(clippedSrcIRect);
1024 SkIRect bmpBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1025 if (!clippedSrcIRect->intersect(bmpBounds)) {
1026 clippedSrcIRect->setEmpty();
1027 }
1028}
1029
1030bool SkGpuDevice::shouldTileBitmap(const SkBitmap& bitmap,
1031 const GrTextureParams& params,
1032 const SkRect* srcRectPtr,
1033 int maxTileSize,
1034 int* tileSize,
1035 SkIRect* clippedSrcRect) const {
1036 // if bitmap is explictly texture backed then just use the texture
1037 if (NULL != bitmap.getTexture()) {
1038 return false;
1039 }
1040
1041 // if it's larger than the max tile size, then we have no choice but tiling.
1042 if (bitmap.width() > maxTileSize || bitmap.height() > maxTileSize) {
1043 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1044 *tileSize = determine_tile_size(bitmap, *clippedSrcRect, maxTileSize);
1045 return true;
1046 }
1047
1048 if (bitmap.width() * bitmap.height() < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
1049 return false;
1050 }
1051
1052 // if the entire texture is already in our cache then no reason to tile it
1053 if (GrIsBitmapInCache(fContext, bitmap, &params)) {
1054 return false;
1055 }
1056
1057 // At this point we know we could do the draw by uploading the entire bitmap
1058 // as a texture. However, if the texture would be large compared to the
1059 // cache size and we don't require most of it for this draw then tile to
1060 // reduce the amount of upload and cache spill.
1061
1062 // assumption here is that sw bitmap size is a good proxy for its size as
1063 // a texture
1064 size_t bmpSize = bitmap.getSize();
1065 size_t cacheSize;
1066 fContext->getTextureCacheLimits(NULL, &cacheSize);
1067 if (bmpSize < cacheSize / 2) {
1068 return false;
1069 }
1070
1071 // Figure out how much of the src we will need based on the src rect and clipping.
1072 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1073 *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
1074 size_t usedTileBytes = get_tile_count(*clippedSrcRect, kBmpSmallTileSize) *
1075 kBmpSmallTileSize * kBmpSmallTileSize;
1076
1077 return usedTileBytes < 2 * bmpSize;
1078}
1079
1080void SkGpuDevice::drawBitmap(const SkDraw& draw,
1081 const SkBitmap& bitmap,
1082 const SkMatrix& m,
1083 const SkPaint& paint) {
1084 // We cannot call drawBitmapRect here since 'm' could be anything
1085 this->drawBitmapCommon(draw, bitmap, NULL, m, paint,
1086 SkCanvas::kNone_DrawBitmapRectFlag);
1087}
1088
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001089// This method outsets 'iRect' by 'outset' all around and then clamps its extents to
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001090// 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
1091// of 'iRect' for all possible outsets/clamps.
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001092static inline void clamped_outset_with_offset(SkIRect* iRect,
1093 int outset,
1094 SkPoint* offset,
1095 const SkIRect& clamp) {
1096 iRect->outset(outset, outset);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001097
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001098 int leftClampDelta = clamp.fLeft - iRect->fLeft;
1099 if (leftClampDelta > 0) {
1100 offset->fX -= outset - leftClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001101 iRect->fLeft = clamp.fLeft;
1102 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001103 offset->fX -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001104 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001105
1106 int topClampDelta = clamp.fTop - iRect->fTop;
1107 if (topClampDelta > 0) {
1108 offset->fY -= outset - topClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001109 iRect->fTop = clamp.fTop;
1110 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001111 offset->fY -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001112 }
1113
1114 if (iRect->fRight > clamp.fRight) {
1115 iRect->fRight = clamp.fRight;
1116 }
1117 if (iRect->fBottom > clamp.fBottom) {
1118 iRect->fBottom = clamp.fBottom;
1119 }
1120}
1121
1122void SkGpuDevice::drawBitmapCommon(const SkDraw& draw,
1123 const SkBitmap& bitmap,
1124 const SkRect* srcRectPtr,
1125 const SkMatrix& m,
1126 const SkPaint& paint,
1127 SkCanvas::DrawBitmapRectFlags flags) {
1128 CHECK_SHOULD_DRAW(draw, false);
1129
1130 SkRect srcRect;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001131 // If there is no src rect, or the src rect contains the entire bitmap then we're effectively
1132 // in the (easier) bleed case, so update flags.
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001133 if (NULL == srcRectPtr) {
1134 srcRect.set(0, 0, SkIntToScalar(bitmap.width()), SkIntToScalar(bitmap.height()));
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001135 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001136 } else {
1137 srcRect = *srcRectPtr;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001138 if (srcRect.fLeft <= 0 && srcRect.fTop <= 0 &&
1139 srcRect.fRight >= bitmap.width() && srcRect.fBottom >= bitmap.height()) {
1140 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1141 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001142 }
1143
1144 if (paint.getMaskFilter()){
1145 // Convert the bitmap to a shader so that the rect can be drawn
1146 // through drawRect, which supports mask filters.
1147 SkMatrix newM(m);
1148 SkBitmap tmp; // subset of bitmap, if necessary
1149 const SkBitmap* bitmapPtr = &bitmap;
1150 if (NULL != srcRectPtr) {
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001151 // In bleed mode we position and trim the bitmap based on the src rect which is
1152 // already accounted for in 'm' and 'srcRect'. In clamp mode we need to chop out
1153 // the desired portion of the bitmap and then update 'm' and 'srcRect' to
1154 // compensate.
1155 if (!(SkCanvas::kBleed_DrawBitmapRectFlag & flags)) {
1156 SkIRect iSrc;
1157 srcRect.roundOut(&iSrc);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001158
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001159 SkPoint offset = SkPoint::Make(SkIntToScalar(iSrc.fLeft),
1160 SkIntToScalar(iSrc.fTop));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001161
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001162 if (!bitmap.extractSubset(&tmp, iSrc)) {
1163 return; // extraction failed
1164 }
1165 bitmapPtr = &tmp;
1166 srcRect.offset(-offset.fX, -offset.fY);
1167 // The source rect has changed so update the matrix
1168 newM.preTranslate(offset.fX, offset.fY);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001169 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001170 }
1171
1172 SkPaint paintWithTexture(paint);
1173 paintWithTexture.setShader(SkShader::CreateBitmapShader(*bitmapPtr,
1174 SkShader::kClamp_TileMode, SkShader::kClamp_TileMode))->unref();
1175
1176 // Transform 'newM' needs to be concatenated to the current matrix,
1177 // rather than transforming the primitive directly, so that 'newM' will
1178 // also affect the behavior of the mask filter.
1179 SkMatrix drawMatrix;
1180 drawMatrix.setConcat(fContext->getMatrix(), newM);
1181 SkDraw transformedDraw(draw);
1182 transformedDraw.fMatrix = &drawMatrix;
1183
1184 this->drawRect(transformedDraw, srcRect, paintWithTexture);
1185
1186 return;
1187 }
1188
1189 fContext->concatMatrix(m);
1190
1191 GrTextureParams params;
1192 SkPaint::FilterLevel paintFilterLevel = paint.getFilterLevel();
1193 GrTextureParams::FilterMode textureFilterMode;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001194
1195 int tileFilterPad;
1196 bool doBicubic = false;
1197
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001198 switch(paintFilterLevel) {
1199 case SkPaint::kNone_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001200 tileFilterPad = 0;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001201 textureFilterMode = GrTextureParams::kNone_FilterMode;
1202 break;
1203 case SkPaint::kLow_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001204 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001205 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1206 break;
1207 case SkPaint::kMedium_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001208 tileFilterPad = 1;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001209 if (fContext->getMatrix().getMinStretch() < SK_Scalar1) {
1210 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1211 } else {
1212 // Don't trigger MIP level generation unnecessarily.
1213 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1214 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001215 break;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001216 case SkPaint::kHigh_FilterLevel:
commit-bot@chromium.orgcea9abb2013-12-09 19:15:37 +00001217 // Minification can look bad with the bicubic effect.
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001218 if (fContext->getMatrix().getMinStretch() >= SK_Scalar1) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001219 // We will install an effect that does the filtering in the shader.
1220 textureFilterMode = GrTextureParams::kNone_FilterMode;
1221 tileFilterPad = GrBicubicEffect::kFilterTexelPad;
1222 doBicubic = true;
1223 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001224 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1225 tileFilterPad = 1;
1226 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001227 break;
1228 default:
1229 SkErrorInternals::SetError( kInvalidPaint_SkError,
1230 "Sorry, I don't understand the filtering "
1231 "mode you asked for. Falling back to "
1232 "MIPMaps.");
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001233 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001234 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1235 break;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001236 }
1237
1238 params.setFilterMode(textureFilterMode);
1239
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001240 int maxTileSize = fContext->getMaxTextureSize() - 2 * tileFilterPad;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001241 int tileSize;
1242
1243 SkIRect clippedSrcRect;
1244 if (this->shouldTileBitmap(bitmap, params, srcRectPtr, maxTileSize, &tileSize,
1245 &clippedSrcRect)) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001246 this->drawTiledBitmap(bitmap, srcRect, clippedSrcRect, params, paint, flags, tileSize,
1247 doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001248 } else {
1249 // take the simple case
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001250 this->internalDrawBitmap(bitmap, srcRect, params, paint, flags, doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001251 }
1252}
1253
1254// Break 'bitmap' into several tiles to draw it since it has already
1255// been determined to be too large to fit in VRAM
1256void SkGpuDevice::drawTiledBitmap(const SkBitmap& bitmap,
1257 const SkRect& srcRect,
1258 const SkIRect& clippedSrcIRect,
1259 const GrTextureParams& params,
1260 const SkPaint& paint,
1261 SkCanvas::DrawBitmapRectFlags flags,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001262 int tileSize,
1263 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001264 SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
1265
1266 int nx = bitmap.width() / tileSize;
1267 int ny = bitmap.height() / tileSize;
1268 for (int x = 0; x <= nx; x++) {
1269 for (int y = 0; y <= ny; y++) {
1270 SkRect tileR;
1271 tileR.set(SkIntToScalar(x * tileSize),
1272 SkIntToScalar(y * tileSize),
1273 SkIntToScalar((x + 1) * tileSize),
1274 SkIntToScalar((y + 1) * tileSize));
1275
1276 if (!SkRect::Intersects(tileR, clippedSrcRect)) {
1277 continue;
1278 }
1279
1280 if (!tileR.intersect(srcRect)) {
1281 continue;
1282 }
1283
1284 SkBitmap tmpB;
1285 SkIRect iTileR;
1286 tileR.roundOut(&iTileR);
1287 SkPoint offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
1288 SkIntToScalar(iTileR.fTop));
1289
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001290 if (SkPaint::kNone_FilterLevel != paint.getFilterLevel() || bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001291 SkIRect iClampRect;
1292
1293 if (SkCanvas::kBleed_DrawBitmapRectFlag & flags) {
1294 // In bleed mode we want to always expand the tile on all edges
1295 // but stay within the bitmap bounds
1296 iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1297 } else {
1298 // In texture-domain/clamp mode we only want to expand the
1299 // tile on edges interior to "srcRect" (i.e., we want to
1300 // not bleed across the original clamped edges)
1301 srcRect.roundOut(&iClampRect);
1302 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001303 int outset = bicubic ? GrBicubicEffect::kFilterTexelPad : 1;
1304 clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001305 }
1306
1307 if (bitmap.extractSubset(&tmpB, iTileR)) {
1308 // now offset it to make it "local" to our tmp bitmap
1309 tileR.offset(-offset.fX, -offset.fY);
1310 SkMatrix tmpM;
1311 tmpM.setTranslate(offset.fX, offset.fY);
1312 GrContext::AutoMatrix am;
1313 am.setPreConcat(fContext, tmpM);
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001314 this->internalDrawBitmap(tmpB, tileR, params, paint, flags, bicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001315 }
1316 }
1317 }
1318}
1319
1320static bool has_aligned_samples(const SkRect& srcRect,
1321 const SkRect& transformedRect) {
1322 // detect pixel disalignment
1323 if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) -
1324 transformedRect.left()) < COLOR_BLEED_TOLERANCE &&
1325 SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) -
1326 transformedRect.top()) < COLOR_BLEED_TOLERANCE &&
1327 SkScalarAbs(transformedRect.width() - srcRect.width()) <
1328 COLOR_BLEED_TOLERANCE &&
1329 SkScalarAbs(transformedRect.height() - srcRect.height()) <
1330 COLOR_BLEED_TOLERANCE) {
1331 return true;
1332 }
1333 return false;
1334}
1335
1336static bool may_color_bleed(const SkRect& srcRect,
1337 const SkRect& transformedRect,
1338 const SkMatrix& m) {
1339 // Only gets called if has_aligned_samples returned false.
1340 // So we can assume that sampling is axis aligned but not texel aligned.
1341 SkASSERT(!has_aligned_samples(srcRect, transformedRect));
1342 SkRect innerSrcRect(srcRect), innerTransformedRect,
1343 outerTransformedRect(transformedRect);
1344 innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
1345 m.mapRect(&innerTransformedRect, innerSrcRect);
1346
1347 // The gap between outerTransformedRect and innerTransformedRect
1348 // represents the projection of the source border area, which is
1349 // problematic for color bleeding. We must check whether any
1350 // destination pixels sample the border area.
1351 outerTransformedRect.inset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1352 innerTransformedRect.outset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1353 SkIRect outer, inner;
1354 outerTransformedRect.round(&outer);
1355 innerTransformedRect.round(&inner);
1356 // If the inner and outer rects round to the same result, it means the
1357 // border does not overlap any pixel centers. Yay!
1358 return inner != outer;
1359}
1360
1361
1362/*
1363 * This is called by drawBitmap(), which has to handle images that may be too
1364 * large to be represented by a single texture.
1365 *
1366 * internalDrawBitmap assumes that the specified bitmap will fit in a texture
1367 * and that non-texture portion of the GrPaint has already been setup.
1368 */
1369void SkGpuDevice::internalDrawBitmap(const SkBitmap& bitmap,
1370 const SkRect& srcRect,
1371 const GrTextureParams& params,
1372 const SkPaint& paint,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001373 SkCanvas::DrawBitmapRectFlags flags,
1374 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001375 SkASSERT(bitmap.width() <= fContext->getMaxTextureSize() &&
1376 bitmap.height() <= fContext->getMaxTextureSize());
1377
1378 GrTexture* texture;
1379 SkAutoCachedTexture act(this, bitmap, &params, &texture);
1380 if (NULL == texture) {
1381 return;
1382 }
1383
1384 SkRect dstRect(srcRect);
1385 SkRect paintRect;
1386 SkScalar wInv = SkScalarInvert(SkIntToScalar(texture->width()));
1387 SkScalar hInv = SkScalarInvert(SkIntToScalar(texture->height()));
1388 paintRect.setLTRB(SkScalarMul(srcRect.fLeft, wInv),
1389 SkScalarMul(srcRect.fTop, hInv),
1390 SkScalarMul(srcRect.fRight, wInv),
1391 SkScalarMul(srcRect.fBottom, hInv));
1392
1393 bool needsTextureDomain = false;
1394 if (!(flags & SkCanvas::kBleed_DrawBitmapRectFlag) &&
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001395 (bicubic || params.filterMode() != GrTextureParams::kNone_FilterMode)) {
1396 // Need texture domain if drawing a sub rect
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001397 needsTextureDomain = srcRect.width() < bitmap.width() ||
1398 srcRect.height() < bitmap.height();
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001399 if (!bicubic && needsTextureDomain && fContext->getMatrix().rectStaysRect()) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001400 const SkMatrix& matrix = fContext->getMatrix();
1401 // sampling is axis-aligned
1402 SkRect transformedRect;
1403 matrix.mapRect(&transformedRect, srcRect);
1404
1405 if (has_aligned_samples(srcRect, transformedRect)) {
1406 // We could also turn off filtering here (but we already did a cache lookup with
1407 // params).
1408 needsTextureDomain = false;
1409 } else {
1410 needsTextureDomain = may_color_bleed(srcRect, transformedRect, matrix);
1411 }
1412 }
1413 }
1414
1415 SkRect textureDomain = SkRect::MakeEmpty();
1416 SkAutoTUnref<GrEffectRef> effect;
1417 if (needsTextureDomain) {
1418 // Use a constrained texture domain to avoid color bleeding
1419 SkScalar left, top, right, bottom;
1420 if (srcRect.width() > SK_Scalar1) {
1421 SkScalar border = SK_ScalarHalf / texture->width();
1422 left = paintRect.left() + border;
1423 right = paintRect.right() - border;
1424 } else {
1425 left = right = SkScalarHalf(paintRect.left() + paintRect.right());
1426 }
1427 if (srcRect.height() > SK_Scalar1) {
1428 SkScalar border = SK_ScalarHalf / texture->height();
1429 top = paintRect.top() + border;
1430 bottom = paintRect.bottom() - border;
1431 } else {
1432 top = bottom = SkScalarHalf(paintRect.top() + paintRect.bottom());
1433 }
1434 textureDomain.setLTRB(left, top, right, bottom);
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001435 if (bicubic) {
1436 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), textureDomain));
1437 } else {
1438 effect.reset(GrTextureDomainEffect::Create(texture,
1439 SkMatrix::I(),
1440 textureDomain,
1441 GrTextureDomain::kClamp_Mode,
1442 params.filterMode()));
1443 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001444 } else if (bicubic) {
commit-bot@chromium.orgbc91fd72013-12-10 12:53:39 +00001445 SkASSERT(GrTextureParams::kNone_FilterMode == params.filterMode());
1446 SkShader::TileMode tileModes[2] = { params.getTileModeX(), params.getTileModeY() };
1447 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), tileModes));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001448 } else {
1449 effect.reset(GrSimpleTextureEffect::Create(texture, SkMatrix::I(), params));
1450 }
1451
1452 // Construct a GrPaint by setting the bitmap texture as the first effect and then configuring
1453 // the rest from the SkPaint.
1454 GrPaint grPaint;
1455 grPaint.addColorEffect(effect);
1456 bool alphaOnly = !(SkBitmap::kA8_Config == bitmap.config());
1457 if (!skPaint2GrPaintNoShader(this, paint, alphaOnly, false, &grPaint)) {
1458 return;
1459 }
1460
1461 fContext->drawRectToRect(grPaint, dstRect, paintRect, NULL);
1462}
1463
1464static bool filter_texture(SkBaseDevice* device, GrContext* context,
1465 GrTexture* texture, SkImageFilter* filter,
1466 int w, int h, const SkMatrix& ctm, SkBitmap* result,
1467 SkIPoint* offset) {
1468 SkASSERT(filter);
1469 SkDeviceImageFilterProxy proxy(device);
1470
1471 if (filter->canFilterImageGPU()) {
1472 // Save the render target and set it to NULL, so we don't accidentally draw to it in the
1473 // filter. Also set the clip wide open and the matrix to identity.
1474 GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
1475 return filter->filterImageGPU(&proxy, wrap_texture(texture), ctm, result, offset);
1476 } else {
1477 return false;
1478 }
1479}
1480
1481void SkGpuDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap,
1482 int left, int top, const SkPaint& paint) {
1483 // drawSprite is defined to be in device coords.
1484 CHECK_SHOULD_DRAW(draw, true);
1485
1486 SkAutoLockPixels alp(bitmap, !bitmap.getTexture());
1487 if (!bitmap.getTexture() && !bitmap.readyToDraw()) {
1488 return;
1489 }
1490
1491 int w = bitmap.width();
1492 int h = bitmap.height();
1493
1494 GrTexture* texture;
1495 // draw sprite uses the default texture params
1496 SkAutoCachedTexture act(this, bitmap, NULL, &texture);
1497
1498 SkImageFilter* filter = paint.getImageFilter();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001499 // This bitmap will own the filtered result as a texture.
1500 SkBitmap filteredBitmap;
1501
1502 if (NULL != filter) {
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001503 SkIPoint offset = SkIPoint::Make(0, 0);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001504 SkMatrix matrix(*draw.fMatrix);
1505 matrix.postTranslate(SkIntToScalar(-left), SkIntToScalar(-top));
1506 if (filter_texture(this, fContext, texture, filter, w, h, matrix, &filteredBitmap,
1507 &offset)) {
1508 texture = (GrTexture*) filteredBitmap.getTexture();
1509 w = filteredBitmap.width();
1510 h = filteredBitmap.height();
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001511 left += offset.x();
1512 top += offset.y();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001513 } else {
1514 return;
1515 }
1516 }
1517
1518 GrPaint grPaint;
1519 grPaint.addColorTextureEffect(texture, SkMatrix::I());
1520
1521 if(!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1522 return;
1523 }
1524
1525 fContext->drawRectToRect(grPaint,
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001526 SkRect::MakeXYWH(SkIntToScalar(left),
1527 SkIntToScalar(top),
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001528 SkIntToScalar(w),
1529 SkIntToScalar(h)),
1530 SkRect::MakeXYWH(0,
1531 0,
1532 SK_Scalar1 * w / texture->width(),
1533 SK_Scalar1 * h / texture->height()));
1534}
1535
1536void SkGpuDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
1537 const SkRect* src, const SkRect& dst,
1538 const SkPaint& paint,
1539 SkCanvas::DrawBitmapRectFlags flags) {
1540 SkMatrix matrix;
1541 SkRect bitmapBounds, tmpSrc;
1542
1543 bitmapBounds.set(0, 0,
1544 SkIntToScalar(bitmap.width()),
1545 SkIntToScalar(bitmap.height()));
1546
1547 // Compute matrix from the two rectangles
1548 if (NULL != src) {
1549 tmpSrc = *src;
1550 } else {
1551 tmpSrc = bitmapBounds;
1552 }
1553 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1554
1555 // clip the tmpSrc to the bounds of the bitmap. No check needed if src==null.
1556 if (NULL != src) {
1557 if (!bitmapBounds.contains(tmpSrc)) {
1558 if (!tmpSrc.intersect(bitmapBounds)) {
1559 return; // nothing to draw
1560 }
1561 }
1562 }
1563
1564 this->drawBitmapCommon(draw, bitmap, &tmpSrc, matrix, paint, flags);
1565}
1566
1567void SkGpuDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device,
1568 int x, int y, const SkPaint& paint) {
1569 // clear of the source device must occur before CHECK_SHOULD_DRAW
1570 SkGpuDevice* dev = static_cast<SkGpuDevice*>(device);
1571 if (dev->fNeedClear) {
1572 // TODO: could check here whether we really need to draw at all
1573 dev->clear(0x0);
1574 }
1575
1576 // drawDevice is defined to be in device coords.
1577 CHECK_SHOULD_DRAW(draw, true);
1578
1579 GrRenderTarget* devRT = dev->accessRenderTarget();
1580 GrTexture* devTex;
1581 if (NULL == (devTex = devRT->asTexture())) {
1582 return;
1583 }
1584
1585 const SkBitmap& bm = dev->accessBitmap(false);
1586 int w = bm.width();
1587 int h = bm.height();
1588
1589 SkImageFilter* filter = paint.getImageFilter();
1590 // This bitmap will own the filtered result as a texture.
1591 SkBitmap filteredBitmap;
1592
1593 if (NULL != filter) {
1594 SkIPoint offset = SkIPoint::Make(0, 0);
1595 SkMatrix matrix(*draw.fMatrix);
1596 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
1597 if (filter_texture(this, fContext, devTex, filter, w, h, matrix, &filteredBitmap,
1598 &offset)) {
1599 devTex = filteredBitmap.getTexture();
1600 w = filteredBitmap.width();
1601 h = filteredBitmap.height();
1602 x += offset.fX;
1603 y += offset.fY;
1604 } else {
1605 return;
1606 }
1607 }
1608
1609 GrPaint grPaint;
1610 grPaint.addColorTextureEffect(devTex, SkMatrix::I());
1611
1612 if (!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1613 return;
1614 }
1615
1616 SkRect dstRect = SkRect::MakeXYWH(SkIntToScalar(x),
1617 SkIntToScalar(y),
1618 SkIntToScalar(w),
1619 SkIntToScalar(h));
1620
1621 // The device being drawn may not fill up its texture (e.g. saveLayer uses approximate
1622 // scratch texture).
1623 SkRect srcRect = SkRect::MakeWH(SK_Scalar1 * w / devTex->width(),
1624 SK_Scalar1 * h / devTex->height());
1625
1626 fContext->drawRectToRect(grPaint, dstRect, srcRect);
1627}
1628
1629bool SkGpuDevice::canHandleImageFilter(SkImageFilter* filter) {
1630 return filter->canFilterImageGPU();
1631}
1632
1633bool SkGpuDevice::filterImage(SkImageFilter* filter, const SkBitmap& src,
1634 const SkMatrix& ctm,
1635 SkBitmap* result, SkIPoint* offset) {
1636 // want explicitly our impl, so guard against a subclass of us overriding it
1637 if (!this->SkGpuDevice::canHandleImageFilter(filter)) {
1638 return false;
1639 }
1640
1641 SkAutoLockPixels alp(src, !src.getTexture());
1642 if (!src.getTexture() && !src.readyToDraw()) {
1643 return false;
1644 }
1645
1646 GrTexture* texture;
1647 // We assume here that the filter will not attempt to tile the src. Otherwise, this cache lookup
1648 // must be pushed upstack.
1649 SkAutoCachedTexture act(this, src, NULL, &texture);
1650
1651 return filter_texture(this, fContext, texture, filter, src.width(), src.height(), ctm, result,
1652 offset);
1653}
1654
1655///////////////////////////////////////////////////////////////////////////////
1656
1657// must be in SkCanvas::VertexMode order
1658static const GrPrimitiveType gVertexMode2PrimitiveType[] = {
1659 kTriangles_GrPrimitiveType,
1660 kTriangleStrip_GrPrimitiveType,
1661 kTriangleFan_GrPrimitiveType,
1662};
1663
1664void SkGpuDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
1665 int vertexCount, const SkPoint vertices[],
1666 const SkPoint texs[], const SkColor colors[],
1667 SkXfermode* xmode,
1668 const uint16_t indices[], int indexCount,
1669 const SkPaint& paint) {
1670 CHECK_SHOULD_DRAW(draw, false);
1671
1672 GrPaint grPaint;
1673 // we ignore the shader if texs is null.
1674 if (NULL == texs) {
1675 if (!skPaint2GrPaintNoShader(this, paint, false, NULL == colors, &grPaint)) {
1676 return;
1677 }
1678 } else {
1679 if (!skPaint2GrPaintShader(this, paint, NULL == colors, &grPaint)) {
1680 return;
1681 }
1682 }
1683
1684 if (NULL != xmode && NULL != texs && NULL != colors) {
1685 if (!SkXfermode::IsMode(xmode, SkXfermode::kModulate_Mode)) {
1686 SkDebugf("Unsupported vertex-color/texture xfer mode.\n");
1687#if 0
1688 return
1689#endif
1690 }
1691 }
1692
1693 SkAutoSTMalloc<128, GrColor> convertedColors(0);
1694 if (NULL != colors) {
1695 // need to convert byte order and from non-PM to PM
1696 convertedColors.reset(vertexCount);
1697 for (int i = 0; i < vertexCount; ++i) {
1698 convertedColors[i] = SkColor2GrColor(colors[i]);
1699 }
1700 colors = convertedColors.get();
1701 }
1702 fContext->drawVertices(grPaint,
1703 gVertexMode2PrimitiveType[vmode],
1704 vertexCount,
1705 (GrPoint*) vertices,
1706 (GrPoint*) texs,
1707 colors,
1708 indices,
1709 indexCount);
1710}
1711
1712///////////////////////////////////////////////////////////////////////////////
1713
1714static void GlyphCacheAuxProc(void* data) {
1715 GrFontScaler* scaler = (GrFontScaler*)data;
1716 SkSafeUnref(scaler);
1717}
1718
1719static GrFontScaler* get_gr_font_scaler(SkGlyphCache* cache) {
1720 void* auxData;
1721 GrFontScaler* scaler = NULL;
1722 if (cache->getAuxProcData(GlyphCacheAuxProc, &auxData)) {
1723 scaler = (GrFontScaler*)auxData;
1724 }
1725 if (NULL == scaler) {
1726 scaler = SkNEW_ARGS(SkGrFontScaler, (cache));
1727 cache->setAuxProc(GlyphCacheAuxProc, scaler);
1728 }
1729 return scaler;
1730}
1731
1732static void SkGPU_Draw1Glyph(const SkDraw1Glyph& state,
1733 SkFixed fx, SkFixed fy,
1734 const SkGlyph& glyph) {
1735 SkASSERT(glyph.fWidth > 0 && glyph.fHeight > 0);
1736
1737 GrSkDrawProcs* procs = static_cast<GrSkDrawProcs*>(state.fDraw->fProcs);
1738
1739 if (NULL == procs->fFontScaler) {
1740 procs->fFontScaler = get_gr_font_scaler(state.fCache);
1741 }
1742
1743 procs->fTextContext->drawPackedGlyph(GrGlyph::Pack(glyph.getGlyphID(),
1744 glyph.getSubXFixed(),
1745 glyph.getSubYFixed()),
1746 SkFixedFloorToFixed(fx),
1747 SkFixedFloorToFixed(fy),
1748 procs->fFontScaler);
1749}
1750
1751SkDrawProcs* SkGpuDevice::initDrawForText(GrTextContext* context) {
1752
1753 // deferred allocation
1754 if (NULL == fDrawProcs) {
1755 fDrawProcs = SkNEW(GrSkDrawProcs);
1756 fDrawProcs->fD1GProc = SkGPU_Draw1Glyph;
1757 fDrawProcs->fContext = fContext;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001758 }
1759
1760 // init our (and GL's) state
1761 fDrawProcs->fTextContext = context;
1762 fDrawProcs->fFontScaler = NULL;
1763 return fDrawProcs;
1764}
1765
1766void SkGpuDevice::drawText(const SkDraw& draw, const void* text,
1767 size_t byteLength, SkScalar x, SkScalar y,
1768 const SkPaint& paint) {
1769 CHECK_SHOULD_DRAW(draw, false);
1770
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001771 if (SkDraw::ShouldDrawTextAsPaths(paint, fContext->getMatrix())) {
1772 draw.drawText_asPaths((const char*)text, byteLength, x, y, paint);
1773#if SK_DISTANCEFIELD_FONTS
1774 } else if (!paint.getRasterizer()) {
1775 GrPaint grPaint;
1776 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1777 return;
1778 }
1779
1780 SkDEBUGCODE(this->validate();)
1781
1782 GrDistanceFieldTextContext context(fContext, grPaint, paint);
1783
1784 SkAutoGlyphCache autoCache(context.getSkPaint(), &this->fLeakyProperties, NULL);
1785 SkGlyphCache* cache = autoCache.getCache();
1786 GrFontScaler* fontScaler = get_gr_font_scaler(cache);
1787
1788 context.drawText((const char *)text, byteLength, x, y, cache, fontScaler);
1789#endif
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001790 } else {
1791 SkDraw myDraw(draw);
1792
1793 GrPaint grPaint;
1794 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1795 return;
1796 }
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001797
1798 GrBitmapTextContext context(fContext, grPaint, paint.getColor());
1799 myDraw.fProcs = this->initDrawForText(&context);
1800 this->INHERITED::drawText(myDraw, text, byteLength, x, y, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001801 }
1802}
1803
1804void SkGpuDevice::drawPosText(const SkDraw& draw, const void* text,
1805 size_t byteLength, const SkScalar pos[],
1806 SkScalar constY, int scalarsPerPos,
1807 const SkPaint& paint) {
1808 CHECK_SHOULD_DRAW(draw, false);
1809
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001810 if (SkDraw::ShouldDrawTextAsPaths(paint, fContext->getMatrix())) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001811 // this guy will just call our drawPath()
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001812 draw.drawPosText_asPaths((const char*)text, byteLength, pos, constY,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001813 scalarsPerPos, paint);
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001814#if SK_DISTANCEFIELD_FONTS
1815 } else if (!paint.getRasterizer()) {
1816 GrPaint grPaint;
1817 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1818 return;
1819 }
1820
1821 SkDEBUGCODE(this->validate();)
1822
1823 GrDistanceFieldTextContext context(fContext, grPaint, paint);
1824
1825 SkAutoGlyphCache autoCache(context.getSkPaint(), &this->fLeakyProperties, NULL);
1826 SkGlyphCache* cache = autoCache.getCache();
1827 GrFontScaler* fontScaler = get_gr_font_scaler(cache);
skia.committer@gmail.com22e96722013-12-20 07:01:36 +00001828
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001829 context.drawPosText((const char *)text, byteLength, pos, constY, scalarsPerPos,
1830 cache, fontScaler);
1831#endif
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001832 } else {
1833 SkDraw myDraw(draw);
1834
1835 GrPaint grPaint;
1836 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1837 return;
1838 }
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001839 GrBitmapTextContext context(fContext, grPaint, paint.getColor());
1840 myDraw.fProcs = this->initDrawForText(&context);
1841 this->INHERITED::drawPosText(myDraw, text, byteLength, pos, constY,
1842 scalarsPerPos, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001843 }
1844}
1845
1846void SkGpuDevice::drawTextOnPath(const SkDraw& draw, const void* text,
1847 size_t len, const SkPath& path,
1848 const SkMatrix* m, const SkPaint& paint) {
1849 CHECK_SHOULD_DRAW(draw, false);
1850
1851 SkASSERT(draw.fDevice == this);
1852 draw.drawTextOnPath((const char*)text, len, path, m, paint);
1853}
1854
1855///////////////////////////////////////////////////////////////////////////////
1856
1857bool SkGpuDevice::filterTextFlags(const SkPaint& paint, TextFlags* flags) {
1858 if (!paint.isLCDRenderText()) {
1859 // we're cool with the paint as is
1860 return false;
1861 }
1862
1863 if (paint.getShader() ||
1864 paint.getXfermode() || // unless its srcover
1865 paint.getMaskFilter() ||
1866 paint.getRasterizer() ||
1867 paint.getColorFilter() ||
1868 paint.getPathEffect() ||
1869 paint.isFakeBoldText() ||
1870 paint.getStyle() != SkPaint::kFill_Style) {
1871 // turn off lcd
1872 flags->fFlags = paint.getFlags() & ~SkPaint::kLCDRenderText_Flag;
1873 flags->fHinting = paint.getHinting();
1874 return true;
1875 }
1876 // we're cool with the paint as is
1877 return false;
1878}
1879
1880void SkGpuDevice::flush() {
1881 DO_DEFERRED_CLEAR();
1882 fContext->resolveRenderTarget(fRenderTarget);
1883}
1884
1885///////////////////////////////////////////////////////////////////////////////
1886
1887SkBaseDevice* SkGpuDevice::onCreateCompatibleDevice(SkBitmap::Config config,
1888 int width, int height,
1889 bool isOpaque,
1890 Usage usage) {
1891 GrTextureDesc desc;
1892 desc.fConfig = fRenderTarget->config();
1893 desc.fFlags = kRenderTarget_GrTextureFlagBit;
1894 desc.fWidth = width;
1895 desc.fHeight = height;
1896 desc.fSampleCnt = fRenderTarget->numSamples();
1897
1898 SkAutoTUnref<GrTexture> texture;
1899 // Skia's convention is to only clear a device if it is non-opaque.
1900 bool needClear = !isOpaque;
1901
1902#if CACHE_COMPATIBLE_DEVICE_TEXTURES
1903 // layers are never draw in repeat modes, so we can request an approx
1904 // match and ignore any padding.
1905 const GrContext::ScratchTexMatch match = (kSaveLayer_Usage == usage) ?
1906 GrContext::kApprox_ScratchTexMatch :
1907 GrContext::kExact_ScratchTexMatch;
1908 texture.reset(fContext->lockAndRefScratchTexture(desc, match));
1909#else
1910 texture.reset(fContext->createUncachedTexture(desc, NULL, 0));
1911#endif
1912 if (NULL != texture.get()) {
1913 return SkNEW_ARGS(SkGpuDevice,(fContext, texture, needClear));
1914 } else {
1915 GrPrintf("---- failed to create compatible device texture [%d %d]\n", width, height);
1916 return NULL;
1917 }
1918}
1919
1920SkGpuDevice::SkGpuDevice(GrContext* context,
1921 GrTexture* texture,
1922 bool needClear)
1923 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
1924
1925 SkASSERT(texture && texture->asRenderTarget());
1926 // This constructor is called from onCreateCompatibleDevice. It has locked the RT in the texture
1927 // cache. We pass true for the third argument so that it will get unlocked.
1928 this->initFromRenderTarget(context, texture->asRenderTarget(), true);
1929 fNeedClear = needClear;
1930}