• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "src/gpu/GrBlurUtils.h"
9 
10 #include "include/private/GrRecordingContext.h"
11 #include "src/gpu/GrBitmapTextureMaker.h"
12 #include "src/gpu/GrCaps.h"
13 #include "src/gpu/GrFixedClip.h"
14 #include "src/gpu/GrProxyProvider.h"
15 #include "src/gpu/GrRecordingContextPriv.h"
16 #include "src/gpu/GrRenderTargetContext.h"
17 #include "src/gpu/GrRenderTargetContextPriv.h"
18 #include "src/gpu/GrSoftwarePathRenderer.h"
19 #include "src/gpu/GrStyle.h"
20 #include "src/gpu/GrTextureProxy.h"
21 #include "src/gpu/effects/GrTextureEffect.h"
22 #include "src/gpu/geometry/GrShape.h"
23 
24 #include "include/core/SkPaint.h"
25 #include "src/core/SkDraw.h"
26 #include "src/core/SkMaskFilterBase.h"
27 #include "src/core/SkTLazy.h"
28 #include "src/gpu/SkGr.h"
29 
clip_bounds_quick_reject(const SkIRect & clipBounds,const SkIRect & rect)30 static bool clip_bounds_quick_reject(const SkIRect& clipBounds, const SkIRect& rect) {
31     return clipBounds.isEmpty() || rect.isEmpty() || !SkIRect::Intersects(clipBounds, rect);
32 }
33 
34 // Draw a mask using the supplied paint. Since the coverage/geometry
35 // is already burnt into the mask this boils down to a rect draw.
36 // Return true if the mask was successfully drawn.
draw_mask(GrRenderTargetContext * renderTargetContext,const GrClip & clip,const SkMatrix & viewMatrix,const SkIRect & maskRect,GrPaint && paint,GrSurfaceProxyView mask)37 static bool draw_mask(GrRenderTargetContext* renderTargetContext,
38                       const GrClip& clip,
39                       const SkMatrix& viewMatrix,
40                       const SkIRect& maskRect,
41                       GrPaint&& paint,
42                       GrSurfaceProxyView mask) {
43     SkMatrix inverse;
44     if (!viewMatrix.invert(&inverse)) {
45         return false;
46     }
47 
48     SkMatrix matrix = SkMatrix::MakeTrans(-SkIntToScalar(maskRect.fLeft),
49                                           -SkIntToScalar(maskRect.fTop));
50     matrix.preConcat(viewMatrix);
51     paint.addCoverageFragmentProcessor(
52             GrTextureEffect::Make(std::move(mask), kUnknown_SkAlphaType, matrix));
53 
54     renderTargetContext->fillRectWithLocalMatrix(clip, std::move(paint), GrAA::kNo, SkMatrix::I(),
55                                                  SkRect::Make(maskRect), inverse);
56     return true;
57 }
58 
mask_release_proc(void * addr,void *)59 static void mask_release_proc(void* addr, void* /*context*/) {
60     SkMask::FreeImage(addr);
61 }
62 
sw_draw_with_mask_filter(GrRecordingContext * context,GrRenderTargetContext * renderTargetContext,const GrClip & clipData,const SkMatrix & viewMatrix,const GrShape & shape,const SkMaskFilter * filter,const SkIRect & clipBounds,GrPaint && paint,const GrUniqueKey & key)63 static bool sw_draw_with_mask_filter(GrRecordingContext* context,
64                                      GrRenderTargetContext* renderTargetContext,
65                                      const GrClip& clipData,
66                                      const SkMatrix& viewMatrix,
67                                      const GrShape& shape,
68                                      const SkMaskFilter* filter,
69                                      const SkIRect& clipBounds,
70                                      GrPaint&& paint,
71                                      const GrUniqueKey& key) {
72     SkASSERT(filter);
73     SkASSERT(!shape.style().applies());
74 
75     auto proxyProvider = context->priv().proxyProvider();
76 
77     GrSurfaceProxyView filteredMaskView;
78 
79     SkStrokeRec::InitStyle fillOrHairline = shape.style().isSimpleHairline()
80                                                     ? SkStrokeRec::kHairline_InitStyle
81                                                     : SkStrokeRec::kFill_InitStyle;
82 
83     if (key.isValid()) {
84         // TODO: this cache look up is duplicated in draw_shape_with_mask_filter for gpu
85         static const GrSurfaceOrigin kCacheOrigin = kTopLeft_GrSurfaceOrigin;
86         auto filteredMask = proxyProvider->findOrCreateProxyByUniqueKey(key, GrColorType::kAlpha_8);
87         if (filteredMask) {
88             GrSwizzle swizzle = context->priv().caps()->getReadSwizzle(
89                     filteredMask->backendFormat(), GrColorType::kAlpha_8);
90             filteredMaskView = GrSurfaceProxyView(std::move(filteredMask), kCacheOrigin, swizzle);
91         }
92     }
93 
94     SkIRect drawRect;
95     if (filteredMaskView.proxy()) {
96         SkRect devBounds = shape.bounds();
97         viewMatrix.mapRect(&devBounds);
98 
99         // Here we need to recompute the destination bounds in order to draw the mask correctly
100         SkMask srcM, dstM;
101         if (!SkDraw::ComputeMaskBounds(devBounds, &clipBounds, filter, &viewMatrix,
102                                        &srcM.fBounds)) {
103             return false;
104         }
105 
106         srcM.fFormat = SkMask::kA8_Format;
107 
108         if (!as_MFB(filter)->filterMask(&dstM, srcM, viewMatrix, nullptr)) {
109             return false;
110         }
111 
112         // Unfortunately, we cannot double check that the computed bounds (i.e., dstM.fBounds)
113         // match the stored bounds of the mask bc the proxy may have been recreated and,
114         // when it is recreated, it just gets the bounds of the underlying GrTexture (which
115         // might be a loose fit).
116         drawRect = dstM.fBounds;
117     } else {
118         // TODO: it seems like we could create an SkDraw here and set its fMatrix field rather
119         // than explicitly transforming the path to device space.
120         SkPath devPath;
121 
122         shape.asPath(&devPath);
123 
124         devPath.transform(viewMatrix);
125 
126         SkMask srcM, dstM;
127         if (!SkDraw::DrawToMask(devPath, &clipBounds, filter, &viewMatrix, &srcM,
128                                 SkMask::kComputeBoundsAndRenderImage_CreateMode, fillOrHairline)) {
129             return false;
130         }
131         SkAutoMaskFreeImage autoSrc(srcM.fImage);
132 
133         SkASSERT(SkMask::kA8_Format == srcM.fFormat);
134 
135         if (!as_MFB(filter)->filterMask(&dstM, srcM, viewMatrix, nullptr)) {
136             return false;
137         }
138         // this will free-up dstM when we're done (allocated in filterMask())
139         SkAutoMaskFreeImage autoDst(dstM.fImage);
140 
141         if (clip_bounds_quick_reject(clipBounds, dstM.fBounds)) {
142             return false;
143         }
144 
145         // we now have a device-aligned 8bit mask in dstM, ready to be drawn using
146         // the current clip (and identity matrix) and GrPaint settings
147         SkBitmap bm;
148         if (!bm.installPixels(SkImageInfo::MakeA8(dstM.fBounds.width(), dstM.fBounds.height()),
149                               autoDst.release(), dstM.fRowBytes, mask_release_proc, nullptr)) {
150             return false;
151         }
152         bm.setImmutable();
153 
154         GrBitmapTextureMaker maker(context, bm, GrBitmapTextureMaker::Cached::kNo,
155                                    SkBackingFit::kApprox);
156         std::tie(filteredMaskView, std::ignore) = maker.view(GrMipMapped::kNo);
157         if (!filteredMaskView.proxy()) {
158             return false;
159         }
160 
161         SkASSERT(kTopLeft_GrSurfaceOrigin == filteredMaskView.origin());
162 
163         drawRect = dstM.fBounds;
164 
165         if (key.isValid()) {
166             proxyProvider->assignUniqueKeyToProxy(key, filteredMaskView.asTextureProxy());
167         }
168     }
169 
170     return draw_mask(renderTargetContext, clipData, viewMatrix, drawRect, std::move(paint),
171                      std::move(filteredMaskView));
172 }
173 
174 // Create a mask of 'shape' and return the resulting renderTargetContext
create_mask_GPU(GrRecordingContext * context,const SkIRect & maskRect,const SkMatrix & origViewMatrix,const GrShape & shape,int sampleCnt)175 static std::unique_ptr<GrRenderTargetContext> create_mask_GPU(GrRecordingContext* context,
176                                                               const SkIRect& maskRect,
177                                                               const SkMatrix& origViewMatrix,
178                                                               const GrShape& shape,
179                                                               int sampleCnt) {
180     // Use GrResourceProvider::MakeApprox to implement our own approximate size matching, but demand
181     // a "SkBackingFit::kExact" size match on the actual render target. We do this because the
182     // filter will reach outside the src bounds, so we need to pre-clear these values to ensure a
183     // "decal" sampling effect (i.e., ensure reads outside the src bounds return alpha=0).
184     //
185     // FIXME: Reads outside the left and top edges will actually clamp to the edge pixel. And in the
186     // event that MakeApprox does not change the size, reads outside the right and/or bottom will do
187     // the same. We should offset our filter within the render target and expand the size as needed
188     // to guarantee at least 1px of padding on all sides.
189     auto approxSize = GrResourceProvider::MakeApprox(maskRect.size());
190     auto rtContext = GrRenderTargetContext::MakeWithFallback(
191             context, GrColorType::kAlpha_8, nullptr, SkBackingFit::kExact, approxSize, sampleCnt,
192             GrMipMapped::kNo, GrProtected::kNo, kTopLeft_GrSurfaceOrigin);
193     if (!rtContext) {
194         return nullptr;
195     }
196 
197     rtContext->clear(SK_PMColor4fTRANSPARENT);
198 
199     GrPaint maskPaint;
200     maskPaint.setCoverageSetOpXPFactory(SkRegion::kReplace_Op);
201 
202     // setup new clip
203     const SkIRect clipRect = SkIRect::MakeWH(maskRect.width(), maskRect.height());
204     GrFixedClip clip(clipRect);
205 
206     // Draw the mask into maskTexture with the path's integerized top-left at
207     // the origin using maskPaint.
208     SkMatrix viewMatrix = origViewMatrix;
209     viewMatrix.postTranslate(-SkIntToScalar(maskRect.fLeft), -SkIntToScalar(maskRect.fTop));
210     rtContext->drawShape(clip, std::move(maskPaint), GrAA::kYes, viewMatrix, shape);
211     return rtContext;
212 }
213 
get_unclipped_shape_dev_bounds(const GrShape & shape,const SkMatrix & matrix,SkIRect * devBounds)214 static bool get_unclipped_shape_dev_bounds(const GrShape& shape, const SkMatrix& matrix,
215                                            SkIRect* devBounds) {
216     SkRect shapeBounds = shape.styledBounds();
217     if (shapeBounds.isEmpty()) {
218         return false;
219     }
220     SkRect shapeDevBounds;
221     matrix.mapRect(&shapeDevBounds, shapeBounds);
222     // Even though these are "unclipped" bounds we still clip to the int32_t range.
223     // This is the largest int32_t that is representable exactly as a float. The next 63 larger ints
224     // would round down to this value when cast to a float, but who really cares.
225     // INT32_MIN is exactly representable.
226     static constexpr int32_t kMaxInt = 2147483520;
227     if (!shapeDevBounds.intersect(SkRect::MakeLTRB(INT32_MIN, INT32_MIN, kMaxInt, kMaxInt))) {
228         return false;
229     }
230     // Make sure that the resulting SkIRect can have representable width and height
231     if (SkScalarRoundToInt(shapeDevBounds.width()) > kMaxInt ||
232         SkScalarRoundToInt(shapeDevBounds.height()) > kMaxInt) {
233         return false;
234     }
235     shapeDevBounds.roundOut(devBounds);
236     return true;
237 }
238 
239 // Gets the shape bounds, the clip bounds, and the intersection (if any). Returns false if there
240 // is no intersection.
get_shape_and_clip_bounds(GrRenderTargetContext * renderTargetContext,const GrClip & clip,const GrShape & shape,const SkMatrix & matrix,SkIRect * unclippedDevShapeBounds,SkIRect * devClipBounds)241 static bool get_shape_and_clip_bounds(GrRenderTargetContext* renderTargetContext,
242                                       const GrClip& clip,
243                                       const GrShape& shape,
244                                       const SkMatrix& matrix,
245                                       SkIRect* unclippedDevShapeBounds,
246                                       SkIRect* devClipBounds) {
247     // compute bounds as intersection of rt size, clip, and path
248     clip.getConservativeBounds(renderTargetContext->width(),
249                                renderTargetContext->height(),
250                                devClipBounds);
251 
252     if (!get_unclipped_shape_dev_bounds(shape, matrix, unclippedDevShapeBounds)) {
253         *unclippedDevShapeBounds = SkIRect::MakeEmpty();
254         return false;
255     }
256 
257     return true;
258 }
259 
draw_shape_with_mask_filter(GrRecordingContext * context,GrRenderTargetContext * renderTargetContext,const GrClip & clip,GrPaint && paint,const SkMatrix & viewMatrix,const SkMaskFilterBase * maskFilter,const GrShape & origShape)260 static void draw_shape_with_mask_filter(GrRecordingContext* context,
261                                         GrRenderTargetContext* renderTargetContext,
262                                         const GrClip& clip,
263                                         GrPaint&& paint,
264                                         const SkMatrix& viewMatrix,
265                                         const SkMaskFilterBase* maskFilter,
266                                         const GrShape& origShape) {
267     SkASSERT(maskFilter);
268 
269     const GrShape* shape = &origShape;
270     SkTLazy<GrShape> tmpShape;
271 
272     if (origShape.style().applies()) {
273         SkScalar styleScale =  GrStyle::MatrixToScaleFactor(viewMatrix);
274         if (0 == styleScale) {
275             return;
276         }
277 
278         tmpShape.init(origShape.applyStyle(GrStyle::Apply::kPathEffectAndStrokeRec, styleScale));
279         if (tmpShape.get()->isEmpty()) {
280             return;
281         }
282 
283         shape = tmpShape.get();
284     }
285 
286     if (maskFilter->directFilterMaskGPU(context,
287                                         renderTargetContext,
288                                         std::move(paint),
289                                         clip,
290                                         viewMatrix,
291                                         *shape)) {
292         // the mask filter was able to draw itself directly, so there's nothing
293         // left to do.
294         return;
295     }
296     assert_alive(paint);
297 
298     // If the path is hairline, ignore inverse fill.
299     bool inverseFilled = shape->inverseFilled() &&
300                          !GrPathRenderer::IsStrokeHairlineOrEquivalent(shape->style(),
301                                                                        viewMatrix, nullptr);
302 
303     SkIRect unclippedDevShapeBounds, devClipBounds;
304     if (!get_shape_and_clip_bounds(renderTargetContext, clip, *shape, viewMatrix,
305                                    &unclippedDevShapeBounds,
306                                    &devClipBounds)) {
307         // TODO: just cons up an opaque mask here
308         if (!inverseFilled) {
309             return;
310         }
311     }
312 
313     // To prevent overloading the cache with entries during animations we limit the cache of masks
314     // to cases where the matrix preserves axis alignment.
315 #ifdef SK_DISABLE_MASKFILTERED_MASK_CACHING
316     bool useCache = false;
317 #else
318     bool useCache = !inverseFilled && viewMatrix.preservesAxisAlignment() &&
319                     shape->hasUnstyledKey() && as_MFB(maskFilter)->asABlur(nullptr);
320 #endif
321 
322     const SkIRect* boundsForClip = &devClipBounds;
323     if (useCache) {
324         SkIRect clippedMaskRect, unClippedMaskRect;
325         maskFilter->canFilterMaskGPU(*shape, unclippedDevShapeBounds, devClipBounds,
326                                      viewMatrix, &clippedMaskRect);
327         maskFilter->canFilterMaskGPU(*shape, unclippedDevShapeBounds, unclippedDevShapeBounds,
328                                      viewMatrix, &unClippedMaskRect);
329         if (clippedMaskRect.isEmpty()) {
330             return;
331         }
332 
333         // Use the cache only if >50% of the filtered mask is visible.
334         int unclippedWidth = unClippedMaskRect.width();
335         int unclippedHeight = unClippedMaskRect.height();
336         int64_t unclippedArea = sk_64_mul(unclippedWidth, unclippedHeight);
337         int64_t clippedArea = sk_64_mul(clippedMaskRect.width(), clippedMaskRect.height());
338         int maxTextureSize = renderTargetContext->caps()->maxTextureSize();
339         if (unclippedArea > 2 * clippedArea || unclippedWidth > maxTextureSize ||
340             unclippedHeight > maxTextureSize) {
341             useCache = false;
342         } else {
343             // Make the clip not affect the mask
344             boundsForClip = &unclippedDevShapeBounds;
345         }
346     }
347 
348     GrUniqueKey maskKey;
349     if (useCache) {
350         static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
351         GrUniqueKey::Builder builder(&maskKey, kDomain, 5 + 2 + shape->unstyledKeySize(),
352                                      "Mask Filtered Masks");
353 
354         // We require the upper left 2x2 of the matrix to match exactly for a cache hit.
355         SkScalar sx = viewMatrix.get(SkMatrix::kMScaleX);
356         SkScalar sy = viewMatrix.get(SkMatrix::kMScaleY);
357         SkScalar kx = viewMatrix.get(SkMatrix::kMSkewX);
358         SkScalar ky = viewMatrix.get(SkMatrix::kMSkewY);
359         SkScalar tx = viewMatrix.get(SkMatrix::kMTransX);
360         SkScalar ty = viewMatrix.get(SkMatrix::kMTransY);
361         // Allow 8 bits each in x and y of subpixel positioning.
362         SkFixed fracX = SkScalarToFixed(SkScalarFraction(tx)) & 0x0000FF00;
363         SkFixed fracY = SkScalarToFixed(SkScalarFraction(ty)) & 0x0000FF00;
364 
365         builder[0] = SkFloat2Bits(sx);
366         builder[1] = SkFloat2Bits(sy);
367         builder[2] = SkFloat2Bits(kx);
368         builder[3] = SkFloat2Bits(ky);
369         // Distinguish between hairline and filled paths. For hairlines, we also need to include
370         // the cap. (SW grows hairlines by 0.5 pixel with round and square caps). Note that
371         // stroke-and-fill of hairlines is turned into pure fill by SkStrokeRec, so this covers
372         // all cases we might see.
373         uint32_t styleBits = shape->style().isSimpleHairline()
374                                     ? ((shape->style().strokeRec().getCap() << 1) | 1)
375                                     : 0;
376         builder[4] = fracX | (fracY >> 8) | (styleBits << 16);
377 
378         SkMaskFilterBase::BlurRec rec;
379         SkAssertResult(as_MFB(maskFilter)->asABlur(&rec));
380 
381         builder[5] = rec.fStyle;  // TODO: we could put this with the other style bits
382         builder[6] = SkFloat2Bits(rec.fSigma);
383         shape->writeUnstyledKey(&builder[7]);
384     }
385 
386     SkIRect maskRect;
387     if (maskFilter->canFilterMaskGPU(*shape,
388                                      unclippedDevShapeBounds,
389                                      *boundsForClip,
390                                      viewMatrix,
391                                      &maskRect)) {
392         if (clip_bounds_quick_reject(*boundsForClip, maskRect)) {
393             // clipped out
394             return;
395         }
396 
397         GrSurfaceProxyView filteredMaskView;
398 
399         GrProxyProvider* proxyProvider = context->priv().proxyProvider();
400 
401         if (maskKey.isValid()) {
402             // TODO: this cache look up is duplicated in sw_draw_with_mask_filter for raster
403             static const GrSurfaceOrigin kCacheOrigin = kTopLeft_GrSurfaceOrigin;
404             auto filteredMask =
405                     proxyProvider->findOrCreateProxyByUniqueKey(maskKey, GrColorType::kAlpha_8);
406             if (filteredMask) {
407                 GrSwizzle swizzle = context->priv().caps()->getReadSwizzle(
408                         filteredMask->backendFormat(), GrColorType::kAlpha_8);
409                 filteredMaskView = GrSurfaceProxyView(std::move(filteredMask), kCacheOrigin,
410                                                       swizzle);
411             }
412         }
413 
414         if (!filteredMaskView.proxy()) {
415             std::unique_ptr<GrRenderTargetContext> maskRTC(create_mask_GPU(
416                                                            context,
417                                                            maskRect,
418                                                            viewMatrix,
419                                                            *shape,
420                                                            renderTargetContext->numSamples()));
421             if (maskRTC) {
422                 filteredMaskView = maskFilter->filterMaskGPU(context,
423                                                              maskRTC->readSurfaceView(),
424                                                              maskRTC->colorInfo().colorType(),
425                                                              maskRTC->colorInfo().alphaType(),
426                                                              viewMatrix,
427                                                              maskRect);
428                 if (filteredMaskView.proxy() && maskKey.isValid()) {
429                     SkASSERT(filteredMaskView.asTextureProxy());
430                     proxyProvider->assignUniqueKeyToProxy(maskKey,
431                                                           filteredMaskView.asTextureProxy());
432                 }
433             }
434         }
435 
436         if (filteredMaskView.proxy()) {
437             if (draw_mask(renderTargetContext, clip, viewMatrix, maskRect, std::move(paint),
438                           std::move(filteredMaskView))) {
439                 // This path is completely drawn
440                 return;
441             }
442             assert_alive(paint);
443         }
444     }
445 
446     sw_draw_with_mask_filter(context, renderTargetContext, clip, viewMatrix, *shape,
447                              maskFilter, *boundsForClip, std::move(paint), maskKey);
448 }
449 
drawShapeWithMaskFilter(GrRecordingContext * context,GrRenderTargetContext * renderTargetContext,const GrClip & clip,const GrShape & shape,GrPaint && paint,const SkMatrix & viewMatrix,const SkMaskFilter * mf)450 void GrBlurUtils::drawShapeWithMaskFilter(GrRecordingContext* context,
451                                           GrRenderTargetContext* renderTargetContext,
452                                           const GrClip& clip,
453                                           const GrShape& shape,
454                                           GrPaint&& paint,
455                                           const SkMatrix& viewMatrix,
456                                           const SkMaskFilter* mf) {
457     draw_shape_with_mask_filter(context, renderTargetContext, clip, std::move(paint),
458                                 viewMatrix, as_MFB(mf), shape);
459 }
460 
drawShapeWithMaskFilter(GrRecordingContext * context,GrRenderTargetContext * renderTargetContext,const GrClip & clip,const SkPaint & paint,const SkMatrix & viewMatrix,const GrShape & shape)461 void GrBlurUtils::drawShapeWithMaskFilter(GrRecordingContext* context,
462                                           GrRenderTargetContext* renderTargetContext,
463                                           const GrClip& clip,
464                                           const SkPaint& paint,
465                                           const SkMatrix& viewMatrix,
466                                           const GrShape& shape) {
467     if (context->priv().abandoned()) {
468         return;
469     }
470 
471     GrPaint grPaint;
472     if (!SkPaintToGrPaint(context, renderTargetContext->colorInfo(), paint, viewMatrix, &grPaint)) {
473         return;
474     }
475 
476     SkMaskFilterBase* mf = as_MFB(paint.getMaskFilter());
477     if (mf && !mf->hasFragmentProcessor()) {
478         // The MaskFilter wasn't already handled in SkPaintToGrPaint
479         draw_shape_with_mask_filter(context, renderTargetContext, clip, std::move(grPaint),
480                                     viewMatrix, mf, shape);
481     } else {
482         GrAA aa = GrAA(paint.isAntiAlias());
483         renderTargetContext->drawShape(clip, std::move(grPaint), aa, viewMatrix, shape);
484     }
485 }
486