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