• 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/v1/Device_v1.h"
9 
10 #include "include/gpu/GrDirectContext.h"
11 #include "include/gpu/GrRecordingContext.h"
12 #include "include/private/SkTPin.h"
13 #include "src/core/SkDraw.h"
14 #include "src/core/SkImagePriv.h"
15 #include "src/core/SkMaskFilterBase.h"
16 #include "src/core/SkSpecialImage.h"
17 #include "src/gpu/GrBlurUtils.h"
18 #include "src/gpu/GrCaps.h"
19 #include "src/gpu/GrColorSpaceXform.h"
20 #include "src/gpu/GrOpsTypes.h"
21 #include "src/gpu/GrRecordingContextPriv.h"
22 #include "src/gpu/GrStyle.h"
23 #include "src/gpu/SkGr.h"
24 #include "src/gpu/effects/GrBicubicEffect.h"
25 #include "src/gpu/effects/GrBlendFragmentProcessor.h"
26 #include "src/gpu/effects/GrTextureEffect.h"
27 #include "src/gpu/geometry/GrRect.h"
28 #include "src/gpu/geometry/GrStyledShape.h"
29 #include "src/gpu/v1/SurfaceDrawContext_v1.h"
30 #include "src/image/SkImage_Base.h"
31 #include "src/image/SkImage_Gpu.h"
32 
33 namespace {
34 
use_shader(bool textureIsAlphaOnly,const SkPaint & paint)35 inline bool use_shader(bool textureIsAlphaOnly, const SkPaint& paint) {
36     return textureIsAlphaOnly && paint.getShader();
37 }
38 
39 //////////////////////////////////////////////////////////////////////////////
40 //  Helper functions for dropping src rect subset with GrSamplerState::Filter::kLinear.
41 
42 static const SkScalar kColorBleedTolerance = 0.001f;
43 
has_aligned_samples(const SkRect & srcRect,const SkRect & transformedRect)44 bool has_aligned_samples(const SkRect& srcRect, const SkRect& transformedRect) {
45     // detect pixel disalignment
46     if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) - transformedRect.left()) < kColorBleedTolerance &&
47         SkScalarAbs(SkScalarRoundToScalar(transformedRect.top())  - transformedRect.top())  < kColorBleedTolerance &&
48         SkScalarAbs(transformedRect.width()  - srcRect.width())  < kColorBleedTolerance &&
49         SkScalarAbs(transformedRect.height() - srcRect.height()) < kColorBleedTolerance) {
50         return true;
51     }
52     return false;
53 }
54 
may_color_bleed(const SkRect & srcRect,const SkRect & transformedRect,const SkMatrix & m,int numSamples)55 bool may_color_bleed(const SkRect& srcRect,
56                      const SkRect& transformedRect,
57                      const SkMatrix& m,
58                      int numSamples) {
59     // Only gets called if has_aligned_samples returned false.
60     // So we can assume that sampling is axis aligned but not texel aligned.
61     SkASSERT(!has_aligned_samples(srcRect, transformedRect));
62     SkRect innerSrcRect(srcRect), innerTransformedRect, outerTransformedRect(transformedRect);
63     if (numSamples > 1) {
64         innerSrcRect.inset(SK_Scalar1, SK_Scalar1);
65     } else {
66         innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
67     }
68     m.mapRect(&innerTransformedRect, innerSrcRect);
69 
70     // The gap between outerTransformedRect and innerTransformedRect
71     // represents the projection of the source border area, which is
72     // problematic for color bleeding.  We must check whether any
73     // destination pixels sample the border area.
74     outerTransformedRect.inset(kColorBleedTolerance, kColorBleedTolerance);
75     innerTransformedRect.outset(kColorBleedTolerance, kColorBleedTolerance);
76     SkIRect outer, inner;
77     outerTransformedRect.round(&outer);
78     innerTransformedRect.round(&inner);
79     // If the inner and outer rects round to the same result, it means the
80     // border does not overlap any pixel centers. Yay!
81     return inner != outer;
82 }
83 
can_ignore_linear_filtering_subset(const SkRect & srcSubset,const SkMatrix & srcRectToDeviceSpace,int numSamples)84 bool can_ignore_linear_filtering_subset(const SkRect& srcSubset,
85                                         const SkMatrix& srcRectToDeviceSpace,
86                                         int numSamples) {
87     if (srcRectToDeviceSpace.rectStaysRect()) {
88         // sampling is axis-aligned
89         SkRect transformedRect;
90         srcRectToDeviceSpace.mapRect(&transformedRect, srcSubset);
91 
92         if (has_aligned_samples(srcSubset, transformedRect) ||
93             !may_color_bleed(srcSubset, transformedRect, srcRectToDeviceSpace, numSamples)) {
94             return true;
95         }
96     }
97     return false;
98 }
99 
100 //////////////////////////////////////////////////////////////////////////////
101 //  Helper functions for tiling a large SkBitmap
102 
103 static const int kBmpSmallTileSize = 1 << 10;
104 
get_tile_count(const SkIRect & srcRect,int tileSize)105 inline int get_tile_count(const SkIRect& srcRect, int tileSize)  {
106     int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1;
107     int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1;
108     return tilesX * tilesY;
109 }
110 
determine_tile_size(const SkIRect & src,int maxTileSize)111 int determine_tile_size(const SkIRect& src, int maxTileSize) {
112     if (maxTileSize <= kBmpSmallTileSize) {
113         return maxTileSize;
114     }
115 
116     size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize);
117     size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize);
118 
119     maxTileTotalTileSize *= maxTileSize * maxTileSize;
120     smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize;
121 
122     if (maxTileTotalTileSize > 2 * smallTotalTileSize) {
123         return kBmpSmallTileSize;
124     } else {
125         return maxTileSize;
126     }
127 }
128 
129 // Given a bitmap, an optional src rect, and a context with a clip and matrix determine what
130 // pixels from the bitmap are necessary.
determine_clipped_src_rect(int width,int height,const GrClip * clip,const SkMatrix & viewMatrix,const SkMatrix & srcToDstRect,const SkISize & imageDimensions,const SkRect * srcRectPtr)131 SkIRect determine_clipped_src_rect(int width, int height,
132                                    const GrClip* clip,
133                                    const SkMatrix& viewMatrix,
134                                    const SkMatrix& srcToDstRect,
135                                    const SkISize& imageDimensions,
136                                    const SkRect* srcRectPtr) {
137     SkIRect clippedSrcIRect = clip ? clip->getConservativeBounds()
138                                    : SkIRect::MakeWH(width, height);
139     SkMatrix inv = SkMatrix::Concat(viewMatrix, srcToDstRect);
140     if (!inv.invert(&inv)) {
141         return SkIRect::MakeEmpty();
142     }
143     SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
144     inv.mapRect(&clippedSrcRect);
145     if (srcRectPtr) {
146         if (!clippedSrcRect.intersect(*srcRectPtr)) {
147             return SkIRect::MakeEmpty();
148         }
149     }
150     clippedSrcRect.roundOut(&clippedSrcIRect);
151     SkIRect bmpBounds = SkIRect::MakeSize(imageDimensions);
152     if (!clippedSrcIRect.intersect(bmpBounds)) {
153         return SkIRect::MakeEmpty();
154     }
155 
156     return clippedSrcIRect;
157 }
158 
159 // tileSize and clippedSubset are valid if true is returned
should_tile_image_id(GrRecordingContext * context,SkISize rtSize,const GrClip * clip,uint32_t imageID,const SkISize & imageSize,const SkMatrix & ctm,const SkMatrix & srcToDst,const SkRect * src,int maxTileSize,int * tileSize,SkIRect * clippedSubset)160 bool should_tile_image_id(GrRecordingContext* context,
161                           SkISize rtSize,
162                           const GrClip* clip,
163                           uint32_t imageID,
164                           const SkISize& imageSize,
165                           const SkMatrix& ctm,
166                           const SkMatrix& srcToDst,
167                           const SkRect* src,
168                           int maxTileSize,
169                           int* tileSize,
170                           SkIRect* clippedSubset) {
171     // if it's larger than the max tile size, then we have no choice but tiling.
172     if (imageSize.width() > maxTileSize || imageSize.height() > maxTileSize) {
173         *clippedSubset = determine_clipped_src_rect(rtSize.width(), rtSize.height(), clip, ctm,
174                                                     srcToDst, imageSize, src);
175         *tileSize = determine_tile_size(*clippedSubset, maxTileSize);
176         return true;
177     }
178 
179     // If the image would only produce 4 tiles of the smaller size, don't bother tiling it.
180     const size_t area = imageSize.width() * imageSize.height();
181     if (area < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
182         return false;
183     }
184 
185     // At this point we know we could do the draw by uploading the entire bitmap as a texture.
186     // However, if the texture would be large compared to the cache size and we don't require most
187     // of it for this draw then tile to reduce the amount of upload and cache spill.
188     // NOTE: if the context is not a direct context, it doesn't have access to the resource cache,
189     // and theoretically, the resource cache's limits could be being changed on another thread, so
190     // even having access to just the limit wouldn't be a reliable test during recording here.
191     // Instead, we will just upload the entire image to be on the safe side and not tile.
192     auto direct = context->asDirectContext();
193     if (!direct) {
194         return false;
195     }
196 
197     // assumption here is that sw bitmap size is a good proxy for its size as
198     // a texture
199     size_t bmpSize = area * sizeof(SkPMColor);  // assume 32bit pixels
200     size_t cacheSize = direct->getResourceCacheLimit();
201     if (bmpSize < cacheSize / 2) {
202         return false;
203     }
204 
205     // Figure out how much of the src we will need based on the src rect and clipping. Reject if
206     // tiling memory savings would be < 50%.
207     *clippedSubset = determine_clipped_src_rect(rtSize.width(), rtSize.height(), clip, ctm,
208                                                 srcToDst, imageSize, src);
209     *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
210     size_t usedTileBytes = get_tile_count(*clippedSubset, kBmpSmallTileSize) *
211                            kBmpSmallTileSize * kBmpSmallTileSize *
212                            sizeof(SkPMColor);  // assume 32bit pixels;
213 
214     return usedTileBytes * 2 < bmpSize;
215 }
216 
217 // This method outsets 'iRect' by 'outset' all around and then clamps its extents to
218 // 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
219 // of 'iRect' for all possible outsets/clamps.
clamped_outset_with_offset(SkIRect * iRect,int outset,SkPoint * offset,const SkIRect & clamp)220 inline void clamped_outset_with_offset(SkIRect* iRect, int outset, SkPoint* offset,
221                                        const SkIRect& clamp) {
222     iRect->outset(outset, outset);
223 
224     int leftClampDelta = clamp.fLeft - iRect->fLeft;
225     if (leftClampDelta > 0) {
226         offset->fX -= outset - leftClampDelta;
227         iRect->fLeft = clamp.fLeft;
228     } else {
229         offset->fX -= outset;
230     }
231 
232     int topClampDelta = clamp.fTop - iRect->fTop;
233     if (topClampDelta > 0) {
234         offset->fY -= outset - topClampDelta;
235         iRect->fTop = clamp.fTop;
236     } else {
237         offset->fY -= outset;
238     }
239 
240     if (iRect->fRight > clamp.fRight) {
241         iRect->fRight = clamp.fRight;
242     }
243     if (iRect->fBottom > clamp.fBottom) {
244         iRect->fBottom = clamp.fBottom;
245     }
246 }
247 
248 //////////////////////////////////////////////////////////////////////////////
249 //  Helper functions for drawing an image with v1::SurfaceDrawContext
250 
251 enum class ImageDrawMode {
252     // Src and dst have been restricted to the image content. May need to clamp, no need to decal.
253     kOptimized,
254     // Src and dst are their original sizes, requires use of a decal instead of plain clamping.
255     // This is used when a dst clip is provided and extends outside of the optimized dst rect.
256     kDecal,
257     // Src or dst are empty, or do not intersect the image content so don't draw anything.
258     kSkip
259 };
260 
261 /**
262  * Optimize the src rect sampling area within an image (sized 'width' x 'height') such that
263  * 'outSrcRect' will be completely contained in the image's bounds. The corresponding rect
264  * to draw will be output to 'outDstRect'. The mapping between src and dst will be cached in
265  * 'srcToDst'. Outputs are not always updated when kSkip is returned.
266  *
267  * If 'origSrcRect' is null, implicitly use the image bounds. If 'origDstRect' is null, use the
268  * original src rect. 'dstClip' should be null when there is no additional clipping.
269  */
optimize_sample_area(const SkISize & image,const SkRect * origSrcRect,const SkRect * origDstRect,const SkPoint dstClip[4],SkRect * outSrcRect,SkRect * outDstRect,SkMatrix * srcToDst)270 ImageDrawMode optimize_sample_area(const SkISize& image, const SkRect* origSrcRect,
271                                    const SkRect* origDstRect, const SkPoint dstClip[4],
272                                    SkRect* outSrcRect, SkRect* outDstRect,
273                                    SkMatrix* srcToDst) {
274     SkRect srcBounds = SkRect::MakeIWH(image.fWidth, image.fHeight);
275 
276     SkRect src = origSrcRect ? *origSrcRect : srcBounds;
277     SkRect dst = origDstRect ? *origDstRect : src;
278 
279     if (src.isEmpty() || dst.isEmpty()) {
280         return ImageDrawMode::kSkip;
281     }
282 
283     if (outDstRect) {
284         *srcToDst = SkMatrix::RectToRect(src, dst);
285     } else {
286         srcToDst->setIdentity();
287     }
288 
289     if (origSrcRect && !srcBounds.contains(src)) {
290         if (!src.intersect(srcBounds)) {
291             return ImageDrawMode::kSkip;
292         }
293         srcToDst->mapRect(&dst, src);
294 
295         // Both src and dst have gotten smaller. If dstClip is provided, confirm it is still
296         // contained in dst, otherwise cannot optimize the sample area and must use a decal instead
297         if (dstClip) {
298             for (int i = 0; i < 4; ++i) {
299                 if (!dst.contains(dstClip[i].fX, dstClip[i].fY)) {
300                     // Must resort to using a decal mode restricted to the clipped 'src', and
301                     // use the original dst rect (filling in src bounds as needed)
302                     *outSrcRect = src;
303                     *outDstRect = (origDstRect ? *origDstRect
304                                                : (origSrcRect ? *origSrcRect : srcBounds));
305                     return ImageDrawMode::kDecal;
306                 }
307             }
308         }
309     }
310 
311     // The original src and dst were fully contained in the image, or there was no dst clip to
312     // worry about, or the clip was still contained in the restricted dst rect.
313     *outSrcRect = src;
314     *outDstRect = dst;
315     return ImageDrawMode::kOptimized;
316 }
317 
318 /**
319  * Checks whether the paint is compatible with using SurfaceDrawContext::drawTexture. It is more
320  * efficient than the SkImage general case.
321  */
can_use_draw_texture(const SkPaint & paint,bool useCubicResampler,SkMipmapMode mm)322 bool can_use_draw_texture(const SkPaint& paint, bool useCubicResampler, SkMipmapMode mm) {
323     return (!paint.getColorFilter() && !paint.getShader() && !paint.getMaskFilter() &&
324             !paint.getImageFilter() && !paint.getBlender() && !useCubicResampler &&
325             mm == SkMipmapMode::kNone);
326 }
327 
texture_color(SkColor4f paintColor,float entryAlpha,GrColorType srcColorType,const GrColorInfo & dstColorInfo)328 SkPMColor4f texture_color(SkColor4f paintColor, float entryAlpha, GrColorType srcColorType,
329                           const GrColorInfo& dstColorInfo) {
330     paintColor.fA *= entryAlpha;
331     if (GrColorTypeIsAlphaOnly(srcColorType)) {
332         return SkColor4fPrepForDst(paintColor, dstColorInfo).premul();
333     } else {
334         float paintAlpha = SkTPin(paintColor.fA, 0.f, 1.f);
335         return { paintAlpha, paintAlpha, paintAlpha, paintAlpha };
336     }
337 }
338 
339 // Assumes srcRect and dstRect have already been optimized to fit the proxy
draw_texture(skgpu::v1::SurfaceDrawContext * sdc,const GrClip * clip,const SkMatrix & ctm,const SkPaint & paint,GrSamplerState::Filter filter,const SkRect & srcRect,const SkRect & dstRect,const SkPoint dstClip[4],GrAA aa,GrQuadAAFlags aaFlags,SkCanvas::SrcRectConstraint constraint,GrSurfaceProxyView view,const GrColorInfo & srcColorInfo,bool supportOpaqueOpt=false)340 void draw_texture(skgpu::v1::SurfaceDrawContext* sdc,
341                   const GrClip* clip,
342                   const SkMatrix& ctm,
343                   const SkPaint& paint,
344                   GrSamplerState::Filter filter,
345                   const SkRect& srcRect,
346                   const SkRect& dstRect,
347                   const SkPoint dstClip[4],
348                   GrAA aa,
349                   GrQuadAAFlags aaFlags,
350                   SkCanvas::SrcRectConstraint constraint,
351                   GrSurfaceProxyView view,
352 #ifdef SUPPORT_OPAQUE_OPTIMIZATION
353                   const GrColorInfo& srcColorInfo,
354                   bool supportOpaqueOpt = false) {
355 #else
356                   const GrColorInfo& srcColorInfo) {
357 #endif
358     if (GrColorTypeIsAlphaOnly(srcColorInfo.colorType())) {
359         view.concatSwizzle(GrSwizzle("aaaa"));
360     }
361     const GrColorInfo& dstInfo = sdc->colorInfo();
362     auto textureXform = GrColorSpaceXform::Make(srcColorInfo, sdc->colorInfo());
363     GrSurfaceProxy* proxy = view.proxy();
364     // Must specify the strict constraint when the proxy is not functionally exact and the src
365     // rect would access pixels outside the proxy's content area without the constraint.
366     if (constraint != SkCanvas::kStrict_SrcRectConstraint && !proxy->isFunctionallyExact()) {
367         // Conservative estimate of how much a coord could be outset from src rect:
368         // 1/2 pixel for AA and 1/2 pixel for linear filtering
369         float buffer = 0.5f * (aa == GrAA::kYes) +
370                        0.5f * (filter == GrSamplerState::Filter::kLinear);
371         SkRect safeBounds = proxy->getBoundsRect();
372         safeBounds.inset(buffer, buffer);
373         if (!safeBounds.contains(srcRect)) {
374             constraint = SkCanvas::kStrict_SrcRectConstraint;
375         }
376     }
377 
378     SkPMColor4f color = texture_color(paint.getColor4f(), 1.f, srcColorInfo.colorType(), dstInfo);
379     if (dstClip) {
380         // Get source coords corresponding to dstClip
381         SkPoint srcQuad[4];
382         GrMapRectPoints(dstRect, srcRect, dstClip, srcQuad, 4);
383 
384         sdc->drawTextureQuad(clip,
385                              std::move(view),
386                              srcColorInfo.colorType(),
387                              srcColorInfo.alphaType(),
388                              filter,
389                              GrSamplerState::MipmapMode::kNone,
390                              paint.getBlendMode_or(SkBlendMode::kSrcOver),
391                              color,
392                              srcQuad,
393                              dstClip,
394                              aa,
395                              aaFlags,
396                              constraint == SkCanvas::kStrict_SrcRectConstraint ? &srcRect : nullptr,
397                              ctm,
398 #ifdef SUPPORT_OPAQUE_OPTIMIZATION
399                              std::move(textureXform),
400                              supportOpaqueOpt);
401 #else
402                              std::move(textureXform));
403 #endif
404     } else {
405         sdc->drawTexture(clip,
406                          std::move(view),
407                          srcColorInfo.alphaType(),
408                          filter,
409                          GrSamplerState::MipmapMode::kNone,
410                          paint.getBlendMode_or(SkBlendMode::kSrcOver),
411                          color,
412                          srcRect,
413                          dstRect,
414                          aa,
415                          aaFlags,
416                          constraint,
417                          ctm,
418 #ifdef SUPPORT_OPAQUE_OPTIMIZATION
419                          std::move(textureXform),
420                          supportOpaqueOpt);
421 #else
422                          std::move(textureXform));
423 #endif
424     }
425 }
426 
427 // Assumes srcRect and dstRect have already been optimized to fit the proxy.
428 void draw_image(GrRecordingContext* rContext,
429                 skgpu::v1::SurfaceDrawContext* sdc,
430                 const GrClip* clip,
431                 const SkMatrixProvider& matrixProvider,
432                 const SkPaint& paint,
433                 const SkImage_Base& image,
434                 const SkRect& src,
435                 const SkRect& dst,
436                 const SkPoint dstClip[4],
437                 const SkMatrix& srcToDst,
438                 GrAA aa,
439                 GrQuadAAFlags aaFlags,
440                 SkCanvas::SrcRectConstraint constraint,
441                 SkSamplingOptions sampling,
442                 SkTileMode tm = SkTileMode::kClamp) {
443     const SkMatrix& ctm(matrixProvider.localToDevice());
444     if (tm == SkTileMode::kClamp &&
445         !image.isYUVA()          &&
446         can_use_draw_texture(paint, sampling.useCubic, sampling.mipmap)) {
447         // We've done enough checks above to allow us to pass ClampNearest() and not check for
448         // scaling adjustments.
449         auto [view, ct] = image.asView(rContext, GrMipmapped::kNo);
450         if (!view) {
451             return;
452         }
453         GrColorInfo info(image.imageInfo().colorInfo());
454         info = info.makeColorType(ct);
455         draw_texture(sdc,
456                      clip,
457                      ctm,
458                      paint,
459                      sampling.filter,
460                      src,
461                      dst,
462                      dstClip,
463                      aa,
464                      aaFlags,
465                      constraint,
466                      std::move(view),
467 #ifdef SUPPORT_OPAQUE_OPTIMIZATION
468                      info,
469                      image.getSupportOpaqueOpt());
470 #else
471                      info);
472 #endif
473         return;
474     }
475 
476     const SkMaskFilter* mf = paint.getMaskFilter();
477 
478     // The shader expects proper local coords, so we can't replace local coords with texture coords
479     // if the shader will be used. If we have a mask filter we will change the underlying geometry
480     // that is rendered.
481     bool canUseTextureCoordsAsLocalCoords = !use_shader(image.isAlphaOnly(), paint) && !mf;
482 
483     // Specifying the texture coords as local coordinates is an attempt to enable more GrDrawOp
484     // combining by not baking anything about the srcRect, dstRect, or ctm, into the texture
485     // FP. In the future this should be an opaque optimization enabled by the combination of
486     // GrDrawOp/GP and FP.
487     if (mf && as_MFB(mf)->hasFragmentProcessor()) {
488         mf = nullptr;
489     }
490 
491     bool restrictToSubset = SkCanvas::kStrict_SrcRectConstraint == constraint;
492 
493     // If we have to outset for AA then we will generate texture coords outside the src rect. The
494     // same happens for any mask filter that extends the bounds rendered in the dst.
495     // This is conservative as a mask filter does not have to expand the bounds rendered.
496     bool coordsAllInsideSrcRect = aaFlags == GrQuadAAFlags::kNone && !mf;
497 
498     // Check for optimization to drop the src rect constraint when using linear filtering.
499     // TODO: Just rely on image to handle this.
500     if (!sampling.useCubic                       &&
501         sampling.filter == SkFilterMode::kLinear &&
502         restrictToSubset                         &&
503         sampling.mipmap == SkMipmapMode::kNone   &&
504         coordsAllInsideSrcRect                   &&
505         !image.isYUVA()) {
506         SkMatrix combinedMatrix;
507         combinedMatrix.setConcat(ctm, srcToDst);
508         if (can_ignore_linear_filtering_subset(src, combinedMatrix, sdc->numSamples())) {
509             restrictToSubset = false;
510         }
511     }
512 
513     SkMatrix textureMatrix;
514     if (canUseTextureCoordsAsLocalCoords) {
515         textureMatrix = SkMatrix::I();
516     } else {
517         if (!srcToDst.invert(&textureMatrix)) {
518             return;
519         }
520     }
521     const SkRect* subset = restrictToSubset       ? &src : nullptr;
522     const SkRect* domain = coordsAllInsideSrcRect ? &src : nullptr;
523     SkTileMode tileModes[] = {tm, tm};
524     std::unique_ptr<GrFragmentProcessor> fp = image.asFragmentProcessor(rContext,
525                                                                         sampling,
526                                                                         tileModes,
527                                                                         textureMatrix,
528                                                                         subset,
529                                                                         domain);
530     fp = GrColorSpaceXformEffect::Make(std::move(fp),
531                                        image.imageInfo().colorInfo(),
532                                        sdc->colorInfo());
533     if (image.isAlphaOnly()) {
534         if (const auto* shader = as_SB(paint.getShader())) {
535             auto shaderFP = shader->asFragmentProcessor(
536                     GrFPArgs(rContext, matrixProvider, &sdc->colorInfo()));
537             if (!shaderFP) {
538                 return;
539             }
540             fp = GrBlendFragmentProcessor::Make(
541                     std::move(fp), std::move(shaderFP), SkBlendMode::kDstIn);
542         } else {
543             // Multiply the input (paint) color by the texture (alpha)
544             fp = GrFragmentProcessor::MulInputByChildAlpha(std::move(fp));
545         }
546     }
547 
548     GrPaint grPaint;
549     if (!SkPaintToGrPaintReplaceShader(
550                 rContext, sdc->colorInfo(), paint, matrixProvider, std::move(fp), &grPaint)) {
551         return;
552     }
553 
554     if (!mf) {
555         // Can draw the image directly (any mask filter on the paint was converted to an FP already)
556         if (dstClip) {
557             SkPoint srcClipPoints[4];
558             SkPoint* srcClip = nullptr;
559             if (canUseTextureCoordsAsLocalCoords) {
560                 // Calculate texture coordinates that match the dst clip
561                 GrMapRectPoints(dst, src, dstClip, srcClipPoints, 4);
562                 srcClip = srcClipPoints;
563             }
564             sdc->fillQuadWithEdgeAA(clip, std::move(grPaint), aa, aaFlags, ctm, dstClip, srcClip);
565         } else {
566             // Provide explicit texture coords when possible, otherwise rely on texture matrix
567             sdc->fillRectWithEdgeAA(clip, std::move(grPaint), aa, aaFlags, ctm, dst,
568                                     canUseTextureCoordsAsLocalCoords ? &src : nullptr);
569         }
570     } else {
571         // Must draw the mask filter as a GrStyledShape. For now, this loses the per-edge AA
572         // information since it always draws with AA, but that should not be noticeable since the
573         // mask filter is probably a blur.
574         GrStyledShape shape;
575         if (dstClip) {
576             // Represent it as an SkPath formed from the dstClip
577             SkPath path;
578             path.addPoly(dstClip, 4, true);
579             shape = GrStyledShape(path);
580         } else {
581             shape = GrStyledShape(dst);
582         }
583 
584         GrBlurUtils::drawShapeWithMaskFilter(
585                 rContext, sdc, clip, shape, std::move(grPaint), ctm, mf);
586     }
587 }
588 
589 void draw_tiled_bitmap(GrRecordingContext* rContext,
590                        skgpu::v1::SurfaceDrawContext* sdc,
591                        const GrClip* clip,
592                        const SkBitmap& bitmap,
593                        int tileSize,
594                        const SkMatrixProvider& matrixProvider,
595                        const SkMatrix& srcToDst,
596                        const SkRect& srcRect,
597                        const SkIRect& clippedSrcIRect,
598                        const SkPaint& paint,
599                        GrAA aa,
600                        SkCanvas::SrcRectConstraint constraint,
601                        SkSamplingOptions sampling,
602                        SkTileMode tileMode) {
603     SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
604 
605     int nx = bitmap.width() / tileSize;
606     int ny = bitmap.height() / tileSize;
607 
608     for (int x = 0; x <= nx; x++) {
609         for (int y = 0; y <= ny; y++) {
610             SkRect tileR;
611             tileR.setLTRB(SkIntToScalar(x * tileSize),       SkIntToScalar(y * tileSize),
612                           SkIntToScalar((x + 1) * tileSize), SkIntToScalar((y + 1) * tileSize));
613 
614             if (!SkRect::Intersects(tileR, clippedSrcRect)) {
615                 continue;
616             }
617 
618             if (!tileR.intersect(srcRect)) {
619                 continue;
620             }
621 
622             SkIRect iTileR;
623             tileR.roundOut(&iTileR);
624             SkVector offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
625                                             SkIntToScalar(iTileR.fTop));
626             SkRect rectToDraw = tileR;
627             srcToDst.mapRect(&rectToDraw);
628             if (sampling.filter != SkFilterMode::kNearest || sampling.useCubic) {
629                 SkIRect iClampRect;
630 
631                 if (SkCanvas::kFast_SrcRectConstraint == constraint) {
632                     // In bleed mode we want to always expand the tile on all edges
633                     // but stay within the bitmap bounds
634                     iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height());
635                 } else {
636                     // In texture-domain/clamp mode we only want to expand the
637                     // tile on edges interior to "srcRect" (i.e., we want to
638                     // not bleed across the original clamped edges)
639                     srcRect.roundOut(&iClampRect);
640                 }
641                 int outset = sampling.useCubic ? GrBicubicEffect::kFilterTexelPad : 1;
642                 clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect);
643             }
644 
645             // We must subset as a bitmap and then turn into an SkImage if we want caching to work.
646             // Image subsets always make a copy of the pixels and lose the association with the
647             // original's SkPixelRef.
648             if (SkBitmap subsetBmp; bitmap.extractSubset(&subsetBmp, iTileR)) {
649                 auto image = SkMakeImageFromRasterBitmap(subsetBmp, kNever_SkCopyPixelsMode);
650                 // We should have already handled bitmaps larger than the max texture size.
651                 SkASSERT(image->width()  <= rContext->priv().caps()->maxTextureSize() &&
652                          image->height() <= rContext->priv().caps()->maxTextureSize());
653 
654                 GrQuadAAFlags aaFlags = GrQuadAAFlags::kNone;
655                 if (aa == GrAA::kYes) {
656                     // If the entire bitmap was anti-aliased, turn on AA for the outside tile edges.
657                     if (tileR.fLeft <= srcRect.fLeft) {
658                         aaFlags |= GrQuadAAFlags::kLeft;
659                     }
660                     if (tileR.fRight >= srcRect.fRight) {
661                         aaFlags |= GrQuadAAFlags::kRight;
662                     }
663                     if (tileR.fTop <= srcRect.fTop) {
664                         aaFlags |= GrQuadAAFlags::kTop;
665                     }
666                     if (tileR.fBottom >= srcRect.fBottom) {
667                         aaFlags |= GrQuadAAFlags::kBottom;
668                     }
669                 }
670 
671                 // now offset it to make it "local" to our tmp bitmap
672                 tileR.offset(-offset.fX, -offset.fY);
673                 SkMatrix offsetSrcToDst = srcToDst;
674                 offsetSrcToDst.preTranslate(offset.fX, offset.fY);
675                 draw_image(rContext,
676                            sdc,
677                            clip,
678                            matrixProvider,
679                            paint,
680                            *as_IB(image.get()),
681                            tileR,
682                            rectToDraw,
683                            nullptr,
684                            offsetSrcToDst,
685                            aa,
686                            aaFlags,
687                            constraint,
688                            sampling,
689                            tileMode);
690             }
691         }
692     }
693 }
694 
695 SkFilterMode downgrade_to_filter(const SkSamplingOptions& sampling) {
696     SkFilterMode filter = sampling.filter;
697     if (sampling.useCubic || sampling.mipmap != SkMipmapMode::kNone) {
698         // if we were "fancier" than just bilerp, only do bilerp
699         filter = SkFilterMode::kLinear;
700     }
701     return filter;
702 }
703 
704 bool can_disable_mipmap(const SkMatrix& viewM,
705                         const SkMatrix& localM,
706                         bool sharpenMipmappedTextures) {
707     SkMatrix matrix;
708     matrix.setConcat(viewM, localM);
709     // With sharp mips, we bias lookups by -0.5. That means our final LOD is >= 0 until
710     // the computed LOD is >= 0.5. At what scale factor does a texture get an LOD of
711     // 0.5?
712     //
713     // Want:  0       = log2(1/s) - 0.5
714     //        0.5     = log2(1/s)
715     //        2^0.5   = 1/s
716     //        1/2^0.5 = s
717     //        2^0.5/2 = s
718     SkScalar mipScale = sharpenMipmappedTextures ? SK_ScalarRoot2Over2 : SK_Scalar1;
719     return matrix.getMinScale() >= mipScale;
720 }
721 
722 } // anonymous namespace
723 
724 //////////////////////////////////////////////////////////////////////////////
725 
726 namespace skgpu::v1 {
727 
drawSpecial(SkSpecialImage * special,const SkMatrix & localToDevice,const SkSamplingOptions & origSampling,const SkPaint & paint)728 void Device::drawSpecial(SkSpecialImage* special,
729                          const SkMatrix& localToDevice,
730                          const SkSamplingOptions& origSampling,
731                          const SkPaint& paint) {
732     SkASSERT(!paint.getMaskFilter() && !paint.getImageFilter());
733     SkASSERT(special->isTextureBacked());
734 
735     SkRect src = SkRect::Make(special->subset());
736     SkRect dst = SkRect::MakeWH(special->width(), special->height());
737     SkMatrix srcToDst = SkMatrix::RectToRect(src, dst);
738 
739     SkSamplingOptions sampling = SkSamplingOptions(downgrade_to_filter(origSampling));
740     GrAA aa = fSurfaceDrawContext->chooseAA(paint);
741     GrQuadAAFlags aaFlags = (aa == GrAA::kYes) ? GrQuadAAFlags::kAll : GrQuadAAFlags::kNone;
742 
743     SkColorInfo colorInfo(special->colorType(),
744                           special->alphaType(),
745                           sk_ref_sp(special->getColorSpace()));
746 
747     GrSurfaceProxyView view = special->view(this->recordingContext());
748     SkImage_Gpu image(sk_ref_sp(special->getContext()),
749                       special->uniqueID(),
750                       std::move(view),
751                       std::move(colorInfo));
752     // In most cases this ought to hit draw_texture since there won't be a color filter,
753     // alpha-only texture+shader, or a high filter quality.
754     SkOverrideDeviceMatrixProvider matrixProvider(this->asMatrixProvider(), localToDevice);
755     draw_image(fContext.get(),
756                fSurfaceDrawContext.get(),
757                this->clip(),
758                matrixProvider,
759                paint,
760                image,
761                src,
762                dst,
763                nullptr,
764                srcToDst,
765                aa,
766                aaFlags,
767                SkCanvas::kStrict_SrcRectConstraint,
768                sampling);
769 }
770 
drawImageQuad(const SkImage * image,const SkRect * srcRect,const SkRect * dstRect,const SkPoint dstClip[4],GrAA aa,GrQuadAAFlags aaFlags,const SkMatrix * preViewMatrix,const SkSamplingOptions & origSampling,const SkPaint & paint,SkCanvas::SrcRectConstraint constraint)771 void Device::drawImageQuad(const SkImage* image,
772                            const SkRect* srcRect,
773                            const SkRect* dstRect,
774                            const SkPoint dstClip[4],
775                            GrAA aa,
776                            GrQuadAAFlags aaFlags,
777                            const SkMatrix* preViewMatrix,
778                            const SkSamplingOptions& origSampling,
779                            const SkPaint& paint,
780                            SkCanvas::SrcRectConstraint constraint) {
781     SkRect src;
782     SkRect dst;
783     SkMatrix srcToDst;
784     ImageDrawMode mode = optimize_sample_area(SkISize::Make(image->width(), image->height()),
785                                               srcRect, dstRect, dstClip, &src, &dst, &srcToDst);
786     if (mode == ImageDrawMode::kSkip) {
787         return;
788     }
789 
790     // OH ISSUE: restricting the drawing of abnormal processes
791     if (fContext->isPidAbnormal()) {
792         return;
793     }
794 
795     if (src.contains(image->bounds())) {
796         constraint = SkCanvas::kFast_SrcRectConstraint;
797     }
798     // Depending on the nature of image, it can flow through more or less optimal pipelines
799     SkTileMode tileMode = mode == ImageDrawMode::kDecal ? SkTileMode::kDecal : SkTileMode::kClamp;
800 
801     // Get final CTM matrix
802     SkPreConcatMatrixProvider matrixProvider(this->asMatrixProvider(),
803                                              preViewMatrix ? *preViewMatrix : SkMatrix::I());
804     const SkMatrix& ctm(matrixProvider.localToDevice());
805 
806     SkSamplingOptions sampling = origSampling;
807     bool sharpenMM = fContext->priv().options().fSharpenMipmappedTextures;
808     if (sampling.mipmap != SkMipmapMode::kNone && can_disable_mipmap(ctm, srcToDst, sharpenMM)) {
809         sampling = SkSamplingOptions(sampling.filter);
810     }
811     auto clip = this->clip();
812 
813     if (!image->isTextureBacked() && !as_IB(image)->isPinnedOnContext(fContext.get())) {
814         int tileFilterPad;
815         if (sampling.useCubic) {
816             tileFilterPad = GrBicubicEffect::kFilterTexelPad;
817         } else if (sampling.filter == SkFilterMode::kNearest) {
818             tileFilterPad = 0;
819         } else {
820             tileFilterPad = 1;
821         }
822         int maxTileSize = fContext->priv().caps()->maxTextureSize() - 2*tileFilterPad;
823         int tileSize;
824         SkIRect clippedSubset;
825         if (should_tile_image_id(fContext.get(),
826                                  fSurfaceDrawContext->dimensions(),
827                                  clip,
828                                  image->unique(),
829                                  image->dimensions(),
830                                  ctm,
831                                  srcToDst,
832                                  &src,
833                                  maxTileSize,
834                                  &tileSize,
835                                  &clippedSubset)) {
836             // Extract pixels on the CPU, since we have to split into separate textures before
837             // sending to the GPU if tiling.
838             if (SkBitmap bm; as_IB(image)->getROPixels(nullptr, &bm)) {
839                 // This is the funnel for all paths that draw tiled bitmaps/images.
840                 draw_tiled_bitmap(fContext.get(),
841                                   fSurfaceDrawContext.get(),
842                                   clip,
843                                   bm,
844                                   tileSize,
845                                   matrixProvider,
846                                   srcToDst,
847                                   src,
848                                   clippedSubset,
849                                   paint,
850                                   aa,
851                                   constraint,
852                                   sampling,
853                                   tileMode);
854                 return;
855             }
856         }
857     }
858 
859     draw_image(fContext.get(),
860                fSurfaceDrawContext.get(),
861                clip,
862                matrixProvider,
863                paint,
864                *as_IB(image),
865                src,
866                dst,
867                dstClip,
868                srcToDst,
869                aa,
870                aaFlags,
871                constraint,
872                sampling);
873     return;
874 }
875 
drawEdgeAAImageSet(const SkCanvas::ImageSetEntry set[],int count,const SkPoint dstClips[],const SkMatrix preViewMatrices[],const SkSamplingOptions & sampling,const SkPaint & paint,SkCanvas::SrcRectConstraint constraint)876 void Device::drawEdgeAAImageSet(const SkCanvas::ImageSetEntry set[], int count,
877                                 const SkPoint dstClips[], const SkMatrix preViewMatrices[],
878                                 const SkSamplingOptions& sampling, const SkPaint& paint,
879                                 SkCanvas::SrcRectConstraint constraint) {
880     SkASSERT(count > 0);
881     if (!can_use_draw_texture(paint, sampling.useCubic, sampling.mipmap)) {
882         // Send every entry through drawImageQuad() to handle the more complicated paint
883         int dstClipIndex = 0;
884         for (int i = 0; i < count; ++i) {
885             // Only no clip or quad clip are supported
886             SkASSERT(!set[i].fHasClip || dstClips);
887             SkASSERT(set[i].fMatrixIndex < 0 || preViewMatrices);
888 
889             SkTCopyOnFirstWrite<SkPaint> entryPaint(paint);
890             if (set[i].fAlpha != 1.f) {
891                 auto paintAlpha = paint.getAlphaf();
892                 entryPaint.writable()->setAlphaf(paintAlpha * set[i].fAlpha);
893             }
894             // Always send GrAA::kYes to preserve seaming across tiling in MSAA
895             this->drawImageQuad(
896                     set[i].fImage.get(), &set[i].fSrcRect, &set[i].fDstRect,
897                     set[i].fHasClip ? dstClips + dstClipIndex : nullptr, GrAA::kYes,
898                     SkToGrQuadAAFlags(set[i].fAAFlags),
899                     set[i].fMatrixIndex < 0 ? nullptr : preViewMatrices + set[i].fMatrixIndex,
900                     sampling, *entryPaint, constraint);
901             dstClipIndex += 4 * set[i].fHasClip;
902         }
903         return;
904     }
905 
906     GrSamplerState::Filter filter = sampling.filter == SkFilterMode::kNearest
907                                             ? GrSamplerState::Filter::kNearest
908                                             : GrSamplerState::Filter::kLinear;
909     SkBlendMode mode = paint.getBlendMode_or(SkBlendMode::kSrcOver);
910 
911     SkAutoTArray<GrTextureSetEntry> textures(count);
912     // We accumulate compatible proxies until we find an an incompatible one or reach the end and
913     // issue the accumulated 'n' draws starting at 'base'. 'p' represents the number of proxy
914     // switches that occur within the 'n' entries.
915     int base = 0, n = 0, p = 0;
916     auto draw = [&](int nextBase) {
917         if (n > 0) {
918             auto textureXform = GrColorSpaceXform::Make(set[base].fImage->imageInfo().colorInfo(),
919                                                         fSurfaceDrawContext->colorInfo());
920             fSurfaceDrawContext->drawTextureSet(this->clip(),
921                                                 textures.get() + base,
922                                                 n,
923                                                 p,
924                                                 filter,
925                                                 GrSamplerState::MipmapMode::kNone,
926                                                 mode,
927                                                 GrAA::kYes,
928                                                 constraint,
929                                                 this->localToDevice(),
930                                                 std::move(textureXform));
931         }
932         base = nextBase;
933         n = 0;
934         p = 0;
935     };
936     int dstClipIndex = 0;
937     for (int i = 0; i < count; ++i) {
938         SkASSERT(!set[i].fHasClip || dstClips);
939         SkASSERT(set[i].fMatrixIndex < 0 || preViewMatrices);
940 
941         // Manage the dst clip pointer tracking before any continues are used so we don't lose
942         // our place in the dstClips array.
943         const SkPoint* clip = set[i].fHasClip ? dstClips + dstClipIndex : nullptr;
944         dstClipIndex += 4 * set[i].fHasClip;
945 
946         // The default SkBaseDevice implementation is based on drawImageRect which does not allow
947         // non-sorted src rects. TODO: Decide this is OK or make sure we handle it.
948         if (!set[i].fSrcRect.isSorted()) {
949             draw(i + 1);
950             continue;
951         }
952 
953         GrSurfaceProxyView view;
954         const SkImage_Base* image = as_IB(set[i].fImage.get());
955         // Extract view from image, but skip YUV images so they get processed through
956         // drawImageQuad and the proper effect to dynamically sample their planes.
957         if (!image->isYUVA()) {
958             std::tie(view, std::ignore) = image->asView(this->recordingContext(), GrMipmapped::kNo);
959             if (image->isAlphaOnly()) {
960                 GrSwizzle swizzle = GrSwizzle::Concat(view.swizzle(), GrSwizzle("aaaa"));
961                 view = {view.detachProxy(), view.origin(), swizzle};
962             }
963         }
964 
965         if (!view) {
966             // This image can't go through the texture op, send through general image pipeline
967             // after flushing current batch.
968             draw(i + 1);
969             SkTCopyOnFirstWrite<SkPaint> entryPaint(paint);
970             if (set[i].fAlpha != 1.f) {
971                 auto paintAlpha = paint.getAlphaf();
972                 entryPaint.writable()->setAlphaf(paintAlpha * set[i].fAlpha);
973             }
974             this->drawImageQuad(
975                     image, &set[i].fSrcRect, &set[i].fDstRect, clip, GrAA::kYes,
976                     SkToGrQuadAAFlags(set[i].fAAFlags),
977                     set[i].fMatrixIndex < 0 ? nullptr : preViewMatrices + set[i].fMatrixIndex,
978                     sampling, *entryPaint, constraint);
979             continue;
980         }
981 
982         textures[i].fProxyView = std::move(view);
983         textures[i].fSrcAlphaType = image->alphaType();
984         textures[i].fSrcRect = set[i].fSrcRect;
985         textures[i].fDstRect = set[i].fDstRect;
986         textures[i].fDstClipQuad = clip;
987         textures[i].fPreViewMatrix =
988                 set[i].fMatrixIndex < 0 ? nullptr : preViewMatrices + set[i].fMatrixIndex;
989         textures[i].fColor = texture_color(paint.getColor4f(), set[i].fAlpha,
990                                            SkColorTypeToGrColorType(image->colorType()),
991                                            fSurfaceDrawContext->colorInfo());
992         textures[i].fAAFlags = SkToGrQuadAAFlags(set[i].fAAFlags);
993 
994         if (n > 0 &&
995             (!GrTextureProxy::ProxiesAreCompatibleAsDynamicState(
996                     textures[i].fProxyView.proxy(),
997                     textures[base].fProxyView.proxy()) ||
998              textures[i].fProxyView.swizzle() != textures[base].fProxyView.swizzle() ||
999              set[i].fImage->alphaType() != set[base].fImage->alphaType() ||
1000              !SkColorSpace::Equals(set[i].fImage->colorSpace(), set[base].fImage->colorSpace()))) {
1001             draw(i);
1002         }
1003         // Whether or not we submitted a draw in the above if(), this ith entry is in the current
1004         // set being accumulated so increment n, and increment p if proxies are different.
1005         ++n;
1006         if (n == 1 || textures[i - 1].fProxyView.proxy() != textures[i].fProxyView.proxy()) {
1007             // First proxy or a different proxy (that is compatible, otherwise we'd have drawn up
1008             // to i - 1).
1009             ++p;
1010         }
1011     }
1012     draw(count);
1013 }
1014 
1015 } // namespace skgpu::v1
1016