• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2006 The Android Open Source Project
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 "include/core/SkBitmap.h"
9 #include "include/core/SkMaskFilter.h"
10 #include "include/core/SkPathBuilder.h"
11 #include "include/core/SkRRect.h"
12 #include "include/core/SkStrokeRec.h"
13 #include "include/core/SkVertices.h"
14 #include "src/core/SkBlurMask.h"
15 #include "src/core/SkGpuBlurUtils.h"
16 #include "src/core/SkMaskFilterBase.h"
17 #include "src/core/SkMathPriv.h"
18 #include "src/core/SkMatrixProvider.h"
19 #include "src/core/SkRRectPriv.h"
20 #include "src/core/SkReadBuffer.h"
21 #include "src/core/SkStringUtils.h"
22 #include "src/core/SkWriteBuffer.h"
23 
24 #if SK_SUPPORT_GPU
25 #include "include/gpu/GrRecordingContext.h"
26 #include "src/gpu/GrFragmentProcessor.h"
27 #include "src/gpu/GrRecordingContextPriv.h"
28 #include "src/gpu/GrResourceProvider.h"
29 #include "src/gpu/GrShaderCaps.h"
30 #include "src/gpu/GrStyle.h"
31 #include "src/gpu/GrSurfaceDrawContext.h"
32 #include "src/gpu/GrTextureProxy.h"
33 #include "src/gpu/effects/GrTextureEffect.h"
34 #include "src/gpu/effects/generated/GrCircleBlurFragmentProcessor.h"
35 #include "src/gpu/effects/generated/GrRRectBlurEffect.h"
36 #include "src/gpu/effects/generated/GrRectBlurEffect.h"
37 #include "src/gpu/geometry/GrStyledShape.h"
38 #include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
39 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
40 #include "src/gpu/glsl/GrGLSLProgramDataManager.h"
41 #include "src/gpu/glsl/GrGLSLUniformHandler.h"
42 #endif
43 
44 class SkBlurMaskFilterImpl : public SkMaskFilterBase {
45 public:
46     SkBlurMaskFilterImpl(SkScalar sigma, SkBlurStyle, bool respectCTM);
47 
48     // overrides from SkMaskFilter
49     SkMask::Format getFormat() const override;
50     bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
51                     SkIPoint* margin) const override;
52 
53 #if SK_SUPPORT_GPU
54     bool canFilterMaskGPU(const GrStyledShape& shape,
55                           const SkIRect& devSpaceShapeBounds,
56                           const SkIRect& clipBounds,
57                           const SkMatrix& ctm,
58                           SkIRect* maskRect) const override;
59     bool directFilterMaskGPU(GrRecordingContext*,
60                              GrSurfaceDrawContext* surfaceDrawContext,
61                              GrPaint&&,
62                              const GrClip*,
63                              const SkMatrix& viewMatrix,
64                              const GrStyledShape& shape) const override;
65     GrSurfaceProxyView filterMaskGPU(GrRecordingContext*,
66                                      GrSurfaceProxyView srcView,
67                                      GrColorType srcColorType,
68                                      SkAlphaType srcAlphaType,
69                                      const SkMatrix& ctm,
70                                      const SkIRect& maskRect) const override;
71 #endif
72 
73     void computeFastBounds(const SkRect&, SkRect*) const override;
74     bool asABlur(BlurRec*) const override;
75 
76 
77 protected:
78     FilterReturn filterRectsToNine(const SkRect[], int count, const SkMatrix&,
79                                    const SkIRect& clipBounds,
80                                    NinePatch*) const override;
81 
82     FilterReturn filterRRectToNine(const SkRRect&, const SkMatrix&,
83                                    const SkIRect& clipBounds,
84                                    NinePatch*) const override;
85 
86     bool filterRectMask(SkMask* dstM, const SkRect& r, const SkMatrix& matrix,
87                         SkIPoint* margin, SkMask::CreateMode createMode) const;
88     bool filterRRectMask(SkMask* dstM, const SkRRect& r, const SkMatrix& matrix,
89                         SkIPoint* margin, SkMask::CreateMode createMode) const;
90 
ignoreXform() const91     bool ignoreXform() const { return !fRespectCTM; }
92 
93 private:
94     SK_FLATTENABLE_HOOKS(SkBlurMaskFilterImpl)
95     // To avoid unseemly allocation requests (esp. for finite platforms like
96     // handset) we limit the radius so something manageable. (as opposed to
97     // a request like 10,000)
98     static const SkScalar kMAX_BLUR_SIGMA;
99 
100     SkScalar    fSigma;
101     SkBlurStyle fBlurStyle;
102     bool        fRespectCTM;
103 
104     SkBlurMaskFilterImpl(SkReadBuffer&);
105     void flatten(SkWriteBuffer&) const override;
106 
computeXformedSigma(const SkMatrix & ctm) const107     SkScalar computeXformedSigma(const SkMatrix& ctm) const {
108         SkScalar xformedSigma = this->ignoreXform() ? fSigma : ctm.mapRadius(fSigma);
109         return std::min(xformedSigma, kMAX_BLUR_SIGMA);
110     }
111 
112     friend class SkBlurMaskFilter;
113 
114     using INHERITED = SkMaskFilter;
115     friend void sk_register_blur_maskfilter_createproc();
116 };
117 
118 const SkScalar SkBlurMaskFilterImpl::kMAX_BLUR_SIGMA = SkIntToScalar(128);
119 
120 ///////////////////////////////////////////////////////////////////////////////
121 
SkBlurMaskFilterImpl(SkScalar sigma,SkBlurStyle style,bool respectCTM)122 SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar sigma, SkBlurStyle style, bool respectCTM)
123     : fSigma(sigma)
124     , fBlurStyle(style)
125     , fRespectCTM(respectCTM) {
126     SkASSERT(fSigma > 0);
127     SkASSERT((unsigned)style <= kLastEnum_SkBlurStyle);
128 }
129 
getFormat() const130 SkMask::Format SkBlurMaskFilterImpl::getFormat() const {
131     return SkMask::kA8_Format;
132 }
133 
asABlur(BlurRec * rec) const134 bool SkBlurMaskFilterImpl::asABlur(BlurRec* rec) const {
135     if (this->ignoreXform()) {
136         return false;
137     }
138 
139     if (rec) {
140         rec->fSigma = fSigma;
141         rec->fStyle = fBlurStyle;
142     }
143     return true;
144 }
145 
filterMask(SkMask * dst,const SkMask & src,const SkMatrix & matrix,SkIPoint * margin) const146 bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
147                                       const SkMatrix& matrix,
148                                       SkIPoint* margin) const {
149     SkScalar sigma = this->computeXformedSigma(matrix);
150     return SkBlurMask::BoxBlur(dst, src, sigma, fBlurStyle, margin);
151 }
152 
filterRectMask(SkMask * dst,const SkRect & r,const SkMatrix & matrix,SkIPoint * margin,SkMask::CreateMode createMode) const153 bool SkBlurMaskFilterImpl::filterRectMask(SkMask* dst, const SkRect& r,
154                                           const SkMatrix& matrix,
155                                           SkIPoint* margin, SkMask::CreateMode createMode) const {
156     SkScalar sigma = computeXformedSigma(matrix);
157 
158     return SkBlurMask::BlurRect(sigma, dst, r, fBlurStyle, margin, createMode);
159 }
160 
filterRRectMask(SkMask * dst,const SkRRect & r,const SkMatrix & matrix,SkIPoint * margin,SkMask::CreateMode createMode) const161 bool SkBlurMaskFilterImpl::filterRRectMask(SkMask* dst, const SkRRect& r,
162                                           const SkMatrix& matrix,
163                                           SkIPoint* margin, SkMask::CreateMode createMode) const {
164     SkScalar sigma = computeXformedSigma(matrix);
165 
166     return SkBlurMask::BlurRRect(sigma, dst, r, fBlurStyle, margin, createMode);
167 }
168 
169 #include "include/core/SkCanvas.h"
170 
prepare_to_draw_into_mask(const SkRect & bounds,SkMask * mask)171 static bool prepare_to_draw_into_mask(const SkRect& bounds, SkMask* mask) {
172     SkASSERT(mask != nullptr);
173 
174     mask->fBounds = bounds.roundOut();
175     mask->fRowBytes = SkAlign4(mask->fBounds.width());
176     mask->fFormat = SkMask::kA8_Format;
177     const size_t size = mask->computeImageSize();
178     mask->fImage = SkMask::AllocImage(size, SkMask::kZeroInit_Alloc);
179     if (nullptr == mask->fImage) {
180         return false;
181     }
182     return true;
183 }
184 
draw_rrect_into_mask(const SkRRect rrect,SkMask * mask)185 static bool draw_rrect_into_mask(const SkRRect rrect, SkMask* mask) {
186     if (!prepare_to_draw_into_mask(rrect.rect(), mask)) {
187         return false;
188     }
189 
190     // FIXME: This code duplicates code in draw_rects_into_mask, below. Is there a
191     // clean way to share more code?
192     SkBitmap bitmap;
193     bitmap.installMaskPixels(*mask);
194 
195     SkCanvas canvas(bitmap);
196     canvas.translate(-SkIntToScalar(mask->fBounds.left()),
197                      -SkIntToScalar(mask->fBounds.top()));
198 
199     SkPaint paint;
200     paint.setAntiAlias(true);
201     canvas.drawRRect(rrect, paint);
202     return true;
203 }
204 
draw_rects_into_mask(const SkRect rects[],int count,SkMask * mask)205 static bool draw_rects_into_mask(const SkRect rects[], int count, SkMask* mask) {
206     if (!prepare_to_draw_into_mask(rects[0], mask)) {
207         return false;
208     }
209 
210     SkBitmap bitmap;
211     bitmap.installPixels(SkImageInfo::Make(mask->fBounds.width(),
212                                            mask->fBounds.height(),
213                                            kAlpha_8_SkColorType,
214                                            kPremul_SkAlphaType),
215                          mask->fImage, mask->fRowBytes);
216 
217     SkCanvas canvas(bitmap);
218     canvas.translate(-SkIntToScalar(mask->fBounds.left()),
219                      -SkIntToScalar(mask->fBounds.top()));
220 
221     SkPaint paint;
222     paint.setAntiAlias(true);
223 
224     if (1 == count) {
225         canvas.drawRect(rects[0], paint);
226     } else {
227         // todo: do I need a fast way to do this?
228         SkPath path = SkPathBuilder().addRect(rects[0])
229                                      .addRect(rects[1])
230                                      .setFillType(SkPathFillType::kEvenOdd)
231                                      .detach();
232         canvas.drawPath(path, paint);
233     }
234     return true;
235 }
236 
rect_exceeds(const SkRect & r,SkScalar v)237 static bool rect_exceeds(const SkRect& r, SkScalar v) {
238     return r.fLeft < -v || r.fTop < -v || r.fRight > v || r.fBottom > v ||
239            r.width() > v || r.height() > v;
240 }
241 
242 #include "src/core/SkMaskCache.h"
243 
copy_mask_to_cacheddata(SkMask * mask)244 static SkCachedData* copy_mask_to_cacheddata(SkMask* mask) {
245     const size_t size = mask->computeTotalImageSize();
246     SkCachedData* data = SkResourceCache::NewCachedData(size);
247     if (data) {
248         memcpy(data->writable_data(), mask->fImage, size);
249         SkMask::FreeImage(mask->fImage);
250         mask->fImage = (uint8_t*)data->data();
251     }
252     return data;
253 }
254 
find_cached_rrect(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRRect & rrect)255 static SkCachedData* find_cached_rrect(SkMask* mask, SkScalar sigma, SkBlurStyle style,
256                                        const SkRRect& rrect) {
257     return SkMaskCache::FindAndRef(sigma, style, rrect, mask);
258 }
259 
add_cached_rrect(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRRect & rrect)260 static SkCachedData* add_cached_rrect(SkMask* mask, SkScalar sigma, SkBlurStyle style,
261                                       const SkRRect& rrect) {
262     SkCachedData* cache = copy_mask_to_cacheddata(mask);
263     if (cache) {
264         SkMaskCache::Add(sigma, style, rrect, *mask, cache);
265     }
266     return cache;
267 }
268 
find_cached_rects(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRect rects[],int count)269 static SkCachedData* find_cached_rects(SkMask* mask, SkScalar sigma, SkBlurStyle style,
270                                        const SkRect rects[], int count) {
271     return SkMaskCache::FindAndRef(sigma, style, rects, count, mask);
272 }
273 
add_cached_rects(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRect rects[],int count)274 static SkCachedData* add_cached_rects(SkMask* mask, SkScalar sigma, SkBlurStyle style,
275                                       const SkRect rects[], int count) {
276     SkCachedData* cache = copy_mask_to_cacheddata(mask);
277     if (cache) {
278         SkMaskCache::Add(sigma, style, rects, count, *mask, cache);
279     }
280     return cache;
281 }
282 
283 static const bool c_analyticBlurRRect{true};
284 
285 SkMaskFilterBase::FilterReturn
filterRRectToNine(const SkRRect & rrect,const SkMatrix & matrix,const SkIRect & clipBounds,NinePatch * patch) const286 SkBlurMaskFilterImpl::filterRRectToNine(const SkRRect& rrect, const SkMatrix& matrix,
287                                         const SkIRect& clipBounds,
288                                         NinePatch* patch) const {
289     SkASSERT(patch != nullptr);
290     switch (rrect.getType()) {
291         case SkRRect::kEmpty_Type:
292             // Nothing to draw.
293             return kFalse_FilterReturn;
294 
295         case SkRRect::kRect_Type:
296             // We should have caught this earlier.
297             SkASSERT(false);
298             [[fallthrough]];
299         case SkRRect::kOval_Type:
300             // The nine patch special case does not handle ovals, and we
301             // already have code for rectangles.
302             return kUnimplemented_FilterReturn;
303 
304         // These three can take advantage of this fast path.
305         case SkRRect::kSimple_Type:
306         case SkRRect::kNinePatch_Type:
307         case SkRRect::kComplex_Type:
308             break;
309     }
310 
311     // TODO: report correct metrics for innerstyle, where we do not grow the
312     // total bounds, but we do need an inset the size of our blur-radius
313     if (kInner_SkBlurStyle == fBlurStyle) {
314         return kUnimplemented_FilterReturn;
315     }
316 
317     // TODO: take clipBounds into account to limit our coordinates up front
318     // for now, just skip too-large src rects (to take the old code path).
319     if (rect_exceeds(rrect.rect(), SkIntToScalar(32767))) {
320         return kUnimplemented_FilterReturn;
321     }
322 
323     SkIPoint margin;
324     SkMask  srcM, dstM;
325     srcM.fBounds = rrect.rect().roundOut();
326     srcM.fFormat = SkMask::kA8_Format;
327     srcM.fRowBytes = 0;
328 
329     bool filterResult = false;
330     if (c_analyticBlurRRect) {
331         // special case for fast round rect blur
332         // don't actually do the blur the first time, just compute the correct size
333         filterResult = this->filterRRectMask(&dstM, rrect, matrix, &margin,
334                                             SkMask::kJustComputeBounds_CreateMode);
335     }
336 
337     if (!filterResult) {
338         filterResult = this->filterMask(&dstM, srcM, matrix, &margin);
339     }
340 
341     if (!filterResult) {
342         return kFalse_FilterReturn;
343     }
344 
345     // Now figure out the appropriate width and height of the smaller round rectangle
346     // to stretch. It will take into account the larger radius per side as well as double
347     // the margin, to account for inner and outer blur.
348     const SkVector& UL = rrect.radii(SkRRect::kUpperLeft_Corner);
349     const SkVector& UR = rrect.radii(SkRRect::kUpperRight_Corner);
350     const SkVector& LR = rrect.radii(SkRRect::kLowerRight_Corner);
351     const SkVector& LL = rrect.radii(SkRRect::kLowerLeft_Corner);
352 
353     const SkScalar leftUnstretched = std::max(UL.fX, LL.fX) + SkIntToScalar(2 * margin.fX);
354     const SkScalar rightUnstretched = std::max(UR.fX, LR.fX) + SkIntToScalar(2 * margin.fX);
355 
356     // Extra space in the middle to ensure an unchanging piece for stretching. Use 3 to cover
357     // any fractional space on either side plus 1 for the part to stretch.
358     const SkScalar stretchSize = SkIntToScalar(3);
359 
360     const SkScalar totalSmallWidth = leftUnstretched + rightUnstretched + stretchSize;
361     if (totalSmallWidth >= rrect.rect().width()) {
362         // There is no valid piece to stretch.
363         return kUnimplemented_FilterReturn;
364     }
365 
366     const SkScalar topUnstretched = std::max(UL.fY, UR.fY) + SkIntToScalar(2 * margin.fY);
367     const SkScalar bottomUnstretched = std::max(LL.fY, LR.fY) + SkIntToScalar(2 * margin.fY);
368 
369     const SkScalar totalSmallHeight = topUnstretched + bottomUnstretched + stretchSize;
370     if (totalSmallHeight >= rrect.rect().height()) {
371         // There is no valid piece to stretch.
372         return kUnimplemented_FilterReturn;
373     }
374 
375     SkRect smallR = SkRect::MakeWH(totalSmallWidth, totalSmallHeight);
376 
377     SkRRect smallRR;
378     SkVector radii[4];
379     radii[SkRRect::kUpperLeft_Corner] = UL;
380     radii[SkRRect::kUpperRight_Corner] = UR;
381     radii[SkRRect::kLowerRight_Corner] = LR;
382     radii[SkRRect::kLowerLeft_Corner] = LL;
383     smallRR.setRectRadii(smallR, radii);
384 
385     const SkScalar sigma = this->computeXformedSigma(matrix);
386     SkCachedData* cache = find_cached_rrect(&patch->fMask, sigma, fBlurStyle, smallRR);
387     if (!cache) {
388         bool analyticBlurWorked = false;
389         if (c_analyticBlurRRect) {
390             analyticBlurWorked =
391                 this->filterRRectMask(&patch->fMask, smallRR, matrix, &margin,
392                                       SkMask::kComputeBoundsAndRenderImage_CreateMode);
393         }
394 
395         if (!analyticBlurWorked) {
396             if (!draw_rrect_into_mask(smallRR, &srcM)) {
397                 return kFalse_FilterReturn;
398             }
399 
400             SkAutoMaskFreeImage amf(srcM.fImage);
401 
402             if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
403                 return kFalse_FilterReturn;
404             }
405         }
406         cache = add_cached_rrect(&patch->fMask, sigma, fBlurStyle, smallRR);
407     }
408 
409     patch->fMask.fBounds.offsetTo(0, 0);
410     patch->fOuterRect = dstM.fBounds;
411     patch->fCenter.fX = SkScalarCeilToInt(leftUnstretched) + 1;
412     patch->fCenter.fY = SkScalarCeilToInt(topUnstretched) + 1;
413     SkASSERT(nullptr == patch->fCache);
414     patch->fCache = cache;  // transfer ownership to patch
415     return kTrue_FilterReturn;
416 }
417 
418 // Use the faster analytic blur approach for ninepatch rects
419 static const bool c_analyticBlurNinepatch{true};
420 
421 SkMaskFilterBase::FilterReturn
filterRectsToNine(const SkRect rects[],int count,const SkMatrix & matrix,const SkIRect & clipBounds,NinePatch * patch) const422 SkBlurMaskFilterImpl::filterRectsToNine(const SkRect rects[], int count,
423                                         const SkMatrix& matrix,
424                                         const SkIRect& clipBounds,
425                                         NinePatch* patch) const {
426     if (count < 1 || count > 2) {
427         return kUnimplemented_FilterReturn;
428     }
429 
430     // TODO: report correct metrics for innerstyle, where we do not grow the
431     // total bounds, but we do need an inset the size of our blur-radius
432     if (kInner_SkBlurStyle == fBlurStyle || kOuter_SkBlurStyle == fBlurStyle) {
433         return kUnimplemented_FilterReturn;
434     }
435 
436     // TODO: take clipBounds into account to limit our coordinates up front
437     // for now, just skip too-large src rects (to take the old code path).
438     if (rect_exceeds(rects[0], SkIntToScalar(32767))) {
439         return kUnimplemented_FilterReturn;
440     }
441 
442     SkIPoint margin;
443     SkMask  srcM, dstM;
444     srcM.fBounds = rects[0].roundOut();
445     srcM.fFormat = SkMask::kA8_Format;
446     srcM.fRowBytes = 0;
447 
448     bool filterResult = false;
449     if (count == 1 && c_analyticBlurNinepatch) {
450         // special case for fast rect blur
451         // don't actually do the blur the first time, just compute the correct size
452         filterResult = this->filterRectMask(&dstM, rects[0], matrix, &margin,
453                                             SkMask::kJustComputeBounds_CreateMode);
454     } else {
455         filterResult = this->filterMask(&dstM, srcM, matrix, &margin);
456     }
457 
458     if (!filterResult) {
459         return kFalse_FilterReturn;
460     }
461 
462     /*
463      *  smallR is the smallest version of 'rect' that will still guarantee that
464      *  we get the same blur results on all edges, plus 1 center row/col that is
465      *  representative of the extendible/stretchable edges of the ninepatch.
466      *  Since our actual edge may be fractional we inset 1 more to be sure we
467      *  don't miss any interior blur.
468      *  x is an added pixel of blur, and { and } are the (fractional) edge
469      *  pixels from the original rect.
470      *
471      *   x x { x x .... x x } x x
472      *
473      *  Thus, in this case, we inset by a total of 5 (on each side) beginning
474      *  with our outer-rect (dstM.fBounds)
475      */
476     SkRect smallR[2];
477     SkIPoint center;
478 
479     // +2 is from +1 for each edge (to account for possible fractional edges
480     int smallW = dstM.fBounds.width() - srcM.fBounds.width() + 2;
481     int smallH = dstM.fBounds.height() - srcM.fBounds.height() + 2;
482     SkIRect innerIR;
483 
484     if (1 == count) {
485         innerIR = srcM.fBounds;
486         center.set(smallW, smallH);
487     } else {
488         SkASSERT(2 == count);
489         rects[1].roundIn(&innerIR);
490         center.set(smallW + (innerIR.left() - srcM.fBounds.left()),
491                    smallH + (innerIR.top() - srcM.fBounds.top()));
492     }
493 
494     // +1 so we get a clean, stretchable, center row/col
495     smallW += 1;
496     smallH += 1;
497 
498     // we want the inset amounts to be integral, so we don't change any
499     // fractional phase on the fRight or fBottom of our smallR.
500     const SkScalar dx = SkIntToScalar(innerIR.width() - smallW);
501     const SkScalar dy = SkIntToScalar(innerIR.height() - smallH);
502     if (dx < 0 || dy < 0) {
503         // we're too small, relative to our blur, to break into nine-patch,
504         // so we ask to have our normal filterMask() be called.
505         return kUnimplemented_FilterReturn;
506     }
507 
508     smallR[0].setLTRB(rects[0].left(),       rects[0].top(),
509                       rects[0].right() - dx, rects[0].bottom() - dy);
510     if (smallR[0].width() < 2 || smallR[0].height() < 2) {
511         return kUnimplemented_FilterReturn;
512     }
513     if (2 == count) {
514         smallR[1].setLTRB(rects[1].left(), rects[1].top(),
515                           rects[1].right() - dx, rects[1].bottom() - dy);
516         SkASSERT(!smallR[1].isEmpty());
517     }
518 
519     const SkScalar sigma = this->computeXformedSigma(matrix);
520     SkCachedData* cache = find_cached_rects(&patch->fMask, sigma, fBlurStyle, smallR, count);
521     if (!cache) {
522         if (count > 1 || !c_analyticBlurNinepatch) {
523             if (!draw_rects_into_mask(smallR, count, &srcM)) {
524                 return kFalse_FilterReturn;
525             }
526 
527             SkAutoMaskFreeImage amf(srcM.fImage);
528 
529             if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
530                 return kFalse_FilterReturn;
531             }
532         } else {
533             if (!this->filterRectMask(&patch->fMask, smallR[0], matrix, &margin,
534                                       SkMask::kComputeBoundsAndRenderImage_CreateMode)) {
535                 return kFalse_FilterReturn;
536             }
537         }
538         cache = add_cached_rects(&patch->fMask, sigma, fBlurStyle, smallR, count);
539     }
540     patch->fMask.fBounds.offsetTo(0, 0);
541     patch->fOuterRect = dstM.fBounds;
542     patch->fCenter = center;
543     SkASSERT(nullptr == patch->fCache);
544     patch->fCache = cache;  // transfer ownership to patch
545     return kTrue_FilterReturn;
546 }
547 
computeFastBounds(const SkRect & src,SkRect * dst) const548 void SkBlurMaskFilterImpl::computeFastBounds(const SkRect& src,
549                                              SkRect* dst) const {
550     SkScalar pad = 3.0f * fSigma;
551 
552     dst->setLTRB(src.fLeft  - pad, src.fTop    - pad,
553                  src.fRight + pad, src.fBottom + pad);
554 }
555 
CreateProc(SkReadBuffer & buffer)556 sk_sp<SkFlattenable> SkBlurMaskFilterImpl::CreateProc(SkReadBuffer& buffer) {
557     const SkScalar sigma = buffer.readScalar();
558     SkBlurStyle style = buffer.read32LE(kLastEnum_SkBlurStyle);
559 
560     uint32_t flags = buffer.read32LE(0x3);  // historically we only recorded 2 bits
561     bool respectCTM = !(flags & 1); // historically we stored ignoreCTM in low bit
562 
563     return SkMaskFilter::MakeBlur((SkBlurStyle)style, sigma, respectCTM);
564 }
565 
flatten(SkWriteBuffer & buffer) const566 void SkBlurMaskFilterImpl::flatten(SkWriteBuffer& buffer) const {
567     buffer.writeScalar(fSigma);
568     buffer.writeUInt(fBlurStyle);
569     buffer.writeUInt(!fRespectCTM); // historically we recorded ignoreCTM
570 }
571 
572 
573 #if SK_SUPPORT_GPU
574 
directFilterMaskGPU(GrRecordingContext * context,GrSurfaceDrawContext * surfaceDrawContext,GrPaint && paint,const GrClip * clip,const SkMatrix & viewMatrix,const GrStyledShape & shape) const575 bool SkBlurMaskFilterImpl::directFilterMaskGPU(GrRecordingContext* context,
576                                                GrSurfaceDrawContext* surfaceDrawContext,
577                                                GrPaint&& paint,
578                                                const GrClip* clip,
579                                                const SkMatrix& viewMatrix,
580                                                const GrStyledShape& shape) const {
581     SkASSERT(surfaceDrawContext);
582 
583     if (fBlurStyle != kNormal_SkBlurStyle) {
584         return false;
585     }
586 
587     // TODO: we could handle blurred stroked circles
588     if (!shape.style().isSimpleFill()) {
589         return false;
590     }
591 
592     SkScalar xformedSigma = this->computeXformedSigma(viewMatrix);
593     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma)) {
594         surfaceDrawContext->drawShape(clip, std::move(paint), GrAA::kYes, viewMatrix,
595                                       GrStyledShape(shape));
596         return true;
597     }
598 
599     SkRRect srcRRect;
600     bool inverted;
601     if (!shape.asRRect(&srcRRect, nullptr, nullptr, &inverted) || inverted) {
602         return false;
603     }
604 
605     std::unique_ptr<GrFragmentProcessor> fp;
606 
607     SkRRect devRRect;
608     bool devRRectIsValid = srcRRect.transform(viewMatrix, &devRRect);
609 
610     bool devRRectIsCircle = devRRectIsValid && SkRRectPriv::IsCircle(devRRect);
611 
612     bool canBeRect = srcRRect.isRect() && viewMatrix.preservesRightAngles();
613     bool canBeCircle = (SkRRectPriv::IsCircle(srcRRect) && viewMatrix.isSimilarity()) ||
614                        devRRectIsCircle;
615 
616     if (canBeRect || canBeCircle) {
617         if (canBeRect) {
618             fp = GrRectBlurEffect::Make(
619                     /*inputFP=*/nullptr, context, *context->priv().caps()->shaderCaps(),
620                     srcRRect.rect(), viewMatrix, xformedSigma);
621         } else {
622             SkRect devBounds;
623             if (devRRectIsCircle) {
624                 devBounds = devRRect.getBounds();
625             } else {
626                 SkPoint center = {srcRRect.getBounds().centerX(), srcRRect.getBounds().centerY()};
627                 viewMatrix.mapPoints(&center, 1);
628                 SkScalar radius = viewMatrix.mapVector(0, srcRRect.width()/2.f).length();
629                 devBounds = {center.x() - radius,
630                              center.y() - radius,
631                              center.x() + radius,
632                              center.y() + radius};
633             }
634             fp = GrCircleBlurFragmentProcessor::Make(/*inputFP=*/nullptr, context, devBounds,
635                                                      xformedSigma);
636         }
637 
638         if (!fp) {
639             return false;
640         }
641         paint.setCoverageFragmentProcessor(std::move(fp));
642 
643         SkRect srcProxyRect = srcRRect.rect();
644         // Determine how much to outset the src rect to ensure we hit pixels within three sigma.
645         SkScalar outsetX = 3.0f*xformedSigma;
646         SkScalar outsetY = 3.0f*xformedSigma;
647         if (viewMatrix.isScaleTranslate()) {
648             outsetX /= SkScalarAbs(viewMatrix.getScaleX());
649             outsetY /= SkScalarAbs(viewMatrix.getScaleY());
650         } else {
651             SkSize scale;
652             if (!viewMatrix.decomposeScale(&scale, nullptr)) {
653                 return false;
654             }
655             outsetX /= scale.width();
656             outsetY /= scale.height();
657         }
658         srcProxyRect.outset(outsetX, outsetY);
659 
660         surfaceDrawContext->drawRect(clip, std::move(paint), GrAA::kNo, viewMatrix, srcProxyRect);
661         return true;
662     }
663     if (!viewMatrix.isScaleTranslate()) {
664         return false;
665     }
666     if (!devRRectIsValid || !SkRRectPriv::AllCornersCircular(devRRect)) {
667         return false;
668     }
669 
670     fp = GrRRectBlurEffect::Make(/*inputFP=*/nullptr, context, fSigma, xformedSigma,
671                                  srcRRect, devRRect);
672     if (!fp) {
673         return false;
674     }
675 
676     if (!this->ignoreXform()) {
677         SkRect srcProxyRect = srcRRect.rect();
678         srcProxyRect.outset(3.0f*fSigma, 3.0f*fSigma);
679         paint.setCoverageFragmentProcessor(std::move(fp));
680         surfaceDrawContext->drawRect(clip, std::move(paint), GrAA::kNo, viewMatrix, srcProxyRect);
681     } else {
682         SkMatrix inverse;
683         if (!viewMatrix.invert(&inverse)) {
684             return false;
685         }
686 
687         SkIRect proxyBounds;
688         float extra=3.f*SkScalarCeilToScalar(xformedSigma-1/6.0f);
689         devRRect.rect().makeOutset(extra, extra).roundOut(&proxyBounds);
690 
691         paint.setCoverageFragmentProcessor(std::move(fp));
692         surfaceDrawContext->fillPixelsWithLocalMatrix(clip, std::move(paint), proxyBounds, inverse);
693     }
694 
695     return true;
696 }
697 
canFilterMaskGPU(const GrStyledShape & shape,const SkIRect & devSpaceShapeBounds,const SkIRect & clipBounds,const SkMatrix & ctm,SkIRect * maskRect) const698 bool SkBlurMaskFilterImpl::canFilterMaskGPU(const GrStyledShape& shape,
699                                             const SkIRect& devSpaceShapeBounds,
700                                             const SkIRect& clipBounds,
701                                             const SkMatrix& ctm,
702                                             SkIRect* maskRect) const {
703     SkScalar xformedSigma = this->computeXformedSigma(ctm);
704     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma)) {
705         *maskRect = devSpaceShapeBounds;
706         return maskRect->intersect(clipBounds);
707     }
708 
709     if (maskRect) {
710         float sigma3 = 3 * SkScalarToFloat(xformedSigma);
711 
712         // Outset srcRect and clipRect by 3 * sigma, to compute affected blur area.
713         SkIRect clipRect = clipBounds.makeOutset(sigma3, sigma3);
714         SkIRect srcRect = devSpaceShapeBounds.makeOutset(sigma3, sigma3);
715 
716         if (!srcRect.intersect(clipRect)) {
717             srcRect.setEmpty();
718         }
719         *maskRect = srcRect;
720     }
721 
722     // We prefer to blur paths with small blur radii on the CPU.
723     static const SkScalar kMIN_GPU_BLUR_SIZE  = SkIntToScalar(64);
724     static const SkScalar kMIN_GPU_BLUR_SIGMA = SkIntToScalar(32);
725 
726     if (devSpaceShapeBounds.width() <= kMIN_GPU_BLUR_SIZE &&
727         devSpaceShapeBounds.height() <= kMIN_GPU_BLUR_SIZE &&
728         xformedSigma <= kMIN_GPU_BLUR_SIGMA) {
729         return false;
730     }
731 
732     return true;
733 }
734 
filterMaskGPU(GrRecordingContext * context,GrSurfaceProxyView srcView,GrColorType srcColorType,SkAlphaType srcAlphaType,const SkMatrix & ctm,const SkIRect & maskRect) const735 GrSurfaceProxyView SkBlurMaskFilterImpl::filterMaskGPU(GrRecordingContext* context,
736                                                        GrSurfaceProxyView srcView,
737                                                        GrColorType srcColorType,
738                                                        SkAlphaType srcAlphaType,
739                                                        const SkMatrix& ctm,
740                                                        const SkIRect& maskRect) const {
741     // 'maskRect' isn't snapped to the UL corner but the mask in 'src' is.
742     const SkIRect clipRect = SkIRect::MakeWH(maskRect.width(), maskRect.height());
743 
744     SkScalar xformedSigma = this->computeXformedSigma(ctm);
745 
746     // If we're doing a normal blur, we can clobber the pathTexture in the
747     // gaussianBlur.  Otherwise, we need to save it for later compositing.
748     bool isNormalBlur = (kNormal_SkBlurStyle == fBlurStyle);
749     auto srcBounds = SkIRect::MakeSize(srcView.proxy()->dimensions());
750     auto surfaceDrawContext = SkGpuBlurUtils::GaussianBlur(context,
751                                                             srcView,
752                                                             srcColorType,
753                                                             srcAlphaType,
754                                                             nullptr,
755                                                             clipRect,
756                                                             srcBounds,
757                                                             xformedSigma,
758                                                             xformedSigma,
759                                                             SkTileMode::kClamp);
760     if (!surfaceDrawContext || !surfaceDrawContext->asTextureProxy()) {
761         return {};
762     }
763 
764     if (!isNormalBlur) {
765         GrPaint paint;
766         // Blend pathTexture over blurTexture.
767         paint.setCoverageFragmentProcessor(GrTextureEffect::Make(std::move(srcView), srcAlphaType));
768         if (kInner_SkBlurStyle == fBlurStyle) {
769             // inner:  dst = dst * src
770             paint.setCoverageSetOpXPFactory(SkRegion::kIntersect_Op);
771         } else if (kSolid_SkBlurStyle == fBlurStyle) {
772             // solid:  dst = src + dst - src * dst
773             //             = src + (1 - src) * dst
774             paint.setCoverageSetOpXPFactory(SkRegion::kUnion_Op);
775         } else if (kOuter_SkBlurStyle == fBlurStyle) {
776             // outer:  dst = dst * (1 - src)
777             //             = 0 * src + (1 - src) * dst
778             paint.setCoverageSetOpXPFactory(SkRegion::kDifference_Op);
779         } else {
780             paint.setCoverageSetOpXPFactory(SkRegion::kReplace_Op);
781         }
782 
783         surfaceDrawContext->fillPixelsWithLocalMatrix(nullptr, std::move(paint), clipRect,
784                                                       SkMatrix::I());
785     }
786 
787     return surfaceDrawContext->readSurfaceView();
788 }
789 
790 #endif // SK_SUPPORT_GPU
791 
sk_register_blur_maskfilter_createproc()792 void sk_register_blur_maskfilter_createproc() { SK_REGISTER_FLATTENABLE(SkBlurMaskFilterImpl); }
793 
MakeBlur(SkBlurStyle style,SkScalar sigma,bool respectCTM)794 sk_sp<SkMaskFilter> SkMaskFilter::MakeBlur(SkBlurStyle style, SkScalar sigma, bool respectCTM) {
795     if (SkScalarIsFinite(sigma) && sigma > 0) {
796         return sk_sp<SkMaskFilter>(new SkBlurMaskFilterImpl(sigma, style, respectCTM));
797     }
798     return nullptr;
799 }
800