• 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/SkSDFFilter.h"
23 #include "src/core/SkWriteBuffer.h"
24 
25 #if SK_SUPPORT_GPU
26 #include "include/gpu/GrRecordingContext.h"
27 #include "src/core/SkRuntimeEffectPriv.h"
28 #include "src/gpu/GrFragmentProcessor.h"
29 #include "src/gpu/GrRecordingContextPriv.h"
30 #include "src/gpu/GrResourceProvider.h"
31 #include "src/gpu/GrShaderCaps.h"
32 #include "src/gpu/GrStyle.h"
33 #include "src/gpu/GrTextureProxy.h"
34 #include "src/gpu/GrThreadSafeCache.h"
35 #include "src/gpu/SkGr.h"
36 #include "src/gpu/effects/GrMatrixEffect.h"
37 #include "src/gpu/effects/GrSkSLFP.h"
38 #include "src/gpu/effects/GrTextureEffect.h"
39 #include "src/gpu/geometry/GrStyledShape.h"
40 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
41 #include "src/gpu/glsl/GrGLSLProgramDataManager.h"
42 #include "src/gpu/glsl/GrGLSLUniformHandler.h"
43 #if SK_GPU_V1
44 #include "src/gpu/v1/SurfaceDrawContext_v1.h"
45 #endif // SK_GPU_V1
46 #endif // SK_SUPPORT_GPU
47 
48 class SkBlurMaskFilterImpl : public SkMaskFilterBase {
49 public:
50     SkBlurMaskFilterImpl(SkScalar sigma, SkBlurStyle, bool respectCTM);
51 
52     // overrides from SkMaskFilter
53     SkMask::Format getFormat() const override;
54     bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
55                     SkIPoint* margin) const override;
56 
57 #if SK_SUPPORT_GPU && SK_GPU_V1
58     bool canFilterMaskGPU(const GrStyledShape& shape,
59                           const SkIRect& devSpaceShapeBounds,
60                           const SkIRect& clipBounds,
61                           const SkMatrix& ctm,
62                           SkIRect* maskRect,
63                           const bool canUseSDFBlur = false) const override;
64     bool directFilterMaskGPU(GrRecordingContext*,
65                              skgpu::v1::SurfaceDrawContext*,
66                              GrPaint&&,
67                              const GrClip*,
68                              const SkMatrix& viewMatrix,
69                              const GrStyledShape&) const override;
70     GrSurfaceProxyView filterMaskGPU(GrRecordingContext*,
71                                      GrSurfaceProxyView srcView,
72                                      GrColorType srcColorType,
73                                      SkAlphaType srcAlphaType,
74                                      const SkMatrix& ctm,
75                                      const SkIRect& maskRect) const override;
76 
77     float getNoxFormedSigma3() const override;
78 
79     GrSurfaceProxyView filterMaskGPUNoxFormed(GrRecordingContext*, GrSurfaceProxyView srcView,
80         GrColorType srcColorType, SkAlphaType srcAlphaType, const SkMatrix& viewMatrix, const SkIRect& maskRect,
81         const SkRRect& srcRRect) const override;
82 #endif
83 
84     void computeFastBounds(const SkRect&, SkRect*) const override;
85     bool asABlur(BlurRec*) const override;
86 
87 
88 protected:
89     FilterReturn filterRectsToNine(const SkRect[], int count, const SkMatrix&,
90                                    const SkIRect& clipBounds,
91                                    NinePatch*) const override;
92 
93     FilterReturn filterRRectToNine(const SkRRect&, const SkMatrix&,
94                                    const SkIRect& clipBounds,
95                                    NinePatch*) const override;
96 
97     bool filterRectMask(SkMask* dstM, const SkRect& r, const SkMatrix& matrix,
98                         SkIPoint* margin, SkMask::CreateMode createMode) const;
99     bool filterRRectMask(SkMask* dstM, const SkRRect& r, const SkMatrix& matrix,
100                         SkIPoint* margin, SkMask::CreateMode createMode) const;
101 
ignoreXform() const102     bool ignoreXform() const { return !fRespectCTM; }
103 
104 private:
105     SK_FLATTENABLE_HOOKS(SkBlurMaskFilterImpl)
106     // To avoid unseemly allocation requests (esp. for finite platforms like
107     // handset) we limit the radius so something manageable. (as opposed to
108     // a request like 10,000)
109     static const SkScalar kMAX_BLUR_SIGMA;
110 
111     SkScalar    fSigma;
112     SkBlurStyle fBlurStyle;
113     bool        fRespectCTM;
114 
115     SkBlurMaskFilterImpl(SkReadBuffer&);
116     void flatten(SkWriteBuffer&) const override;
117 
computeXformedSigma(const SkMatrix & ctm) const118     SkScalar computeXformedSigma(const SkMatrix& ctm) const {
119         SkScalar xformedSigma = this->ignoreXform() ? fSigma : ctm.mapRadius(fSigma);
120         return std::min(xformedSigma, kMAX_BLUR_SIGMA);
121     }
122 
123     friend class SkBlurMaskFilter;
124 
125     using INHERITED = SkMaskFilter;
126     friend void sk_register_blur_maskfilter_createproc();
127 };
128 
129 const SkScalar SkBlurMaskFilterImpl::kMAX_BLUR_SIGMA = SkIntToScalar(128);
130 
131 ///////////////////////////////////////////////////////////////////////////////
132 
SkBlurMaskFilterImpl(SkScalar sigma,SkBlurStyle style,bool respectCTM)133 SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar sigma, SkBlurStyle style, bool respectCTM)
134     : fSigma(sigma)
135     , fBlurStyle(style)
136     , fRespectCTM(respectCTM) {
137     SkASSERT(fSigma > 0);
138     SkASSERT((unsigned)style <= kLastEnum_SkBlurStyle);
139 }
140 
getFormat() const141 SkMask::Format SkBlurMaskFilterImpl::getFormat() const {
142     return SkMask::kA8_Format;
143 }
144 
asABlur(BlurRec * rec) const145 bool SkBlurMaskFilterImpl::asABlur(BlurRec* rec) const {
146     if (this->ignoreXform()) {
147         return false;
148     }
149 
150     if (rec) {
151         rec->fSigma = fSigma;
152         rec->fStyle = fBlurStyle;
153     }
154     return true;
155 }
156 
filterMask(SkMask * dst,const SkMask & src,const SkMatrix & matrix,SkIPoint * margin) const157 bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
158                                       const SkMatrix& matrix,
159                                       SkIPoint* margin) const {
160     SkScalar sigma = this->computeXformedSigma(matrix);
161     return SkBlurMask::BoxBlur(dst, src, sigma, fBlurStyle, margin);
162 }
163 
filterRectMask(SkMask * dst,const SkRect & r,const SkMatrix & matrix,SkIPoint * margin,SkMask::CreateMode createMode) const164 bool SkBlurMaskFilterImpl::filterRectMask(SkMask* dst, const SkRect& r,
165                                           const SkMatrix& matrix,
166                                           SkIPoint* margin, SkMask::CreateMode createMode) const {
167     SkScalar sigma = computeXformedSigma(matrix);
168 
169     return SkBlurMask::BlurRect(sigma, dst, r, fBlurStyle, margin, createMode);
170 }
171 
filterRRectMask(SkMask * dst,const SkRRect & r,const SkMatrix & matrix,SkIPoint * margin,SkMask::CreateMode createMode) const172 bool SkBlurMaskFilterImpl::filterRRectMask(SkMask* dst, const SkRRect& r,
173                                           const SkMatrix& matrix,
174                                           SkIPoint* margin, SkMask::CreateMode createMode) const {
175     SkScalar sigma = computeXformedSigma(matrix);
176 
177     return SkBlurMask::BlurRRect(sigma, dst, r, fBlurStyle, margin, createMode);
178 }
179 
180 #include "include/core/SkCanvas.h"
181 
prepare_to_draw_into_mask(const SkRect & bounds,SkMask * mask)182 static bool prepare_to_draw_into_mask(const SkRect& bounds, SkMask* mask) {
183     SkASSERT(mask != nullptr);
184 
185     mask->fBounds = bounds.roundOut();
186     mask->fRowBytes = SkAlign4(mask->fBounds.width());
187     mask->fFormat = SkMask::kA8_Format;
188     const size_t size = mask->computeImageSize();
189     if (size == 0) {
190         return false;
191     }
192     mask->fImage = SkMask::AllocImage(size, SkMask::kZeroInit_Alloc);
193     if (nullptr == mask->fImage) {
194         return false;
195     }
196     return true;
197 }
198 
draw_rrect_into_mask(const SkRRect rrect,SkMask * mask)199 static bool draw_rrect_into_mask(const SkRRect rrect, SkMask* mask) {
200     if (!prepare_to_draw_into_mask(rrect.rect(), mask)) {
201         return false;
202     }
203 
204     // FIXME: This code duplicates code in draw_rects_into_mask, below. Is there a
205     // clean way to share more code?
206     SkBitmap bitmap;
207     bitmap.installMaskPixels(*mask);
208 
209     SkCanvas canvas(bitmap);
210     canvas.translate(-SkIntToScalar(mask->fBounds.left()),
211                      -SkIntToScalar(mask->fBounds.top()));
212 
213     SkPaint paint;
214     paint.setAntiAlias(true);
215     canvas.drawRRect(rrect, paint);
216     return true;
217 }
218 
draw_rects_into_mask(const SkRect rects[],int count,SkMask * mask)219 static bool draw_rects_into_mask(const SkRect rects[], int count, SkMask* mask) {
220     if (!prepare_to_draw_into_mask(rects[0], mask)) {
221         return false;
222     }
223 
224     SkBitmap bitmap;
225     bitmap.installPixels(SkImageInfo::Make(mask->fBounds.width(),
226                                            mask->fBounds.height(),
227                                            kAlpha_8_SkColorType,
228                                            kPremul_SkAlphaType),
229                          mask->fImage, mask->fRowBytes);
230 
231     SkCanvas canvas(bitmap);
232     canvas.translate(-SkIntToScalar(mask->fBounds.left()),
233                      -SkIntToScalar(mask->fBounds.top()));
234 
235     SkPaint paint;
236     paint.setAntiAlias(true);
237 
238     if (1 == count) {
239         canvas.drawRect(rects[0], paint);
240     } else {
241         // todo: do I need a fast way to do this?
242         SkPath path = SkPathBuilder().addRect(rects[0])
243                                      .addRect(rects[1])
244                                      .setFillType(SkPathFillType::kEvenOdd)
245                                      .detach();
246         canvas.drawPath(path, paint);
247     }
248     return true;
249 }
250 
rect_exceeds(const SkRect & r,SkScalar v)251 static bool rect_exceeds(const SkRect& r, SkScalar v) {
252     return r.fLeft < -v || r.fTop < -v || r.fRight > v || r.fBottom > v ||
253            r.width() > v || r.height() > v;
254 }
255 
256 #include "src/core/SkMaskCache.h"
257 
copy_mask_to_cacheddata(SkMask * mask)258 static SkCachedData* copy_mask_to_cacheddata(SkMask* mask) {
259     const size_t size = mask->computeTotalImageSize();
260     SkCachedData* data = SkResourceCache::NewCachedData(size);
261     if (data) {
262         memcpy(data->writable_data(), mask->fImage, size);
263         SkMask::FreeImage(mask->fImage);
264         mask->fImage = (uint8_t*)data->data();
265     }
266     return data;
267 }
268 
find_cached_rrect(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRRect & rrect)269 static SkCachedData* find_cached_rrect(SkMask* mask, SkScalar sigma, SkBlurStyle style,
270                                        const SkRRect& rrect) {
271     return SkMaskCache::FindAndRef(sigma, style, rrect, mask);
272 }
273 
add_cached_rrect(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRRect & rrect)274 static SkCachedData* add_cached_rrect(SkMask* mask, SkScalar sigma, SkBlurStyle style,
275                                       const SkRRect& rrect) {
276     SkCachedData* cache = copy_mask_to_cacheddata(mask);
277     if (cache) {
278         SkMaskCache::Add(sigma, style, rrect, *mask, cache);
279     }
280     return cache;
281 }
282 
find_cached_rects(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRect rects[],int count)283 static SkCachedData* find_cached_rects(SkMask* mask, SkScalar sigma, SkBlurStyle style,
284                                        const SkRect rects[], int count) {
285     return SkMaskCache::FindAndRef(sigma, style, rects, count, mask);
286 }
287 
add_cached_rects(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRect rects[],int count)288 static SkCachedData* add_cached_rects(SkMask* mask, SkScalar sigma, SkBlurStyle style,
289                                       const SkRect rects[], int count) {
290     SkCachedData* cache = copy_mask_to_cacheddata(mask);
291     if (cache) {
292         SkMaskCache::Add(sigma, style, rects, count, *mask, cache);
293     }
294     return cache;
295 }
296 
297 static const bool c_analyticBlurRRect{true};
298 
299 SkMaskFilterBase::FilterReturn
filterRRectToNine(const SkRRect & rrect,const SkMatrix & matrix,const SkIRect & clipBounds,NinePatch * patch) const300 SkBlurMaskFilterImpl::filterRRectToNine(const SkRRect& rrect, const SkMatrix& matrix,
301                                         const SkIRect& clipBounds,
302                                         NinePatch* patch) const {
303     SkASSERT(patch != nullptr);
304     switch (rrect.getType()) {
305         case SkRRect::kEmpty_Type:
306             // Nothing to draw.
307             return kFalse_FilterReturn;
308 
309         case SkRRect::kRect_Type:
310             // We should have caught this earlier.
311             SkASSERT(false);
312             [[fallthrough]];
313         case SkRRect::kOval_Type:
314             // The nine patch special case does not handle ovals, and we
315             // already have code for rectangles.
316             return kUnimplemented_FilterReturn;
317 
318         // These three can take advantage of this fast path.
319         case SkRRect::kSimple_Type:
320         case SkRRect::kNinePatch_Type:
321         case SkRRect::kComplex_Type:
322             break;
323     }
324 
325     // TODO: report correct metrics for innerstyle, where we do not grow the
326     // total bounds, but we do need an inset the size of our blur-radius
327     if (kInner_SkBlurStyle == fBlurStyle) {
328         return kUnimplemented_FilterReturn;
329     }
330 
331     // TODO: take clipBounds into account to limit our coordinates up front
332     // for now, just skip too-large src rects (to take the old code path).
333     if (rect_exceeds(rrect.rect(), SkIntToScalar(32767))) {
334         return kUnimplemented_FilterReturn;
335     }
336 
337     SkIPoint margin;
338     SkMask  srcM, dstM;
339     srcM.fBounds = rrect.rect().roundOut();
340     srcM.fFormat = SkMask::kA8_Format;
341     srcM.fRowBytes = 0;
342 
343     bool filterResult = false;
344     if (c_analyticBlurRRect) {
345         // special case for fast round rect blur
346         // don't actually do the blur the first time, just compute the correct size
347         filterResult = this->filterRRectMask(&dstM, rrect, matrix, &margin,
348                                             SkMask::kJustComputeBounds_CreateMode);
349     }
350 
351     if (!filterResult) {
352         filterResult = this->filterMask(&dstM, srcM, matrix, &margin);
353     }
354 
355     if (!filterResult) {
356         return kFalse_FilterReturn;
357     }
358 
359     // Now figure out the appropriate width and height of the smaller round rectangle
360     // to stretch. It will take into account the larger radius per side as well as double
361     // the margin, to account for inner and outer blur.
362     const SkVector& UL = rrect.radii(SkRRect::kUpperLeft_Corner);
363     const SkVector& UR = rrect.radii(SkRRect::kUpperRight_Corner);
364     const SkVector& LR = rrect.radii(SkRRect::kLowerRight_Corner);
365     const SkVector& LL = rrect.radii(SkRRect::kLowerLeft_Corner);
366 
367     const SkScalar leftUnstretched = std::max(UL.fX, LL.fX) + SkIntToScalar(2 * margin.fX);
368     const SkScalar rightUnstretched = std::max(UR.fX, LR.fX) + SkIntToScalar(2 * margin.fX);
369 
370     // Extra space in the middle to ensure an unchanging piece for stretching. Use 3 to cover
371     // any fractional space on either side plus 1 for the part to stretch.
372     const SkScalar stretchSize = SkIntToScalar(3);
373 
374     const SkScalar totalSmallWidth = leftUnstretched + rightUnstretched + stretchSize;
375     if (totalSmallWidth >= rrect.rect().width()) {
376         // There is no valid piece to stretch.
377         return kUnimplemented_FilterReturn;
378     }
379 
380     const SkScalar topUnstretched = std::max(UL.fY, UR.fY) + SkIntToScalar(2 * margin.fY);
381     const SkScalar bottomUnstretched = std::max(LL.fY, LR.fY) + SkIntToScalar(2 * margin.fY);
382 
383     const SkScalar totalSmallHeight = topUnstretched + bottomUnstretched + stretchSize;
384     if (totalSmallHeight >= rrect.rect().height()) {
385         // There is no valid piece to stretch.
386         return kUnimplemented_FilterReturn;
387     }
388 
389     SkRect smallR = SkRect::MakeWH(totalSmallWidth, totalSmallHeight);
390 
391     SkRRect smallRR;
392     SkVector radii[4];
393     radii[SkRRect::kUpperLeft_Corner] = UL;
394     radii[SkRRect::kUpperRight_Corner] = UR;
395     radii[SkRRect::kLowerRight_Corner] = LR;
396     radii[SkRRect::kLowerLeft_Corner] = LL;
397     smallRR.setRectRadii(smallR, radii);
398 
399     const SkScalar sigma = this->computeXformedSigma(matrix);
400     SkCachedData* cache = find_cached_rrect(&patch->fMask, sigma, fBlurStyle, smallRR);
401     if (!cache) {
402         bool analyticBlurWorked = false;
403         if (c_analyticBlurRRect) {
404             analyticBlurWorked =
405                 this->filterRRectMask(&patch->fMask, smallRR, matrix, &margin,
406                                       SkMask::kComputeBoundsAndRenderImage_CreateMode);
407         }
408 
409         if (!analyticBlurWorked) {
410             if (!draw_rrect_into_mask(smallRR, &srcM)) {
411                 return kFalse_FilterReturn;
412             }
413 
414             SkAutoMaskFreeImage amf(srcM.fImage);
415 
416             if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
417                 return kFalse_FilterReturn;
418             }
419         }
420         cache = add_cached_rrect(&patch->fMask, sigma, fBlurStyle, smallRR);
421     }
422 
423     patch->fMask.fBounds.offsetTo(0, 0);
424     patch->fOuterRect = dstM.fBounds;
425     patch->fCenter.fX = SkScalarCeilToInt(leftUnstretched) + 1;
426     patch->fCenter.fY = SkScalarCeilToInt(topUnstretched) + 1;
427     SkASSERT(nullptr == patch->fCache);
428     patch->fCache = cache;  // transfer ownership to patch
429     return kTrue_FilterReturn;
430 }
431 
432 // Use the faster analytic blur approach for ninepatch rects
433 static const bool c_analyticBlurNinepatch{true};
434 
435 SkMaskFilterBase::FilterReturn
filterRectsToNine(const SkRect rects[],int count,const SkMatrix & matrix,const SkIRect & clipBounds,NinePatch * patch) const436 SkBlurMaskFilterImpl::filterRectsToNine(const SkRect rects[], int count,
437                                         const SkMatrix& matrix,
438                                         const SkIRect& clipBounds,
439                                         NinePatch* patch) const {
440     if (count < 1 || count > 2) {
441         return kUnimplemented_FilterReturn;
442     }
443 
444     // TODO: report correct metrics for innerstyle, where we do not grow the
445     // total bounds, but we do need an inset the size of our blur-radius
446     if (kInner_SkBlurStyle == fBlurStyle || kOuter_SkBlurStyle == fBlurStyle) {
447         return kUnimplemented_FilterReturn;
448     }
449 
450     // TODO: take clipBounds into account to limit our coordinates up front
451     // for now, just skip too-large src rects (to take the old code path).
452     if (rect_exceeds(rects[0], SkIntToScalar(32767))) {
453         return kUnimplemented_FilterReturn;
454     }
455 
456     SkIPoint margin;
457     SkMask  srcM, dstM;
458     srcM.fBounds = rects[0].roundOut();
459     srcM.fFormat = SkMask::kA8_Format;
460     srcM.fRowBytes = 0;
461 
462     bool filterResult = false;
463     if (count == 1 && c_analyticBlurNinepatch) {
464         // special case for fast rect blur
465         // don't actually do the blur the first time, just compute the correct size
466         filterResult = this->filterRectMask(&dstM, rects[0], matrix, &margin,
467                                             SkMask::kJustComputeBounds_CreateMode);
468     } else {
469         filterResult = this->filterMask(&dstM, srcM, matrix, &margin);
470     }
471 
472     if (!filterResult) {
473         return kFalse_FilterReturn;
474     }
475 
476     /*
477      *  smallR is the smallest version of 'rect' that will still guarantee that
478      *  we get the same blur results on all edges, plus 1 center row/col that is
479      *  representative of the extendible/stretchable edges of the ninepatch.
480      *  Since our actual edge may be fractional we inset 1 more to be sure we
481      *  don't miss any interior blur.
482      *  x is an added pixel of blur, and { and } are the (fractional) edge
483      *  pixels from the original rect.
484      *
485      *   x x { x x .... x x } x x
486      *
487      *  Thus, in this case, we inset by a total of 5 (on each side) beginning
488      *  with our outer-rect (dstM.fBounds)
489      */
490     SkRect smallR[2];
491     SkIPoint center;
492 
493     // +2 is from +1 for each edge (to account for possible fractional edges
494     int smallW = dstM.fBounds.width() - srcM.fBounds.width() + 2;
495     int smallH = dstM.fBounds.height() - srcM.fBounds.height() + 2;
496     SkIRect innerIR;
497 
498     if (1 == count) {
499         innerIR = srcM.fBounds;
500         center.set(smallW, smallH);
501     } else {
502         SkASSERT(2 == count);
503         rects[1].roundIn(&innerIR);
504         center.set(smallW + (innerIR.left() - srcM.fBounds.left()),
505                    smallH + (innerIR.top() - srcM.fBounds.top()));
506     }
507 
508     // +1 so we get a clean, stretchable, center row/col
509     smallW += 1;
510     smallH += 1;
511 
512     // we want the inset amounts to be integral, so we don't change any
513     // fractional phase on the fRight or fBottom of our smallR.
514     const SkScalar dx = SkIntToScalar(innerIR.width() - smallW);
515     const SkScalar dy = SkIntToScalar(innerIR.height() - smallH);
516     if (dx < 0 || dy < 0) {
517         // we're too small, relative to our blur, to break into nine-patch,
518         // so we ask to have our normal filterMask() be called.
519         return kUnimplemented_FilterReturn;
520     }
521 
522     smallR[0].setLTRB(rects[0].left(),       rects[0].top(),
523                       rects[0].right() - dx, rects[0].bottom() - dy);
524     if (smallR[0].width() < 2 || smallR[0].height() < 2) {
525         return kUnimplemented_FilterReturn;
526     }
527     if (2 == count) {
528         smallR[1].setLTRB(rects[1].left(), rects[1].top(),
529                           rects[1].right() - dx, rects[1].bottom() - dy);
530         SkASSERT(!smallR[1].isEmpty());
531     }
532 
533     const SkScalar sigma = this->computeXformedSigma(matrix);
534     SkCachedData* cache = find_cached_rects(&patch->fMask, sigma, fBlurStyle, smallR, count);
535     if (!cache) {
536         if (count > 1 || !c_analyticBlurNinepatch) {
537             if (!draw_rects_into_mask(smallR, count, &srcM)) {
538                 return kFalse_FilterReturn;
539             }
540 
541             SkAutoMaskFreeImage amf(srcM.fImage);
542 
543             if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
544                 return kFalse_FilterReturn;
545             }
546         } else {
547             if (!this->filterRectMask(&patch->fMask, smallR[0], matrix, &margin,
548                                       SkMask::kComputeBoundsAndRenderImage_CreateMode)) {
549                 return kFalse_FilterReturn;
550             }
551         }
552         cache = add_cached_rects(&patch->fMask, sigma, fBlurStyle, smallR, count);
553     }
554     patch->fMask.fBounds.offsetTo(0, 0);
555     patch->fOuterRect = dstM.fBounds;
556     patch->fCenter = center;
557     SkASSERT(nullptr == patch->fCache);
558     patch->fCache = cache;  // transfer ownership to patch
559     return kTrue_FilterReturn;
560 }
561 
computeFastBounds(const SkRect & src,SkRect * dst) const562 void SkBlurMaskFilterImpl::computeFastBounds(const SkRect& src,
563                                              SkRect* dst) const {
564     // TODO: if we're doing kInner blur, should we return a different outset?
565     //       i.e. pad == 0 ?
566 
567     SkScalar pad = 3.0f * fSigma;
568 
569     dst->setLTRB(src.fLeft  - pad, src.fTop    - pad,
570                  src.fRight + pad, src.fBottom + pad);
571 }
572 
CreateProc(SkReadBuffer & buffer)573 sk_sp<SkFlattenable> SkBlurMaskFilterImpl::CreateProc(SkReadBuffer& buffer) {
574     const SkScalar sigma = buffer.readScalar();
575     SkBlurStyle style = buffer.read32LE(kLastEnum_SkBlurStyle);
576 
577     uint32_t flags = buffer.read32LE(0x3);  // historically we only recorded 2 bits
578     bool respectCTM = !(flags & 1); // historically we stored ignoreCTM in low bit
579 
580     return SkMaskFilter::MakeBlur((SkBlurStyle)style, sigma, respectCTM);
581 }
582 
flatten(SkWriteBuffer & buffer) const583 void SkBlurMaskFilterImpl::flatten(SkWriteBuffer& buffer) const {
584     buffer.writeScalar(fSigma);
585     buffer.writeUInt(fBlurStyle);
586     buffer.writeUInt(!fRespectCTM); // historically we recorded ignoreCTM
587 }
588 
589 
590 #if SK_SUPPORT_GPU && SK_GPU_V1
591 
592 ///////////////////////////////////////////////////////////////////////////////
593 //  Circle Blur
594 ///////////////////////////////////////////////////////////////////////////////
595 
596 // Computes an unnormalized half kernel (right side). Returns the summation of all the half
597 // kernel values.
make_unnormalized_half_kernel(float * halfKernel,int halfKernelSize,float sigma)598 static float make_unnormalized_half_kernel(float* halfKernel, int halfKernelSize, float sigma) {
599     const float invSigma = 1.f / sigma;
600     const float b = -0.5f * invSigma * invSigma;
601     float tot = 0.0f;
602     // Compute half kernel values at half pixel steps out from the center.
603     float t = 0.5f;
604     for (int i = 0; i < halfKernelSize; ++i) {
605         float value = expf(t * t * b);
606         tot += value;
607         halfKernel[i] = value;
608         t += 1.f;
609     }
610     return tot;
611 }
612 
613 // Create a Gaussian half-kernel (right side) and a summed area table given a sigma and number
614 // of discrete steps. The half kernel is normalized to sum to 0.5.
make_half_kernel_and_summed_table(float * halfKernel,float * summedHalfKernel,int halfKernelSize,float sigma)615 static void make_half_kernel_and_summed_table(float* halfKernel,
616                                               float* summedHalfKernel,
617                                               int halfKernelSize,
618                                               float sigma) {
619     // The half kernel should sum to 0.5 not 1.0.
620     const float tot = 2.f * make_unnormalized_half_kernel(halfKernel, halfKernelSize, sigma);
621     float sum = 0.f;
622     for (int i = 0; i < halfKernelSize; ++i) {
623         halfKernel[i] /= tot;
624         sum += halfKernel[i];
625         summedHalfKernel[i] = sum;
626     }
627 }
628 
629 // Applies the 1D half kernel vertically at points along the x axis to a circle centered at the
630 // origin with radius circleR.
apply_kernel_in_y(float * results,int numSteps,float firstX,float circleR,int halfKernelSize,const float * summedHalfKernelTable)631 void apply_kernel_in_y(float* results,
632                        int numSteps,
633                        float firstX,
634                        float circleR,
635                        int halfKernelSize,
636                        const float* summedHalfKernelTable) {
637     float x = firstX;
638     for (int i = 0; i < numSteps; ++i, x += 1.f) {
639         if (x < -circleR || x > circleR) {
640             results[i] = 0;
641             continue;
642         }
643         float y = sqrtf(circleR * circleR - x * x);
644         // In the column at x we exit the circle at +y and -y
645         // The summed table entry j is actually reflects an offset of j + 0.5.
646         y -= 0.5f;
647         int yInt = SkScalarFloorToInt(y);
648         SkASSERT(yInt >= -1);
649         if (y < 0) {
650             results[i] = (y + 0.5f) * summedHalfKernelTable[0];
651         } else if (yInt >= halfKernelSize - 1) {
652             results[i] = 0.5f;
653         } else {
654             float yFrac = y - yInt;
655             results[i] = (1.f - yFrac) * summedHalfKernelTable[yInt] +
656                          yFrac * summedHalfKernelTable[yInt + 1];
657         }
658     }
659 }
660 
661 // Apply a Gaussian at point (evalX, 0) to a circle centered at the origin with radius circleR.
662 // This relies on having a half kernel computed for the Gaussian and a table of applications of
663 // the half kernel in y to columns at (evalX - halfKernel, evalX - halfKernel + 1, ..., evalX +
664 // halfKernel) passed in as yKernelEvaluations.
eval_at(float evalX,float circleR,const float * halfKernel,int halfKernelSize,const float * yKernelEvaluations)665 static uint8_t eval_at(float evalX,
666                        float circleR,
667                        const float* halfKernel,
668                        int halfKernelSize,
669                        const float* yKernelEvaluations) {
670     float acc = 0;
671 
672     float x = evalX - halfKernelSize;
673     for (int i = 0; i < halfKernelSize; ++i, x += 1.f) {
674         if (x < -circleR || x > circleR) {
675             continue;
676         }
677         float verticalEval = yKernelEvaluations[i];
678         acc += verticalEval * halfKernel[halfKernelSize - i - 1];
679     }
680     for (int i = 0; i < halfKernelSize; ++i, x += 1.f) {
681         if (x < -circleR || x > circleR) {
682             continue;
683         }
684         float verticalEval = yKernelEvaluations[i + halfKernelSize];
685         acc += verticalEval * halfKernel[i];
686     }
687     // Since we applied a half kernel in y we multiply acc by 2 (the circle is symmetric about
688     // the x axis).
689     return SkUnitScalarClampToByte(2.f * acc);
690 }
691 
692 // This function creates a profile of a blurred circle. It does this by computing a kernel for
693 // half the Gaussian and a matching summed area table. The summed area table is used to compute
694 // an array of vertical applications of the half kernel to the circle along the x axis. The
695 // table of y evaluations has 2 * k + n entries where k is the size of the half kernel and n is
696 // the size of the profile being computed. Then for each of the n profile entries we walk out k
697 // steps in each horizontal direction multiplying the corresponding y evaluation by the half
698 // kernel entry and sum these values to compute the profile entry.
create_circle_profile(uint8_t * weights,float sigma,float circleR,int profileTextureWidth)699 static void create_circle_profile(uint8_t* weights,
700                                   float sigma,
701                                   float circleR,
702                                   int profileTextureWidth) {
703     const int numSteps = profileTextureWidth;
704 
705     // The full kernel is 6 sigmas wide.
706     int halfKernelSize = SkScalarCeilToInt(6.0f * sigma);
707     // round up to next multiple of 2 and then divide by 2
708     halfKernelSize = ((halfKernelSize + 1) & ~1) >> 1;
709 
710     // Number of x steps at which to apply kernel in y to cover all the profile samples in x.
711     int numYSteps = numSteps + 2 * halfKernelSize;
712 
713     SkAutoTArray<float> bulkAlloc(halfKernelSize + halfKernelSize + numYSteps);
714     float* halfKernel = bulkAlloc.get();
715     float* summedKernel = bulkAlloc.get() + halfKernelSize;
716     float* yEvals = bulkAlloc.get() + 2 * halfKernelSize;
717     make_half_kernel_and_summed_table(halfKernel, summedKernel, halfKernelSize, sigma);
718 
719     float firstX = -halfKernelSize + 0.5f;
720     apply_kernel_in_y(yEvals, numYSteps, firstX, circleR, halfKernelSize, summedKernel);
721 
722     for (int i = 0; i < numSteps - 1; ++i) {
723         float evalX = i + 0.5f;
724         weights[i] = eval_at(evalX, circleR, halfKernel, halfKernelSize, yEvals + i);
725     }
726     // Ensure the tail of the Gaussian goes to zero.
727     weights[numSteps - 1] = 0;
728 }
729 
create_half_plane_profile(uint8_t * profile,int profileWidth)730 static void create_half_plane_profile(uint8_t* profile, int profileWidth) {
731     SkASSERT(!(profileWidth & 0x1));
732     // The full kernel is 6 sigmas wide.
733     float sigma = profileWidth / 6.f;
734     int halfKernelSize = profileWidth / 2;
735 
736     SkAutoTArray<float> halfKernel(halfKernelSize);
737 
738     // The half kernel should sum to 0.5.
739     const float tot = 2.f * make_unnormalized_half_kernel(halfKernel.get(), halfKernelSize, sigma);
740     float sum = 0.f;
741     // Populate the profile from the right edge to the middle.
742     for (int i = 0; i < halfKernelSize; ++i) {
743         halfKernel[halfKernelSize - i - 1] /= tot;
744         sum += halfKernel[halfKernelSize - i - 1];
745         profile[profileWidth - i - 1] = SkUnitScalarClampToByte(sum);
746     }
747     // Populate the profile from the middle to the left edge (by flipping the half kernel and
748     // continuing the summation).
749     for (int i = 0; i < halfKernelSize; ++i) {
750         sum += halfKernel[i];
751         profile[halfKernelSize - i - 1] = SkUnitScalarClampToByte(sum);
752     }
753     // Ensure tail goes to 0.
754     profile[profileWidth - 1] = 0;
755 }
756 
create_profile_effect(GrRecordingContext * rContext,const SkRect & circle,float sigma,float * solidRadius,float * textureRadius)757 static std::unique_ptr<GrFragmentProcessor> create_profile_effect(GrRecordingContext* rContext,
758                                                                   const SkRect& circle,
759                                                                   float sigma,
760                                                                   float* solidRadius,
761                                                                   float* textureRadius) {
762     float circleR = circle.width() / 2.0f;
763     if (!sk_float_isfinite(circleR) || circleR < SK_ScalarNearlyZero) {
764         return nullptr;
765     }
766 
767     auto threadSafeCache = rContext->priv().threadSafeCache();
768 
769     // Profile textures are cached by the ratio of sigma to circle radius and by the size of the
770     // profile texture (binned by powers of 2).
771     SkScalar sigmaToCircleRRatio = sigma / circleR;
772     // When sigma is really small this becomes a equivalent to convolving a Gaussian with a
773     // half-plane. Similarly, in the extreme high ratio cases circle becomes a point WRT to the
774     // Guassian and the profile texture is a just a Gaussian evaluation. However, we haven't yet
775     // implemented this latter optimization.
776     sigmaToCircleRRatio = std::min(sigmaToCircleRRatio, 8.f);
777     SkFixed sigmaToCircleRRatioFixed;
778     static const SkScalar kHalfPlaneThreshold = 0.1f;
779     bool useHalfPlaneApprox = false;
780     if (sigmaToCircleRRatio <= kHalfPlaneThreshold) {
781         useHalfPlaneApprox = true;
782         sigmaToCircleRRatioFixed = 0;
783         *solidRadius = circleR - 3 * sigma;
784         *textureRadius = 6 * sigma;
785     } else {
786         // Convert to fixed point for the key.
787         sigmaToCircleRRatioFixed = SkScalarToFixed(sigmaToCircleRRatio);
788         // We shave off some bits to reduce the number of unique entries. We could probably
789         // shave off more than we do.
790         sigmaToCircleRRatioFixed &= ~0xff;
791         sigmaToCircleRRatio = SkFixedToScalar(sigmaToCircleRRatioFixed);
792         sigma = circleR * sigmaToCircleRRatio;
793         *solidRadius = 0;
794         *textureRadius = circleR + 3 * sigma;
795     }
796 
797     static constexpr int kProfileTextureWidth = 512;
798     // This would be kProfileTextureWidth/textureRadius if it weren't for the fact that we do
799     // the calculation of the profile coord in a coord space that has already been scaled by
800     // 1 / textureRadius. This is done to avoid overflow in length().
801     SkMatrix texM = SkMatrix::Scale(kProfileTextureWidth, 1.f);
802 
803     static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
804     GrUniqueKey key;
805     GrUniqueKey::Builder builder(&key, kDomain, 1, "1-D Circular Blur");
806     builder[0] = sigmaToCircleRRatioFixed;
807     builder.finish();
808 
809     GrSurfaceProxyView profileView = threadSafeCache->find(key);
810     if (profileView) {
811         SkASSERT(profileView.asTextureProxy());
812         SkASSERT(profileView.origin() == kTopLeft_GrSurfaceOrigin);
813         return GrTextureEffect::Make(std::move(profileView), kPremul_SkAlphaType, texM);
814     }
815 
816     SkBitmap bm;
817     if (!bm.tryAllocPixels(SkImageInfo::MakeA8(kProfileTextureWidth, 1))) {
818         return nullptr;
819     }
820 
821     if (useHalfPlaneApprox) {
822         create_half_plane_profile(bm.getAddr8(0, 0), kProfileTextureWidth);
823     } else {
824         // Rescale params to the size of the texture we're creating.
825         SkScalar scale = kProfileTextureWidth / *textureRadius;
826         create_circle_profile(
827                 bm.getAddr8(0, 0), sigma * scale, circleR * scale, kProfileTextureWidth);
828     }
829     bm.setImmutable();
830 
831     profileView = std::get<0>(GrMakeUncachedBitmapProxyView(rContext, bm));
832     if (!profileView) {
833         return nullptr;
834     }
835 
836     profileView = threadSafeCache->add(key, profileView);
837     return GrTextureEffect::Make(std::move(profileView), kPremul_SkAlphaType, texM);
838 }
839 
make_circle_blur(GrRecordingContext * context,const SkRect & circle,float sigma)840 static std::unique_ptr<GrFragmentProcessor> make_circle_blur(GrRecordingContext* context,
841                                                              const SkRect& circle,
842                                                              float sigma) {
843     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(sigma)) {
844         return nullptr;
845     }
846 
847     float solidRadius;
848     float textureRadius;
849     std::unique_ptr<GrFragmentProcessor> profile =
850             create_profile_effect(context, circle, sigma, &solidRadius, &textureRadius);
851     if (!profile) {
852         return nullptr;
853     }
854 
855     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, R"(
856         uniform shader blurProfile;
857         uniform float4 circleData;
858 
859         half4 main(float2 xy, half4 inColor) {
860             // We just want to compute "(length(vec) - circleData.z + 0.5) * circleData.w" but need
861             // to rearrange to avoid passing large values to length() that would overflow.
862             half4 halfCircleData = circleData;
863             half2 vec = (sk_FragCoord.xy - halfCircleData.xy) * circleData.w;
864             half dist = length(vec) + (0.5 - halfCircleData.z) * halfCircleData.w;
865             return inColor * blurProfile.eval(half2(dist, 0.5)).a;
866         }
867     )");
868 
869     SkV4 circleData = {circle.centerX(), circle.centerY(), solidRadius, 1.f / textureRadius};
870     return GrSkSLFP::Make(effect, "CircleBlur", /*inputFP=*/nullptr,
871                           GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
872                           "blurProfile", GrSkSLFP::IgnoreOptFlags(std::move(profile)),
873                           "circleData", circleData);
874 }
875 
876 ///////////////////////////////////////////////////////////////////////////////
877 //  Rect Blur
878 ///////////////////////////////////////////////////////////////////////////////
879 
make_rect_integral_fp(GrRecordingContext * rContext,float sixSigma)880 static std::unique_ptr<GrFragmentProcessor> make_rect_integral_fp(GrRecordingContext* rContext,
881                                                                   float sixSigma) {
882     SkASSERT(!SkGpuBlurUtils::IsEffectivelyZeroSigma(sixSigma / 6.f));
883     auto threadSafeCache = rContext->priv().threadSafeCache();
884 
885     int width = SkGpuBlurUtils::CreateIntegralTable(sixSigma, nullptr);
886 
887     static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
888     GrUniqueKey key;
889     GrUniqueKey::Builder builder(&key, kDomain, 1, "Rect Blur Mask");
890     builder[0] = width;
891     builder.finish();
892 
893     SkMatrix m = SkMatrix::Scale(width / sixSigma, 1.f);
894 
895     GrSurfaceProxyView view = threadSafeCache->find(key);
896 
897     if (view) {
898         SkASSERT(view.origin() == kTopLeft_GrSurfaceOrigin);
899         return GrTextureEffect::Make(
900                 std::move(view), kPremul_SkAlphaType, m, GrSamplerState::Filter::kLinear);
901     }
902 
903     SkBitmap bitmap;
904     if (!SkGpuBlurUtils::CreateIntegralTable(sixSigma, &bitmap)) {
905         return {};
906     }
907 
908     view = std::get<0>(GrMakeUncachedBitmapProxyView(rContext, bitmap));
909     if (!view) {
910         return {};
911     }
912 
913     view = threadSafeCache->add(key, view);
914 
915     SkASSERT(view.origin() == kTopLeft_GrSurfaceOrigin);
916     return GrTextureEffect::Make(
917             std::move(view), kPremul_SkAlphaType, m, GrSamplerState::Filter::kLinear);
918 }
919 
make_rect_blur(GrRecordingContext * context,const GrShaderCaps & caps,const SkRect & srcRect,const SkMatrix & viewMatrix,float transformedSigma)920 static std::unique_ptr<GrFragmentProcessor> make_rect_blur(GrRecordingContext* context,
921                                                            const GrShaderCaps& caps,
922                                                            const SkRect& srcRect,
923                                                            const SkMatrix& viewMatrix,
924                                                            float transformedSigma) {
925     SkASSERT(viewMatrix.preservesRightAngles());
926     SkASSERT(srcRect.isSorted());
927 
928     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(transformedSigma)) {
929         // No need to blur the rect
930         return nullptr;
931     }
932 
933     SkMatrix invM;
934     SkRect rect;
935     if (viewMatrix.rectStaysRect()) {
936         invM = SkMatrix::I();
937         // We can do everything in device space when the src rect projects to a rect in device space
938         SkAssertResult(viewMatrix.mapRect(&rect, srcRect));
939     } else {
940         // The view matrix may scale, perhaps anisotropically. But we want to apply our device space
941         // "transformedSigma" to the delta of frag coord from the rect edges. Factor out the scaling
942         // to define a space that is purely rotation/translation from device space (and scale from
943         // src space) We'll meet in the middle: pre-scale the src rect to be in this space and then
944         // apply the inverse of the rotation/translation portion to the frag coord.
945         SkMatrix m;
946         SkSize scale;
947         if (!viewMatrix.decomposeScale(&scale, &m)) {
948             return nullptr;
949         }
950         if (!m.invert(&invM)) {
951             return nullptr;
952         }
953         rect = {srcRect.left() * scale.width(),
954                 srcRect.top() * scale.height(),
955                 srcRect.right() * scale.width(),
956                 srcRect.bottom() * scale.height()};
957     }
958 
959     if (!caps.floatIs32Bits()) {
960         // We promote the math that gets us into the Gaussian space to full float when the rect
961         // coords are large. If we don't have full float then fail. We could probably clip the rect
962         // to an outset device bounds instead.
963         if (SkScalarAbs(rect.fLeft) > 16000.f || SkScalarAbs(rect.fTop) > 16000.f ||
964             SkScalarAbs(rect.fRight) > 16000.f || SkScalarAbs(rect.fBottom) > 16000.f) {
965             return nullptr;
966         }
967     }
968 
969     const float sixSigma = 6 * transformedSigma;
970     std::unique_ptr<GrFragmentProcessor> integral = make_rect_integral_fp(context, sixSigma);
971     if (!integral) {
972         return nullptr;
973     }
974 
975     // In the fast variant we think of the midpoint of the integral texture as aligning with the
976     // closest rect edge both in x and y. To simplify texture coord calculation we inset the rect so
977     // that the edge of the inset rect corresponds to t = 0 in the texture. It actually simplifies
978     // things a bit in the !isFast case, too.
979     float threeSigma = sixSigma / 2;
980     SkRect insetRect = {rect.left() + threeSigma,
981                         rect.top() + threeSigma,
982                         rect.right() - threeSigma,
983                         rect.bottom() - threeSigma};
984 
985     // In our fast variant we find the nearest horizontal and vertical edges and for each do a
986     // lookup in the integral texture for each and multiply them. When the rect is less than 6 sigma
987     // wide then things aren't so simple and we have to consider both the left and right edge of the
988     // rectangle (and similar in y).
989     bool isFast = insetRect.isSorted();
990 
991     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, R"(
992         // Effect that is a LUT for integral of normal distribution. The value at x:[0,6*sigma] is
993         // the integral from -inf to (3*sigma - x). I.e. x is mapped from [0, 6*sigma] to
994         // [3*sigma to -3*sigma]. The flip saves a reversal in the shader.
995         uniform shader integral;
996 
997         uniform float4 rect;
998         uniform int isFast;  // specialized
999 
1000         half4 main(float2 pos, half4 inColor) {
1001             half xCoverage, yCoverage;
1002             if (bool(isFast)) {
1003                 // Get the smaller of the signed distance from the frag coord to the left and right
1004                 // edges and similar for y.
1005                 // The integral texture goes "backwards" (from 3*sigma to -3*sigma), So, the below
1006                 // computations align the left edge of the integral texture with the inset rect's
1007                 // edge extending outward 6 * sigma from the inset rect.
1008                 half2 xy = max(half2(rect.LT - pos), half2(pos - rect.RB));
1009                 xCoverage = integral.eval(half2(xy.x, 0.5)).a;
1010                 yCoverage = integral.eval(half2(xy.y, 0.5)).a;
1011             } else {
1012                 // We just consider just the x direction here. In practice we compute x and y
1013                 // separately and multiply them together.
1014                 // We define our coord system so that the point at which we're evaluating a kernel
1015                 // defined by the normal distribution (K) at 0. In this coord system let L be left
1016                 // edge and R be the right edge of the rectangle.
1017                 // We can calculate C by integrating K with the half infinite ranges outside the
1018                 // L to R range and subtracting from 1:
1019                 //   C = 1 - <integral of K from from -inf to  L> - <integral of K from R to inf>
1020                 // K is symmetric about x=0 so:
1021                 //   C = 1 - <integral of K from from -inf to  L> - <integral of K from -inf to -R>
1022 
1023                 // The integral texture goes "backwards" (from 3*sigma to -3*sigma) which is
1024                 // factored in to the below calculations.
1025                 // Also, our rect uniform was pre-inset by 3 sigma from the actual rect being
1026                 // blurred, also factored in.
1027                 half4 rect = half4(half2(rect.LT - pos), half2(pos - rect.RB));
1028                 xCoverage = 1 - integral.eval(half2(rect.L, 0.5)).a
1029                               - integral.eval(half2(rect.R, 0.5)).a;
1030                 yCoverage = 1 - integral.eval(half2(rect.T, 0.5)).a
1031                               - integral.eval(half2(rect.B, 0.5)).a;
1032             }
1033             return inColor * xCoverage * yCoverage;
1034         }
1035     )");
1036 
1037     std::unique_ptr<GrFragmentProcessor> fp =
1038             GrSkSLFP::Make(effect, "RectBlur", /*inputFP=*/nullptr,
1039                            GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
1040                            "integral", GrSkSLFP::IgnoreOptFlags(std::move(integral)),
1041                            "rect", insetRect,
1042                            "isFast", GrSkSLFP::Specialize<int>(isFast));
1043     if (!invM.isIdentity()) {
1044         fp = GrMatrixEffect::Make(invM, std::move(fp));
1045     }
1046     return GrFragmentProcessor::DeviceSpace(std::move(fp));
1047 }
1048 
1049 ///////////////////////////////////////////////////////////////////////////////
1050 //  RRect Blur
1051 ///////////////////////////////////////////////////////////////////////////////
1052 
1053 static constexpr auto kBlurredRRectMaskOrigin = kTopLeft_GrSurfaceOrigin;
1054 
make_blurred_rrect_key(GrUniqueKey * key,const SkRRect & rrectToDraw,float xformedSigma)1055 static void make_blurred_rrect_key(GrUniqueKey* key,
1056                                    const SkRRect& rrectToDraw,
1057                                    float xformedSigma) {
1058     SkASSERT(!SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma));
1059     static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
1060 
1061     GrUniqueKey::Builder builder(key, kDomain, 9, "RoundRect Blur Mask");
1062     builder[0] = SkScalarCeilToInt(xformedSigma - 1 / 6.0f);
1063 
1064     int index = 1;
1065     // TODO: this is overkill for _simple_ circular rrects
1066     for (auto c : {SkRRect::kUpperLeft_Corner,
1067                    SkRRect::kUpperRight_Corner,
1068                    SkRRect::kLowerRight_Corner,
1069                    SkRRect::kLowerLeft_Corner}) {
1070         SkASSERT(SkScalarIsInt(rrectToDraw.radii(c).fX) && SkScalarIsInt(rrectToDraw.radii(c).fY));
1071         builder[index++] = SkScalarCeilToInt(rrectToDraw.radii(c).fX);
1072         builder[index++] = SkScalarCeilToInt(rrectToDraw.radii(c).fY);
1073     }
1074     builder.finish();
1075 }
1076 
fillin_view_on_gpu(GrDirectContext * dContext,const GrSurfaceProxyView & lazyView,sk_sp<GrThreadSafeCache::Trampoline> trampoline,const SkRRect & rrectToDraw,const SkISize & dimensions,float xformedSigma)1077 static bool fillin_view_on_gpu(GrDirectContext* dContext,
1078                                const GrSurfaceProxyView& lazyView,
1079                                sk_sp<GrThreadSafeCache::Trampoline> trampoline,
1080                                const SkRRect& rrectToDraw,
1081                                const SkISize& dimensions,
1082                                float xformedSigma) {
1083 #if SK_GPU_V1
1084     SkASSERT(!SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma));
1085 
1086     // We cache blur masks. Use default surface props here so we can use the same cached mask
1087     // regardless of the final dst surface.
1088     SkSurfaceProps defaultSurfaceProps;
1089 
1090     std::unique_ptr<skgpu::v1::SurfaceDrawContext> sdc =
1091             skgpu::v1::SurfaceDrawContext::MakeWithFallback(dContext,
1092                                                             GrColorType::kAlpha_8,
1093                                                             nullptr,
1094                                                             SkBackingFit::kExact,
1095                                                             dimensions,
1096                                                             defaultSurfaceProps,
1097                                                             1,
1098                                                             GrMipmapped::kNo,
1099                                                             GrProtected::kNo,
1100                                                             kBlurredRRectMaskOrigin);
1101     if (!sdc) {
1102         return false;
1103     }
1104 
1105     GrPaint paint;
1106 
1107     sdc->clear(SK_PMColor4fTRANSPARENT);
1108     sdc->drawRRect(nullptr,
1109                    std::move(paint),
1110                    GrAA::kYes,
1111                    SkMatrix::I(),
1112                    rrectToDraw,
1113                    GrStyle::SimpleFill());
1114 
1115     GrSurfaceProxyView srcView = sdc->readSurfaceView();
1116     SkASSERT(srcView.asTextureProxy());
1117     auto rtc2 = SkGpuBlurUtils::GaussianBlur(dContext,
1118                                              std::move(srcView),
1119                                              sdc->colorInfo().colorType(),
1120                                              sdc->colorInfo().alphaType(),
1121                                              nullptr,
1122                                              SkIRect::MakeSize(dimensions),
1123                                              SkIRect::MakeSize(dimensions),
1124                                              xformedSigma,
1125                                              xformedSigma,
1126                                              SkTileMode::kClamp,
1127                                              SkBackingFit::kExact);
1128     if (!rtc2 || !rtc2->readSurfaceView()) {
1129         return false;
1130     }
1131 
1132     auto view = rtc2->readSurfaceView();
1133     SkASSERT(view.swizzle() == lazyView.swizzle());
1134     SkASSERT(view.origin() == lazyView.origin());
1135     trampoline->fProxy = view.asTextureProxyRef();
1136 
1137     return true;
1138 #else
1139     return false;
1140 #endif
1141 }
1142 
1143 // Evaluate the vertical blur at the specified 'y' value given the location of the top of the
1144 // rrect.
eval_V(float top,int y,const uint8_t * integral,int integralSize,float sixSigma)1145 static uint8_t eval_V(float top, int y, const uint8_t* integral, int integralSize, float sixSigma) {
1146     if (top < 0) {
1147         return 0;  // an empty column
1148     }
1149 
1150     float fT = (top - y - 0.5f) * (integralSize / sixSigma);
1151     if (fT < 0) {
1152         return 255;
1153     } else if (fT >= integralSize - 1) {
1154         return 0;
1155     }
1156 
1157     int lower = (int)fT;
1158     float frac = fT - lower;
1159 
1160     SkASSERT(lower + 1 < integralSize);
1161 
1162     return integral[lower] * (1.0f - frac) + integral[lower + 1] * frac;
1163 }
1164 
1165 // Apply a gaussian 'kernel' horizontally at the specified 'x', 'y' location.
eval_H(int x,int y,const std::vector<float> & topVec,const float * kernel,int kernelSize,const uint8_t * integral,int integralSize,float sixSigma)1166 static uint8_t eval_H(int x,
1167                       int y,
1168                       const std::vector<float>& topVec,
1169                       const float* kernel,
1170                       int kernelSize,
1171                       const uint8_t* integral,
1172                       int integralSize,
1173                       float sixSigma) {
1174     SkASSERT(0 <= x && x < (int)topVec.size());
1175     SkASSERT(kernelSize % 2);
1176 
1177     float accum = 0.0f;
1178 
1179     int xSampleLoc = x - (kernelSize / 2);
1180     for (int i = 0; i < kernelSize; ++i, ++xSampleLoc) {
1181         if (xSampleLoc < 0 || xSampleLoc >= (int)topVec.size()) {
1182             continue;
1183         }
1184 
1185         accum += kernel[i] * eval_V(topVec[xSampleLoc], y, integral, integralSize, sixSigma);
1186     }
1187 
1188     return accum + 0.5f;
1189 }
1190 
1191 // Create a cpu-side blurred-rrect mask that is close to the version the gpu would've produced.
1192 // The match needs to be close bc the cpu- and gpu-generated version must be interchangeable.
create_mask_on_cpu(GrRecordingContext * rContext,const SkRRect & rrectToDraw,const SkISize & dimensions,float xformedSigma)1193 static GrSurfaceProxyView create_mask_on_cpu(GrRecordingContext* rContext,
1194                                              const SkRRect& rrectToDraw,
1195                                              const SkISize& dimensions,
1196                                              float xformedSigma) {
1197     SkASSERT(!SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma));
1198     int radius = SkGpuBlurUtils::SigmaRadius(xformedSigma);
1199     int kernelSize = 2 * radius + 1;
1200 
1201     SkASSERT(kernelSize % 2);
1202     SkASSERT(dimensions.width() % 2);
1203     SkASSERT(dimensions.height() % 2);
1204 
1205     SkVector radii = rrectToDraw.getSimpleRadii();
1206     SkASSERT(SkScalarNearlyEqual(radii.fX, radii.fY));
1207 
1208     const int halfWidthPlus1 = (dimensions.width() / 2) + 1;
1209     const int halfHeightPlus1 = (dimensions.height() / 2) + 1;
1210 
1211     std::unique_ptr<float[]> kernel(new float[kernelSize]);
1212 
1213     SkGpuBlurUtils::Compute1DGaussianKernel(kernel.get(), xformedSigma, radius);
1214 
1215     SkBitmap integral;
1216     if (!SkGpuBlurUtils::CreateIntegralTable(6 * xformedSigma, &integral)) {
1217         return {};
1218     }
1219 
1220     SkBitmap result;
1221     if (!result.tryAllocPixels(SkImageInfo::MakeA8(dimensions.width(), dimensions.height()))) {
1222         return {};
1223     }
1224 
1225     std::vector<float> topVec;
1226     topVec.reserve(dimensions.width());
1227     for (int x = 0; x < dimensions.width(); ++x) {
1228         if (x < rrectToDraw.rect().fLeft || x > rrectToDraw.rect().fRight) {
1229             topVec.push_back(-1);
1230         } else {
1231             if (x + 0.5f < rrectToDraw.rect().fLeft + radii.fX) {  // in the circular section
1232                 float xDist = rrectToDraw.rect().fLeft + radii.fX - x - 0.5f;
1233                 float h = sqrtf(radii.fX * radii.fX - xDist * xDist);
1234                 SkASSERT(0 <= h && h < radii.fY);
1235                 topVec.push_back(rrectToDraw.rect().fTop + radii.fX - h + 3 * xformedSigma);
1236             } else {
1237                 topVec.push_back(rrectToDraw.rect().fTop + 3 * xformedSigma);
1238             }
1239         }
1240     }
1241 
1242     for (int y = 0; y < halfHeightPlus1; ++y) {
1243         uint8_t* scanline = result.getAddr8(0, y);
1244 
1245         for (int x = 0; x < halfWidthPlus1; ++x) {
1246             scanline[x] = eval_H(x,
1247                                  y,
1248                                  topVec,
1249                                  kernel.get(),
1250                                  kernelSize,
1251                                  integral.getAddr8(0, 0),
1252                                  integral.width(),
1253                                  6 * xformedSigma);
1254             scanline[dimensions.width() - x - 1] = scanline[x];
1255         }
1256 
1257         memcpy(result.getAddr8(0, dimensions.height() - y - 1), scanline, result.rowBytes());
1258     }
1259 
1260     result.setImmutable();
1261 
1262     auto view = std::get<0>(GrMakeUncachedBitmapProxyView(rContext, result));
1263     if (!view) {
1264         return {};
1265     }
1266 
1267     SkASSERT(view.origin() == kBlurredRRectMaskOrigin);
1268     return view;
1269 }
1270 
find_or_create_rrect_blur_mask_fp(GrRecordingContext * rContext,const SkRRect & rrectToDraw,const SkISize & dimensions,float xformedSigma)1271 static std::unique_ptr<GrFragmentProcessor> find_or_create_rrect_blur_mask_fp(
1272         GrRecordingContext* rContext,
1273         const SkRRect& rrectToDraw,
1274         const SkISize& dimensions,
1275         float xformedSigma) {
1276     SkASSERT(!SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma));
1277     GrUniqueKey key;
1278     make_blurred_rrect_key(&key, rrectToDraw, xformedSigma);
1279 
1280     auto threadSafeCache = rContext->priv().threadSafeCache();
1281 
1282     // It seems like we could omit this matrix and modify the shader code to not normalize
1283     // the coords used to sample the texture effect. However, the "proxyDims" value in the
1284     // shader is not always the actual the proxy dimensions. This is because 'dimensions' here
1285     // was computed using integer corner radii as determined in
1286     // SkComputeBlurredRRectParams whereas the shader code uses the float radius to compute
1287     // 'proxyDims'. Why it draws correctly with these unequal values is a mystery for the ages.
1288     auto m = SkMatrix::Scale(dimensions.width(), dimensions.height());
1289 
1290     GrSurfaceProxyView view;
1291 
1292     if (GrDirectContext* dContext = rContext->asDirectContext()) {
1293         // The gpu thread gets priority over the recording threads. If the gpu thread is first,
1294         // it crams a lazy proxy into the cache and then fills it in later.
1295         auto [lazyView, trampoline] = GrThreadSafeCache::CreateLazyView(dContext,
1296                                                                         GrColorType::kAlpha_8,
1297                                                                         dimensions,
1298                                                                         kBlurredRRectMaskOrigin,
1299                                                                         SkBackingFit::kExact);
1300         if (!lazyView) {
1301             return nullptr;
1302         }
1303 
1304         view = threadSafeCache->findOrAdd(key, lazyView);
1305         if (view != lazyView) {
1306             SkASSERT(view.asTextureProxy());
1307             SkASSERT(view.origin() == kBlurredRRectMaskOrigin);
1308             return GrTextureEffect::Make(std::move(view), kPremul_SkAlphaType, m);
1309         }
1310 
1311         if (!fillin_view_on_gpu(dContext,
1312                                 lazyView,
1313                                 std::move(trampoline),
1314                                 rrectToDraw,
1315                                 dimensions,
1316                                 xformedSigma)) {
1317             // In this case something has gone disastrously wrong so set up to drop the draw
1318             // that needed this resource and reduce future pollution of the cache.
1319             threadSafeCache->remove(key);
1320             return nullptr;
1321         }
1322     } else {
1323         view = threadSafeCache->find(key);
1324         if (view) {
1325             SkASSERT(view.asTextureProxy());
1326             SkASSERT(view.origin() == kBlurredRRectMaskOrigin);
1327             return GrTextureEffect::Make(std::move(view), kPremul_SkAlphaType, m);
1328         }
1329 
1330         view = create_mask_on_cpu(rContext, rrectToDraw, dimensions, xformedSigma);
1331         if (!view) {
1332             return nullptr;
1333         }
1334 
1335         view = threadSafeCache->add(key, view);
1336     }
1337 
1338     SkASSERT(view.asTextureProxy());
1339     SkASSERT(view.origin() == kBlurredRRectMaskOrigin);
1340     return GrTextureEffect::Make(std::move(view), kPremul_SkAlphaType, m);
1341 }
1342 
make_rrect_blur(GrRecordingContext * context,float sigma,float xformedSigma,const SkRRect & srcRRect,const SkRRect & devRRect)1343 static std::unique_ptr<GrFragmentProcessor> make_rrect_blur(GrRecordingContext* context,
1344                                                             float sigma,
1345                                                             float xformedSigma,
1346                                                             const SkRRect& srcRRect,
1347                                                             const SkRRect& devRRect) {
1348     // Should've been caught up-stream
1349 #ifdef SK_DEBUG
1350     SkASSERTF(!SkRRectPriv::IsCircle(devRRect),
1351               "Unexpected circle. %d\n\t%s\n\t%s",
1352               SkRRectPriv::IsCircle(srcRRect),
1353               srcRRect.dumpToString(true).c_str(),
1354               devRRect.dumpToString(true).c_str());
1355     SkASSERTF(!devRRect.isRect(),
1356               "Unexpected rect. %d\n\t%s\n\t%s",
1357               srcRRect.isRect(),
1358               srcRRect.dumpToString(true).c_str(),
1359               devRRect.dumpToString(true).c_str());
1360 #endif
1361 
1362     // TODO: loosen this up
1363     if (!SkRRectPriv::IsSimpleCircular(devRRect)) {
1364         return nullptr;
1365     }
1366 
1367     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma)) {
1368         return nullptr;
1369     }
1370 
1371     // Make sure we can successfully ninepatch this rrect -- the blur sigma has to be sufficiently
1372     // small relative to both the size of the corner radius and the width (and height) of the rrect.
1373     SkRRect rrectToDraw;
1374     SkISize dimensions;
1375     SkScalar ignored[SkGpuBlurUtils::kBlurRRectMaxDivisions];
1376 
1377     bool ninePatchable = SkGpuBlurUtils::ComputeBlurredRRectParams(srcRRect,
1378                                                                    devRRect,
1379                                                                    sigma,
1380                                                                    xformedSigma,
1381                                                                    &rrectToDraw,
1382                                                                    &dimensions,
1383                                                                    ignored,
1384                                                                    ignored,
1385                                                                    ignored,
1386                                                                    ignored);
1387     if (!ninePatchable) {
1388         return nullptr;
1389     }
1390 
1391     std::unique_ptr<GrFragmentProcessor> maskFP =
1392             find_or_create_rrect_blur_mask_fp(context, rrectToDraw, dimensions, xformedSigma);
1393     if (!maskFP) {
1394         return nullptr;
1395     }
1396 
1397     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, R"(
1398         uniform shader ninePatchFP;
1399 
1400         uniform half cornerRadius;
1401         uniform float4 proxyRect;
1402         uniform half blurRadius;
1403 
1404         half4 main(float2 xy, half4 inColor) {
1405             // Warp the fragment position to the appropriate part of the 9-patch blur texture by
1406             // snipping out the middle section of the proxy rect.
1407             float2 translatedFragPosFloat = sk_FragCoord.xy - proxyRect.LT;
1408             float2 proxyCenter = (proxyRect.RB - proxyRect.LT) * 0.5;
1409             half edgeSize = 2.0 * blurRadius + cornerRadius + 0.5;
1410 
1411             // Position the fragment so that (0, 0) marks the center of the proxy rectangle.
1412             // Negative coordinates are on the left/top side and positive numbers are on the
1413             // right/bottom.
1414             translatedFragPosFloat -= proxyCenter;
1415 
1416             // Temporarily strip off the fragment's sign. x/y are now strictly increasing as we
1417             // move away from the center.
1418             half2 fragDirection = half2(sign(translatedFragPosFloat));
1419             translatedFragPosFloat = abs(translatedFragPosFloat);
1420 
1421             // Our goal is to snip out the "middle section" of the proxy rect (everything but the
1422             // edge). We've repositioned our fragment position so that (0, 0) is the centerpoint
1423             // and x/y are always positive, so we can subtract here and interpret negative results
1424             // as being within the middle section.
1425             half2 translatedFragPosHalf = half2(translatedFragPosFloat - (proxyCenter - edgeSize));
1426 
1427             // Remove the middle section by clamping to zero.
1428             translatedFragPosHalf = max(translatedFragPosHalf, 0);
1429 
1430             // Reapply the fragment's sign, so that negative coordinates once again mean left/top
1431             // side and positive means bottom/right side.
1432             translatedFragPosHalf *= fragDirection;
1433 
1434             // Offset the fragment so that (0, 0) marks the upper-left again, instead of the center
1435             // point.
1436             translatedFragPosHalf += half2(edgeSize);
1437 
1438             half2 proxyDims = half2(2.0 * edgeSize);
1439             half2 texCoord = translatedFragPosHalf / proxyDims;
1440 
1441             return inColor * ninePatchFP.eval(texCoord).a;
1442         }
1443     )");
1444 
1445     float cornerRadius = SkRRectPriv::GetSimpleRadii(devRRect).fX;
1446     float blurRadius = 3.f * SkScalarCeilToScalar(xformedSigma - 1 / 6.0f);
1447     SkRect proxyRect = devRRect.getBounds().makeOutset(blurRadius, blurRadius);
1448 
1449     return GrSkSLFP::Make(effect, "RRectBlur", /*inputFP=*/nullptr,
1450                           GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
1451                           "ninePatchFP", GrSkSLFP::IgnoreOptFlags(std::move(maskFP)),
1452                           "cornerRadius", cornerRadius,
1453                           "proxyRect", proxyRect,
1454                           "blurRadius", blurRadius);
1455 }
1456 
1457 ///////////////////////////////////////////////////////////////////////////////
1458 
directFilterMaskGPU(GrRecordingContext * context,skgpu::v1::SurfaceDrawContext * sdc,GrPaint && paint,const GrClip * clip,const SkMatrix & viewMatrix,const GrStyledShape & shape) const1459 bool SkBlurMaskFilterImpl::directFilterMaskGPU(GrRecordingContext* context,
1460                                                skgpu::v1::SurfaceDrawContext* sdc,
1461                                                GrPaint&& paint,
1462                                                const GrClip* clip,
1463                                                const SkMatrix& viewMatrix,
1464                                                const GrStyledShape& shape) const {
1465     SkASSERT(sdc);
1466 
1467     if (fBlurStyle != kNormal_SkBlurStyle) {
1468         return false;
1469     }
1470 
1471     // TODO: we could handle blurred stroked circles
1472     if (!shape.style().isSimpleFill()) {
1473         return false;
1474     }
1475 
1476     SkScalar xformedSigma = this->computeXformedSigma(viewMatrix);
1477     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma)) {
1478         sdc->drawShape(clip, std::move(paint), GrAA::kYes, viewMatrix, GrStyledShape(shape));
1479         return true;
1480     }
1481 
1482     SkRRect srcRRect;
1483     bool inverted;
1484     if (!shape.asRRect(&srcRRect, nullptr, nullptr, &inverted) || inverted) {
1485         return false;
1486     }
1487 
1488     std::unique_ptr<GrFragmentProcessor> fp;
1489 
1490     SkRRect devRRect;
1491     bool devRRectIsValid = srcRRect.transform(viewMatrix, &devRRect);
1492 
1493     bool devRRectIsCircle = devRRectIsValid && SkRRectPriv::IsCircle(devRRect);
1494 
1495     bool canBeRect = srcRRect.isRect() && viewMatrix.preservesRightAngles();
1496     bool canBeCircle = (SkRRectPriv::IsCircle(srcRRect) && viewMatrix.isSimilarity()) ||
1497                        devRRectIsCircle;
1498 
1499     if (canBeRect || canBeCircle) {
1500         if (canBeRect) {
1501             fp = make_rect_blur(context, *context->priv().caps()->shaderCaps(),
1502                                 srcRRect.rect(), viewMatrix, xformedSigma);
1503         } else {
1504             SkRect devBounds;
1505             if (devRRectIsCircle) {
1506                 devBounds = devRRect.getBounds();
1507             } else {
1508                 SkPoint center = {srcRRect.getBounds().centerX(), srcRRect.getBounds().centerY()};
1509                 viewMatrix.mapPoints(&center, 1);
1510                 SkScalar radius = viewMatrix.mapVector(0, srcRRect.width()/2.f).length();
1511                 devBounds = {center.x() - radius,
1512                              center.y() - radius,
1513                              center.x() + radius,
1514                              center.y() + radius};
1515             }
1516             fp = make_circle_blur(context, devBounds, xformedSigma);
1517         }
1518 
1519         if (!fp) {
1520             return false;
1521         }
1522 
1523         SkRect srcProxyRect = srcRRect.rect();
1524         // Determine how much to outset the src rect to ensure we hit pixels within three sigma.
1525         SkScalar outsetX = 3.0f*xformedSigma;
1526         SkScalar outsetY = 3.0f*xformedSigma;
1527         if (viewMatrix.isScaleTranslate()) {
1528             outsetX /= SkScalarAbs(viewMatrix.getScaleX());
1529             outsetY /= SkScalarAbs(viewMatrix.getScaleY());
1530         } else {
1531             SkSize scale;
1532             if (!viewMatrix.decomposeScale(&scale, nullptr)) {
1533                 return false;
1534             }
1535             outsetX /= scale.width();
1536             outsetY /= scale.height();
1537         }
1538         srcProxyRect.outset(outsetX, outsetY);
1539 
1540         paint.setCoverageFragmentProcessor(std::move(fp));
1541         sdc->drawRect(clip, std::move(paint), GrAA::kNo, viewMatrix, srcProxyRect);
1542         return true;
1543     }
1544     if (!viewMatrix.isScaleTranslate()) {
1545         return false;
1546     }
1547     if (!devRRectIsValid || !SkRRectPriv::AllCornersCircular(devRRect)) {
1548         return false;
1549     }
1550 
1551     fp = make_rrect_blur(context, fSigma, xformedSigma, srcRRect, devRRect);
1552     if (!fp) {
1553         return false;
1554     }
1555 
1556     if (!this->ignoreXform()) {
1557         SkRect srcProxyRect = srcRRect.rect();
1558         srcProxyRect.outset(3.0f*fSigma, 3.0f*fSigma);
1559         paint.setCoverageFragmentProcessor(std::move(fp));
1560         sdc->drawRect(clip, std::move(paint), GrAA::kNo, viewMatrix, srcProxyRect);
1561     } else {
1562         SkMatrix inverse;
1563         if (!viewMatrix.invert(&inverse)) {
1564             return false;
1565         }
1566 
1567         SkIRect proxyBounds;
1568         float extra=3.f*SkScalarCeilToScalar(xformedSigma-1/6.0f);
1569         devRRect.rect().makeOutset(extra, extra).roundOut(&proxyBounds);
1570 
1571         paint.setCoverageFragmentProcessor(std::move(fp));
1572         sdc->fillPixelsWithLocalMatrix(clip, std::move(paint), proxyBounds, inverse);
1573     }
1574 
1575     return true;
1576 }
1577 
canFilterMaskGPU(const GrStyledShape & shape,const SkIRect & devSpaceShapeBounds,const SkIRect & clipBounds,const SkMatrix & ctm,SkIRect * maskRect,const bool canUseSDFBlur) const1578 bool SkBlurMaskFilterImpl::canFilterMaskGPU(const GrStyledShape& shape,
1579                                             const SkIRect& devSpaceShapeBounds,
1580                                             const SkIRect& clipBounds,
1581                                             const SkMatrix& ctm,
1582                                             SkIRect* maskRect,
1583                                             const bool canUseSDFBlur) const {
1584     SkScalar xformedSigma = this->computeXformedSigma(ctm);
1585     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma)) {
1586         *maskRect = devSpaceShapeBounds;
1587         return maskRect->intersect(clipBounds);
1588     }
1589 
1590     if (maskRect) {
1591         float sigma3 = 3 * SkScalarToFloat(xformedSigma);
1592 
1593         // Outset srcRect and clipRect by 3 * sigma, to compute affected blur area.
1594         SkIRect clipRect = clipBounds.makeOutset(sigma3, sigma3);
1595         SkIRect srcRect = devSpaceShapeBounds.makeOutset(sigma3, sigma3);
1596 
1597         if (!canUseSDFBlur && !srcRect.intersect(clipRect)) {
1598             srcRect.setEmpty();
1599         }
1600         SkRRect srcRRect;
1601         bool inverted;
1602         if (canUseSDFBlur && shape.asRRect(&srcRRect, nullptr, nullptr, &inverted)) {
1603             SkScalar sx = ctm.getScaleX();
1604             SkScalar sy = ctm.getScaleY();
1605             float noxFormedSigma3 = this->getNoxFormedSigma3();
1606             int sigmaX = noxFormedSigma3 * sx;
1607             int sigmaY = noxFormedSigma3 * sy;
1608             srcRect = devSpaceShapeBounds.makeOutset(sigmaX, sigmaY);
1609             srcRect = SkIRect::MakeXYWH(srcRect.fLeft, srcRect.fTop,
1610                 srcRect.width() + srcRRect.rect().fLeft * sx,
1611                 srcRect.height() + srcRRect.rect().fTop * sy);
1612         }
1613         *maskRect = srcRect;
1614     }
1615 
1616     // We prefer to blur paths with small blur radii on the CPU.
1617     static const SkScalar kMIN_GPU_BLUR_SIZE  = SkIntToScalar(64);
1618     static const SkScalar kMIN_GPU_BLUR_SIGMA = SkIntToScalar(32);
1619 
1620     if (devSpaceShapeBounds.width() <= kMIN_GPU_BLUR_SIZE &&
1621         devSpaceShapeBounds.height() <= kMIN_GPU_BLUR_SIZE &&
1622         xformedSigma <= kMIN_GPU_BLUR_SIGMA) {
1623         return false;
1624     }
1625 
1626     return true;
1627 }
1628 
filterMaskGPU(GrRecordingContext * context,GrSurfaceProxyView srcView,GrColorType srcColorType,SkAlphaType srcAlphaType,const SkMatrix & ctm,const SkIRect & maskRect) const1629 GrSurfaceProxyView SkBlurMaskFilterImpl::filterMaskGPU(GrRecordingContext* context,
1630                                                        GrSurfaceProxyView srcView,
1631                                                        GrColorType srcColorType,
1632                                                        SkAlphaType srcAlphaType,
1633                                                        const SkMatrix& ctm,
1634                                                        const SkIRect& maskRect) const {
1635     // 'maskRect' isn't snapped to the UL corner but the mask in 'src' is.
1636     const SkIRect clipRect = SkIRect::MakeWH(maskRect.width(), maskRect.height());
1637 
1638     SkScalar xformedSigma = this->computeXformedSigma(ctm);
1639 
1640     // If we're doing a normal blur, we can clobber the pathTexture in the
1641     // gaussianBlur.  Otherwise, we need to save it for later compositing.
1642     bool isNormalBlur = (kNormal_SkBlurStyle == fBlurStyle);
1643     auto srcBounds = SkIRect::MakeSize(srcView.proxy()->dimensions());
1644     auto surfaceDrawContext = SkGpuBlurUtils::GaussianBlur(context,
1645                                                             srcView,
1646                                                             srcColorType,
1647                                                             srcAlphaType,
1648                                                             nullptr,
1649                                                             clipRect,
1650                                                             srcBounds,
1651                                                             xformedSigma,
1652                                                             xformedSigma,
1653                                                             SkTileMode::kClamp);
1654     if (!surfaceDrawContext || !surfaceDrawContext->asTextureProxy()) {
1655         return {};
1656     }
1657 
1658     if (!isNormalBlur) {
1659         GrPaint paint;
1660         // Blend pathTexture over blurTexture.
1661         paint.setCoverageFragmentProcessor(GrTextureEffect::Make(std::move(srcView), srcAlphaType));
1662         if (kInner_SkBlurStyle == fBlurStyle) {
1663             // inner:  dst = dst * src
1664             paint.setCoverageSetOpXPFactory(SkRegion::kIntersect_Op);
1665         } else if (kSolid_SkBlurStyle == fBlurStyle) {
1666             // solid:  dst = src + dst - src * dst
1667             //             = src + (1 - src) * dst
1668             paint.setCoverageSetOpXPFactory(SkRegion::kUnion_Op);
1669         } else if (kOuter_SkBlurStyle == fBlurStyle) {
1670             // outer:  dst = dst * (1 - src)
1671             //             = 0 * src + (1 - src) * dst
1672             paint.setCoverageSetOpXPFactory(SkRegion::kDifference_Op);
1673         } else {
1674             paint.setCoverageSetOpXPFactory(SkRegion::kReplace_Op);
1675         }
1676 
1677         surfaceDrawContext->fillPixelsWithLocalMatrix(nullptr, std::move(paint), clipRect,
1678                                                       SkMatrix::I());
1679     }
1680 
1681     return surfaceDrawContext->readSurfaceView();
1682 }
1683 
getNoxFormedSigma3() const1684 float SkBlurMaskFilterImpl::getNoxFormedSigma3() const
1685 {
1686     constexpr float kSigma_Factor = 3.f;
1687     return kSigma_Factor * fSigma;
1688 }
1689 
filterMaskGPUNoxFormed(GrRecordingContext * context,GrSurfaceProxyView srcView,GrColorType srcColorType,SkAlphaType srcAlphaType,const SkMatrix & viewMatrix,const SkIRect & maskRect,const SkRRect & srcRRect) const1690 GrSurfaceProxyView SkBlurMaskFilterImpl::filterMaskGPUNoxFormed(GrRecordingContext* context,
1691     GrSurfaceProxyView srcView, GrColorType srcColorType, SkAlphaType srcAlphaType, const SkMatrix& viewMatrix,
1692     const SkIRect& maskRect, const SkRRect& srcRRect) const
1693 {
1694     const SkIRect clipRect = SkIRect::MakeWH(maskRect.width(), maskRect.height());
1695 
1696     float noxFormedSigma = this->getNoxFormedSigma3();
1697 
1698     bool isNormalBlur = (kNormal_SkBlurStyle == fBlurStyle);
1699     if (!isNormalBlur) {
1700         return {};
1701     }
1702     auto srcBounds = SkIRect::MakeSize(srcView.proxy()->dimensions());
1703     auto surfaceDrawContext = SDFBlur::SDFBlur(context, srcView, srcColorType, srcAlphaType, nullptr,
1704         clipRect, srcBounds, noxFormedSigma, SkTileMode::kClamp, viewMatrix, srcRRect);
1705     if (!surfaceDrawContext || !surfaceDrawContext->asTextureProxy()) {
1706         return {};
1707     }
1708 
1709     return surfaceDrawContext->readSurfaceView();
1710 }
1711 
1712 #endif // SK_SUPPORT_GPU && SK_GPU_V1
1713 
sk_register_blur_maskfilter_createproc()1714 void sk_register_blur_maskfilter_createproc() { SK_REGISTER_FLATTENABLE(SkBlurMaskFilterImpl); }
1715 
MakeBlur(SkBlurStyle style,SkScalar sigma,bool respectCTM)1716 sk_sp<SkMaskFilter> SkMaskFilter::MakeBlur(SkBlurStyle style, SkScalar sigma, bool respectCTM) {
1717     if (SkScalarIsFinite(sigma) && sigma > 0) {
1718         return sk_sp<SkMaskFilter>(new SkBlurMaskFilterImpl(sigma, style, respectCTM));
1719     }
1720     return nullptr;
1721 }
1722