• 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/ganesh/SurfaceDrawContext.h"
9 
10 #include "include/core/SkColorSpace.h"
11 #include "include/core/SkDrawable.h"
12 #include "include/core/SkTypes.h"
13 #include "include/core/SkVertices.h"
14 #include "include/gpu/GrBackendSemaphore.h"
15 #include "include/gpu/GrDirectContext.h"
16 #include "include/gpu/GrRecordingContext.h"
17 #include "include/private/SkShadowFlags.h"
18 #include "include/private/gpu/ganesh/GrImageContext.h"
19 #include "include/utils/SkShadowUtils.h"
20 #include "src/base/SkVx.h"
21 #include "src/core/SkAutoPixmapStorage.h"
22 #include "src/core/SkBlendModePriv.h"
23 #include "src/core/SkConvertPixels.h"
24 #include "src/core/SkDrawProcs.h"
25 #include "src/core/SkDrawShadowInfo.h"
26 #include "src/core/SkLatticeIter.h"
27 #include "src/core/SkMatrixPriv.h"
28 #include "src/core/SkMatrixProvider.h"
29 #include "src/core/SkMeshPriv.h"
30 #include "src/core/SkPointPriv.h"
31 #include "src/core/SkRRectPriv.h"
32 #include "src/core/SkStrikeCache.h"
33 #include "src/gpu/ganesh/GrAppliedClip.h"
34 #include "src/gpu/ganesh/GrAttachment.h"
35 #include "src/gpu/ganesh/GrCaps.h"
36 #include "src/gpu/ganesh/GrClip.h"
37 #include "src/gpu/ganesh/GrColor.h"
38 #include "src/gpu/ganesh/GrColorSpaceXform.h"
39 #include "src/gpu/ganesh/GrDataUtils.h"
40 #include "src/gpu/ganesh/GrDirectContextPriv.h"
41 #include "src/gpu/ganesh/GrDrawingManager.h"
42 #include "src/gpu/ganesh/GrGpuResourcePriv.h"
43 #include "src/gpu/ganesh/GrImageContextPriv.h"
44 #include "src/gpu/ganesh/GrImageInfo.h"
45 #include "src/gpu/ganesh/GrMemoryPool.h"
46 #include "src/gpu/ganesh/GrProxyProvider.h"
47 #include "src/gpu/ganesh/GrRenderTarget.h"
48 #include "src/gpu/ganesh/GrResourceProvider.h"
49 #include "src/gpu/ganesh/GrSemaphore.h"
50 #include "src/gpu/ganesh/GrStencilSettings.h"
51 #include "src/gpu/ganesh/GrStyle.h"
52 #include "src/gpu/ganesh/GrTracing.h"
53 #include "src/gpu/ganesh/PathRenderer.h"
54 #include "src/gpu/ganesh/SkGr.h"
55 #include "src/gpu/ganesh/effects/GrBicubicEffect.h"
56 #include "src/gpu/ganesh/effects/GrBlendFragmentProcessor.h"
57 #include "src/gpu/ganesh/effects/GrDisableColorXP.h"
58 #include "src/gpu/ganesh/effects/GrTextureEffect.h"
59 #include "src/gpu/ganesh/geometry/GrQuad.h"
60 #include "src/gpu/ganesh/geometry/GrQuadUtils.h"
61 #include "src/gpu/ganesh/geometry/GrStyledShape.h"
62 #include "src/gpu/ganesh/ops/ClearOp.h"
63 #include "src/gpu/ganesh/ops/DrawAtlasOp.h"
64 #include "src/gpu/ganesh/ops/DrawMeshOp.h"
65 #include "src/gpu/ganesh/ops/DrawableOp.h"
66 #include "src/gpu/ganesh/ops/FillRRectOp.h"
67 #include "src/gpu/ganesh/ops/FillRectOp.h"
68 #include "src/gpu/ganesh/ops/GrDrawOp.h"
69 #include "src/gpu/ganesh/ops/GrOp.h"
70 #include "src/gpu/ganesh/ops/GrOvalOpFactory.h"
71 #include "src/gpu/ganesh/ops/LatticeOp.h"
72 #include "src/gpu/ganesh/ops/RegionOp.h"
73 #include "src/gpu/ganesh/ops/ShadowRRectOp.h"
74 #include "src/gpu/ganesh/ops/StrokeRectOp.h"
75 #include "src/gpu/ganesh/ops/TextureOp.h"
76 #include "src/text/gpu/SDFTControl.h"
77 #include "src/text/gpu/TextBlobRedrawCoordinator.h"
78 
79 #define ASSERT_OWNED_RESOURCE(R) SkASSERT(!(R) || (R)->getContext() == this->drawingManager()->getContext())
80 #define ASSERT_SINGLE_OWNER        SKGPU_ASSERT_SINGLE_OWNER(this->singleOwner())
81 #define RETURN_IF_ABANDONED        if (fContext->abandoned()) { return; }
82 #define RETURN_FALSE_IF_ABANDONED  if (fContext->abandoned()) { return false; }
83 
84 //////////////////////////////////////////////////////////////////////////////
85 
86 namespace {
87 
op_bounds(SkRect * bounds,const GrOp * op)88 void op_bounds(SkRect* bounds, const GrOp* op) {
89     *bounds = op->bounds();
90     if (op->hasZeroArea()) {
91         if (op->hasAABloat()) {
92             bounds->outset(0.5f, 0.5f);
93         } else {
94             // We don't know which way the particular GPU will snap lines or points at integer
95             // coords. So we ensure that the bounds is large enough for either snap.
96             SkRect before = *bounds;
97             bounds->roundOut(bounds);
98             if (bounds->fLeft == before.fLeft) {
99                 bounds->fLeft -= 1;
100             }
101             if (bounds->fTop == before.fTop) {
102                 bounds->fTop -= 1;
103             }
104             if (bounds->fRight == before.fRight) {
105                 bounds->fRight += 1;
106             }
107             if (bounds->fBottom == before.fBottom) {
108                 bounds->fBottom += 1;
109             }
110         }
111     }
112 }
113 
114 } // anonymous namespace
115 
116 namespace skgpu::v1 {
117 
118 using DoSimplify = GrStyledShape::DoSimplify;
119 
120 class AutoCheckFlush {
121 public:
AutoCheckFlush(GrDrawingManager * drawingManager)122     AutoCheckFlush(GrDrawingManager* drawingManager) : fDrawingManager(drawingManager) {
123         SkASSERT(fDrawingManager);
124     }
~AutoCheckFlush()125     ~AutoCheckFlush() { fDrawingManager->flushIfNecessary(); }
126 
127 private:
128     GrDrawingManager* fDrawingManager;
129 };
130 
Make(GrRecordingContext * rContext,GrColorType colorType,sk_sp<GrSurfaceProxy> proxy,sk_sp<SkColorSpace> colorSpace,GrSurfaceOrigin origin,const SkSurfaceProps & surfaceProps)131 std::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::Make(GrRecordingContext* rContext,
132                                                              GrColorType colorType,
133                                                              sk_sp<GrSurfaceProxy> proxy,
134                                                              sk_sp<SkColorSpace> colorSpace,
135                                                              GrSurfaceOrigin origin,
136                                                              const SkSurfaceProps& surfaceProps) {
137     if (!rContext || !proxy || colorType == GrColorType::kUnknown) {
138         return nullptr;
139     }
140 
141     const GrBackendFormat& format = proxy->backendFormat();
142     skgpu::Swizzle readSwizzle = rContext->priv().caps()->getReadSwizzle(format, colorType);
143     skgpu::Swizzle writeSwizzle = rContext->priv().caps()->getWriteSwizzle(format, colorType);
144 
145     GrSurfaceProxyView readView (          proxy,  origin, readSwizzle);
146     GrSurfaceProxyView writeView(std::move(proxy), origin, writeSwizzle);
147 
148     return std::make_unique<SurfaceDrawContext>(rContext,
149                                                 std::move(readView),
150                                                 std::move(writeView),
151                                                 colorType,
152                                                 std::move(colorSpace),
153                                                 surfaceProps);
154 }
155 
Make(GrRecordingContext * rContext,sk_sp<SkColorSpace> colorSpace,SkBackingFit fit,SkISize dimensions,const GrBackendFormat & format,int sampleCnt,GrMipmapped mipmapped,GrProtected isProtected,skgpu::Swizzle readSwizzle,skgpu::Swizzle writeSwizzle,GrSurfaceOrigin origin,skgpu::Budgeted budgeted,const SkSurfaceProps & surfaceProps,std::string_view label)156 std::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::Make(GrRecordingContext* rContext,
157                                                              sk_sp<SkColorSpace> colorSpace,
158                                                              SkBackingFit fit,
159                                                              SkISize dimensions,
160                                                              const GrBackendFormat& format,
161                                                              int sampleCnt,
162                                                              GrMipmapped mipmapped,
163                                                              GrProtected isProtected,
164                                                              skgpu::Swizzle readSwizzle,
165                                                              skgpu::Swizzle writeSwizzle,
166                                                              GrSurfaceOrigin origin,
167                                                              skgpu::Budgeted budgeted,
168                                                              const SkSurfaceProps& surfaceProps,
169                                                              std::string_view label) {
170     // It is probably not necessary to check if the context is abandoned here since uses of the
171     // SurfaceDrawContext which need the context will mostly likely fail later on without an
172     // issue. However having this hear adds some reassurance in case there is a path doesn't handle
173     // an abandoned context correctly. It also lets us early out of some extra work.
174     if (rContext->abandoned()) {
175         return nullptr;
176     }
177 
178     sk_sp<GrTextureProxy> proxy = rContext->priv().proxyProvider()->createProxy(
179             format,
180             dimensions,
181             GrRenderable::kYes,
182             sampleCnt,
183             mipmapped,
184             fit,
185             budgeted,
186             isProtected,
187             label);
188     if (!proxy) {
189         return nullptr;
190     }
191 
192     GrSurfaceProxyView readView (           proxy, origin,  readSwizzle);
193     GrSurfaceProxyView writeView(std::move(proxy), origin, writeSwizzle);
194 
195     auto sdc = std::make_unique<SurfaceDrawContext>(rContext,
196                                                     std::move(readView),
197                                                     std::move(writeView),
198                                                     GrColorType::kUnknown,
199                                                     std::move(colorSpace),
200                                                     surfaceProps);
201     sdc->discard();
202     return sdc;
203 }
204 
Make(GrRecordingContext * rContext,GrColorType colorType,sk_sp<SkColorSpace> colorSpace,SkBackingFit fit,SkISize dimensions,const SkSurfaceProps & surfaceProps,std::string_view label,int sampleCnt,GrMipmapped mipmapped,GrProtected isProtected,GrSurfaceOrigin origin,skgpu::Budgeted budgeted)205 std::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::Make(GrRecordingContext* rContext,
206                                                              GrColorType colorType,
207                                                              sk_sp<SkColorSpace> colorSpace,
208                                                              SkBackingFit fit,
209                                                              SkISize dimensions,
210                                                              const SkSurfaceProps& surfaceProps,
211                                                              std::string_view label,
212                                                              int sampleCnt,
213                                                              GrMipmapped mipmapped,
214                                                              GrProtected isProtected,
215                                                              GrSurfaceOrigin origin,
216                                                              skgpu::Budgeted budgeted) {
217     if (!rContext) {
218         return nullptr;
219     }
220 
221     auto format = rContext->priv().caps()->getDefaultBackendFormat(colorType, GrRenderable::kYes);
222     if (!format.isValid()) {
223         return nullptr;
224     }
225     sk_sp<GrTextureProxy> proxy = rContext->priv().proxyProvider()->createProxy(
226             format,
227             dimensions,
228             GrRenderable::kYes,
229             sampleCnt,
230             mipmapped,
231             fit,
232             budgeted,
233             isProtected,
234             label);
235     if (!proxy) {
236         return nullptr;
237     }
238 
239     return SurfaceDrawContext::Make(rContext,
240                                     colorType,
241                                     std::move(proxy),
242                                     std::move(colorSpace),
243                                     origin,
244                                     surfaceProps);
245 }
246 
MakeWithFallback(GrRecordingContext * rContext,GrColorType colorType,sk_sp<SkColorSpace> colorSpace,SkBackingFit fit,SkISize dimensions,const SkSurfaceProps & surfaceProps,int sampleCnt,GrMipmapped mipmapped,GrProtected isProtected,GrSurfaceOrigin origin,skgpu::Budgeted budgeted)247 std::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::MakeWithFallback(
248         GrRecordingContext* rContext,
249         GrColorType colorType,
250         sk_sp<SkColorSpace> colorSpace,
251         SkBackingFit fit,
252         SkISize dimensions,
253         const SkSurfaceProps& surfaceProps,
254         int sampleCnt,
255         GrMipmapped mipmapped,
256         GrProtected isProtected,
257         GrSurfaceOrigin origin,
258         skgpu::Budgeted budgeted) {
259     const GrCaps* caps = rContext->priv().caps();
260     auto [ct, _] = caps->getFallbackColorTypeAndFormat(colorType, sampleCnt);
261     if (ct == GrColorType::kUnknown) {
262         return nullptr;
263     }
264     return SurfaceDrawContext::Make(rContext, ct, colorSpace, fit, dimensions, surfaceProps,
265                                     /*label=*/"MakeSurfaceDrawContextWithFallback", sampleCnt,
266                                     mipmapped, isProtected, origin, budgeted);
267 }
268 
MakeFromBackendTexture(GrRecordingContext * rContext,GrColorType colorType,sk_sp<SkColorSpace> colorSpace,const GrBackendTexture & tex,int sampleCnt,GrSurfaceOrigin origin,const SkSurfaceProps & surfaceProps,sk_sp<skgpu::RefCntedCallback> releaseHelper)269 std::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::MakeFromBackendTexture(
270         GrRecordingContext* rContext,
271         GrColorType colorType,
272         sk_sp<SkColorSpace> colorSpace,
273         const GrBackendTexture& tex,
274         int sampleCnt,
275         GrSurfaceOrigin origin,
276         const SkSurfaceProps& surfaceProps,
277         sk_sp<skgpu::RefCntedCallback> releaseHelper) {
278     SkASSERT(sampleCnt > 0);
279     sk_sp<GrTextureProxy> proxy(rContext->priv().proxyProvider()->wrapRenderableBackendTexture(
280             tex, sampleCnt, kBorrow_GrWrapOwnership, GrWrapCacheable::kNo,
281             std::move(releaseHelper)));
282     if (!proxy) {
283         return nullptr;
284     }
285 
286     return SurfaceDrawContext::Make(rContext, colorType, std::move(proxy), std::move(colorSpace),
287                                     origin, surfaceProps);
288 }
289 
290 // In MDB mode the reffing of the 'getLastOpsTask' call's result allows in-progress
291 // OpsTask to be picked up and added to by SurfaceDrawContexts lower in the call
292 // stack. When this occurs with a closed OpsTask, a new one will be allocated
293 // when the surfaceDrawContext attempts to use it (via getOpsTask).
SurfaceDrawContext(GrRecordingContext * rContext,GrSurfaceProxyView readView,GrSurfaceProxyView writeView,GrColorType colorType,sk_sp<SkColorSpace> colorSpace,const SkSurfaceProps & surfaceProps)294 SurfaceDrawContext::SurfaceDrawContext(GrRecordingContext* rContext,
295                                        GrSurfaceProxyView readView,
296                                        GrSurfaceProxyView writeView,
297                                        GrColorType colorType,
298                                        sk_sp<SkColorSpace> colorSpace,
299                                        const SkSurfaceProps& surfaceProps)
300         : SurfaceFillContext(rContext,
301                              std::move(readView),
302                              std::move(writeView),
303                              {colorType, kPremul_SkAlphaType, std::move(colorSpace)})
304         , fSurfaceProps(surfaceProps)
305         , fCanUseDynamicMSAA(
306                 (fSurfaceProps.flags() & SkSurfaceProps::kDynamicMSAA_Flag) &&
307                 rContext->priv().caps()->supportsDynamicMSAA(this->asRenderTargetProxy())) {
308     SkDEBUGCODE(this->validate();)
309 }
310 
~SurfaceDrawContext()311 SurfaceDrawContext::~SurfaceDrawContext() {
312     ASSERT_SINGLE_OWNER
313 }
314 
willReplaceOpsTask(OpsTask * prevTask,OpsTask * nextTask)315 void SurfaceDrawContext::willReplaceOpsTask(OpsTask* prevTask, OpsTask* nextTask) {
316     if (prevTask && fNeedsStencil) {
317         // Store the stencil values in memory upon completion of fOpsTask.
318         prevTask->setMustPreserveStencil();
319         // Reload the stencil buffer content at the beginning of newOpsTask.
320         // FIXME: Could the topo sort insert a task between these two that modifies the stencil
321         // values?
322         nextTask->setInitialStencilContent(OpsTask::StencilContent::kPreserved);
323     }
324 #if GR_GPU_STATS && GR_TEST_UTILS
325     if (fCanUseDynamicMSAA) {
326         fContext->priv().dmsaaStats().fNumRenderPasses++;
327     }
328 #endif
329 }
330 
drawGlyphRunList(SkCanvas * canvas,const GrClip * clip,const SkMatrixProvider & viewMatrix,const sktext::GlyphRunList & glyphRunList,SkStrikeDeviceInfo strikeDeviceInfo,const SkPaint & paint)331 void SurfaceDrawContext::drawGlyphRunList(SkCanvas* canvas,
332                                           const GrClip* clip,
333                                           const SkMatrixProvider& viewMatrix,
334                                           const sktext::GlyphRunList& glyphRunList,
335                                           SkStrikeDeviceInfo strikeDeviceInfo,
336                                           const SkPaint& paint) {
337     ASSERT_SINGLE_OWNER
338     RETURN_IF_ABANDONED
339     SkDEBUGCODE(this->validate();)
340     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawGlyphRunList", fContext);
341 
342     // Drawing text can cause us to do inline uploads. This is not supported for wrapped vulkan
343     // secondary command buffers because it would require stopping and starting a render pass which
344     // we don't have access to.
345     if (this->wrapsVkSecondaryCB()) {
346         return;
347     }
348 
349     sktext::gpu::TextBlobRedrawCoordinator* textBlobCache = fContext->priv().getTextBlobCache();
350     textBlobCache->drawGlyphRunList(
351             canvas, clip, viewMatrix, glyphRunList, paint, strikeDeviceInfo, this);
352 }
353 
drawPaint(const GrClip * clip,GrPaint && paint,const SkMatrix & viewMatrix)354 void SurfaceDrawContext::drawPaint(const GrClip* clip,
355                                    GrPaint&& paint,
356                                    const SkMatrix& viewMatrix) {
357     // Start with the render target, since that is the maximum content we could possibly fill.
358     // drawFilledQuad() will automatically restrict it to clip bounds for us if possible.
359     if (!paint.numTotalFragmentProcessors()) {
360         // The paint is trivial so we won't need to use local coordinates, so skip calculating the
361         // inverse view matrix.
362         SkRect r = this->asSurfaceProxy()->getBoundsRect();
363         this->fillRectToRect(clip, std::move(paint), GrAA::kNo, SkMatrix::I(), r, r);
364     } else {
365         // Use the inverse view matrix to arrive at appropriate local coordinates for the paint.
366         SkMatrix localMatrix;
367         if (!viewMatrix.invert(&localMatrix)) {
368             return;
369         }
370         SkIRect bounds = SkIRect::MakeSize(this->asSurfaceProxy()->dimensions());
371         this->fillPixelsWithLocalMatrix(clip, std::move(paint), bounds, localMatrix);
372     }
373 }
374 
375 enum class SurfaceDrawContext::QuadOptimization {
376     // The rect to draw doesn't intersect clip or render target, so no draw op should be added
377     kDiscarded,
378     // The rect to draw was converted to some other op and appended to the oplist, so no additional
379     // op is necessary. Currently this can convert it to a clear op or a rrect op. Only valid if
380     // a constColor is provided.
381     kSubmitted,
382     // The clip was folded into the device quad, with updated edge flags and local coords, and
383     // caller is responsible for adding an appropriate op.
384     kClipApplied,
385     // No change to clip, but quad updated to better fit clip/render target, and caller is
386     // responsible for adding an appropriate op.
387     kCropped
388 };
389 
attemptQuadOptimization(const GrClip * clip,const GrUserStencilSettings * stencilSettings,DrawQuad * quad,GrPaint * paint)390 SurfaceDrawContext::QuadOptimization SurfaceDrawContext::attemptQuadOptimization(
391         const GrClip* clip,
392         const GrUserStencilSettings* stencilSettings,
393         DrawQuad* quad,
394         GrPaint* paint) {
395     // Optimization requirements:
396     // 1. kDiscard applies when clip bounds and quad bounds do not intersect
397     // 2a. kSubmitted applies when constColor and final geom is pixel aligned rect;
398     //       pixel aligned rect requires rect clip and (rect quad or quad covers clip) OR
399     // 2b. kSubmitted applies when constColor and rrect clip and quad covers clip
400     // 4. kClipApplied applies when rect clip and (rect quad or quad covers clip)
401     // 5. kCropped in all other scenarios (although a crop may be a no-op)
402     const SkPMColor4f* constColor = nullptr;
403     SkPMColor4f paintColor;
404     if (!stencilSettings && paint && !paint->hasCoverageFragmentProcessor() &&
405         paint->isConstantBlendedColor(&paintColor)) {
406         // Only consider clears/rrects when it's easy to guarantee 100% fill with single color
407         constColor = &paintColor;
408     }
409 
410     // Save the old AA flags since CropToRect will modify 'quad' and if kCropped is returned, it's
411     // better to just keep the old flags instead of introducing mixed edge flags.
412     GrQuadAAFlags oldFlags = quad->fEdgeFlags;
413 
414     // Use the logical size of the render target, which allows for "fullscreen" clears even if
415     // the render target has an approximate backing fit
416     SkRect rtRect = this->asSurfaceProxy()->getBoundsRect();
417 
418     // For historical reasons, we assume AA for exact bounds checking in IsOutsideClip.
419     // TODO(michaelludwig) - Hopefully that can be revisited when the clipping optimizations are
420     // refactored to work better with round rects and dmsaa.
421     SkRect drawBounds = quad->fDevice.bounds();
422     if (!quad->fDevice.isFinite() || drawBounds.isEmpty() ||
423         GrClip::IsOutsideClip(SkIRect::MakeSize(this->dimensions()), drawBounds, GrAA::kYes)) {
424         return QuadOptimization::kDiscarded;
425     } else if (GrQuadUtils::WillUseHairline(quad->fDevice, GrAAType::kCoverage, quad->fEdgeFlags)) {
426         // Don't try to apply the clip early if we know rendering will use hairline methods, as this
427         // has an effect on the op bounds not otherwise taken into account in this function.
428         return QuadOptimization::kCropped;
429     }
430 
431     GrAA drawUsesAA{quad->fEdgeFlags != GrQuadAAFlags::kNone};
432     auto conservativeCrop = [&]() {
433         static constexpr int kLargeDrawLimit = 15000;
434         // Crop the quad to the render target. This doesn't change the visual results of drawing but
435         // is meant to help numerical stability for excessively large draws.
436         if (drawBounds.width() > kLargeDrawLimit || drawBounds.height() > kLargeDrawLimit) {
437             GrQuadUtils::CropToRect(rtRect, drawUsesAA, quad, /* compute local */ !constColor);
438         }
439     };
440 
441     bool simpleColor = !stencilSettings && constColor;
442     GrClip::PreClipResult result = clip ? clip->preApply(drawBounds, drawUsesAA)
443                                         : GrClip::PreClipResult(GrClip::Effect::kUnclipped);
444     switch(result.fEffect) {
445         case GrClip::Effect::kClippedOut:
446             return QuadOptimization::kDiscarded;
447         case GrClip::Effect::kUnclipped:
448             if (!simpleColor) {
449                 conservativeCrop();
450                 return QuadOptimization::kClipApplied;
451             } else {
452                 // Update result to store the render target bounds in order and then fall
453                 // through to attempt the draw->native clear optimization. Pick an AA value such
454                 // that any geometric clipping doesn't need to change aa or edge flags (since we
455                 // know this is on pixel boundaries, it will draw the same regardless).
456                 // See skbug.com/13114 for more details.
457                 result = GrClip::PreClipResult(SkRRect::MakeRect(rtRect), drawUsesAA);
458             }
459             break;
460         case GrClip::Effect::kClipped:
461             if (!result.fIsRRect || (stencilSettings && result.fAA != drawUsesAA) ||
462                 (!result.fRRect.isRect() && !simpleColor)) {
463                 // The clip and draw state are too complicated to try and reduce
464                 conservativeCrop();
465                 return QuadOptimization::kCropped;
466             } // Else fall through to attempt to combine the draw and clip geometry together
467             break;
468         default:
469             SkUNREACHABLE;
470     }
471 
472     // If we reached here, we know we're an axis-aligned clip that is either a rect or a round rect,
473     // so we can potentially combine it with the draw geometry so that no clipping is needed.
474     SkASSERT(result.fEffect == GrClip::Effect::kClipped && result.fIsRRect);
475     SkRect clippedBounds = result.fRRect.getBounds();
476     clippedBounds.intersect(rtRect);
477     if (!drawBounds.intersect(clippedBounds)) {
478         // Our fractional bounds aren't actually inside the clip. GrClip::preApply() can sometimes
479         // think in terms of rounded-out bounds. Discard the draw.
480         return QuadOptimization::kDiscarded;
481     }
482     // Guard against the clipped draw turning into a hairline draw after intersection
483     if (drawBounds.width() < 1.f || drawBounds.height() < 1.f) {
484         return QuadOptimization::kCropped;
485     }
486 
487     if (result.fRRect.isRect()) {
488         // No rounded corners, so we might be able to become a native clear or we might be able to
489         // modify geometry and edge flags to represent intersected shape of clip and draw.
490         if (GrQuadUtils::CropToRect(clippedBounds, result.fAA, quad,
491                                     /*compute local*/ !constColor)) {
492             if (simpleColor && quad->fDevice.quadType() == GrQuad::Type::kAxisAligned) {
493                 // Clear optimization is possible
494                 drawBounds = quad->fDevice.bounds();
495                 if (drawBounds.contains(rtRect)) {
496                     // Fullscreen clear
497                     this->clear(*constColor);
498                     return QuadOptimization::kSubmitted;
499                 } else if (GrClip::IsPixelAligned(drawBounds) &&
500                            drawBounds.width() > 256 && drawBounds.height() > 256) {
501                     // Scissor + clear (round shouldn't do anything since we are pixel aligned)
502                     SkIRect scissorRect;
503                     drawBounds.round(&scissorRect);
504                     this->clear(scissorRect, *constColor);
505                     return QuadOptimization::kSubmitted;
506                 }
507             }
508 
509             return QuadOptimization::kClipApplied;
510         }
511     } else {
512         // Rounded corners and constant filled color (limit ourselves to solid colors because
513         // there is no way to use custom local coordinates with drawRRect).
514         SkASSERT(simpleColor);
515         if (GrQuadUtils::CropToRect(clippedBounds, result.fAA, quad,
516                                     /* compute local */ false) &&
517             quad->fDevice.quadType() == GrQuad::Type::kAxisAligned &&
518             quad->fDevice.bounds().contains(clippedBounds)) {
519             // Since the cropped quad became a rectangle which covered the bounds of the rrect,
520             // we can draw the rrect directly and ignore the edge flags
521             this->drawRRect(nullptr, std::move(*paint), result.fAA, SkMatrix::I(), result.fRRect,
522                             GrStyle::SimpleFill());
523             return QuadOptimization::kSubmitted;
524         }
525     }
526 
527     // The quads have been updated to better fit the clip bounds, but can't get rid of
528     // the clip entirely
529     quad->fEdgeFlags = oldFlags;
530     return QuadOptimization::kCropped;
531 }
532 
drawFilledQuad(const GrClip * clip,GrPaint && paint,DrawQuad * quad,const GrUserStencilSettings * ss)533 void SurfaceDrawContext::drawFilledQuad(const GrClip* clip,
534                                         GrPaint&& paint,
535                                         DrawQuad* quad,
536                                         const GrUserStencilSettings* ss) {
537     ASSERT_SINGLE_OWNER
538     RETURN_IF_ABANDONED
539     SkDEBUGCODE(this->validate();)
540     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawFilledQuad", fContext);
541 
542     AutoCheckFlush acf(this->drawingManager());
543 
544     QuadOptimization opt = this->attemptQuadOptimization(clip, ss, quad, &paint);
545     if (opt >= QuadOptimization::kClipApplied) {
546         // These optimizations require caller to add an op themselves
547         const GrClip* finalClip = opt == QuadOptimization::kClipApplied ? nullptr : clip;
548         // The quad being drawn requires AA if any of its edges requires AA
549         GrAA aa{quad->fEdgeFlags != GrQuadAAFlags::kNone};
550         GrAAType aaType;
551         if (ss) {
552             aaType = (aa == GrAA::kYes) ? GrAAType::kMSAA : GrAAType::kNone;
553         } else if (fCanUseDynamicMSAA && aa == GrAA::kNo) {
554             // The SkGpuDevice ensures GrAA is always kYes when using dmsaa. If the caller calls
555             // into here with GrAA::kNo, trust that they know what they're doing and that the
556             // rendering will be equal with or without msaa.
557             aaType = GrAAType::kNone;
558         } else {
559             aaType = this->chooseAAType(aa);
560         }
561         this->addDrawOp(finalClip, FillRectOp::Make(fContext, std::move(paint), aaType,
562                                                     quad, ss));
563     }
564     // All other optimization levels were completely handled inside attempt(), so no extra op needed
565 }
566 
drawTexture(const GrClip * clip,GrSurfaceProxyView view,SkAlphaType srcAlphaType,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,SkBlendMode blendMode,const SkPMColor4f & color,const SkRect & srcRect,const SkRect & dstRect,GrQuadAAFlags edgeAA,SkCanvas::SrcRectConstraint constraint,const SkMatrix & viewMatrix,sk_sp<GrColorSpaceXform> colorSpaceXform)567 void SurfaceDrawContext::drawTexture(const GrClip* clip,
568                                      GrSurfaceProxyView view,
569                                      SkAlphaType srcAlphaType,
570                                      GrSamplerState::Filter filter,
571                                      GrSamplerState::MipmapMode mm,
572                                      SkBlendMode blendMode,
573                                      const SkPMColor4f& color,
574                                      const SkRect& srcRect,
575                                      const SkRect& dstRect,
576                                      GrQuadAAFlags edgeAA,
577                                      SkCanvas::SrcRectConstraint constraint,
578                                      const SkMatrix& viewMatrix,
579                                      sk_sp<GrColorSpaceXform> colorSpaceXform) {
580     // If we are using dmsaa then go through FillRRectOp (via fillRectToRect).
581     if ((this->alwaysAntialias() || this->caps()->reducedShaderMode()) &&
582         edgeAA != GrQuadAAFlags::kNone) {
583 
584         GrPaint paint;
585         paint.setColor4f(color);
586         std::unique_ptr<GrFragmentProcessor> fp;
587         if (constraint == SkCanvas::kStrict_SrcRectConstraint) {
588             fp = GrTextureEffect::MakeSubset(view, srcAlphaType, SkMatrix::I(),
589                                              GrSamplerState(filter, mm), srcRect,
590                                              *this->caps());
591         } else {
592             fp = GrTextureEffect::Make(view, srcAlphaType, SkMatrix::I(), filter, mm);
593         }
594         if (colorSpaceXform) {
595             fp = GrColorSpaceXformEffect::Make(std::move(fp), std::move(colorSpaceXform));
596         }
597         fp = GrBlendFragmentProcessor::Make<SkBlendMode::kModulate>(std::move(fp), nullptr);
598         paint.setColorFragmentProcessor(std::move(fp));
599         if (blendMode != SkBlendMode::kSrcOver) {
600             paint.setXPFactory(SkBlendMode_AsXPFactory(blendMode));
601         }
602         this->fillRectToRect(clip, std::move(paint), GrAA::kYes, viewMatrix, dstRect, srcRect);
603         return;
604     }
605 
606     const SkRect* subset = constraint == SkCanvas::kStrict_SrcRectConstraint ?
607             &srcRect : nullptr;
608     DrawQuad quad{GrQuad::MakeFromRect(dstRect, viewMatrix), GrQuad(srcRect), edgeAA};
609 
610     this->drawTexturedQuad(clip, std::move(view), srcAlphaType, std::move(colorSpaceXform), filter,
611                            mm, color, blendMode, &quad, subset);
612 }
613 
drawTexturedQuad(const GrClip * clip,GrSurfaceProxyView proxyView,SkAlphaType srcAlphaType,sk_sp<GrColorSpaceXform> textureXform,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,const SkPMColor4f & color,SkBlendMode blendMode,DrawQuad * quad,const SkRect * subset)614 void SurfaceDrawContext::drawTexturedQuad(const GrClip* clip,
615                                           GrSurfaceProxyView proxyView,
616                                           SkAlphaType srcAlphaType,
617                                           sk_sp<GrColorSpaceXform> textureXform,
618                                           GrSamplerState::Filter filter,
619                                           GrSamplerState::MipmapMode mm,
620                                           const SkPMColor4f& color,
621                                           SkBlendMode blendMode,
622                                           DrawQuad* quad,
623                                           const SkRect* subset) {
624     ASSERT_SINGLE_OWNER
625     RETURN_IF_ABANDONED
626     SkDEBUGCODE(this->validate();)
627     SkASSERT(proxyView.asTextureProxy());
628     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawTexturedQuad", fContext);
629 
630     AutoCheckFlush acf(this->drawingManager());
631 
632     // Functionally this is very similar to drawFilledQuad except that there's no constColor to
633     // enable the kSubmitted optimizations, no stencil settings support, and its a TextureOp.
634     QuadOptimization opt = this->attemptQuadOptimization(clip, nullptr/*stencil*/, quad,
635                                                          nullptr/*paint*/);
636 
637     SkASSERT(opt != QuadOptimization::kSubmitted);
638     if (opt != QuadOptimization::kDiscarded) {
639         // Add the texture op if not discarded
640         const GrClip* finalClip = opt == QuadOptimization::kClipApplied ? nullptr : clip;
641         GrAAType aaType = this->chooseAAType(GrAA{quad->fEdgeFlags != GrQuadAAFlags::kNone});
642         auto clampType = GrColorTypeClampType(this->colorInfo().colorType());
643         auto saturate = clampType == GrClampType::kManual ? ganesh::TextureOp::Saturate::kYes
644                                                           : ganesh::TextureOp::Saturate::kNo;
645         // Use the provided subset, although hypothetically we could detect that the cropped local
646         // quad is sufficiently inside the subset and the constraint could be dropped.
647         this->addDrawOp(finalClip,
648                         ganesh::TextureOp::Make(fContext, std::move(proxyView), srcAlphaType,
649                                                 std::move(textureXform), filter, mm, color,
650                                                 saturate, blendMode, aaType, quad, subset));
651     }
652 }
653 
drawRect(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRect & rect,const GrStyle * style)654 void SurfaceDrawContext::drawRect(const GrClip* clip,
655                                   GrPaint&& paint,
656                                   GrAA aa,
657                                   const SkMatrix& viewMatrix,
658                                   const SkRect& rect,
659                                   const GrStyle* style) {
660     if (!style) {
661         style = &GrStyle::SimpleFill();
662     }
663     ASSERT_SINGLE_OWNER
664     RETURN_IF_ABANDONED
665     SkDEBUGCODE(this->validate();)
666     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawRect", fContext);
667 
668     // Path effects should've been devolved to a path in SkGpuDevice
669     SkASSERT(!style->pathEffect());
670 
671     AutoCheckFlush acf(this->drawingManager());
672 
673     const SkStrokeRec& stroke = style->strokeRec();
674     if (stroke.getStyle() == SkStrokeRec::kFill_Style) {
675         // Fills the rect, using rect as its own local coordinates
676         this->fillRectToRect(clip, std::move(paint), aa, viewMatrix, rect, rect);
677         return;
678     } else if ((stroke.getStyle() == SkStrokeRec::kStroke_Style ||
679                 stroke.getStyle() == SkStrokeRec::kHairline_Style) &&
680                rect.width()                                        &&
681                rect.height()                                       &&
682                !this->caps()->reducedShaderMode()) {
683         // Only use the StrokeRectOp for non-empty rectangles. Empty rectangles will be processed by
684         // GrStyledShape to handle stroke caps and dashing properly.
685         //
686         // http://skbug.com/12206 -- there is a double-blend issue with the bevel version of
687         // AAStrokeRectOp, and if we increase the AA bloat for MSAA it becomes more pronounced.
688         // Don't use the bevel version with DMSAA.
689         GrAAType aaType = (fCanUseDynamicMSAA &&
690                            stroke.getJoin() == SkPaint::kMiter_Join &&
691                            stroke.getMiter() >= SK_ScalarSqrt2) ? GrAAType::kCoverage
692                                                                 : this->chooseAAType(aa);
693         GrOp::Owner op = ganesh::StrokeRectOp::Make(fContext, std::move(paint), aaType, viewMatrix,
694                                                     rect, stroke);
695         // op may be null if the stroke is not supported or if using coverage aa and the view matrix
696         // does not preserve rectangles.
697         if (op) {
698             this->addDrawOp(clip, std::move(op));
699             return;
700         }
701     }
702     assert_alive(paint);
703     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,
704                                      GrStyledShape(rect, *style, DoSimplify::kNo));
705 }
706 
fillRectToRect(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRect & rectToDraw,const SkRect & localRect)707 void SurfaceDrawContext::fillRectToRect(const GrClip* clip,
708                                         GrPaint&& paint,
709                                         GrAA aa,
710                                         const SkMatrix& viewMatrix,
711                                         const SkRect& rectToDraw,
712                                         const SkRect& localRect) {
713     DrawQuad quad{GrQuad::MakeFromRect(rectToDraw, viewMatrix), GrQuad(localRect),
714                   aa == GrAA::kYes ? GrQuadAAFlags::kAll : GrQuadAAFlags::kNone};
715 
716     // If we are using dmsaa then attempt to draw the rect with FillRRectOp.
717     if ((fContext->priv().caps()->reducedShaderMode() || this->alwaysAntialias()) &&
718         this->caps()->drawInstancedSupport()                                      &&
719         aa == GrAA::kYes) {  // If aa is kNo when using dmsaa, the rect is axis aligned. Don't use
720                              // FillRRectOp because it might require dual source blending.
721                              // http://skbug.com/11756
722         QuadOptimization opt = this->attemptQuadOptimization(clip, nullptr/*stencil*/, &quad,
723                                                              &paint);
724         if (opt < QuadOptimization::kClipApplied) {
725             // The optimization was completely handled inside attempt().
726             return;
727         }
728 
729         SkRect croppedRect, croppedLocal{};
730         const GrClip* optimizedClip = clip;
731         if (clip && viewMatrix.isScaleTranslate() && quad.fDevice.asRect(&croppedRect) &&
732             (!paint.usesLocalCoords() || quad.fLocal.asRect(&croppedLocal))) {
733             // The cropped quad is still a rect, and our view matrix preserves rects. Map it back
734             // to pre-matrix space.
735             SkMatrix inverse;
736             if (!viewMatrix.invert(&inverse)) {
737                 return;
738             }
739             SkASSERT(inverse.rectStaysRect());
740             inverse.mapRect(&croppedRect);
741             if (opt == QuadOptimization::kClipApplied) {
742                 optimizedClip = nullptr;
743             }
744         } else {
745             // Even if attemptQuadOptimization gave us an optimized quad, FillRRectOp needs a rect
746             // in pre-matrix space, so use the original rect. Also preserve the original clip.
747             croppedRect = rectToDraw;
748             croppedLocal = localRect;
749         }
750 
751         if (auto op = FillRRectOp::Make(fContext, this->arenaAlloc(), std::move(paint),
752                                         viewMatrix, SkRRect::MakeRect(croppedRect), croppedLocal,
753                                         GrAA::kYes)) {
754             this->addDrawOp(optimizedClip, std::move(op));
755             return;
756         }
757     }
758 
759     assert_alive(paint);
760     this->drawFilledQuad(clip, std::move(paint), &quad);
761 }
762 
drawQuadSet(const GrClip * clip,GrPaint && paint,const SkMatrix & viewMatrix,const GrQuadSetEntry quads[],int cnt)763 void SurfaceDrawContext::drawQuadSet(const GrClip* clip,
764                                      GrPaint&& paint,
765                                      const SkMatrix& viewMatrix,
766                                      const GrQuadSetEntry quads[],
767                                      int cnt) {
768     GrAAType aaType = this->chooseAAType(GrAA::kYes);
769 
770     FillRectOp::AddFillRectOps(this, clip, fContext, std::move(paint), aaType, viewMatrix,
771                                quads, cnt);
772 }
773 
maxWindowRectangles() const774 int SurfaceDrawContext::maxWindowRectangles() const {
775     return this->asRenderTargetProxy()->maxWindowRectangles(*this->caps());
776 }
777 
canDiscardPreviousOpsOnFullClear() const778 OpsTask::CanDiscardPreviousOps SurfaceDrawContext::canDiscardPreviousOpsOnFullClear() const {
779 #if GR_TEST_UTILS
780     if (fPreserveOpsOnFullClear_TestingOnly) {
781         return OpsTask::CanDiscardPreviousOps::kNo;
782     }
783 #endif
784     // Regardless of how the clear is implemented (native clear or a fullscreen quad), all prior ops
785     // would normally be overwritten. The one exception is if the render target context is marked as
786     // needing a stencil buffer then there may be a prior op that writes to the stencil buffer.
787     // Although the clear will ignore the stencil buffer, following draw ops may not so we can't get
788     // rid of all the preceding ops. Beware! If we ever add any ops that have a side effect beyond
789     // modifying the stencil buffer we will need a more elaborate tracking system (skbug.com/7002).
790     return OpsTask::CanDiscardPreviousOps(!fNeedsStencil);
791 }
792 
setNeedsStencil()793 void SurfaceDrawContext::setNeedsStencil() {
794     // Don't clear stencil until after we've set fNeedsStencil. This ensures we don't loop forever
795     // in the event that there are driver bugs and we need to clear as a draw.
796     bool hasInitializedStencil = fNeedsStencil;
797     fNeedsStencil = true;
798     if (!hasInitializedStencil) {
799         this->asRenderTargetProxy()->setNeedsStencil();
800         if (this->caps()->performStencilClearsAsDraws()) {
801             // There is a driver bug with clearing stencil. We must use an op to manually clear the
802             // stencil buffer before the op that required 'setNeedsStencil'.
803             this->internalStencilClear(nullptr, /* inside mask */ false);
804         } else {
805             this->getOpsTask()->setInitialStencilContent(
806                     OpsTask::StencilContent::kUserBitsCleared);
807         }
808     }
809 }
810 
internalStencilClear(const SkIRect * scissor,bool insideStencilMask)811 void SurfaceDrawContext::internalStencilClear(const SkIRect* scissor, bool insideStencilMask) {
812     this->setNeedsStencil();
813 
814     GrScissorState scissorState(this->asSurfaceProxy()->backingStoreDimensions());
815     if (scissor && !scissorState.set(*scissor)) {
816         // The requested clear region is off screen, so nothing to do.
817         return;
818     }
819 
820     bool clearWithDraw = this->caps()->performStencilClearsAsDraws() ||
821                          (scissorState.enabled() && this->caps()->performPartialClearsAsDraws());
822     if (clearWithDraw) {
823         const GrUserStencilSettings* ss = GrStencilSettings::SetClipBitSettings(insideStencilMask);
824 
825         // Configure the paint to have no impact on the color buffer
826         GrPaint paint;
827         paint.setXPFactory(GrDisableColorXPFactory::Get());
828         this->addDrawOp(nullptr,
829                         FillRectOp::MakeNonAARect(fContext, std::move(paint), SkMatrix::I(),
830                                                   SkRect::Make(scissorState.rect()), ss));
831     } else {
832         this->addOp(ClearOp::MakeStencilClip(fContext, scissorState, insideStencilMask));
833     }
834 }
835 
stencilPath(const GrHardClip * clip,GrAA doStencilMSAA,const SkMatrix & viewMatrix,const SkPath & path)836 bool SurfaceDrawContext::stencilPath(const GrHardClip* clip,
837                                      GrAA doStencilMSAA,
838                                      const SkMatrix& viewMatrix,
839                                      const SkPath& path) {
840     SkIRect clipBounds = clip ? clip->getConservativeBounds()
841                               : SkIRect::MakeSize(this->dimensions());
842     GrStyledShape shape(path, GrStyledShape::DoSimplify::kNo);
843 
844     PathRenderer::CanDrawPathArgs canDrawArgs;
845     canDrawArgs.fCaps = fContext->priv().caps();
846     canDrawArgs.fProxy = this->asRenderTargetProxy();
847     canDrawArgs.fClipConservativeBounds = &clipBounds;
848     canDrawArgs.fViewMatrix = &viewMatrix;
849     canDrawArgs.fShape = &shape;
850     canDrawArgs.fPaint = nullptr;
851     canDrawArgs.fSurfaceProps = &fSurfaceProps;
852     canDrawArgs.fAAType = (doStencilMSAA == GrAA::kYes) ? GrAAType::kMSAA : GrAAType::kNone;
853     canDrawArgs.fHasUserStencilSettings = false;
854     auto pr = this->drawingManager()->getPathRenderer(canDrawArgs,
855                                                       false,
856                                                       PathRendererChain::DrawType::kStencil);
857     if (!pr) {
858         SkDebugf("WARNING: No path renderer to stencil path.\n");
859         return false;
860     }
861 
862     PathRenderer::StencilPathArgs args;
863     args.fContext = fContext;
864     args.fSurfaceDrawContext = this;
865     args.fClip = clip;
866     args.fClipConservativeBounds = &clipBounds;
867     args.fViewMatrix = &viewMatrix;
868     args.fShape = &shape;
869     args.fDoStencilMSAA = doStencilMSAA;
870     pr->stencilPath(args);
871     return true;
872 }
873 
drawTextureSet(const GrClip * clip,GrTextureSetEntry set[],int cnt,int proxyRunCnt,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,SkBlendMode mode,SkCanvas::SrcRectConstraint constraint,const SkMatrix & viewMatrix,sk_sp<GrColorSpaceXform> texXform)874 void SurfaceDrawContext::drawTextureSet(const GrClip* clip,
875                                         GrTextureSetEntry set[],
876                                         int cnt,
877                                         int proxyRunCnt,
878                                         GrSamplerState::Filter filter,
879                                         GrSamplerState::MipmapMode mm,
880                                         SkBlendMode mode,
881                                         SkCanvas::SrcRectConstraint constraint,
882                                         const SkMatrix& viewMatrix,
883                                         sk_sp<GrColorSpaceXform> texXform) {
884     ASSERT_SINGLE_OWNER
885     RETURN_IF_ABANDONED
886     SkDEBUGCODE(this->validate();)
887     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawTextureSet", fContext);
888 
889     // Create the minimum number of GrTextureOps needed to draw this set. Individual
890     // GrTextureOps can rebind the texture between draws thus avoiding GrPaint (re)creation.
891     AutoCheckFlush acf(this->drawingManager());
892     GrAAType aaType = this->chooseAAType(GrAA::kYes);
893     auto clampType = GrColorTypeClampType(this->colorInfo().colorType());
894     auto saturate = clampType == GrClampType::kManual ? ganesh::TextureOp::Saturate::kYes
895                                                       : ganesh::TextureOp::Saturate::kNo;
896     ganesh::TextureOp::AddTextureSetOps(this, clip, fContext, set, cnt, proxyRunCnt, filter, mm,
897                                         saturate, mode, aaType, constraint, viewMatrix,
898                                         std::move(texXform));
899 }
900 
drawVertices(const GrClip * clip,GrPaint && paint,const SkMatrixProvider & matrixProvider,sk_sp<SkVertices> vertices,GrPrimitiveType * overridePrimType,bool skipColorXform)901 void SurfaceDrawContext::drawVertices(const GrClip* clip,
902                                       GrPaint&& paint,
903                                       const SkMatrixProvider& matrixProvider,
904                                       sk_sp<SkVertices> vertices,
905                                       GrPrimitiveType* overridePrimType,
906                                       bool skipColorXform) {
907     ASSERT_SINGLE_OWNER
908     RETURN_IF_ABANDONED
909     SkDEBUGCODE(this->validate();)
910     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawVertices", fContext);
911 
912     AutoCheckFlush acf(this->drawingManager());
913 
914     SkASSERT(vertices);
915     auto xform = skipColorXform ? nullptr : this->colorInfo().refColorSpaceXformFromSRGB();
916     GrAAType aaType = fCanUseDynamicMSAA ? GrAAType::kMSAA : this->chooseAAType(GrAA::kNo);
917     GrOp::Owner op = DrawMeshOp::Make(fContext,
918                                       std::move(paint),
919                                       std::move(vertices),
920                                       overridePrimType,
921                                       matrixProvider,
922                                       aaType,
923                                       std::move(xform));
924     this->addDrawOp(clip, std::move(op));
925 }
926 
drawMesh(const GrClip * clip,GrPaint && paint,const SkMatrixProvider & matrixProvider,const SkMesh & mesh)927 void SurfaceDrawContext::drawMesh(const GrClip* clip,
928                                   GrPaint&& paint,
929                                   const SkMatrixProvider& matrixProvider,
930                                   const SkMesh& mesh) {
931     ASSERT_SINGLE_OWNER
932     RETURN_IF_ABANDONED
933     SkDEBUGCODE(this->validate();)
934     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawMesh", fContext);
935 
936     AutoCheckFlush acf(this->drawingManager());
937 
938     SkASSERT(mesh.isValid());
939 
940     auto xform = GrColorSpaceXform::Make(SkMeshSpecificationPriv::ColorSpace(*mesh.spec()),
941                                          SkMeshSpecificationPriv::AlphaType(*mesh.spec()),
942                                          this->colorInfo().colorSpace(),
943                                          this->colorInfo().alphaType());
944     GrAAType aaType = fCanUseDynamicMSAA ? GrAAType::kMSAA : this->chooseAAType(GrAA::kNo);
945     GrOp::Owner op = DrawMeshOp::Make(fContext,
946                                       std::move(paint),
947                                       mesh,
948                                       matrixProvider,
949                                       aaType,
950                                       std::move(xform));
951     this->addDrawOp(clip, std::move(op));
952 }
953 
954 ///////////////////////////////////////////////////////////////////////////////
955 
drawAtlas(const GrClip * clip,GrPaint && paint,const SkMatrix & viewMatrix,int spriteCount,const SkRSXform xform[],const SkRect texRect[],const SkColor colors[])956 void SurfaceDrawContext::drawAtlas(const GrClip* clip,
957                                    GrPaint&& paint,
958                                    const SkMatrix& viewMatrix,
959                                    int spriteCount,
960                                    const SkRSXform xform[],
961                                    const SkRect texRect[],
962                                    const SkColor colors[]) {
963     ASSERT_SINGLE_OWNER
964     RETURN_IF_ABANDONED
965     SkDEBUGCODE(this->validate();)
966     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawAtlas", fContext);
967 
968     AutoCheckFlush acf(this->drawingManager());
969 
970     GrAAType aaType = this->chooseAAType(GrAA::kNo);
971     GrOp::Owner op = DrawAtlasOp::Make(fContext, std::move(paint), viewMatrix,
972                                        aaType, spriteCount, xform, texRect, colors);
973     this->addDrawOp(clip, std::move(op));
974 }
975 
976 ///////////////////////////////////////////////////////////////////////////////
977 
drawRRect(const GrClip * origClip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRRect & rrect,const GrStyle & style)978 void SurfaceDrawContext::drawRRect(const GrClip* origClip,
979                                    GrPaint&& paint,
980                                    GrAA aa,
981                                    const SkMatrix& viewMatrix,
982                                    const SkRRect& rrect,
983                                    const GrStyle& style) {
984     ASSERT_SINGLE_OWNER
985     RETURN_IF_ABANDONED
986     SkDEBUGCODE(this->validate();)
987     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawRRect", fContext);
988 
989     SkASSERT(!style.pathEffect()); // this should've been devolved to a path in SkGpuDevice
990 
991     const SkStrokeRec& stroke = style.strokeRec();
992     if (stroke.getStyle() == SkStrokeRec::kFill_Style && rrect.isEmpty()) {
993        return;
994     }
995 
996     const GrClip* clip = origClip;
997     // It is not uncommon to clip to a round rect and then draw that same round rect. Since our
998     // lower level clip code works from op bounds, which are SkRects, it doesn't detect that the
999     // clip can be ignored. The following test attempts to mitigate the stencil clip cost but only
1000     // works for axis-aligned round rects. This also only works for filled rrects since the stroke
1001     // width outsets beyond the rrect itself.
1002     // TODO: skbug.com/10462 - There was mixed performance wins and regressions when this
1003     // optimization was turned on outside of Android Framework. I (michaelludwig) believe this is
1004     // do to the overhead in determining if an SkClipStack is just a rrect. Once that is improved,
1005     // re-enable this and see if we avoid the regressions.
1006 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1007     SkRRect devRRect;
1008     if (clip && stroke.getStyle() == SkStrokeRec::kFill_Style &&
1009         rrect.transform(viewMatrix, &devRRect)) {
1010         GrClip::PreClipResult result = clip->preApply(devRRect.getBounds(), aa);
1011         switch(result.fEffect) {
1012             case GrClip::Effect::kClippedOut:
1013                 return;
1014             case GrClip::Effect::kUnclipped:
1015                 clip = nullptr;
1016                 break;
1017             case GrClip::Effect::kClipped:
1018                 // Currently there's no general-purpose rrect-to-rrect contains function, and if we
1019                 // got here, we know the devRRect's bounds aren't fully contained by the clip.
1020                 // Testing for equality between the two is a reasonable stop-gap for now.
1021                 if (result.fIsRRect && result.fRRect == devRRect) {
1022                     // NOTE: On the android framework, we allow this optimization even when the clip
1023                     // is non-AA and the draw is AA.
1024                     if (result.fAA == aa || (result.fAA == GrAA::kNo && aa == GrAA::kYes)) {
1025                         clip = nullptr;
1026                     }
1027                 }
1028                 break;
1029             default:
1030                 SkUNREACHABLE;
1031         }
1032     }
1033 #endif
1034 
1035     AutoCheckFlush acf(this->drawingManager());
1036 
1037     GrAAType aaType = this->chooseAAType(aa);
1038 
1039     GrOp::Owner op;
1040 #ifndef SK_ENABLE_OPTIMIZE_SIZE
1041     if (aaType == GrAAType::kCoverage                          &&
1042         !fCanUseDynamicMSAA                                    &&
1043         !this->caps()->reducedShaderMode()                     &&
1044         rrect.isSimple()                                       &&
1045         rrect.getSimpleRadii().fX == rrect.getSimpleRadii().fY &&
1046         viewMatrix.rectStaysRect() && viewMatrix.isSimilarity()) {
1047         // In specific cases we use a dedicated circular round rect op to try and get better perf.
1048         assert_alive(paint);
1049         op = GrOvalOpFactory::MakeCircularRRectOp(fContext, std::move(paint), viewMatrix, rrect,
1050                                                   stroke, this->caps()->shaderCaps());
1051     }
1052 #endif
1053     if (!op && style.isSimpleFill()) {
1054         assert_alive(paint);
1055         op = FillRRectOp::Make(fContext, this->arenaAlloc(), std::move(paint), viewMatrix, rrect,
1056                                rrect.rect(), GrAA(aaType != GrAAType::kNone));
1057     }
1058 #ifndef SK_ENABLE_OPTIMIZE_SIZE
1059     if (!op && (aaType == GrAAType::kCoverage || fCanUseDynamicMSAA)) {
1060         assert_alive(paint);
1061         op = GrOvalOpFactory::MakeRRectOp(
1062                 fContext, std::move(paint), viewMatrix, rrect, stroke, this->caps()->shaderCaps());
1063     }
1064 #endif
1065     if (op) {
1066         this->addDrawOp(clip, std::move(op));
1067         return;
1068     }
1069 
1070     assert_alive(paint);
1071     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,
1072                                      GrStyledShape(rrect, style, DoSimplify::kNo));
1073 }
1074 
1075 ///////////////////////////////////////////////////////////////////////////////
1076 
drawFastShadow(const GrClip * clip,const SkMatrix & viewMatrix,const SkPath & path,const SkDrawShadowRec & rec)1077 bool SurfaceDrawContext::drawFastShadow(const GrClip* clip,
1078                                         const SkMatrix& viewMatrix,
1079                                         const SkPath& path,
1080                                         const SkDrawShadowRec& rec) {
1081     ASSERT_SINGLE_OWNER
1082     if (fContext->abandoned()) {
1083         return true;
1084     }
1085     SkDEBUGCODE(this->validate();)
1086     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawFastShadow", fContext);
1087 
1088     // check z plane
1089     bool tiltZPlane = SkToBool(!SkScalarNearlyZero(rec.fZPlaneParams.fX) ||
1090                                !SkScalarNearlyZero(rec.fZPlaneParams.fY));
1091     bool skipAnalytic = SkToBool(rec.fFlags & SkShadowFlags::kGeometricOnly_ShadowFlag);
1092     if (tiltZPlane || skipAnalytic || !viewMatrix.rectStaysRect() || !viewMatrix.isSimilarity()) {
1093         return false;
1094     }
1095 
1096     SkRRect rrect;
1097     SkRect rect;
1098     // we can only handle rects, circles, and simple rrects with circular corners
1099     bool isRRect = path.isRRect(&rrect) && SkRRectPriv::IsNearlySimpleCircular(rrect) &&
1100                    rrect.getSimpleRadii().fX > SK_ScalarNearlyZero;
1101     if (!isRRect &&
1102         path.isOval(&rect) && SkScalarNearlyEqual(rect.width(), rect.height()) &&
1103         rect.width() > SK_ScalarNearlyZero) {
1104         rrect.setOval(rect);
1105         isRRect = true;
1106     }
1107     if (!isRRect && path.isRect(&rect)) {
1108         rrect.setRect(rect);
1109         isRRect = true;
1110     }
1111 
1112     if (!isRRect) {
1113         return false;
1114     }
1115 
1116     if (rrect.isEmpty()) {
1117         return true;
1118     }
1119 
1120     AutoCheckFlush acf(this->drawingManager());
1121 
1122     SkPoint3 devLightPos = rec.fLightPos;
1123     bool directional = SkToBool(rec.fFlags & kDirectionalLight_ShadowFlag);
1124     if (!directional) {
1125         // transform light
1126         viewMatrix.mapPoints((SkPoint*)&devLightPos.fX, 1);
1127     }
1128 
1129     // 1/scale
1130     SkScalar devToSrcScale = viewMatrix.isScaleTranslate() ?
1131         SkScalarInvert(SkScalarAbs(viewMatrix[SkMatrix::kMScaleX])) :
1132         sk_float_rsqrt(viewMatrix[SkMatrix::kMScaleX] * viewMatrix[SkMatrix::kMScaleX] +
1133                        viewMatrix[SkMatrix::kMSkewX] * viewMatrix[SkMatrix::kMSkewX]);
1134 
1135     SkScalar occluderHeight = rec.fZPlaneParams.fZ;
1136     bool transparent = SkToBool(rec.fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag);
1137 
1138     if (SkColorGetA(rec.fAmbientColor) > 0) {
1139         SkScalar devSpaceInsetWidth = SkDrawShadowMetrics::AmbientBlurRadius(occluderHeight);
1140         const SkScalar umbraRecipAlpha = SkDrawShadowMetrics::AmbientRecipAlpha(occluderHeight);
1141         const SkScalar devSpaceAmbientBlur = devSpaceInsetWidth * umbraRecipAlpha;
1142 
1143         // Outset the shadow rrect to the border of the penumbra
1144         SkScalar ambientPathOutset = devSpaceInsetWidth * devToSrcScale;
1145         SkRRect ambientRRect;
1146         SkRect outsetRect = rrect.rect().makeOutset(ambientPathOutset, ambientPathOutset);
1147         // If the rrect was an oval then its outset will also be one.
1148         // We set it explicitly to avoid errors.
1149         if (rrect.isOval()) {
1150             ambientRRect = SkRRect::MakeOval(outsetRect);
1151         } else {
1152             SkScalar outsetRad = SkRRectPriv::GetSimpleRadii(rrect).fX + ambientPathOutset;
1153             ambientRRect = SkRRect::MakeRectXY(outsetRect, outsetRad, outsetRad);
1154         }
1155 
1156         // The ShadowRRectOp still uses 8888 colors, so it might get clamped if the shadow color
1157         // does not fit in bytes after being transformed to the destination color space. This can
1158         // happen if the destination color space is smaller than sRGB, which is highly unlikely.
1159         GrColor ambientColor = SkColorToPMColor4f(rec.fAmbientColor, colorInfo()).toBytes_RGBA();
1160         if (transparent) {
1161             // set a large inset to force a fill
1162             devSpaceInsetWidth = ambientRRect.width();
1163         }
1164 
1165         GrOp::Owner op = ShadowRRectOp::Make(fContext,
1166                                              ambientColor,
1167                                              viewMatrix,
1168                                              ambientRRect,
1169                                              devSpaceAmbientBlur,
1170                                              devSpaceInsetWidth);
1171         if (op) {
1172             this->addDrawOp(clip, std::move(op));
1173         }
1174     }
1175 
1176     if (SkColorGetA(rec.fSpotColor) > 0) {
1177         SkScalar devSpaceSpotBlur;
1178         SkScalar spotScale;
1179         SkVector spotOffset;
1180         if (directional) {
1181             SkDrawShadowMetrics::GetDirectionalParams(occluderHeight, devLightPos.fX,
1182                                                       devLightPos.fY, devLightPos.fZ,
1183                                                       rec.fLightRadius, &devSpaceSpotBlur,
1184                                                       &spotScale, &spotOffset);
1185         } else {
1186             SkDrawShadowMetrics::GetSpotParams(occluderHeight, devLightPos.fX, devLightPos.fY,
1187                                                devLightPos.fZ, rec.fLightRadius,
1188                                                &devSpaceSpotBlur, &spotScale, &spotOffset);
1189         }
1190         // handle scale of radius due to CTM
1191         const SkScalar srcSpaceSpotBlur = devSpaceSpotBlur * devToSrcScale;
1192 
1193         // Adjust translate for the effect of the scale.
1194         spotOffset.fX += spotScale*viewMatrix[SkMatrix::kMTransX];
1195         spotOffset.fY += spotScale*viewMatrix[SkMatrix::kMTransY];
1196         // This offset is in dev space, need to transform it into source space.
1197         SkMatrix ctmInverse;
1198         if (viewMatrix.invert(&ctmInverse)) {
1199             ctmInverse.mapPoints(&spotOffset, 1);
1200         } else {
1201             // Since the matrix is a similarity, this should never happen, but just in case...
1202             SkDebugf("Matrix is degenerate. Will not render spot shadow correctly!\n");
1203             SkASSERT(false);
1204         }
1205 
1206         // Compute the transformed shadow rrect
1207         SkRRect spotShadowRRect;
1208         SkMatrix shadowTransform;
1209         shadowTransform.setScaleTranslate(spotScale, spotScale, spotOffset.fX, spotOffset.fY);
1210         rrect.transform(shadowTransform, &spotShadowRRect);
1211         SkScalar spotRadius = spotShadowRRect.getSimpleRadii().fX;
1212 
1213         // Compute the insetWidth
1214         SkScalar blurOutset = srcSpaceSpotBlur;
1215         SkScalar insetWidth = blurOutset;
1216         if (transparent) {
1217             // If transparent, just do a fill
1218             insetWidth += spotShadowRRect.width();
1219         } else {
1220             // For shadows, instead of using a stroke we specify an inset from the penumbra
1221             // border. We want to extend this inset area so that it meets up with the caster
1222             // geometry. The inset geometry will by default already be inset by the blur width.
1223             //
1224             // We compare the min and max corners inset by the radius between the original
1225             // rrect and the shadow rrect. The distance between the two plus the difference
1226             // between the scaled radius and the original radius gives the distance from the
1227             // transformed shadow shape to the original shape in that corner. The max
1228             // of these gives the maximum distance we need to cover.
1229             //
1230             // Since we are outsetting by 1/2 the blur distance, we just add the maxOffset to
1231             // that to get the full insetWidth.
1232             SkScalar maxOffset;
1233             if (rrect.isRect()) {
1234                 // Manhattan distance works better for rects
1235                 maxOffset = std::max(std::max(SkTAbs(spotShadowRRect.rect().fLeft -
1236                                                  rrect.rect().fLeft),
1237                                           SkTAbs(spotShadowRRect.rect().fTop -
1238                                                  rrect.rect().fTop)),
1239                                    std::max(SkTAbs(spotShadowRRect.rect().fRight -
1240                                                  rrect.rect().fRight),
1241                                           SkTAbs(spotShadowRRect.rect().fBottom -
1242                                                  rrect.rect().fBottom)));
1243             } else {
1244                 SkScalar dr = spotRadius - SkRRectPriv::GetSimpleRadii(rrect).fX;
1245                 SkPoint upperLeftOffset = SkPoint::Make(spotShadowRRect.rect().fLeft -
1246                                                         rrect.rect().fLeft + dr,
1247                                                         spotShadowRRect.rect().fTop -
1248                                                         rrect.rect().fTop + dr);
1249                 SkPoint lowerRightOffset = SkPoint::Make(spotShadowRRect.rect().fRight -
1250                                                          rrect.rect().fRight - dr,
1251                                                          spotShadowRRect.rect().fBottom -
1252                                                          rrect.rect().fBottom - dr);
1253                 maxOffset = SkScalarSqrt(std::max(SkPointPriv::LengthSqd(upperLeftOffset),
1254                                                   SkPointPriv::LengthSqd(lowerRightOffset))) + dr;
1255             }
1256             insetWidth += std::max(blurOutset, maxOffset);
1257         }
1258 
1259         // Outset the shadow rrect to the border of the penumbra
1260         SkRect outsetRect = spotShadowRRect.rect().makeOutset(blurOutset, blurOutset);
1261         if (spotShadowRRect.isOval()) {
1262             spotShadowRRect = SkRRect::MakeOval(outsetRect);
1263         } else {
1264             SkScalar outsetRad = spotRadius + blurOutset;
1265             spotShadowRRect = SkRRect::MakeRectXY(outsetRect, outsetRad, outsetRad);
1266         }
1267 
1268         // The ShadowRRectOp still uses 8888 colors, so it might get clamped if the shadow color
1269         // does not fit in bytes after being transformed to the destination color space. This can
1270         // happen if the destination color space is smaller than sRGB, which is highly unlikely.
1271         GrColor spotColor = SkColorToPMColor4f(rec.fSpotColor, colorInfo()).toBytes_RGBA();
1272         GrOp::Owner op = ShadowRRectOp::Make(fContext,
1273                                              spotColor,
1274                                              viewMatrix,
1275                                              spotShadowRRect,
1276                                              2.0f * devSpaceSpotBlur,
1277                                              insetWidth);
1278         if (op) {
1279             this->addDrawOp(clip, std::move(op));
1280         }
1281     }
1282 
1283     return true;
1284 }
1285 
1286 ///////////////////////////////////////////////////////////////////////////////
1287 
drawRegion(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRegion & region,const GrStyle & style,const GrUserStencilSettings * ss)1288 void SurfaceDrawContext::drawRegion(const GrClip* clip,
1289                                     GrPaint&& paint,
1290                                     GrAA aa,
1291                                     const SkMatrix& viewMatrix,
1292                                     const SkRegion& region,
1293                                     const GrStyle& style,
1294                                     const GrUserStencilSettings* ss) {
1295     ASSERT_SINGLE_OWNER
1296     RETURN_IF_ABANDONED
1297     SkDEBUGCODE(this->validate();)
1298     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawRegion", fContext);
1299 
1300     if (GrAA::kYes == aa) {
1301         // GrRegionOp performs no antialiasing but is much faster, so here we check the matrix
1302         // to see whether aa is really required.
1303         if (!SkToBool(viewMatrix.getType() & ~(SkMatrix::kTranslate_Mask)) &&
1304             SkScalarIsInt(viewMatrix.getTranslateX()) &&
1305             SkScalarIsInt(viewMatrix.getTranslateY())) {
1306             aa = GrAA::kNo;
1307         }
1308     }
1309     bool complexStyle = !style.isSimpleFill();
1310     if (complexStyle || GrAA::kYes == aa) {
1311         SkPath path;
1312         region.getBoundaryPath(&path);
1313         path.setIsVolatile(true);
1314 
1315         return this->drawPath(clip, std::move(paint), aa, viewMatrix, path, style);
1316     }
1317 
1318     GrAAType aaType = (this->numSamples() > 1) ? GrAAType::kMSAA : GrAAType::kNone;
1319     GrOp::Owner op = RegionOp::Make(fContext, std::move(paint), viewMatrix, region, aaType, ss);
1320     this->addDrawOp(clip, std::move(op));
1321 }
1322 
drawOval(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRect & oval,const GrStyle & style)1323 void SurfaceDrawContext::drawOval(const GrClip* clip,
1324                                   GrPaint&& paint,
1325                                   GrAA aa,
1326                                   const SkMatrix& viewMatrix,
1327                                   const SkRect& oval,
1328                                   const GrStyle& style) {
1329     ASSERT_SINGLE_OWNER
1330     RETURN_IF_ABANDONED
1331     SkDEBUGCODE(this->validate();)
1332     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawOval", fContext);
1333 
1334     const SkStrokeRec& stroke = style.strokeRec();
1335 
1336     if (oval.isEmpty() && !style.pathEffect()) {
1337         if (stroke.getStyle() == SkStrokeRec::kFill_Style) {
1338             return;
1339         }
1340 
1341         this->drawRect(clip, std::move(paint), aa, viewMatrix, oval, &style);
1342         return;
1343     }
1344 
1345     AutoCheckFlush acf(this->drawingManager());
1346 
1347     GrAAType aaType = this->chooseAAType(aa);
1348 
1349     GrOp::Owner op;
1350 #ifndef SK_ENABLE_OPTIMIZE_SIZE
1351     if (aaType == GrAAType::kCoverage      &&
1352         !fCanUseDynamicMSAA                &&
1353         !this->caps()->reducedShaderMode() &&
1354         oval.width() > SK_ScalarNearlyZero &&
1355         oval.width() == oval.height()      &&
1356         viewMatrix.isSimilarity()) {
1357         // In specific cases we use a dedicated circle op to try and get better perf.
1358         assert_alive(paint);
1359         op = GrOvalOpFactory::MakeCircleOp(fContext, std::move(paint), viewMatrix, oval, style,
1360                                            this->caps()->shaderCaps());
1361     }
1362 #endif
1363     if (!op && style.isSimpleFill()) {
1364         // FillRRectOp has special geometry and a fragment-shader branch to conditionally evaluate
1365         // the arc equation. This same special geometry and fragment branch also turn out to be a
1366         // substantial optimization for drawing ovals (namely, by not evaluating the arc equation
1367         // inside the oval's inner diamond). Given these optimizations, it's a clear win to draw
1368         // ovals the exact same way we do round rects.
1369         assert_alive(paint);
1370         op = FillRRectOp::Make(fContext, this->arenaAlloc(), std::move(paint), viewMatrix,
1371                                SkRRect::MakeOval(oval), oval, GrAA(aaType != GrAAType::kNone));
1372     }
1373 #ifndef SK_ENABLE_OPTIMIZE_SIZE
1374     if (!op && (aaType == GrAAType::kCoverage || fCanUseDynamicMSAA)) {
1375         assert_alive(paint);
1376         op = GrOvalOpFactory::MakeOvalOp(fContext, std::move(paint), viewMatrix, oval, style,
1377                                          this->caps()->shaderCaps());
1378     }
1379 #endif
1380     if (op) {
1381         this->addDrawOp(clip, std::move(op));
1382         return;
1383     }
1384 
1385     assert_alive(paint);
1386     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,
1387                                      GrStyledShape(SkRRect::MakeOval(oval), SkPathDirection::kCW, 2,
1388                                                    false, style, DoSimplify::kNo));
1389 }
1390 
drawArc(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRect & oval,SkScalar startAngle,SkScalar sweepAngle,bool useCenter,const GrStyle & style)1391 void SurfaceDrawContext::drawArc(const GrClip* clip,
1392                                  GrPaint&& paint,
1393                                  GrAA aa,
1394                                  const SkMatrix& viewMatrix,
1395                                  const SkRect& oval,
1396                                  SkScalar startAngle,
1397                                  SkScalar sweepAngle,
1398                                  bool useCenter,
1399                                  const GrStyle& style) {
1400     ASSERT_SINGLE_OWNER
1401     RETURN_IF_ABANDONED
1402     SkDEBUGCODE(this->validate();)
1403             GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawArc", fContext);
1404 
1405     AutoCheckFlush acf(this->drawingManager());
1406 
1407 #ifndef SK_ENABLE_OPTIMIZE_SIZE
1408     GrAAType aaType = this->chooseAAType(aa);
1409     if (aaType == GrAAType::kCoverage) {
1410         const GrShaderCaps* shaderCaps = this->caps()->shaderCaps();
1411         GrOp::Owner op = GrOvalOpFactory::MakeArcOp(fContext,
1412                                                     std::move(paint),
1413                                                     viewMatrix,
1414                                                     oval,
1415                                                     startAngle,
1416                                                     sweepAngle,
1417                                                     useCenter,
1418                                                     style,
1419                                                     shaderCaps);
1420         if (op) {
1421             this->addDrawOp(clip, std::move(op));
1422             return;
1423         }
1424         assert_alive(paint);
1425     }
1426 #endif
1427     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,
1428                                      GrStyledShape::MakeArc(oval, startAngle, sweepAngle, useCenter,
1429                                                             style, DoSimplify::kNo));
1430 }
1431 
drawImageLattice(const GrClip * clip,GrPaint && paint,const SkMatrix & viewMatrix,GrSurfaceProxyView view,SkAlphaType alphaType,sk_sp<GrColorSpaceXform> csxf,GrSamplerState::Filter filter,std::unique_ptr<SkLatticeIter> iter,const SkRect & dst)1432 void SurfaceDrawContext::drawImageLattice(const GrClip* clip,
1433                                           GrPaint&& paint,
1434                                           const SkMatrix& viewMatrix,
1435                                           GrSurfaceProxyView view,
1436                                           SkAlphaType alphaType,
1437                                           sk_sp<GrColorSpaceXform> csxf,
1438                                           GrSamplerState::Filter filter,
1439                                           std::unique_ptr<SkLatticeIter> iter,
1440                                           const SkRect& dst) {
1441     ASSERT_SINGLE_OWNER
1442     RETURN_IF_ABANDONED
1443     SkDEBUGCODE(this->validate();)
1444     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawImageLattice", fContext);
1445 
1446     AutoCheckFlush acf(this->drawingManager());
1447 
1448     GrOp::Owner op =
1449               LatticeOp::MakeNonAA(fContext, std::move(paint), viewMatrix, std::move(view),
1450                                    alphaType, std::move(csxf), filter, std::move(iter), dst);
1451     this->addDrawOp(clip, std::move(op));
1452 }
1453 
drawDrawable(std::unique_ptr<SkDrawable::GpuDrawHandler> drawable,const SkRect & bounds)1454 void SurfaceDrawContext::drawDrawable(std::unique_ptr<SkDrawable::GpuDrawHandler> drawable,
1455                                       const SkRect& bounds) {
1456     ASSERT_SINGLE_OWNER
1457     RETURN_IF_ABANDONED
1458     SkDEBUGCODE(this->validate();)
1459     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawDrawable", fContext);
1460     GrOp::Owner op(DrawableOp::Make(fContext, std::move(drawable), bounds));
1461     SkASSERT(op);
1462     this->addOp(std::move(op));
1463 }
1464 
setLastClip(uint32_t clipStackGenID,const SkIRect & devClipBounds,int numClipAnalyticElements)1465 void SurfaceDrawContext::setLastClip(uint32_t clipStackGenID,
1466                                      const SkIRect& devClipBounds,
1467                                      int numClipAnalyticElements) {
1468     auto opsTask = this->getOpsTask();
1469     opsTask->fLastClipStackGenID = clipStackGenID;
1470     opsTask->fLastDevClipBounds = devClipBounds;
1471     opsTask->fLastClipNumAnalyticElements = numClipAnalyticElements;
1472 }
1473 
mustRenderClip(uint32_t clipStackGenID,const SkIRect & devClipBounds,int numClipAnalyticElements)1474 bool SurfaceDrawContext::mustRenderClip(uint32_t clipStackGenID,
1475                                         const SkIRect& devClipBounds,
1476                                         int numClipAnalyticElements) {
1477     auto opsTask = this->getOpsTask();
1478     return opsTask->fLastClipStackGenID != clipStackGenID ||
1479            !opsTask->fLastDevClipBounds.contains(devClipBounds) ||
1480            opsTask->fLastClipNumAnalyticElements != numClipAnalyticElements;
1481 }
1482 
waitOnSemaphores(int numSemaphores,const GrBackendSemaphore waitSemaphores[],bool deleteSemaphoresAfterWait)1483 bool SurfaceDrawContext::waitOnSemaphores(int numSemaphores,
1484                                           const GrBackendSemaphore waitSemaphores[],
1485                                           bool deleteSemaphoresAfterWait) {
1486     ASSERT_SINGLE_OWNER
1487     RETURN_FALSE_IF_ABANDONED
1488     SkDEBUGCODE(this->validate();)
1489     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "waitOnSemaphores", fContext);
1490 
1491     AutoCheckFlush acf(this->drawingManager());
1492 
1493     if (numSemaphores && !this->caps()->semaphoreSupport()) {
1494         return false;
1495     }
1496 
1497     auto direct = fContext->asDirectContext();
1498     if (!direct) {
1499         return false;
1500     }
1501 
1502     auto resourceProvider = direct->priv().resourceProvider();
1503 
1504     GrWrapOwnership ownership =
1505             deleteSemaphoresAfterWait ? kAdopt_GrWrapOwnership : kBorrow_GrWrapOwnership;
1506 
1507     std::unique_ptr<std::unique_ptr<GrSemaphore>[]> grSemaphores(
1508             new std::unique_ptr<GrSemaphore>[numSemaphores]);
1509     for (int i = 0; i < numSemaphores; ++i) {
1510         grSemaphores[i] = resourceProvider->wrapBackendSemaphore(waitSemaphores[i],
1511                                                                  GrSemaphoreWrapType::kWillWait,
1512                                                                  ownership);
1513     }
1514     this->drawingManager()->newWaitRenderTask(this->asSurfaceProxyRef(), std::move(grSemaphores),
1515                                               numSemaphores);
1516     return true;
1517 }
1518 
drawPath(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkPath & path,const GrStyle & style)1519 void SurfaceDrawContext::drawPath(const GrClip* clip,
1520                                   GrPaint&& paint,
1521                                   GrAA aa,
1522                                   const SkMatrix& viewMatrix,
1523                                   const SkPath& path,
1524                                   const GrStyle& style) {
1525     ASSERT_SINGLE_OWNER
1526     RETURN_IF_ABANDONED
1527     SkDEBUGCODE(this->validate();)
1528     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawPath", fContext);
1529 
1530     GrStyledShape shape(path, style, DoSimplify::kNo);
1531     this->drawShape(clip, std::move(paint), aa, viewMatrix, std::move(shape));
1532 }
1533 
drawShape(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,GrStyledShape && shape)1534 void SurfaceDrawContext::drawShape(const GrClip* clip,
1535                                    GrPaint&& paint,
1536                                    GrAA aa,
1537                                    const SkMatrix& viewMatrix,
1538                                    GrStyledShape&& shape) {
1539     ASSERT_SINGLE_OWNER
1540     RETURN_IF_ABANDONED
1541     SkDEBUGCODE(this->validate();)
1542     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawShape", fContext);
1543 
1544     if (shape.isEmpty()) {
1545         if (shape.inverseFilled()) {
1546             this->drawPaint(clip, std::move(paint), viewMatrix);
1547         }
1548         return;
1549     }
1550 
1551     AutoCheckFlush acf(this->drawingManager());
1552 
1553     // If we get here in drawShape(), we definitely need to use path rendering
1554     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix, std::move(shape),
1555                                      /* attemptDrawSimple */ true);
1556 }
1557 
get_clip_bounds(const SurfaceDrawContext * sdc,const GrClip * clip)1558 static SkIRect get_clip_bounds(const SurfaceDrawContext* sdc, const GrClip* clip) {
1559     return clip ? clip->getConservativeBounds() : SkIRect::MakeWH(sdc->width(), sdc->height());
1560 }
1561 
drawAndStencilPath(const GrHardClip * clip,const GrUserStencilSettings * ss,SkRegion::Op op,bool invert,GrAA aa,const SkMatrix & viewMatrix,const SkPath & path)1562 bool SurfaceDrawContext::drawAndStencilPath(const GrHardClip* clip,
1563                                             const GrUserStencilSettings* ss,
1564                                             SkRegion::Op op,
1565                                             bool invert,
1566                                             GrAA aa,
1567                                             const SkMatrix& viewMatrix,
1568                                             const SkPath& path) {
1569     ASSERT_SINGLE_OWNER
1570     RETURN_FALSE_IF_ABANDONED
1571     SkDEBUGCODE(this->validate();)
1572     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawAndStencilPath", fContext);
1573 
1574     if (path.isEmpty() && path.isInverseFillType()) {
1575         GrPaint paint;
1576         paint.setCoverageSetOpXPFactory(op, invert);
1577         this->stencilRect(clip, ss, std::move(paint), GrAA::kNo, SkMatrix::I(),
1578                           SkRect::Make(this->dimensions()));
1579         return true;
1580     }
1581 
1582     AutoCheckFlush acf(this->drawingManager());
1583 
1584     // An Assumption here is that path renderer would use some form of tweaking
1585     // the src color (either the input alpha or in the frag shader) to implement
1586     // aa. If we have some future driver-mojo path AA that can do the right
1587     // thing WRT to the blend then we'll need some query on the PR.
1588     GrAAType aaType = this->chooseAAType(aa);
1589     bool hasUserStencilSettings = !ss->isUnused();
1590 
1591     SkIRect clipConservativeBounds = get_clip_bounds(this, clip);
1592 
1593     GrPaint paint;
1594     paint.setCoverageSetOpXPFactory(op, invert);
1595 
1596     GrStyledShape shape(path, GrStyle::SimpleFill());
1597     PathRenderer::CanDrawPathArgs canDrawArgs;
1598     canDrawArgs.fCaps = this->caps();
1599     canDrawArgs.fProxy = this->asRenderTargetProxy();
1600     canDrawArgs.fViewMatrix = &viewMatrix;
1601     canDrawArgs.fShape = &shape;
1602     canDrawArgs.fPaint = &paint;
1603     canDrawArgs.fSurfaceProps = &fSurfaceProps;
1604     canDrawArgs.fClipConservativeBounds = &clipConservativeBounds;
1605     canDrawArgs.fAAType = aaType;
1606     canDrawArgs.fHasUserStencilSettings = hasUserStencilSettings;
1607 
1608     using DrawType = PathRendererChain::DrawType;
1609 
1610     // Don't allow the SW renderer
1611     auto pr = this->drawingManager()->getPathRenderer(canDrawArgs,
1612                                                       false,
1613                                                       DrawType::kStencilAndColor);
1614     if (!pr) {
1615         return false;
1616     }
1617 
1618     PathRenderer::DrawPathArgs args{this->drawingManager()->getContext(),
1619                                     std::move(paint),
1620                                     ss,
1621                                     this,
1622                                     clip,
1623                                     &clipConservativeBounds,
1624                                     &viewMatrix,
1625                                     &shape,
1626                                     aaType,
1627                                     this->colorInfo().isLinearlyBlended()};
1628     pr->drawPath(args);
1629     return true;
1630 }
1631 
isBudgeted() const1632 skgpu::Budgeted SurfaceDrawContext::isBudgeted() const {
1633     ASSERT_SINGLE_OWNER
1634 
1635     if (fContext->abandoned()) {
1636         return skgpu::Budgeted::kNo;
1637     }
1638 
1639     SkDEBUGCODE(this->validate();)
1640 
1641     return this->asSurfaceProxy()->isBudgeted();
1642 }
1643 
drawStrokedLine(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkPoint points[2],const SkStrokeRec & stroke)1644 void SurfaceDrawContext::drawStrokedLine(const GrClip* clip,
1645                                          GrPaint&& paint,
1646                                          GrAA aa,
1647                                          const SkMatrix& viewMatrix,
1648                                          const SkPoint points[2],
1649                                          const SkStrokeRec& stroke) {
1650     ASSERT_SINGLE_OWNER
1651 
1652     SkASSERT(stroke.getStyle() == SkStrokeRec::kStroke_Style);
1653     SkASSERT(stroke.getWidth() > 0);
1654     // Adding support for round capping would require a
1655     // SurfaceDrawContext::fillRRectWithLocalMatrix entry point
1656     SkASSERT(SkPaint::kRound_Cap != stroke.getCap());
1657 
1658     const SkScalar halfWidth = 0.5f * stroke.getWidth();
1659     if (halfWidth <= 0.f) {
1660         // Prevents underflow when stroke width is epsilon > 0 (so technically not a hairline).
1661         // The CTM would need to have a scale near 1/epsilon in order for this to have meaningful
1662         // coverage (although that would likely overflow elsewhere and cause the draw to drop due
1663         // to non-finite bounds). At any other scale, this line is so thin, it's coverage is
1664         // negligible, so discarding the draw is visually equivalent.
1665         return;
1666     }
1667 
1668     SkVector parallel = points[1] - points[0];
1669 
1670     if (!SkPoint::Normalize(&parallel)) {
1671         parallel.fX = 1.0f;
1672         parallel.fY = 0.0f;
1673     }
1674     parallel *= halfWidth;
1675 
1676     SkVector ortho = { parallel.fY, -parallel.fX };
1677     SkPoint p0 = points[0], p1 = points[1];
1678     if (stroke.getCap() == SkPaint::kSquare_Cap) {
1679         // Extra extension for square caps
1680         p0 -= parallel;
1681         p1 += parallel;
1682     }
1683 
1684     // If we are using dmsaa or reduced shader mode then attempt to draw with FillRRectOp.
1685     if (this->caps()->drawInstancedSupport() &&
1686         (this->alwaysAntialias() ||
1687          (fContext->priv().caps()->reducedShaderMode() && aa == GrAA::kYes))) {
1688         SkMatrix localMatrix = SkMatrix::MakeAll(p1.fX - p0.fX, ortho.fX, p0.fX,
1689                                                  p1.fY - p0.fY, ortho.fY, p0.fY,
1690                                                  0, 0, 1);
1691         if (auto op = FillRRectOp::Make(fContext,
1692                                         this->arenaAlloc(),
1693                                         std::move(paint),
1694                                         SkMatrix::Concat(viewMatrix, localMatrix),
1695                                         SkRRect::MakeRect({0,-1,1,1}),
1696                                         localMatrix,
1697                                         GrAA::kYes)) {
1698             this->addDrawOp(clip, std::move(op));
1699             return;
1700         }
1701     }
1702 
1703     // Order is TL, TR, BR, BL where arbitrarily "down" is p0 to p1 and "right" is positive
1704     SkPoint corners[4] = { p0 - ortho,
1705                            p0 + ortho,
1706                            p1 + ortho,
1707                            p1 - ortho };
1708 
1709     GrQuadAAFlags edgeAA = (aa == GrAA::kYes) ? GrQuadAAFlags::kAll : GrQuadAAFlags::kNone;
1710 
1711     assert_alive(paint);
1712     this->fillQuadWithEdgeAA(clip, std::move(paint), edgeAA, viewMatrix, corners, nullptr);
1713 }
1714 
drawSimpleShape(const GrClip * clip,GrPaint * paint,GrAA aa,const SkMatrix & viewMatrix,const GrStyledShape & shape)1715 bool SurfaceDrawContext::drawSimpleShape(const GrClip* clip,
1716                                          GrPaint* paint,
1717                                          GrAA aa,
1718                                          const SkMatrix& viewMatrix,
1719                                          const GrStyledShape& shape) {
1720     if (!shape.style().hasPathEffect()) {
1721         GrAAType aaType = this->chooseAAType(aa);
1722         SkPoint linePts[2];
1723         SkRRect rrect;
1724         // We can ignore the starting point and direction since there is no path effect.
1725         bool inverted;
1726         if (shape.asLine(linePts, &inverted) && !inverted &&
1727             shape.style().strokeRec().getStyle() == SkStrokeRec::kStroke_Style &&
1728             shape.style().strokeRec().getCap() != SkPaint::kRound_Cap) {
1729             // The stroked line is an oriented rectangle, which looks the same or better (if
1730             // perspective) compared to path rendering. The exception is subpixel/hairline lines
1731             // that are non-AA or MSAA, in which case the default path renderer achieves higher
1732             // quality.
1733             // FIXME(michaelludwig): If the fill rect op could take an external coverage, or checks
1734             // for and outsets thin non-aa rects to 1px, the path renderer could be skipped.
1735             SkScalar coverage;
1736             if (aaType == GrAAType::kCoverage ||
1737                 !SkDrawTreatAAStrokeAsHairline(shape.style().strokeRec().getWidth(), viewMatrix,
1738                                                &coverage)) {
1739                 this->drawStrokedLine(clip, std::move(*paint), aa, viewMatrix, linePts,
1740                                       shape.style().strokeRec());
1741                 return true;
1742             }
1743         } else if (shape.asRRect(&rrect, nullptr, nullptr, &inverted) && !inverted) {
1744             if (rrect.isRect()) {
1745                 this->drawRect(clip, std::move(*paint), aa, viewMatrix, rrect.rect(),
1746                                &shape.style());
1747                 return true;
1748             } else if (rrect.isOval()) {
1749                 this->drawOval(clip, std::move(*paint), aa, viewMatrix, rrect.rect(),
1750                                shape.style());
1751                 return true;
1752             }
1753             this->drawRRect(clip, std::move(*paint), aa, viewMatrix, rrect, shape.style());
1754             return true;
1755         } else if (GrAAType::kCoverage == aaType &&
1756                    shape.style().isSimpleFill()  &&
1757                    viewMatrix.rectStaysRect()    &&
1758                    !this->caps()->reducedShaderMode()) {
1759             // TODO: the rectStaysRect restriction could be lifted if we were willing to apply the
1760             // matrix to all the points individually rather than just to the rect
1761             SkRect rects[2];
1762             if (shape.asNestedRects(rects)) {
1763                 // Concave AA paths are expensive - try to avoid them for special cases
1764                 GrOp::Owner op = ganesh::StrokeRectOp::MakeNested(fContext, std::move(*paint),
1765                                                                   viewMatrix, rects);
1766                 if (op) {
1767                     this->addDrawOp(clip, std::move(op));
1768                     return true;
1769                 }
1770                 // Fall through to let path renderer handle subpixel nested rects with unequal
1771                 // stroke widths along X/Y.
1772             }
1773         }
1774     }
1775     return false;
1776 }
1777 
drawShapeUsingPathRenderer(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,GrStyledShape && shape,bool attemptDrawSimple)1778 void SurfaceDrawContext::drawShapeUsingPathRenderer(const GrClip* clip,
1779                                                     GrPaint&& paint,
1780                                                     GrAA aa,
1781                                                     const SkMatrix& viewMatrix,
1782                                                     GrStyledShape&& shape,
1783                                                     bool attemptDrawSimple) {
1784     ASSERT_SINGLE_OWNER
1785     RETURN_IF_ABANDONED
1786     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "internalDrawPath", fContext);
1787 
1788     if (!viewMatrix.isFinite() || !shape.bounds().isFinite()) {
1789         return;
1790     }
1791 
1792     SkIRect clipConservativeBounds = get_clip_bounds(this, clip);
1793 
1794     // Always allow paths to trigger DMSAA.
1795     GrAAType aaType = fCanUseDynamicMSAA ? GrAAType::kMSAA : this->chooseAAType(aa);
1796 
1797     PathRenderer::CanDrawPathArgs canDrawArgs;
1798     canDrawArgs.fCaps = this->caps();
1799     canDrawArgs.fProxy = this->asRenderTargetProxy();
1800     canDrawArgs.fViewMatrix = &viewMatrix;
1801     canDrawArgs.fShape = &shape;
1802     canDrawArgs.fPaint = &paint;
1803     canDrawArgs.fSurfaceProps = &fSurfaceProps;
1804     canDrawArgs.fClipConservativeBounds = &clipConservativeBounds;
1805     canDrawArgs.fHasUserStencilSettings = false;
1806     canDrawArgs.fAAType = aaType;
1807 
1808     constexpr static bool kDisallowSWPathRenderer = false;
1809     constexpr static bool kAllowSWPathRenderer = true;
1810     using DrawType = PathRendererChain::DrawType;
1811 
1812     PathRenderer* pr = nullptr;
1813 
1814     if (!shape.style().strokeRec().isFillStyle() && !shape.isEmpty()) {
1815         // Give the tessellation path renderer a chance to claim this stroke before we simplify it.
1816         PathRenderer* tess = this->drawingManager()->getTessellationPathRenderer();
1817         if (tess && tess->canDrawPath(canDrawArgs) == PathRenderer::CanDrawPath::kYes) {
1818             pr = tess;
1819         }
1820     }
1821 
1822     if (!pr) {
1823         // The shape isn't a stroke that can be drawn directly. Simplify if possible.
1824         shape.simplify();
1825 
1826         if (shape.isEmpty() && !shape.inverseFilled()) {
1827             return;
1828         }
1829 
1830         if (attemptDrawSimple || shape.simplified()) {
1831             // Usually we enter drawShapeUsingPathRenderer() because the shape+style was too complex
1832             // for dedicated draw ops. However, if GrStyledShape was able to reduce something we
1833             // ought to try again instead of going right to path rendering.
1834             if (this->drawSimpleShape(clip, &paint, aa, viewMatrix, shape)) {
1835                 return;
1836             }
1837         }
1838 
1839         // Try a 1st time without applying any of the style to the geometry (and barring sw)
1840         pr = this->drawingManager()->getPathRenderer(canDrawArgs, kDisallowSWPathRenderer,
1841                                                      DrawType::kColor);
1842     }
1843 
1844     SkScalar styleScale =  GrStyle::MatrixToScaleFactor(viewMatrix);
1845     if (styleScale == 0.0f) {
1846         return;
1847     }
1848 
1849     if (!pr && shape.style().pathEffect()) {
1850         // It didn't work above, so try again with the path effect applied.
1851         shape = shape.applyStyle(GrStyle::Apply::kPathEffectOnly, styleScale);
1852         if (shape.isEmpty()) {
1853             return;
1854         }
1855         pr = this->drawingManager()->getPathRenderer(canDrawArgs, kDisallowSWPathRenderer,
1856                                                      DrawType::kColor);
1857     }
1858     if (!pr) {
1859         if (shape.style().applies()) {
1860             shape = shape.applyStyle(GrStyle::Apply::kPathEffectAndStrokeRec, styleScale);
1861             if (shape.isEmpty()) {
1862                 return;
1863             }
1864             // This time, allow SW renderer
1865             pr = this->drawingManager()->getPathRenderer(canDrawArgs, kAllowSWPathRenderer,
1866                                                          DrawType::kColor);
1867         } else {
1868             pr = this->drawingManager()->getSoftwarePathRenderer();
1869 #if GR_PATH_RENDERER_SPEW
1870             SkDebugf("falling back to: %s\n", pr->name());
1871 #endif
1872         }
1873     }
1874 
1875     if (!pr) {
1876 #ifdef SK_DEBUG
1877         SkDebugf("Unable to find path renderer compatible with path.\n");
1878 #endif
1879         return;
1880     }
1881 
1882     PathRenderer::DrawPathArgs args{this->drawingManager()->getContext(),
1883                                     std::move(paint),
1884                                     &GrUserStencilSettings::kUnused,
1885                                     this,
1886                                     clip,
1887                                     &clipConservativeBounds,
1888                                     &viewMatrix,
1889                                     canDrawArgs.fShape,
1890                                     aaType,
1891                                     this->colorInfo().isLinearlyBlended()};
1892     pr->drawPath(args);
1893 }
1894 
addDrawOp(const GrClip * clip,GrOp::Owner op,const std::function<WillAddOpFn> & willAddFn)1895 void SurfaceDrawContext::addDrawOp(const GrClip* clip,
1896                                    GrOp::Owner op,
1897                                    const std::function<WillAddOpFn>& willAddFn) {
1898     ASSERT_SINGLE_OWNER
1899     if (fContext->abandoned()) {
1900         return;
1901     }
1902     GrDrawOp* drawOp = (GrDrawOp*)op.get();
1903     SkDEBUGCODE(this->validate();)
1904     SkDEBUGCODE(drawOp->fAddDrawOpCalled = true;)
1905     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "addDrawOp", fContext);
1906 
1907     // Setup clip
1908     SkRect bounds;
1909     op_bounds(&bounds, op.get());
1910     GrAppliedClip appliedClip(this->dimensions(), this->asSurfaceProxy()->backingStoreDimensions());
1911     const bool opUsesMSAA = drawOp->usesMSAA();
1912     bool skipDraw = false;
1913     if (clip) {
1914         // Have a complex clip, so defer to its early clip culling
1915         GrAAType aaType;
1916         if (opUsesMSAA) {
1917             aaType = GrAAType::kMSAA;
1918         } else {
1919             aaType = op->hasAABloat() ? GrAAType::kCoverage : GrAAType::kNone;
1920         }
1921         skipDraw = clip->apply(fContext, this, drawOp, aaType,
1922                                &appliedClip, &bounds) == GrClip::Effect::kClippedOut;
1923     } else {
1924         // No clipping, so just clip the bounds against the logical render target dimensions
1925         skipDraw = !bounds.intersect(this->asSurfaceProxy()->getBoundsRect());
1926     }
1927 
1928     if (skipDraw) {
1929         return;
1930     }
1931 
1932     GrClampType clampType = GrColorTypeClampType(this->colorInfo().colorType());
1933     GrProcessorSet::Analysis analysis = drawOp->finalize(*this->caps(), &appliedClip, clampType);
1934 
1935     const bool opUsesStencil = drawOp->usesStencil();
1936 
1937     // Always trigger DMSAA when there is stencil. This ensures stencil contents get properly
1938     // preserved between render passes, if needed.
1939     const bool drawNeedsMSAA = opUsesMSAA || (fCanUseDynamicMSAA && opUsesStencil);
1940 
1941     // Must be called before setDstProxyView so that it sees the final bounds of the op.
1942     op->setClippedBounds(bounds);
1943 
1944     // Determine if the Op will trigger the use of a separate DMSAA attachment that requires manual
1945     // resolves.
1946     // TODO: Currently usesAttachmentIfDMSAA checks if this is a textureProxy or not. This check is
1947     // really only for GL which uses a normal texture sampling when using barriers. For Vulkan it
1948     // is possible to use the msaa buffer as an input attachment even if this is not a texture.
1949     // However, support for that is not fully implemented yet in Vulkan. Once it is, this check
1950     // should change to a virtual caps check that returns whether we need to break up an OpsTask
1951     // if it has barriers and we are about to promote to MSAA.
1952     bool usesAttachmentIfDMSAA =
1953             fCanUseDynamicMSAA &&
1954             (!this->caps()->msaaResolvesAutomatically() || !this->asTextureProxy());
1955     bool opRequiresDMSAAAttachment = usesAttachmentIfDMSAA && drawNeedsMSAA;
1956     bool opTriggersDMSAAAttachment =
1957             opRequiresDMSAAAttachment && !this->getOpsTask()->usesMSAASurface();
1958     if (opTriggersDMSAAAttachment) {
1959         // This will be the op that actually triggers use of a DMSAA attachment. Texture barriers
1960         // can't be moved to a DMSAA attachment, so if there already are any on the current opsTask
1961         // then we need to split.
1962         if (this->getOpsTask()->renderPassXferBarriers() & GrXferBarrierFlags::kTexture) {
1963             SkASSERT(!this->getOpsTask()->isColorNoOp());
1964             this->replaceOpsTask()->setCannotMergeBackward();
1965         }
1966     }
1967 
1968     GrDstProxyView dstProxyView;
1969     if (analysis.requiresDstTexture()) {
1970         if (!this->setupDstProxyView(drawOp->bounds(), drawNeedsMSAA, &dstProxyView)) {
1971             return;
1972         }
1973 #ifdef SK_DEBUG
1974         if (fCanUseDynamicMSAA && drawNeedsMSAA && !this->caps()->msaaResolvesAutomatically()) {
1975             // Since we aren't literally writing to the render target texture while using a DMSAA
1976             // attachment, we need to resolve that texture before sampling it. Ensure the current
1977             // opsTask got closed off in order to initiate an implicit resolve.
1978             SkASSERT(this->getOpsTask()->isEmpty());
1979         }
1980 #endif
1981     }
1982 
1983     auto opsTask = this->getOpsTask();
1984     if (willAddFn) {
1985         willAddFn(op.get(), opsTask->uniqueID());
1986     }
1987 
1988     // Note if the op needs stencil. Stencil clipping already called setNeedsStencil for itself, if
1989     // needed.
1990     if (opUsesStencil) {
1991         this->setNeedsStencil();
1992     }
1993 
1994 #if GR_GPU_STATS && GR_TEST_UTILS
1995     if (fCanUseDynamicMSAA && drawNeedsMSAA) {
1996         if (!opsTask->usesMSAASurface()) {
1997             fContext->priv().dmsaaStats().fNumMultisampleRenderPasses++;
1998         }
1999         fContext->priv().dmsaaStats().fTriggerCounts[op->name()]++;
2000     }
2001 #endif
2002 
2003     opsTask->addDrawOp(this->drawingManager(), std::move(op), drawNeedsMSAA, analysis,
2004                        std::move(appliedClip), dstProxyView,
2005                        GrTextureResolveManager(this->drawingManager()), *this->caps());
2006 
2007 #ifdef SK_DEBUG
2008     if (fCanUseDynamicMSAA && drawNeedsMSAA) {
2009         SkASSERT(opsTask->usesMSAASurface());
2010     }
2011 #endif
2012 }
2013 
setupDstProxyView(const SkRect & opBounds,bool opRequiresMSAA,GrDstProxyView * dstProxyView)2014 bool SurfaceDrawContext::setupDstProxyView(const SkRect& opBounds,
2015                                            bool opRequiresMSAA,
2016                                            GrDstProxyView* dstProxyView) {
2017     // If we are wrapping a vulkan secondary command buffer, we can't make a dst copy because we
2018     // don't actually have a VkImage to make a copy of. Additionally we don't have the power to
2019     // start and stop the render pass in order to make the copy.
2020     if (this->asRenderTargetProxy()->wrapsVkSecondaryCB()) {
2021         return false;
2022     }
2023 
2024     // First get the dstSampleFlags as if we will put the draw into the current OpsTask
2025     auto dstSampleFlags = this->caps()->getDstSampleFlagsForProxy(
2026             this->asRenderTargetProxy(), this->getOpsTask()->usesMSAASurface() || opRequiresMSAA);
2027 
2028     // If we don't have barriers for this draw then we will definitely be breaking up the OpsTask.
2029     // However, if using dynamic MSAA, the new OpsTask will not have MSAA already enabled on it
2030     // and that may allow us to use texture barriers. So we check if we can use barriers on the new
2031     // ops task and then break it up if so.
2032     if (!(dstSampleFlags & GrDstSampleFlags::kRequiresTextureBarrier) &&
2033         fCanUseDynamicMSAA && this->getOpsTask()->usesMSAASurface() && !opRequiresMSAA) {
2034         auto newFlags =
2035                 this->caps()->getDstSampleFlagsForProxy(this->asRenderTargetProxy(),
2036                                                         false/*=opRequiresMSAA*/);
2037         if (newFlags & GrDstSampleFlags::kRequiresTextureBarrier) {
2038             // We can't have an empty ops task if we are in DMSAA and the ops task already returns
2039             // true for usesMSAASurface.
2040             SkASSERT(!this->getOpsTask()->isColorNoOp());
2041             this->replaceOpsTask()->setCannotMergeBackward();
2042             dstSampleFlags = newFlags;
2043         }
2044     }
2045 
2046     if (dstSampleFlags & GrDstSampleFlags::kRequiresTextureBarrier) {
2047         // If we require a barrier to sample the dst it means we are sampling the RT itself
2048         // either as a texture or input attachment. In this case we don't need to break up the
2049         // OpsTask.
2050         dstProxyView->setProxyView(this->readSurfaceView());
2051         dstProxyView->setOffset(0, 0);
2052         dstProxyView->setDstSampleFlags(dstSampleFlags);
2053         return true;
2054     }
2055     SkASSERT(dstSampleFlags == GrDstSampleFlags::kNone);
2056 
2057     // We are using a different surface from the main color attachment to sample the dst from. If we
2058     // are in DMSAA we can just use the single sampled RT texture itself. Otherwise, we must do a
2059     // copy.
2060     // We do have to check if we ended up here becasue we don't have texture barriers but do have
2061     // msaaResolvesAutomatically (i.e. render-to-msaa-texture). In that case there will be no op or
2062     // barrier between draws to flush the render target before being used as a texture in the next
2063     // draw. So in that case we just fall through to doing a copy.
2064     if (fCanUseDynamicMSAA && opRequiresMSAA && this->asTextureProxy() &&
2065         !this->caps()->msaaResolvesAutomatically() &&
2066         this->caps()->dmsaaResolveCanBeUsedAsTextureInSameRenderPass()) {
2067         this->replaceOpsTaskIfModifiesColor()->setCannotMergeBackward();
2068         dstProxyView->setProxyView(this->readSurfaceView());
2069         dstProxyView->setOffset(0, 0);
2070         dstProxyView->setDstSampleFlags(dstSampleFlags);
2071         return true;
2072     }
2073 
2074     // Now we fallback to doing a copy.
2075 
2076     GrColorType colorType = this->colorInfo().colorType();
2077     // MSAA consideration: When there is support for reading MSAA samples in the shader we could
2078     // have per-sample dst values by making the copy multisampled.
2079     GrCaps::DstCopyRestrictions restrictions = this->caps()->getDstCopyRestrictions(
2080             this->asRenderTargetProxy(), colorType);
2081 
2082     SkIRect copyRect = SkIRect::MakeSize(this->asSurfaceProxy()->backingStoreDimensions());
2083     if (!restrictions.fMustCopyWholeSrc) {
2084         // If we don't need the whole source, restrict to the op's bounds. We add an extra pixel
2085         // of padding to account for AA bloat and the unpredictable rounding of coords near pixel
2086         // centers during rasterization.
2087         SkIRect conservativeDrawBounds = opBounds.roundOut();
2088         conservativeDrawBounds.outset(1, 1);
2089         SkAssertResult(copyRect.intersect(conservativeDrawBounds));
2090     }
2091 
2092     SkIPoint dstOffset;
2093     SkBackingFit fit;
2094     if (restrictions.fRectsMustMatch == GrSurfaceProxy::RectsMustMatch::kYes) {
2095         dstOffset = {0, 0};
2096         fit = SkBackingFit::kExact;
2097     } else {
2098         dstOffset = {copyRect.fLeft, copyRect.fTop};
2099         fit = SkBackingFit::kApprox;
2100     }
2101     auto copy = GrSurfaceProxy::Copy(fContext,
2102                                      this->asSurfaceProxyRef(),
2103                                      this->origin(),
2104                                      GrMipmapped::kNo,
2105                                      copyRect,
2106                                      fit,
2107                                      skgpu::Budgeted::kYes,
2108                                      /*label=*/{},
2109                                      restrictions.fRectsMustMatch);
2110     SkASSERT(copy);
2111 
2112     dstProxyView->setProxyView({std::move(copy), this->origin(), this->readSwizzle()});
2113     dstProxyView->setOffset(dstOffset);
2114     dstProxyView->setDstSampleFlags(dstSampleFlags);
2115     return true;
2116 }
2117 
replaceOpsTaskIfModifiesColor()2118 OpsTask* SurfaceDrawContext::replaceOpsTaskIfModifiesColor() {
2119     if (!this->getOpsTask()->isColorNoOp()) {
2120         this->replaceOpsTask();
2121     }
2122     return this->getOpsTask();
2123 }
2124 
2125 } // namespace skgpu::v1
2126