1
2 /*
3 * Copyright 2006 The Android Open Source Project
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9 #include "SkBlurMaskFilter.h"
10 #include "SkBlurMask.h"
11 #include "SkGpuBlurUtils.h"
12 #include "SkReadBuffer.h"
13 #include "SkWriteBuffer.h"
14 #include "SkMaskFilter.h"
15 #include "SkRRect.h"
16 #include "SkRTConf.h"
17 #include "SkStringUtils.h"
18 #include "SkStrokeRec.h"
19
20 #if SK_SUPPORT_GPU
21 #include "GrContext.h"
22 #include "GrTexture.h"
23 #include "GrProcessor.h"
24 #include "gl/GrGLProcessor.h"
25 #include "gl/builders/GrGLProgramBuilder.h"
26 #include "effects/GrSimpleTextureEffect.h"
27 #include "GrTBackendProcessorFactory.h"
28 #include "SkGrPixelRef.h"
29 #include "SkDraw.h"
30 #endif
31
ConvertRadiusToSigma(SkScalar radius)32 SkScalar SkBlurMaskFilter::ConvertRadiusToSigma(SkScalar radius) {
33 return SkBlurMask::ConvertRadiusToSigma(radius);
34 }
35
36 class SkBlurMaskFilterImpl : public SkMaskFilter {
37 public:
38 SkBlurMaskFilterImpl(SkScalar sigma, SkBlurStyle, uint32_t flags);
39
40 // overrides from SkMaskFilter
41 virtual SkMask::Format getFormat() const SK_OVERRIDE;
42 virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
43 SkIPoint* margin) const SK_OVERRIDE;
44
45 #if SK_SUPPORT_GPU
46 virtual bool canFilterMaskGPU(const SkRect& devBounds,
47 const SkIRect& clipBounds,
48 const SkMatrix& ctm,
49 SkRect* maskRect) const SK_OVERRIDE;
50 virtual bool directFilterMaskGPU(GrContext* context,
51 GrPaint* grp,
52 const SkStrokeRec& strokeRec,
53 const SkPath& path) const SK_OVERRIDE;
54 virtual bool directFilterRRectMaskGPU(GrContext* context,
55 GrPaint* grp,
56 const SkStrokeRec& strokeRec,
57 const SkRRect& rrect) const SK_OVERRIDE;
58
59 virtual bool filterMaskGPU(GrTexture* src,
60 const SkMatrix& ctm,
61 const SkRect& maskRect,
62 GrTexture** result,
63 bool canOverwriteSrc) const SK_OVERRIDE;
64 #endif
65
66 virtual void computeFastBounds(const SkRect&, SkRect*) const SK_OVERRIDE;
67 virtual bool asABlur(BlurRec*) const SK_OVERRIDE;
68
69 SK_TO_STRING_OVERRIDE()
70 SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkBlurMaskFilterImpl)
71
72 protected:
73 virtual FilterReturn filterRectsToNine(const SkRect[], int count, const SkMatrix&,
74 const SkIRect& clipBounds,
75 NinePatch*) const SK_OVERRIDE;
76
77 virtual FilterReturn filterRRectToNine(const SkRRect&, const SkMatrix&,
78 const SkIRect& clipBounds,
79 NinePatch*) const SK_OVERRIDE;
80
81 bool filterRectMask(SkMask* dstM, const SkRect& r, const SkMatrix& matrix,
82 SkIPoint* margin, SkMask::CreateMode createMode) const;
83 bool filterRRectMask(SkMask* dstM, const SkRRect& r, const SkMatrix& matrix,
84 SkIPoint* margin, SkMask::CreateMode createMode) const;
85
86 private:
87 // To avoid unseemly allocation requests (esp. for finite platforms like
88 // handset) we limit the radius so something manageable. (as opposed to
89 // a request like 10,000)
90 static const SkScalar kMAX_BLUR_SIGMA;
91
92 SkScalar fSigma;
93 SkBlurStyle fBlurStyle;
94 uint32_t fBlurFlags;
95
getQuality() const96 SkBlurQuality getQuality() const {
97 return (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ?
98 kHigh_SkBlurQuality : kLow_SkBlurQuality;
99 }
100
101 SkBlurMaskFilterImpl(SkReadBuffer&);
102 virtual void flatten(SkWriteBuffer&) const SK_OVERRIDE;
103
computeXformedSigma(const SkMatrix & ctm) const104 SkScalar computeXformedSigma(const SkMatrix& ctm) const {
105 bool ignoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag);
106
107 SkScalar xformedSigma = ignoreTransform ? fSigma : ctm.mapRadius(fSigma);
108 return SkMinScalar(xformedSigma, kMAX_BLUR_SIGMA);
109 }
110
111 friend class SkBlurMaskFilter;
112
113 typedef SkMaskFilter INHERITED;
114 };
115
116 const SkScalar SkBlurMaskFilterImpl::kMAX_BLUR_SIGMA = SkIntToScalar(128);
117
Create(SkBlurStyle style,SkScalar sigma,uint32_t flags)118 SkMaskFilter* SkBlurMaskFilter::Create(SkBlurStyle style, SkScalar sigma, uint32_t flags) {
119 if (!SkScalarIsFinite(sigma) || sigma <= 0) {
120 return NULL;
121 }
122 if ((unsigned)style > (unsigned)kLastEnum_SkBlurStyle) {
123 return NULL;
124 }
125 if (flags > SkBlurMaskFilter::kAll_BlurFlag) {
126 return NULL;
127 }
128 return SkNEW_ARGS(SkBlurMaskFilterImpl, (sigma, style, flags));
129 }
130
131 ///////////////////////////////////////////////////////////////////////////////
132
SkBlurMaskFilterImpl(SkScalar sigma,SkBlurStyle style,uint32_t flags)133 SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar sigma, SkBlurStyle style, uint32_t flags)
134 : fSigma(sigma)
135 , fBlurStyle(style)
136 , fBlurFlags(flags) {
137 SkASSERT(fSigma > 0);
138 SkASSERT((unsigned)style <= kLastEnum_SkBlurStyle);
139 SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag);
140 }
141
getFormat() const142 SkMask::Format SkBlurMaskFilterImpl::getFormat() const {
143 return SkMask::kA8_Format;
144 }
145
asABlur(BlurRec * rec) const146 bool SkBlurMaskFilterImpl::asABlur(BlurRec* rec) const {
147 if (fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) {
148 return false;
149 }
150
151 if (rec) {
152 rec->fSigma = fSigma;
153 rec->fStyle = fBlurStyle;
154 rec->fQuality = this->getQuality();
155 }
156 return true;
157 }
158
filterMask(SkMask * dst,const SkMask & src,const SkMatrix & matrix,SkIPoint * margin) const159 bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
160 const SkMatrix& matrix,
161 SkIPoint* margin) const{
162 SkScalar sigma = this->computeXformedSigma(matrix);
163 return SkBlurMask::BoxBlur(dst, src, sigma, fBlurStyle, this->getQuality(), margin);
164 }
165
filterRectMask(SkMask * dst,const SkRect & r,const SkMatrix & matrix,SkIPoint * margin,SkMask::CreateMode createMode) const166 bool SkBlurMaskFilterImpl::filterRectMask(SkMask* dst, const SkRect& r,
167 const SkMatrix& matrix,
168 SkIPoint* margin, SkMask::CreateMode createMode) const{
169 SkScalar sigma = computeXformedSigma(matrix);
170
171 return SkBlurMask::BlurRect(sigma, dst, r, fBlurStyle,
172 margin, createMode);
173 }
174
filterRRectMask(SkMask * dst,const SkRRect & r,const SkMatrix & matrix,SkIPoint * margin,SkMask::CreateMode createMode) const175 bool SkBlurMaskFilterImpl::filterRRectMask(SkMask* dst, const SkRRect& r,
176 const SkMatrix& matrix,
177 SkIPoint* margin, SkMask::CreateMode createMode) const{
178 SkScalar sigma = computeXformedSigma(matrix);
179
180 return SkBlurMask::BlurRRect(sigma, dst, r, fBlurStyle,
181 margin, createMode);
182 }
183
184 #include "SkCanvas.h"
185
prepare_to_draw_into_mask(const SkRect & bounds,SkMask * mask)186 static bool prepare_to_draw_into_mask(const SkRect& bounds, SkMask* mask) {
187 SkASSERT(mask != NULL);
188
189 bounds.roundOut(&mask->fBounds);
190 mask->fRowBytes = SkAlign4(mask->fBounds.width());
191 mask->fFormat = SkMask::kA8_Format;
192 const size_t size = mask->computeImageSize();
193 mask->fImage = SkMask::AllocImage(size);
194 if (NULL == mask->fImage) {
195 return false;
196 }
197
198 // FIXME: use sk_calloc in AllocImage?
199 sk_bzero(mask->fImage, size);
200 return true;
201 }
202
draw_rrect_into_mask(const SkRRect rrect,SkMask * mask)203 static bool draw_rrect_into_mask(const SkRRect rrect, SkMask* mask) {
204 if (!prepare_to_draw_into_mask(rrect.rect(), mask)) {
205 return false;
206 }
207
208 // FIXME: This code duplicates code in draw_rects_into_mask, below. Is there a
209 // clean way to share more code?
210 SkBitmap bitmap;
211 bitmap.installMaskPixels(*mask);
212
213 SkCanvas canvas(bitmap);
214 canvas.translate(-SkIntToScalar(mask->fBounds.left()),
215 -SkIntToScalar(mask->fBounds.top()));
216
217 SkPaint paint;
218 paint.setAntiAlias(true);
219 canvas.drawRRect(rrect, paint);
220 return true;
221 }
222
draw_rects_into_mask(const SkRect rects[],int count,SkMask * mask)223 static bool draw_rects_into_mask(const SkRect rects[], int count, SkMask* mask) {
224 if (!prepare_to_draw_into_mask(rects[0], mask)) {
225 return false;
226 }
227
228 SkBitmap bitmap;
229 bitmap.installPixels(SkImageInfo::Make(mask->fBounds.width(),
230 mask->fBounds.height(),
231 kAlpha_8_SkColorType,
232 kPremul_SkAlphaType),
233 mask->fImage, mask->fRowBytes);
234
235 SkCanvas canvas(bitmap);
236 canvas.translate(-SkIntToScalar(mask->fBounds.left()),
237 -SkIntToScalar(mask->fBounds.top()));
238
239 SkPaint paint;
240 paint.setAntiAlias(true);
241
242 if (1 == count) {
243 canvas.drawRect(rects[0], paint);
244 } else {
245 // todo: do I need a fast way to do this?
246 SkPath path;
247 path.addRect(rects[0]);
248 path.addRect(rects[1]);
249 path.setFillType(SkPath::kEvenOdd_FillType);
250 canvas.drawPath(path, paint);
251 }
252 return true;
253 }
254
rect_exceeds(const SkRect & r,SkScalar v)255 static bool rect_exceeds(const SkRect& r, SkScalar v) {
256 return r.fLeft < -v || r.fTop < -v || r.fRight > v || r.fBottom > v ||
257 r.width() > v || r.height() > v;
258 }
259
260 #ifdef SK_IGNORE_FAST_RRECT_BLUR
261 SK_CONF_DECLARE( bool, c_analyticBlurRRect, "mask.filter.blur.analyticblurrrect", false, "Use the faster analytic blur approach for ninepatch rects" );
262 #else
263 SK_CONF_DECLARE( bool, c_analyticBlurRRect, "mask.filter.blur.analyticblurrrect", true, "Use the faster analytic blur approach for ninepatch round rects" );
264 #endif
265
266 SkMaskFilter::FilterReturn
filterRRectToNine(const SkRRect & rrect,const SkMatrix & matrix,const SkIRect & clipBounds,NinePatch * patch) const267 SkBlurMaskFilterImpl::filterRRectToNine(const SkRRect& rrect, const SkMatrix& matrix,
268 const SkIRect& clipBounds,
269 NinePatch* patch) const {
270 SkASSERT(patch != NULL);
271 switch (rrect.getType()) {
272 case SkRRect::kUnknown_Type:
273 // Unknown should never be returned.
274 SkASSERT(false);
275 // Fall through.
276 case SkRRect::kEmpty_Type:
277 // Nothing to draw.
278 return kFalse_FilterReturn;
279
280 case SkRRect::kRect_Type:
281 // We should have caught this earlier.
282 SkASSERT(false);
283 // Fall through.
284 case SkRRect::kOval_Type:
285 // The nine patch special case does not handle ovals, and we
286 // already have code for rectangles.
287 return kUnimplemented_FilterReturn;
288
289 // These three can take advantage of this fast path.
290 case SkRRect::kSimple_Type:
291 case SkRRect::kNinePatch_Type:
292 case SkRRect::kComplex_Type:
293 break;
294 }
295
296 // TODO: report correct metrics for innerstyle, where we do not grow the
297 // total bounds, but we do need an inset the size of our blur-radius
298 if (kInner_SkBlurStyle == fBlurStyle) {
299 return kUnimplemented_FilterReturn;
300 }
301
302 // TODO: take clipBounds into account to limit our coordinates up front
303 // for now, just skip too-large src rects (to take the old code path).
304 if (rect_exceeds(rrect.rect(), SkIntToScalar(32767))) {
305 return kUnimplemented_FilterReturn;
306 }
307
308 SkIPoint margin;
309 SkMask srcM, dstM;
310 rrect.rect().roundOut(&srcM.fBounds);
311 srcM.fImage = NULL;
312 srcM.fFormat = SkMask::kA8_Format;
313 srcM.fRowBytes = 0;
314
315 bool filterResult = false;
316 if (c_analyticBlurRRect) {
317 // special case for fast round rect blur
318 // don't actually do the blur the first time, just compute the correct size
319 filterResult = this->filterRRectMask(&dstM, rrect, matrix, &margin,
320 SkMask::kJustComputeBounds_CreateMode);
321 }
322
323 if (!filterResult) {
324 filterResult = this->filterMask(&dstM, srcM, matrix, &margin);
325 }
326
327 if (!filterResult) {
328 return kFalse_FilterReturn;
329 }
330
331 // Now figure out the appropriate width and height of the smaller round rectangle
332 // to stretch. It will take into account the larger radius per side as well as double
333 // the margin, to account for inner and outer blur.
334 const SkVector& UL = rrect.radii(SkRRect::kUpperLeft_Corner);
335 const SkVector& UR = rrect.radii(SkRRect::kUpperRight_Corner);
336 const SkVector& LR = rrect.radii(SkRRect::kLowerRight_Corner);
337 const SkVector& LL = rrect.radii(SkRRect::kLowerLeft_Corner);
338
339 const SkScalar leftUnstretched = SkTMax(UL.fX, LL.fX) + SkIntToScalar(2 * margin.fX);
340 const SkScalar rightUnstretched = SkTMax(UR.fX, LR.fX) + SkIntToScalar(2 * margin.fX);
341
342 // Extra space in the middle to ensure an unchanging piece for stretching. Use 3 to cover
343 // any fractional space on either side plus 1 for the part to stretch.
344 const SkScalar stretchSize = SkIntToScalar(3);
345
346 const SkScalar totalSmallWidth = leftUnstretched + rightUnstretched + stretchSize;
347 if (totalSmallWidth >= rrect.rect().width()) {
348 // There is no valid piece to stretch.
349 return kUnimplemented_FilterReturn;
350 }
351
352 const SkScalar topUnstretched = SkTMax(UL.fY, UR.fY) + SkIntToScalar(2 * margin.fY);
353 const SkScalar bottomUnstretched = SkTMax(LL.fY, LR.fY) + SkIntToScalar(2 * margin.fY);
354
355 const SkScalar totalSmallHeight = topUnstretched + bottomUnstretched + stretchSize;
356 if (totalSmallHeight >= rrect.rect().height()) {
357 // There is no valid piece to stretch.
358 return kUnimplemented_FilterReturn;
359 }
360
361 SkRect smallR = SkRect::MakeWH(totalSmallWidth, totalSmallHeight);
362
363 SkRRect smallRR;
364 SkVector radii[4];
365 radii[SkRRect::kUpperLeft_Corner] = UL;
366 radii[SkRRect::kUpperRight_Corner] = UR;
367 radii[SkRRect::kLowerRight_Corner] = LR;
368 radii[SkRRect::kLowerLeft_Corner] = LL;
369 smallRR.setRectRadii(smallR, radii);
370
371 bool analyticBlurWorked = false;
372 if (c_analyticBlurRRect) {
373 analyticBlurWorked =
374 this->filterRRectMask(&patch->fMask, smallRR, matrix, &margin,
375 SkMask::kComputeBoundsAndRenderImage_CreateMode);
376 }
377
378 if (!analyticBlurWorked) {
379 if (!draw_rrect_into_mask(smallRR, &srcM)) {
380 return kFalse_FilterReturn;
381 }
382
383 SkAutoMaskFreeImage amf(srcM.fImage);
384
385 if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
386 return kFalse_FilterReturn;
387 }
388 }
389
390 patch->fMask.fBounds.offsetTo(0, 0);
391 patch->fOuterRect = dstM.fBounds;
392 patch->fCenter.fX = SkScalarCeilToInt(leftUnstretched) + 1;
393 patch->fCenter.fY = SkScalarCeilToInt(topUnstretched) + 1;
394 return kTrue_FilterReturn;
395 }
396
397 SK_CONF_DECLARE( bool, c_analyticBlurNinepatch, "mask.filter.analyticNinePatch", true, "Use the faster analytic blur approach for ninepatch rects" );
398
399 SkMaskFilter::FilterReturn
filterRectsToNine(const SkRect rects[],int count,const SkMatrix & matrix,const SkIRect & clipBounds,NinePatch * patch) const400 SkBlurMaskFilterImpl::filterRectsToNine(const SkRect rects[], int count,
401 const SkMatrix& matrix,
402 const SkIRect& clipBounds,
403 NinePatch* patch) const {
404 if (count < 1 || count > 2) {
405 return kUnimplemented_FilterReturn;
406 }
407
408 // TODO: report correct metrics for innerstyle, where we do not grow the
409 // total bounds, but we do need an inset the size of our blur-radius
410 if (kInner_SkBlurStyle == fBlurStyle || kOuter_SkBlurStyle == fBlurStyle) {
411 return kUnimplemented_FilterReturn;
412 }
413
414 // TODO: take clipBounds into account to limit our coordinates up front
415 // for now, just skip too-large src rects (to take the old code path).
416 if (rect_exceeds(rects[0], SkIntToScalar(32767))) {
417 return kUnimplemented_FilterReturn;
418 }
419
420 SkIPoint margin;
421 SkMask srcM, dstM;
422 rects[0].roundOut(&srcM.fBounds);
423 srcM.fImage = NULL;
424 srcM.fFormat = SkMask::kA8_Format;
425 srcM.fRowBytes = 0;
426
427 bool filterResult = false;
428 if (count == 1 && c_analyticBlurNinepatch) {
429 // special case for fast rect blur
430 // don't actually do the blur the first time, just compute the correct size
431 filterResult = this->filterRectMask(&dstM, rects[0], matrix, &margin,
432 SkMask::kJustComputeBounds_CreateMode);
433 } else {
434 filterResult = this->filterMask(&dstM, srcM, matrix, &margin);
435 }
436
437 if (!filterResult) {
438 return kFalse_FilterReturn;
439 }
440
441 /*
442 * smallR is the smallest version of 'rect' that will still guarantee that
443 * we get the same blur results on all edges, plus 1 center row/col that is
444 * representative of the extendible/stretchable edges of the ninepatch.
445 * Since our actual edge may be fractional we inset 1 more to be sure we
446 * don't miss any interior blur.
447 * x is an added pixel of blur, and { and } are the (fractional) edge
448 * pixels from the original rect.
449 *
450 * x x { x x .... x x } x x
451 *
452 * Thus, in this case, we inset by a total of 5 (on each side) beginning
453 * with our outer-rect (dstM.fBounds)
454 */
455 SkRect smallR[2];
456 SkIPoint center;
457
458 // +2 is from +1 for each edge (to account for possible fractional edges
459 int smallW = dstM.fBounds.width() - srcM.fBounds.width() + 2;
460 int smallH = dstM.fBounds.height() - srcM.fBounds.height() + 2;
461 SkIRect innerIR;
462
463 if (1 == count) {
464 innerIR = srcM.fBounds;
465 center.set(smallW, smallH);
466 } else {
467 SkASSERT(2 == count);
468 rects[1].roundIn(&innerIR);
469 center.set(smallW + (innerIR.left() - srcM.fBounds.left()),
470 smallH + (innerIR.top() - srcM.fBounds.top()));
471 }
472
473 // +1 so we get a clean, stretchable, center row/col
474 smallW += 1;
475 smallH += 1;
476
477 // we want the inset amounts to be integral, so we don't change any
478 // fractional phase on the fRight or fBottom of our smallR.
479 const SkScalar dx = SkIntToScalar(innerIR.width() - smallW);
480 const SkScalar dy = SkIntToScalar(innerIR.height() - smallH);
481 if (dx < 0 || dy < 0) {
482 // we're too small, relative to our blur, to break into nine-patch,
483 // so we ask to have our normal filterMask() be called.
484 return kUnimplemented_FilterReturn;
485 }
486
487 smallR[0].set(rects[0].left(), rects[0].top(), rects[0].right() - dx, rects[0].bottom() - dy);
488 if (smallR[0].width() < 2 || smallR[0].height() < 2) {
489 return kUnimplemented_FilterReturn;
490 }
491 if (2 == count) {
492 smallR[1].set(rects[1].left(), rects[1].top(),
493 rects[1].right() - dx, rects[1].bottom() - dy);
494 SkASSERT(!smallR[1].isEmpty());
495 }
496
497 if (count > 1 || !c_analyticBlurNinepatch) {
498 if (!draw_rects_into_mask(smallR, count, &srcM)) {
499 return kFalse_FilterReturn;
500 }
501
502 SkAutoMaskFreeImage amf(srcM.fImage);
503
504 if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
505 return kFalse_FilterReturn;
506 }
507 } else {
508 if (!this->filterRectMask(&patch->fMask, smallR[0], matrix, &margin,
509 SkMask::kComputeBoundsAndRenderImage_CreateMode)) {
510 return kFalse_FilterReturn;
511 }
512 }
513 patch->fMask.fBounds.offsetTo(0, 0);
514 patch->fOuterRect = dstM.fBounds;
515 patch->fCenter = center;
516 return kTrue_FilterReturn;
517 }
518
computeFastBounds(const SkRect & src,SkRect * dst) const519 void SkBlurMaskFilterImpl::computeFastBounds(const SkRect& src,
520 SkRect* dst) const {
521 SkScalar pad = 3.0f * fSigma;
522
523 dst->set(src.fLeft - pad, src.fTop - pad,
524 src.fRight + pad, src.fBottom + pad);
525 }
526
527 #ifdef SK_SUPPORT_LEGACY_DEEPFLATTENING
SkBlurMaskFilterImpl(SkReadBuffer & buffer)528 SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkReadBuffer& buffer) : SkMaskFilter(buffer) {
529 fSigma = buffer.readScalar();
530 fBlurStyle = (SkBlurStyle)buffer.readInt();
531 fBlurFlags = buffer.readUInt() & SkBlurMaskFilter::kAll_BlurFlag;
532 SkASSERT(fSigma > 0);
533 SkASSERT((unsigned)fBlurStyle <= kLastEnum_SkBlurStyle);
534 }
535 #endif
536
CreateProc(SkReadBuffer & buffer)537 SkFlattenable* SkBlurMaskFilterImpl::CreateProc(SkReadBuffer& buffer) {
538 const SkScalar sigma = buffer.readScalar();
539 const unsigned style = buffer.readUInt();
540 const unsigned flags = buffer.readUInt();
541 if (style <= kLastEnum_SkBlurStyle) {
542 return SkBlurMaskFilter::Create((SkBlurStyle)style, sigma, flags);
543 }
544 return NULL;
545 }
546
flatten(SkWriteBuffer & buffer) const547 void SkBlurMaskFilterImpl::flatten(SkWriteBuffer& buffer) const {
548 buffer.writeScalar(fSigma);
549 buffer.writeUInt(fBlurStyle);
550 buffer.writeUInt(fBlurFlags);
551 }
552
553 #if SK_SUPPORT_GPU
554
555 class GrGLRectBlurEffect;
556
557 class GrRectBlurEffect : public GrFragmentProcessor {
558 public:
559 virtual ~GrRectBlurEffect();
560
Name()561 static const char* Name() { return "RectBlur"; }
562
563 typedef GrGLRectBlurEffect GLProcessor;
564
565 virtual const GrBackendFragmentProcessorFactory& getFactory() const SK_OVERRIDE;
566 virtual void getConstantColorComponents(GrColor* color, uint32_t* validFlags) const SK_OVERRIDE;
567
568 /**
569 * Create a simple filter effect with custom bicubic coefficients.
570 */
Create(GrContext * context,const SkRect & rect,float sigma)571 static GrFragmentProcessor* Create(GrContext *context, const SkRect& rect, float sigma) {
572 GrTexture *blurProfileTexture = NULL;
573 int doubleProfileSize = SkScalarCeilToInt(12*sigma);
574
575 if (doubleProfileSize >= rect.width() || doubleProfileSize >= rect.height()) {
576 // if the blur sigma is too large so the gaussian overlaps the whole
577 // rect in either direction, fall back to CPU path for now.
578
579 return NULL;
580 }
581
582 bool createdBlurProfileTexture = CreateBlurProfileTexture(context, sigma, &blurProfileTexture);
583 SkAutoTUnref<GrTexture> hunref(blurProfileTexture);
584 if (!createdBlurProfileTexture) {
585 return NULL;
586 }
587 return SkNEW_ARGS(GrRectBlurEffect, (rect, sigma, blurProfileTexture));
588 }
589
getRect() const590 const SkRect& getRect() const { return fRect; }
getSigma() const591 float getSigma() const { return fSigma; }
592
593 private:
594 GrRectBlurEffect(const SkRect& rect, float sigma, GrTexture *blur_profile);
595 virtual bool onIsEqual(const GrProcessor&) const SK_OVERRIDE;
596
597 static bool CreateBlurProfileTexture(GrContext *context, float sigma,
598 GrTexture **blurProfileTexture);
599
600 SkRect fRect;
601 float fSigma;
602 GrTextureAccess fBlurProfileAccess;
603
604 GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
605
606 typedef GrFragmentProcessor INHERITED;
607 };
608
609 class GrGLRectBlurEffect : public GrGLFragmentProcessor {
610 public:
611 GrGLRectBlurEffect(const GrBackendProcessorFactory& factory,
612 const GrProcessor&);
613 virtual void emitCode(GrGLProgramBuilder*,
614 const GrFragmentProcessor&,
615 const GrProcessorKey&,
616 const char* outputColor,
617 const char* inputColor,
618 const TransformedCoordsArray&,
619 const TextureSamplerArray&) SK_OVERRIDE;
620
621 virtual void setData(const GrGLProgramDataManager&, const GrProcessor&) SK_OVERRIDE;
622
623 private:
624 typedef GrGLProgramDataManager::UniformHandle UniformHandle;
625
626 UniformHandle fProxyRectUniform;
627 UniformHandle fProfileSizeUniform;
628
629 typedef GrGLFragmentProcessor INHERITED;
630 };
631
632
633
GrGLRectBlurEffect(const GrBackendProcessorFactory & factory,const GrProcessor &)634 GrGLRectBlurEffect::GrGLRectBlurEffect(const GrBackendProcessorFactory& factory, const GrProcessor&)
635 : INHERITED(factory) {
636 }
637
OutputRectBlurProfileLookup(GrGLFragmentShaderBuilder * fsBuilder,const GrGLShaderBuilder::TextureSampler & sampler,const char * output,const char * profileSize,const char * loc,const char * blurred_width,const char * sharp_width)638 void OutputRectBlurProfileLookup(GrGLFragmentShaderBuilder* fsBuilder,
639 const GrGLShaderBuilder::TextureSampler& sampler,
640 const char *output,
641 const char *profileSize, const char *loc,
642 const char *blurred_width,
643 const char *sharp_width) {
644 fsBuilder->codeAppendf("\tfloat %s;\n", output);
645 fsBuilder->codeAppendf("\t\t{\n");
646 fsBuilder->codeAppendf("\t\t\tfloat coord = (0.5 * (abs(2.0*%s - %s) - %s))/%s;\n",
647 loc, blurred_width, sharp_width, profileSize);
648 fsBuilder->codeAppendf("\t\t\t%s = ", output);
649 fsBuilder->appendTextureLookup(sampler, "vec2(coord,0.5)");
650 fsBuilder->codeAppend(".a;\n");
651 fsBuilder->codeAppendf("\t\t}\n");
652 }
653
emitCode(GrGLProgramBuilder * builder,const GrFragmentProcessor &,const GrProcessorKey & key,const char * outputColor,const char * inputColor,const TransformedCoordsArray & coords,const TextureSamplerArray & samplers)654 void GrGLRectBlurEffect::emitCode(GrGLProgramBuilder* builder,
655 const GrFragmentProcessor&,
656 const GrProcessorKey& key,
657 const char* outputColor,
658 const char* inputColor,
659 const TransformedCoordsArray& coords,
660 const TextureSamplerArray& samplers) {
661
662 const char *rectName;
663 const char *profileSizeName;
664
665 fProxyRectUniform = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
666 kVec4f_GrSLType,
667 "proxyRect",
668 &rectName);
669 fProfileSizeUniform = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
670 kFloat_GrSLType,
671 "profileSize",
672 &profileSizeName);
673
674 GrGLFragmentShaderBuilder* fsBuilder = builder->getFragmentShaderBuilder();
675 const char *fragmentPos = fsBuilder->fragmentPosition();
676
677 if (inputColor) {
678 fsBuilder->codeAppendf("\tvec4 src=%s;\n", inputColor);
679 } else {
680 fsBuilder->codeAppendf("\tvec4 src=vec4(1)\n;");
681 }
682
683 fsBuilder->codeAppendf("\tvec2 translatedPos = %s.xy - %s.xy;\n", fragmentPos, rectName );
684 fsBuilder->codeAppendf("\tfloat width = %s.z - %s.x;\n", rectName, rectName);
685 fsBuilder->codeAppendf("\tfloat height = %s.w - %s.y;\n", rectName, rectName);
686
687 fsBuilder->codeAppendf("\tvec2 smallDims = vec2(width - %s, height-%s);\n", profileSizeName, profileSizeName);
688 fsBuilder->codeAppendf("\tfloat center = 2.0 * floor(%s/2.0 + .25) - 1.0;\n", profileSizeName);
689 fsBuilder->codeAppendf("\tvec2 wh = smallDims - vec2(center,center);\n");
690
691 OutputRectBlurProfileLookup(fsBuilder, samplers[0], "horiz_lookup", profileSizeName, "translatedPos.x", "width", "wh.x");
692 OutputRectBlurProfileLookup(fsBuilder, samplers[0], "vert_lookup", profileSizeName, "translatedPos.y", "height", "wh.y");
693
694 fsBuilder->codeAppendf("\tfloat final = horiz_lookup * vert_lookup;\n");
695 fsBuilder->codeAppendf("\t%s = src * vec4(final);\n", outputColor );
696 }
697
setData(const GrGLProgramDataManager & pdman,const GrProcessor & proc)698 void GrGLRectBlurEffect::setData(const GrGLProgramDataManager& pdman,
699 const GrProcessor& proc) {
700 const GrRectBlurEffect& rbe = proc.cast<GrRectBlurEffect>();
701 SkRect rect = rbe.getRect();
702
703 pdman.set4f(fProxyRectUniform, rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
704 pdman.set1f(fProfileSizeUniform, SkScalarCeilToScalar(6*rbe.getSigma()));
705 }
706
CreateBlurProfileTexture(GrContext * context,float sigma,GrTexture ** blurProfileTexture)707 bool GrRectBlurEffect::CreateBlurProfileTexture(GrContext *context, float sigma,
708 GrTexture **blurProfileTexture) {
709 GrTextureParams params;
710 GrTextureDesc texDesc;
711
712 unsigned int profile_size = SkScalarCeilToInt(6*sigma);
713
714 texDesc.fWidth = profile_size;
715 texDesc.fHeight = 1;
716 texDesc.fConfig = kAlpha_8_GrPixelConfig;
717
718 static const GrCacheID::Domain gBlurProfileDomain = GrCacheID::GenerateDomain();
719 GrCacheID::Key key;
720 memset(&key, 0, sizeof(key));
721 key.fData32[0] = profile_size;
722 key.fData32[1] = 1;
723 GrCacheID blurProfileKey(gBlurProfileDomain, key);
724
725 uint8_t *profile = NULL;
726 SkAutoTDeleteArray<uint8_t> ada(NULL);
727
728 *blurProfileTexture = context->findAndRefTexture(texDesc, blurProfileKey, ¶ms);
729
730 if (NULL == *blurProfileTexture) {
731
732 SkBlurMask::ComputeBlurProfile(sigma, &profile);
733 ada.reset(profile);
734
735 *blurProfileTexture = context->createTexture(¶ms, texDesc, blurProfileKey,
736 profile, 0);
737
738 if (NULL == *blurProfileTexture) {
739 return false;
740 }
741 }
742
743 return true;
744 }
745
GrRectBlurEffect(const SkRect & rect,float sigma,GrTexture * blur_profile)746 GrRectBlurEffect::GrRectBlurEffect(const SkRect& rect, float sigma,
747 GrTexture *blur_profile)
748 : INHERITED(),
749 fRect(rect),
750 fSigma(sigma),
751 fBlurProfileAccess(blur_profile) {
752 this->addTextureAccess(&fBlurProfileAccess);
753 this->setWillReadFragmentPosition();
754 }
755
~GrRectBlurEffect()756 GrRectBlurEffect::~GrRectBlurEffect() {
757 }
758
getFactory() const759 const GrBackendFragmentProcessorFactory& GrRectBlurEffect::getFactory() const {
760 return GrTBackendFragmentProcessorFactory<GrRectBlurEffect>::getInstance();
761 }
762
onIsEqual(const GrProcessor & sBase) const763 bool GrRectBlurEffect::onIsEqual(const GrProcessor& sBase) const {
764 const GrRectBlurEffect& s = sBase.cast<GrRectBlurEffect>();
765 return this->getSigma() == s.getSigma() && this->getRect() == s.getRect();
766 }
767
getConstantColorComponents(GrColor * color,uint32_t * validFlags) const768 void GrRectBlurEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const {
769 *validFlags = 0;
770 return;
771 }
772
773 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrRectBlurEffect);
774
TestCreate(SkRandom * random,GrContext * context,const GrDrawTargetCaps &,GrTexture **)775 GrFragmentProcessor* GrRectBlurEffect::TestCreate(SkRandom* random,
776 GrContext* context,
777 const GrDrawTargetCaps&,
778 GrTexture**) {
779 float sigma = random->nextRangeF(3,8);
780 float width = random->nextRangeF(200,300);
781 float height = random->nextRangeF(200,300);
782 return GrRectBlurEffect::Create(context, SkRect::MakeWH(width, height), sigma);
783 }
784
785
directFilterMaskGPU(GrContext * context,GrPaint * grp,const SkStrokeRec & strokeRec,const SkPath & path) const786 bool SkBlurMaskFilterImpl::directFilterMaskGPU(GrContext* context,
787 GrPaint* grp,
788 const SkStrokeRec& strokeRec,
789 const SkPath& path) const {
790 if (fBlurStyle != kNormal_SkBlurStyle) {
791 return false;
792 }
793
794 SkRect rect;
795 if (!path.isRect(&rect)) {
796 return false;
797 }
798
799 if (!strokeRec.isFillStyle()) {
800 return false;
801 }
802
803 SkMatrix ctm = context->getMatrix();
804 SkScalar xformedSigma = this->computeXformedSigma(ctm);
805
806 int pad=SkScalarCeilToInt(6*xformedSigma)/2;
807 rect.outset(SkIntToScalar(pad), SkIntToScalar(pad));
808
809 SkAutoTUnref<GrFragmentProcessor> fp(GrRectBlurEffect::Create(context, rect, xformedSigma));
810 if (!fp) {
811 return false;
812 }
813
814 GrContext::AutoMatrix am;
815 if (!am.setIdentity(context, grp)) {
816 return false;
817 }
818
819 grp->addCoverageProcessor(fp);
820
821 context->drawRect(*grp, rect);
822 return true;
823 }
824
825 class GrGLRRectBlurEffect;
826
827 class GrRRectBlurEffect : public GrFragmentProcessor {
828 public:
829
830 static GrFragmentProcessor* Create(GrContext* context, float sigma, const SkRRect&);
831
~GrRRectBlurEffect()832 virtual ~GrRRectBlurEffect() {};
Name()833 static const char* Name() { return "GrRRectBlur"; }
834
getRRect() const835 const SkRRect& getRRect() const { return fRRect; }
getSigma() const836 float getSigma() const { return fSigma; }
837
838 typedef GrGLRRectBlurEffect GLProcessor;
839
840 virtual void getConstantColorComponents(GrColor* color, uint32_t* validFlags) const SK_OVERRIDE;
841
842 virtual const GrBackendFragmentProcessorFactory& getFactory() const SK_OVERRIDE;
843
844 private:
845 GrRRectBlurEffect(float sigma, const SkRRect&, GrTexture* profileTexture);
846
847 virtual bool onIsEqual(const GrProcessor& other) const SK_OVERRIDE;
848
849 SkRRect fRRect;
850 float fSigma;
851 GrTextureAccess fNinePatchAccess;
852
853 GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
854
855 typedef GrFragmentProcessor INHERITED;
856 };
857
858
Create(GrContext * context,float sigma,const SkRRect & rrect)859 GrFragmentProcessor* GrRRectBlurEffect::Create(GrContext* context, float sigma,
860 const SkRRect& rrect) {
861 if (!rrect.isSimpleCircular()) {
862 return NULL;
863 }
864
865 // Make sure we can successfully ninepatch this rrect -- the blur sigma has to be
866 // sufficiently small relative to both the size of the corner radius and the
867 // width (and height) of the rrect.
868
869 unsigned int blurRadius = 3*SkScalarCeilToInt(sigma-1/6.0f);
870 unsigned int cornerRadius = SkScalarCeilToInt(rrect.getSimpleRadii().x());
871 if (cornerRadius + blurRadius > rrect.width()/2 ||
872 cornerRadius + blurRadius > rrect.height()/2) {
873 return NULL;
874 }
875
876 static const GrCacheID::Domain gRRectBlurDomain = GrCacheID::GenerateDomain();
877 GrCacheID::Key key;
878 memset(&key, 0, sizeof(key));
879 key.fData32[0] = blurRadius;
880 key.fData32[1] = cornerRadius;
881 GrCacheID blurRRectNinePatchID(gRRectBlurDomain, key);
882
883 GrTextureParams params;
884 params.setFilterMode(GrTextureParams::kBilerp_FilterMode);
885
886 unsigned int smallRectSide = 2*(blurRadius + cornerRadius) + 1;
887 unsigned int texSide = smallRectSide + 2*blurRadius;
888 GrTextureDesc texDesc;
889 texDesc.fWidth = texSide;
890 texDesc.fHeight = texSide;
891 texDesc.fConfig = kAlpha_8_GrPixelConfig;
892
893 GrTexture *blurNinePatchTexture = context->findAndRefTexture(texDesc, blurRRectNinePatchID, ¶ms);
894
895 if (NULL == blurNinePatchTexture) {
896 SkMask mask;
897
898 mask.fBounds = SkIRect::MakeWH(smallRectSide, smallRectSide);
899 mask.fFormat = SkMask::kA8_Format;
900 mask.fRowBytes = mask.fBounds.width();
901 mask.fImage = SkMask::AllocImage(mask.computeTotalImageSize());
902 SkAutoMaskFreeImage amfi(mask.fImage);
903
904 memset(mask.fImage, 0, mask.computeTotalImageSize());
905
906 SkRect smallRect;
907 smallRect.setWH(SkIntToScalar(smallRectSide), SkIntToScalar(smallRectSide));
908
909 SkRRect smallRRect;
910 smallRRect.setRectXY(smallRect, SkIntToScalar(cornerRadius), SkIntToScalar(cornerRadius));
911
912 SkPath path;
913 path.addRRect( smallRRect );
914
915 SkDraw::DrawToMask(path, &mask.fBounds, NULL, NULL, &mask, SkMask::kJustRenderImage_CreateMode, SkPaint::kFill_Style);
916
917 SkMask blurred_mask;
918 SkBlurMask::BoxBlur(&blurred_mask, mask, sigma, kNormal_SkBlurStyle, kHigh_SkBlurQuality, NULL, true );
919
920 blurNinePatchTexture = context->createTexture(¶ms, texDesc, blurRRectNinePatchID, blurred_mask.fImage, 0);
921 SkMask::FreeImage(blurred_mask.fImage);
922 }
923
924 SkAutoTUnref<GrTexture> blurunref(blurNinePatchTexture);
925 if (NULL == blurNinePatchTexture) {
926 return NULL;
927 }
928
929 return SkNEW_ARGS(GrRRectBlurEffect, (sigma, rrect, blurNinePatchTexture));
930 }
931
getConstantColorComponents(GrColor * color,uint32_t * validFlags) const932 void GrRRectBlurEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const {
933 *validFlags = 0;
934 }
935
getFactory() const936 const GrBackendFragmentProcessorFactory& GrRRectBlurEffect::getFactory() const {
937 return GrTBackendFragmentProcessorFactory<GrRRectBlurEffect>::getInstance();
938 }
939
GrRRectBlurEffect(float sigma,const SkRRect & rrect,GrTexture * ninePatchTexture)940 GrRRectBlurEffect::GrRRectBlurEffect(float sigma, const SkRRect& rrect, GrTexture *ninePatchTexture)
941 : fRRect(rrect),
942 fSigma(sigma),
943 fNinePatchAccess(ninePatchTexture) {
944 this->addTextureAccess(&fNinePatchAccess);
945 this->setWillReadFragmentPosition();
946 }
947
onIsEqual(const GrProcessor & other) const948 bool GrRRectBlurEffect::onIsEqual(const GrProcessor& other) const {
949 const GrRRectBlurEffect& rrbe = other.cast<GrRRectBlurEffect>();
950 return fRRect.getSimpleRadii().fX == rrbe.fRRect.getSimpleRadii().fX && fSigma == rrbe.fSigma;
951 }
952
953 //////////////////////////////////////////////////////////////////////////////
954
955 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrRRectBlurEffect);
956
TestCreate(SkRandom * random,GrContext * context,const GrDrawTargetCaps & caps,GrTexture * [])957 GrFragmentProcessor* GrRRectBlurEffect::TestCreate(SkRandom* random,
958 GrContext* context,
959 const GrDrawTargetCaps& caps,
960 GrTexture*[]) {
961 SkScalar w = random->nextRangeScalar(100.f, 1000.f);
962 SkScalar h = random->nextRangeScalar(100.f, 1000.f);
963 SkScalar r = random->nextRangeF(1.f, 9.f);
964 SkScalar sigma = random->nextRangeF(1.f,10.f);
965 SkRRect rrect;
966 rrect.setRectXY(SkRect::MakeWH(w, h), r, r);
967 return GrRRectBlurEffect::Create(context, sigma, rrect);
968 }
969
970 //////////////////////////////////////////////////////////////////////////////
971
972 class GrGLRRectBlurEffect : public GrGLFragmentProcessor {
973 public:
974 GrGLRRectBlurEffect(const GrBackendProcessorFactory&, const GrProcessor&);
975
976 virtual void emitCode(GrGLProgramBuilder*,
977 const GrFragmentProcessor&,
978 const GrProcessorKey&,
979 const char* outputColor,
980 const char* inputColor,
981 const TransformedCoordsArray&,
982 const TextureSamplerArray&) SK_OVERRIDE;
983
984 virtual void setData(const GrGLProgramDataManager&, const GrProcessor&) SK_OVERRIDE;
985
986 private:
987 GrGLProgramDataManager::UniformHandle fProxyRectUniform;
988 GrGLProgramDataManager::UniformHandle fCornerRadiusUniform;
989 GrGLProgramDataManager::UniformHandle fBlurRadiusUniform;
990 typedef GrGLFragmentProcessor INHERITED;
991 };
992
GrGLRRectBlurEffect(const GrBackendProcessorFactory & factory,const GrProcessor &)993 GrGLRRectBlurEffect::GrGLRRectBlurEffect(const GrBackendProcessorFactory& factory,
994 const GrProcessor&)
995 : INHERITED (factory) {
996 }
997
emitCode(GrGLProgramBuilder * builder,const GrFragmentProcessor &,const GrProcessorKey &,const char * outputColor,const char * inputColor,const TransformedCoordsArray &,const TextureSamplerArray & samplers)998 void GrGLRRectBlurEffect::emitCode(GrGLProgramBuilder* builder,
999 const GrFragmentProcessor&,
1000 const GrProcessorKey&,
1001 const char* outputColor,
1002 const char* inputColor,
1003 const TransformedCoordsArray&,
1004 const TextureSamplerArray& samplers) {
1005 const char *rectName;
1006 const char *cornerRadiusName;
1007 const char *blurRadiusName;
1008
1009 // The proxy rect has left, top, right, and bottom edges correspond to
1010 // components x, y, z, and w, respectively.
1011
1012 fProxyRectUniform = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
1013 kVec4f_GrSLType,
1014 "proxyRect",
1015 &rectName);
1016 fCornerRadiusUniform = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
1017 kFloat_GrSLType,
1018 "cornerRadius",
1019 &cornerRadiusName);
1020 fBlurRadiusUniform = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
1021 kFloat_GrSLType,
1022 "blurRadius",
1023 &blurRadiusName);
1024
1025 GrGLFragmentShaderBuilder* fsBuilder = builder->getFragmentShaderBuilder();
1026 const char* fragmentPos = fsBuilder->fragmentPosition();
1027
1028 // warp the fragment position to the appropriate part of the 9patch blur texture
1029
1030 fsBuilder->codeAppendf("\t\tvec2 rectCenter = (%s.xy + %s.zw)/2.0;\n", rectName, rectName);
1031 fsBuilder->codeAppendf("\t\tvec2 translatedFragPos = %s.xy - %s.xy;\n", fragmentPos, rectName);
1032 fsBuilder->codeAppendf("\t\tfloat threshold = %s + 2.0*%s;\n", cornerRadiusName, blurRadiusName );
1033 fsBuilder->codeAppendf("\t\tvec2 middle = %s.zw - %s.xy - 2.0*threshold;\n", rectName, rectName );
1034
1035 fsBuilder->codeAppendf("\t\tif (translatedFragPos.x >= threshold && translatedFragPos.x < (middle.x+threshold)) {\n" );
1036 fsBuilder->codeAppendf("\t\t\ttranslatedFragPos.x = threshold;\n");
1037 fsBuilder->codeAppendf("\t\t} else if (translatedFragPos.x >= (middle.x + threshold)) {\n");
1038 fsBuilder->codeAppendf("\t\t\ttranslatedFragPos.x -= middle.x - 1.0;\n");
1039 fsBuilder->codeAppendf("\t\t}\n");
1040
1041 fsBuilder->codeAppendf("\t\tif (translatedFragPos.y > threshold && translatedFragPos.y < (middle.y+threshold)) {\n" );
1042 fsBuilder->codeAppendf("\t\t\ttranslatedFragPos.y = threshold;\n");
1043 fsBuilder->codeAppendf("\t\t} else if (translatedFragPos.y >= (middle.y + threshold)) {\n");
1044 fsBuilder->codeAppendf("\t\t\ttranslatedFragPos.y -= middle.y - 1.0;\n");
1045 fsBuilder->codeAppendf("\t\t}\n");
1046
1047 fsBuilder->codeAppendf("\t\tvec2 proxyDims = vec2(2.0*threshold+1.0);\n");
1048 fsBuilder->codeAppendf("\t\tvec2 texCoord = translatedFragPos / proxyDims;\n");
1049
1050 fsBuilder->codeAppendf("\t%s = ", outputColor);
1051 fsBuilder->appendTextureLookupAndModulate(inputColor, samplers[0], "texCoord");
1052 fsBuilder->codeAppend(";\n");
1053 }
1054
setData(const GrGLProgramDataManager & pdman,const GrProcessor & proc)1055 void GrGLRRectBlurEffect::setData(const GrGLProgramDataManager& pdman,
1056 const GrProcessor& proc) {
1057 const GrRRectBlurEffect& brre = proc.cast<GrRRectBlurEffect>();
1058 SkRRect rrect = brre.getRRect();
1059
1060 float blurRadius = 3.f*SkScalarCeilToScalar(brre.getSigma()-1/6.0f);
1061 pdman.set1f(fBlurRadiusUniform, blurRadius);
1062
1063 SkRect rect = rrect.getBounds();
1064 rect.outset(blurRadius, blurRadius);
1065 pdman.set4f(fProxyRectUniform, rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
1066
1067 SkScalar radius = 0;
1068 SkASSERT(rrect.isSimpleCircular() || rrect.isRect());
1069 radius = rrect.getSimpleRadii().fX;
1070 pdman.set1f(fCornerRadiusUniform, radius);
1071 }
1072
1073
directFilterRRectMaskGPU(GrContext * context,GrPaint * grp,const SkStrokeRec & strokeRec,const SkRRect & rrect) const1074 bool SkBlurMaskFilterImpl::directFilterRRectMaskGPU(GrContext* context,
1075 GrPaint* grp,
1076 const SkStrokeRec& strokeRec,
1077 const SkRRect& rrect) const {
1078 if (fBlurStyle != kNormal_SkBlurStyle) {
1079 return false;
1080 }
1081
1082 if (!strokeRec.isFillStyle()) {
1083 return false;
1084 }
1085
1086 SkRect proxy_rect = rrect.rect();
1087 SkMatrix ctm = context->getMatrix();
1088 SkScalar xformedSigma = this->computeXformedSigma(ctm);
1089 float extra=3.f*SkScalarCeilToScalar(xformedSigma-1/6.0f);
1090 proxy_rect.outset(extra, extra);
1091
1092 SkAutoTUnref<GrFragmentProcessor> fp(GrRRectBlurEffect::Create(context, xformedSigma, rrect));
1093 if (!fp) {
1094 return false;
1095 }
1096
1097 GrContext::AutoMatrix am;
1098 if (!am.setIdentity(context, grp)) {
1099 return false;
1100 }
1101
1102 grp->addCoverageProcessor(fp);
1103
1104 context->drawRect(*grp, proxy_rect);
1105 return true;
1106 }
1107
canFilterMaskGPU(const SkRect & srcBounds,const SkIRect & clipBounds,const SkMatrix & ctm,SkRect * maskRect) const1108 bool SkBlurMaskFilterImpl::canFilterMaskGPU(const SkRect& srcBounds,
1109 const SkIRect& clipBounds,
1110 const SkMatrix& ctm,
1111 SkRect* maskRect) const {
1112 SkScalar xformedSigma = this->computeXformedSigma(ctm);
1113 if (xformedSigma <= 0) {
1114 return false;
1115 }
1116
1117 static const SkScalar kMIN_GPU_BLUR_SIZE = SkIntToScalar(64);
1118 static const SkScalar kMIN_GPU_BLUR_SIGMA = SkIntToScalar(32);
1119
1120 if (srcBounds.width() <= kMIN_GPU_BLUR_SIZE &&
1121 srcBounds.height() <= kMIN_GPU_BLUR_SIZE &&
1122 xformedSigma <= kMIN_GPU_BLUR_SIGMA) {
1123 // We prefer to blur small rect with small radius via CPU.
1124 return false;
1125 }
1126
1127 if (NULL == maskRect) {
1128 // don't need to compute maskRect
1129 return true;
1130 }
1131
1132 float sigma3 = 3 * SkScalarToFloat(xformedSigma);
1133
1134 SkRect clipRect = SkRect::Make(clipBounds);
1135 SkRect srcRect(srcBounds);
1136
1137 // Outset srcRect and clipRect by 3 * sigma, to compute affected blur area.
1138 srcRect.outset(sigma3, sigma3);
1139 clipRect.outset(sigma3, sigma3);
1140 srcRect.intersect(clipRect);
1141 *maskRect = srcRect;
1142 return true;
1143 }
1144
filterMaskGPU(GrTexture * src,const SkMatrix & ctm,const SkRect & maskRect,GrTexture ** result,bool canOverwriteSrc) const1145 bool SkBlurMaskFilterImpl::filterMaskGPU(GrTexture* src,
1146 const SkMatrix& ctm,
1147 const SkRect& maskRect,
1148 GrTexture** result,
1149 bool canOverwriteSrc) const {
1150 SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height());
1151
1152 GrContext* context = src->getContext();
1153
1154 GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
1155
1156 SkScalar xformedSigma = this->computeXformedSigma(ctm);
1157 SkASSERT(xformedSigma > 0);
1158
1159 // If we're doing a normal blur, we can clobber the pathTexture in the
1160 // gaussianBlur. Otherwise, we need to save it for later compositing.
1161 bool isNormalBlur = (kNormal_SkBlurStyle == fBlurStyle);
1162 *result = SkGpuBlurUtils::GaussianBlur(context, src, isNormalBlur && canOverwriteSrc,
1163 clipRect, false, xformedSigma, xformedSigma);
1164 if (NULL == *result) {
1165 return false;
1166 }
1167
1168 if (!isNormalBlur) {
1169 context->setIdentityMatrix();
1170 GrPaint paint;
1171 SkMatrix matrix;
1172 matrix.setIDiv(src->width(), src->height());
1173 // Blend pathTexture over blurTexture.
1174 GrContext::AutoRenderTarget art(context, (*result)->asRenderTarget());
1175 paint.addColorProcessor(GrSimpleTextureEffect::Create(src, matrix))->unref();
1176 if (kInner_SkBlurStyle == fBlurStyle) {
1177 // inner: dst = dst * src
1178 paint.setBlendFunc(kDC_GrBlendCoeff, kZero_GrBlendCoeff);
1179 } else if (kSolid_SkBlurStyle == fBlurStyle) {
1180 // solid: dst = src + dst - src * dst
1181 // = (1 - dst) * src + 1 * dst
1182 paint.setBlendFunc(kIDC_GrBlendCoeff, kOne_GrBlendCoeff);
1183 } else if (kOuter_SkBlurStyle == fBlurStyle) {
1184 // outer: dst = dst * (1 - src)
1185 // = 0 * src + (1 - src) * dst
1186 paint.setBlendFunc(kZero_GrBlendCoeff, kISC_GrBlendCoeff);
1187 }
1188 context->drawRect(paint, clipRect);
1189 }
1190
1191 return true;
1192 }
1193
1194 #endif // SK_SUPPORT_GPU
1195
1196
1197 #ifndef SK_IGNORE_TO_STRING
toString(SkString * str) const1198 void SkBlurMaskFilterImpl::toString(SkString* str) const {
1199 str->append("SkBlurMaskFilterImpl: (");
1200
1201 str->append("sigma: ");
1202 str->appendScalar(fSigma);
1203 str->append(" ");
1204
1205 static const char* gStyleName[kLastEnum_SkBlurStyle + 1] = {
1206 "normal", "solid", "outer", "inner"
1207 };
1208
1209 str->appendf("style: %s ", gStyleName[fBlurStyle]);
1210 str->append("flags: (");
1211 if (fBlurFlags) {
1212 bool needSeparator = false;
1213 SkAddFlagToString(str,
1214 SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag),
1215 "IgnoreXform", &needSeparator);
1216 SkAddFlagToString(str,
1217 SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag),
1218 "HighQuality", &needSeparator);
1219 } else {
1220 str->append("None");
1221 }
1222 str->append("))");
1223 }
1224 #endif
1225
1226 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkBlurMaskFilter)
1227 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkBlurMaskFilterImpl)
1228 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
1229