Debian Codegraph @

src/gpu/ganesh/SurfaceDrawContext.cpp

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