Debian Codegraph @

src/gpu/ganesh/SurfaceDrawContext.cpp

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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 this->internalStencilClear(nullptr, /* inside mask */ false);
834 } else {
835 this->getOpsTask()->setInitialStencilContent(
836 OpsTask::StencilContent::kUserBitsCleared);
837 }
838 }
839 }
840
841 void SurfaceDrawContext::internalStencilClear(const SkIRect* scissor, bool insideStencilMask) {
842 this->setNeedsStencil();
843
844 GrScissorState scissorState(this->asSurfaceProxy()->backingStoreDimensions());
845 if (scissor && !scissorState.set(*scissor)) {
846 // The requested clear region is off screen, so nothing to do.
847 return;
848 }
849
850 bool clearWithDraw = this->caps()->performStencilClearsAsDraws() ||
851 (scissorState.enabled() && this->caps()->performPartialClearsAsDraws());
852 if (clearWithDraw) {
853 const GrUserStencilSettings* ss = GrStencilSettings::SetClipBitSettings(insideStencilMask);
854
855 // Configure the paint to have no impact on the color buffer
856 GrPaint paint;
857 paint.setXPFactory(GrDisableColorXPFactory::Get());
858 this->addDrawOp(nullptr,
859 FillRectOp::MakeNonAARect(fContext, std::move(paint), SkMatrix::I(),
860 SkRect::Make(scissorState.rect()), ss));
861 } else {
862 this->addOp(ClearOp::MakeStencilClip(fContext, scissorState, insideStencilMask));
863 }
864 }
865
866 bool SurfaceDrawContext::stencilPath(const GrHardClip* clip,
867 GrAA doStencilMSAA,
868 const SkMatrix& viewMatrix,
869 const SkPath& path) {
870 SkIRect clipBounds = clip ? clip->getConservativeBounds()
871 : SkIRect::MakeSize(this->dimensions());
872 GrStyledShape shape(path, GrStyledShape::DoSimplify::kNo);
873
874 PathRenderer::CanDrawPathArgs canDrawArgs;
875 canDrawArgs.fCaps = fContext->priv().caps();
876 canDrawArgs.fProxy = this->asRenderTargetProxy();
877 canDrawArgs.fClipConservativeBounds = &clipBounds;
878 canDrawArgs.fViewMatrix = &viewMatrix;
879 canDrawArgs.fShape = &shape;
880 canDrawArgs.fPaint = nullptr;
881 canDrawArgs.fSurfaceProps = &fSurfaceProps;
882 canDrawArgs.fAAType = (doStencilMSAA == GrAA::kYes) ? GrAAType::kMSAA : GrAAType::kNone;
883 canDrawArgs.fHasUserStencilSettings = false;
884 auto pr = this->drawingManager()->getPathRenderer(canDrawArgs,
885 false,
886 PathRendererChain::DrawType::kStencil);
887 if (!pr) {
888 SkDebugf("WARNING: No path renderer to stencil path.\n");
889 return false;
890 }
891
892 PathRenderer::StencilPathArgs args;
893 args.fContext = fContext;
894 args.fSurfaceDrawContext = this;
895 args.fClip = clip;
896 args.fClipConservativeBounds = &clipBounds;
897 args.fViewMatrix = &viewMatrix;
898 args.fShape = &shape;
899 args.fDoStencilMSAA = doStencilMSAA;
900 pr->stencilPath(args);
901 return true;
902 }
903
904 void SurfaceDrawContext::drawTextureSet(const GrClip* clip,
905 GrTextureSetEntry set[],
906 int cnt,
907 int proxyRunCnt,
908 GrSamplerState::Filter filter,
909 GrSamplerState::MipmapMode mm,
910 SkBlendMode mode,
911 SkCanvas::SrcRectConstraint constraint,
912 const SkMatrix& viewMatrix,
913 sk_sp<GrColorSpaceXform> texXform) {
914 ASSERT_SINGLE_OWNER
915 RETURN_IF_ABANDONED
916 SkDEBUGCODE(this->validate();)
917 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawTextureSet", fContext);
918
919 // Create the minimum number of GrTextureOps needed to draw this set. Individual
920 // GrTextureOps can rebind the texture between draws thus avoiding GrPaint (re)creation.
921 GrAAType aaType = this->chooseAAType(GrAA::kYes);
922 auto clampType = GrColorTypeClampType(this->colorInfo().colorType());
923 auto saturate = clampType == GrClampType::kManual ? ganesh::TextureOp::Saturate::kYes
924 : ganesh::TextureOp::Saturate::kNo;
925 ganesh::TextureOp::AddTextureSetOps(this, clip, fContext, set, cnt, proxyRunCnt, filter, mm,
926 saturate, mode, aaType, constraint, viewMatrix,
927 std::move(texXform));
928 }
929
930 void SurfaceDrawContext::drawVertices(const GrClip* clip,
931 GrPaint&& paint,
932 const SkMatrix& viewMatrix,
933 sk_sp<SkVertices> vertices,
934 GrPrimitiveType* overridePrimType,
935 bool skipColorXform) {
936 ASSERT_SINGLE_OWNER
937 RETURN_IF_ABANDONED
938 SkDEBUGCODE(this->validate();)
939 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawVertices", fContext);
940
941 SkASSERT(vertices);
942 auto xform = skipColorXform ? nullptr : this->colorInfo().refColorSpaceXformFromSRGB();
943 GrAAType aaType = fCanUseDynamicMSAA ? GrAAType::kMSAA : this->chooseAAType(GrAA::kNo);
944 GrOp::Owner op = DrawMeshOp::Make(fContext,
945 std::move(paint),
946 std::move(vertices),
947 overridePrimType,
948 viewMatrix,
949 aaType,
950 std::move(xform));
951 this->addDrawOp(clip, std::move(op));
952 }
953
954 void SurfaceDrawContext::drawMesh(const GrClip* clip,
955 GrPaint&& paint,
956 const SkMatrix& viewMatrix,
957 const SkMesh& mesh,
958 TArray<std::unique_ptr<GrFragmentProcessor>> children) {
959 ASSERT_SINGLE_OWNER
960 RETURN_IF_ABANDONED
961 SkDEBUGCODE(this->validate();)
962 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawMesh", fContext);
963
964 SkASSERT(mesh.isValid());
965
966 auto xform = GrColorSpaceXform::Make(SkMeshSpecificationPriv::ColorSpace(*mesh.spec()),
967 SkMeshSpecificationPriv::AlphaType(*mesh.spec()),
968 this->colorInfo().colorSpace(),
969 this->colorInfo().alphaType());
970 GrAAType aaType = fCanUseDynamicMSAA ? GrAAType::kMSAA : this->chooseAAType(GrAA::kNo);
971 GrOp::Owner op = DrawMeshOp::Make(fContext,
972 std::move(paint),
973 mesh,
974 std::move(children),
975 viewMatrix,
976 aaType,
977 std::move(xform));
978 this->addDrawOp(clip, std::move(op));
979 }
980
981 ///////////////////////////////////////////////////////////////////////////////
982
983 void SurfaceDrawContext::drawAtlas(const GrClip* clip,
984 GrPaint&& paint,
985 const SkMatrix& viewMatrix,
986 SkSpan<const SkRSXform> xform,
987 SkSpan<const SkRect> texRect,
988 SkSpan<const SkColor> colors) {
989 ASSERT_SINGLE_OWNER
990 RETURN_IF_ABANDONED
991 SkDEBUGCODE(this->validate();)
992 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawAtlas", fContext);
993
994 GrAAType aaType = this->chooseAAType(GrAA::kNo);
995 GrOp::Owner op = DrawAtlasOp::Make(fContext, std::move(paint), viewMatrix,
996 aaType, xform.size(), xform.data(),
997 texRect.data(), colors.data());
998 this->addDrawOp(clip, std::move(op));
999 }
1000
1001 ///////////////////////////////////////////////////////////////////////////////
1002
1003 void SurfaceDrawContext::drawRRect(const GrClip* origClip,
1004 GrPaint&& paint,
1005 GrAA aa,
1006 const SkMatrix& viewMatrix,
1007 const SkRRect& rrect,
1008 const GrStyle& style) {
1009 ASSERT_SINGLE_OWNER
1010 RETURN_IF_ABANDONED
1011 SkDEBUGCODE(this->validate();)
1012 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawRRect", fContext);
1013
1014 SkASSERT(!style.pathEffect()); // this should've been devolved to a path in SkGpuDevice
1015
1016 const SkStrokeRec& stroke = style.strokeRec();
1017 if (stroke.getStyle() == SkStrokeRec::kFill_Style && rrect.isEmpty()) {
1018 return;
1019 }
1020
1021 const GrClip* clip = origClip;
1022 // It is not uncommon to clip to a round rect and then draw that same round rect. Since our
1023 // lower level clip code works from op bounds, which are SkRects, it doesn't detect that the
1024 // clip can be ignored. The following test attempts to mitigate the stencil clip cost but only
1025 // works for axis-aligned round rects. This also only works for filled rrects since the stroke
1026 // width outsets beyond the rrect itself.
1027 // TODO: skbug.com/40041797 - There was mixed performance wins and regressions when this
1028 // optimization was turned on outside of Android Framework. I (michaelludwig) believe this is
1029 // do to the overhead in determining if an SkClipStack is just a rrect. Once that is improved,
1030 // re-enable this and see if we avoid the regressions.
1031 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1032 SkRRect devRRect;
1033 if (clip && stroke.getStyle() == SkStrokeRec::kFill_Style &&
1034 rrect.transform(viewMatrix, &devRRect)) {
1035 GrClip::PreClipResult result = clip->preApply(devRRect.getBounds(), aa);
1036 switch(result.fEffect) {
1037 case GrClip::Effect::kClippedOut:
1038 return;
1039 case GrClip::Effect::kUnclipped:
1040 clip = nullptr;
1041 break;
1042 case GrClip::Effect::kClipped:
1043 // Currently there's no general-purpose rrect-to-rrect contains function, and if we
1044 // got here, we know the devRRect's bounds aren't fully contained by the clip.
1045 // Testing for equality between the two is a reasonable stop-gap for now.
1046 if (result.fIsRRect && result.fRRect == devRRect) {
1047 // NOTE: On the android framework, we allow this optimization even when the clip
1048 // is non-AA and the draw is AA.
1049 if (result.fAA == aa || (result.fAA == GrAA::kNo && aa == GrAA::kYes)) {
1050 clip = nullptr;
1051 }
1052 }
1053 break;
1054 default:
1055 SkUNREACHABLE;
1056 }
1057 }
1058 #endif
1059
1060 GrAAType aaType = this->chooseAAType(aa);
1061
1062 GrOp::Owner op;
1063 #ifndef SK_ENABLE_OPTIMIZE_SIZE
1064 if (aaType == GrAAType::kCoverage &&
1065 !fCanUseDynamicMSAA &&
1066 !this->caps()->reducedShaderMode() &&
1067 rrect.isSimple() &&
1068 rrect.getSimpleRadii().fX == rrect.getSimpleRadii().fY &&
1069 viewMatrix.rectStaysRect() && viewMatrix.isSimilarity()) {
1070 // In specific cases we use a dedicated circular round rect op to try and get better perf.
1071 assert_alive(paint);
1072 op = GrOvalOpFactory::MakeCircularRRectOp(fContext, std::move(paint), viewMatrix, rrect,
1073 stroke, this->caps()->shaderCaps());
1074 }
1075 #endif
1076 if (!op && style.isSimpleFill()) {
1077 assert_alive(paint);
1078 op = FillRRectOp::Make(fContext, this->arenaAlloc(), std::move(paint), viewMatrix, rrect,
1079 rrect.rect(), GrAA(aaType != GrAAType::kNone));
1080 }
1081 #ifndef SK_ENABLE_OPTIMIZE_SIZE
1082 if (!op && (aaType == GrAAType::kCoverage || fCanUseDynamicMSAA)) {
1083 assert_alive(paint);
1084 op = GrOvalOpFactory::MakeRRectOp(
1085 fContext, std::move(paint), viewMatrix, rrect, stroke, this->caps()->shaderCaps());
1086 }
1087 #endif
1088 if (op) {
1089 this->addDrawOp(clip, std::move(op));
1090 return;
1091 }
1092
1093 assert_alive(paint);
1094 this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,
1095 GrStyledShape(rrect, style, DoSimplify::kNo));
1096 }
1097
1098 ///////////////////////////////////////////////////////////////////////////////
1099
1100 bool SurfaceDrawContext::drawFastShadow(const GrClip* clip,
1101 const SkMatrix& viewMatrix,
1102 const SkPath& path,
1103 const SkDrawShadowRec& rec) {
1104 ASSERT_SINGLE_OWNER
1105 if (fContext->abandoned()) {
1106 return true;
1107 }
1108 SkDEBUGCODE(this->validate();)
1109 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawFastShadow", fContext);
1110
1111 // check z plane
1112 bool tiltZPlane = SkToBool(!SkScalarNearlyZero(rec.fZPlaneParams.fX) ||
1113 !SkScalarNearlyZero(rec.fZPlaneParams.fY));
1114 bool skipAnalytic = SkToBool(rec.fFlags & SkShadowFlags::kGeometricOnly_ShadowFlag);
1115 if (tiltZPlane || skipAnalytic || !viewMatrix.rectStaysRect() || !viewMatrix.isSimilarity()) {
1116 return false;
1117 }
1118
1119 SkRRect rrect;
1120 SkRect rect;
1121 // we can only handle rects, circles, and simple rrects with circular corners
1122 bool isRRect = path.isRRect(&rrect) && SkRRectPriv::IsNearlySimpleCircular(rrect) &&
1123 rrect.getSimpleRadii().fX > SK_ScalarNearlyZero;
1124 if (!isRRect &&
1125 path.isOval(&rect) && SkScalarNearlyEqual(rect.width(), rect.height()) &&
1126 rect.width() > SK_ScalarNearlyZero) {
1127 rrect.setOval(rect);
1128 isRRect = true;
1129 }
1130 if (!isRRect && path.isRect(&rect)) {
1131 rrect.setRect(rect);
1132 isRRect = true;
1133 }
1134
1135 if (!isRRect) {
1136 return false;
1137 }
1138
1139 if (rrect.isEmpty()) {
1140 return true;
1141 }
1142
1143 SkPoint3 devLightPos = rec.fLightPos;
1144 bool directional = SkToBool(rec.fFlags & kDirectionalLight_ShadowFlag);
1145 if (!directional) {
1146 // transform light
1147 viewMatrix.mapPoints({(SkPoint*)&devLightPos.fX, 1});
1148 }
1149
1150 // 1/scale
1151 SkScalar devToSrcScale = viewMatrix.isScaleTranslate() ?
1152 SkScalarInvert(SkScalarAbs(viewMatrix[SkMatrix::kMScaleX])) :
1153 sk_float_rsqrt(viewMatrix[SkMatrix::kMScaleX] * viewMatrix[SkMatrix::kMScaleX] +
1154 viewMatrix[SkMatrix::kMSkewX] * viewMatrix[SkMatrix::kMSkewX]);
1155
1156 SkScalar occluderHeight = rec.fZPlaneParams.fZ;
1157 bool transparent = SkToBool(rec.fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag);
1158
1159 if (SkColorGetA(rec.fAmbientColor) > 0) {
1160 SkScalar devSpaceInsetWidth = SkDrawShadowMetrics::AmbientBlurRadius(occluderHeight);
1161 const SkScalar umbraRecipAlpha = SkDrawShadowMetrics::AmbientRecipAlpha(occluderHeight);
1162 const SkScalar devSpaceAmbientBlur = devSpaceInsetWidth * umbraRecipAlpha;
1163
1164 // Outset the shadow rrect to the border of the penumbra
1165 SkScalar ambientPathOutset = devSpaceInsetWidth * devToSrcScale;
1166 SkRRect ambientRRect;
1167 SkRect outsetRect = rrect.rect().makeOutset(ambientPathOutset, ambientPathOutset);
1168 // If the rrect was an oval then its outset will also be one.
1169 // We set it explicitly to avoid errors.
1170 if (rrect.isOval()) {
1171 ambientRRect = SkRRect::MakeOval(outsetRect);
1172 } else {
1173 SkScalar outsetRad = SkRRectPriv::GetSimpleRadii(rrect).fX + ambientPathOutset;
1174 ambientRRect = SkRRect::MakeRectXY(outsetRect, outsetRad, outsetRad);
1175 }
1176
1177 // The ShadowRRectOp still uses 8888 colors, so it might get clamped if the shadow color
1178 // does not fit in bytes after being transformed to the destination color space. This can
1179 // happen if the destination color space is smaller than sRGB, which is highly unlikely.
1180 GrColor ambientColor = SkColorToPMColor4f(rec.fAmbientColor, colorInfo()).toBytes_RGBA();
1181 if (transparent) {
1182 // set a large inset to force a fill
1183 devSpaceInsetWidth = ambientRRect.width();
1184 }
1185
1186 GrOp::Owner op = ShadowRRectOp::Make(fContext,
1187 ambientColor,
1188 viewMatrix,
1189 ambientRRect,
1190 devSpaceAmbientBlur,
1191 devSpaceInsetWidth);
1192 if (op) {
1193 this->addDrawOp(clip, std::move(op));
1194 }
1195 }
1196
1197 if (SkColorGetA(rec.fSpotColor) > 0) {
1198 SkScalar devSpaceSpotBlur;
1199 SkScalar spotScale;
1200 SkVector spotOffset;
1201 if (directional) {
1202 SkDrawShadowMetrics::GetDirectionalParams(occluderHeight, devLightPos.fX,
1203 devLightPos.fY, devLightPos.fZ,
1204 rec.fLightRadius, &devSpaceSpotBlur,
1205 &spotScale, &spotOffset);
1206 } else {
1207 SkDrawShadowMetrics::GetSpotParams(occluderHeight, devLightPos.fX, devLightPos.fY,
1208 devLightPos.fZ, rec.fLightRadius,
1209 &devSpaceSpotBlur, &spotScale, &spotOffset);
1210 }
1211 // handle scale of radius due to CTM
1212 const SkScalar srcSpaceSpotBlur = devSpaceSpotBlur * devToSrcScale;
1213
1214 // Adjust translate for the effect of the scale.
1215 spotOffset.fX += spotScale*viewMatrix[SkMatrix::kMTransX];
1216 spotOffset.fY += spotScale*viewMatrix[SkMatrix::kMTransY];
1217 // This offset is in dev space, need to transform it into source space.
1218 if (auto ctmInverse = viewMatrix.invert()) {
1219 spotOffset = ctmInverse->mapPoint(spotOffset);
1220 } else {
1221 // Since the matrix is a similarity, this should never happen, but just in case...
1222 SkDebugf("Matrix is degenerate. Will not render spot shadow correctly!\n");
1223 SkASSERT(false);
1224 }
1225
1226 // Compute the transformed shadow rrect
1227 SkMatrix shadowTransform;
1228 shadowTransform.setScaleTranslate(spotScale, spotScale, spotOffset.fX, spotOffset.fY);
1229 SkRRect spotShadowRRect = rrect.transform(shadowTransform).value_or(SkRRect());
1230 SkScalar spotRadius = spotShadowRRect.getSimpleRadii().fX;
1231
1232 // Compute the insetWidth
1233 SkScalar blurOutset = srcSpaceSpotBlur;
1234 SkScalar insetWidth = blurOutset;
1235 if (transparent) {
1236 // If transparent, just do a fill
1237 insetWidth += spotShadowRRect.width();
1238 } else {
1239 // For shadows, instead of using a stroke we specify an inset from the penumbra
1240 // border. We want to extend this inset area so that it meets up with the caster
1241 // geometry. The inset geometry will by default already be inset by the blur width.
1242 //
1243 // We compare the min and max corners inset by the radius between the original
1244 // rrect and the shadow rrect. The distance between the two plus the difference
1245 // between the scaled radius and the original radius gives the distance from the
1246 // transformed shadow shape to the original shape in that corner. The max
1247 // of these gives the maximum distance we need to cover.
1248 //
1249 // Since we are outsetting by 1/2 the blur distance, we just add the maxOffset to
1250 // that to get the full insetWidth.
1251 SkScalar maxOffset;
1252 if (rrect.isRect()) {
1253 // Manhattan distance works better for rects
1254 maxOffset = std::max(std::max(SkTAbs(spotShadowRRect.rect().fLeft -
1255 rrect.rect().fLeft),
1256 SkTAbs(spotShadowRRect.rect().fTop -
1257 rrect.rect().fTop)),
1258 std::max(SkTAbs(spotShadowRRect.rect().fRight -
1259 rrect.rect().fRight),
1260 SkTAbs(spotShadowRRect.rect().fBottom -
1261 rrect.rect().fBottom)));
1262 } else {
1263 SkScalar dr = spotRadius - SkRRectPriv::GetSimpleRadii(rrect).fX;
1264 SkPoint upperLeftOffset = SkPoint::Make(spotShadowRRect.rect().fLeft -
1265 rrect.rect().fLeft + dr,
1266 spotShadowRRect.rect().fTop -
1267 rrect.rect().fTop + dr);
1268 SkPoint lowerRightOffset = SkPoint::Make(spotShadowRRect.rect().fRight -
1269 rrect.rect().fRight - dr,
1270 spotShadowRRect.rect().fBottom -
1271 rrect.rect().fBottom - dr);
1272 maxOffset = SkScalarSqrt(std::max(SkPointPriv::LengthSqd(upperLeftOffset),
1273 SkPointPriv::LengthSqd(lowerRightOffset))) + dr;
1274 }
1275 insetWidth += std::max(blurOutset, maxOffset);
1276 }
1277
1278 // Outset the shadow rrect to the border of the penumbra
1279 SkRect outsetRect = spotShadowRRect.rect().makeOutset(blurOutset, blurOutset);
1280 if (spotShadowRRect.isOval()) {
1281 spotShadowRRect = SkRRect::MakeOval(outsetRect);
1282 } else {
1283 SkScalar outsetRad = spotRadius + blurOutset;
1284 spotShadowRRect = SkRRect::MakeRectXY(outsetRect, outsetRad, outsetRad);
1285 }
1286
1287 // The ShadowRRectOp still uses 8888 colors, so it might get clamped if the shadow color
1288 // does not fit in bytes after being transformed to the destination color space. This can
1289 // happen if the destination color space is smaller than sRGB, which is highly unlikely.
1290 GrColor spotColor = SkColorToPMColor4f(rec.fSpotColor, colorInfo()).toBytes_RGBA();
1291 GrOp::Owner op = ShadowRRectOp::Make(fContext,
1292 spotColor,
1293 viewMatrix,
1294 spotShadowRRect,
1295 2.0f * devSpaceSpotBlur,
1296 insetWidth);
1297 if (op) {
1298 this->addDrawOp(clip, std::move(op));
1299 }
1300 }
1301
1302 return true;
1303 }
1304
1305 ///////////////////////////////////////////////////////////////////////////////
1306
1307 void SurfaceDrawContext::drawRegion(const GrClip* clip,
1308 GrPaint&& paint,
1309 GrAA aa,
1310 const SkMatrix& viewMatrix,
1311 const SkRegion& region,
1312 const GrStyle& style,
1313 const GrUserStencilSettings* ss) {
1314 ASSERT_SINGLE_OWNER
1315 RETURN_IF_ABANDONED
1316 SkDEBUGCODE(this->validate();)
1317 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawRegion", fContext);
1318
1319 if (GrAA::kYes == aa) {
1320 // GrRegionOp performs no antialiasing but is much faster, so here we check the matrix
1321 // to see whether aa is really required.
1322 if (!SkToBool(viewMatrix.getType() & ~(SkMatrix::kTranslate_Mask)) &&
1323 SkScalarIsInt(viewMatrix.getTranslateX()) &&
1324 SkScalarIsInt(viewMatrix.getTranslateY())) {
1325 aa = GrAA::kNo;
1326 }
1327 }
1328 bool complexStyle = !style.isSimpleFill();
1329 if (complexStyle || GrAA::kYes == aa) {
1330 SkPath path = region.getBoundaryPath();
1331 path.setIsVolatile(true);
1332
1333 return this->drawPath(clip, std::move(paint), aa, viewMatrix, path, style);
1334 }
1335
1336 GrAAType aaType = (this->numSamples() > 1) ? GrAAType::kMSAA : GrAAType::kNone;
1337 GrOp::Owner op = RegionOp::Make(fContext, std::move(paint), viewMatrix, region, aaType, ss);
1338 this->addDrawOp(clip, std::move(op));
1339 }
1340
1341 void SurfaceDrawContext::drawOval(const GrClip* clip,
1342 GrPaint&& paint,
1343 GrAA aa,
1344 const SkMatrix& viewMatrix,
1345 const SkRect& oval,
1346 const GrStyle& style) {
1347 ASSERT_SINGLE_OWNER
1348 RETURN_IF_ABANDONED
1349 SkDEBUGCODE(this->validate();)
1350 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawOval", fContext);
1351
1352 const SkStrokeRec& stroke = style.strokeRec();
1353
1354 if (oval.isEmpty() && !style.pathEffect()) {
1355 if (stroke.getStyle() == SkStrokeRec::kFill_Style) {
1356 return;
1357 }
1358
1359 this->drawRect(clip, std::move(paint), aa, viewMatrix, oval, &style);
1360 return;
1361 }
1362
1363 GrAAType aaType = this->chooseAAType(aa);
1364
1365 GrOp::Owner op;
1366 #ifndef SK_ENABLE_OPTIMIZE_SIZE
1367 if (aaType == GrAAType::kCoverage &&
1368 !fCanUseDynamicMSAA &&
1369 !this->caps()->reducedShaderMode() &&
1370 oval.width() > SK_ScalarNearlyZero &&
1371 oval.width() == oval.height() &&
1372 viewMatrix.isSimilarity()) {
1373 // In specific cases we use a dedicated circle op to try and get better perf.
1374 assert_alive(paint);
1375 op = GrOvalOpFactory::MakeCircleOp(fContext, std::move(paint), viewMatrix, oval, style,
1376 this->caps()->shaderCaps());
1377 }
1378 #endif
1379 if (!op && style.isSimpleFill()) {
1380 // FillRRectOp has special geometry and a fragment-shader branch to conditionally evaluate
1381 // the arc equation. This same special geometry and fragment branch also turn out to be a
1382 // substantial optimization for drawing ovals (namely, by not evaluating the arc equation
1383 // inside the oval's inner diamond). Given these optimizations, it's a clear win to draw
1384 // ovals the exact same way we do round rects.
1385 assert_alive(paint);
1386 op = FillRRectOp::Make(fContext, this->arenaAlloc(), std::move(paint), viewMatrix,
1387 SkRRect::MakeOval(oval), oval, GrAA(aaType != GrAAType::kNone));
1388 }
1389 #ifndef SK_ENABLE_OPTIMIZE_SIZE
1390 if (!op && (aaType == GrAAType::kCoverage || fCanUseDynamicMSAA)) {
1391 assert_alive(paint);
1392 op = GrOvalOpFactory::MakeOvalOp(fContext, std::move(paint), viewMatrix, oval, style,
1393 this->caps()->shaderCaps());
1394 }
1395 #endif
1396 if (op) {
1397 this->addDrawOp(clip, std::move(op));
1398 return;
1399 }
1400
1401 assert_alive(paint);
1402 this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,
1403 GrStyledShape(SkRRect::MakeOval(oval), SkPathDirection::kCW, 2,
1404 false, style, DoSimplify::kNo));
1405 }
1406
1407 void SurfaceDrawContext::drawArc(const GrClip* clip,
1408 GrPaint&& paint,
1409 GrAA aa,
1410 const SkMatrix& viewMatrix,
1411 const SkArc& arc,
1412 const GrStyle& style) {
1413 ASSERT_SINGLE_OWNER
1414 RETURN_IF_ABANDONED
1415 SkDEBUGCODE(this->validate();)
1416 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawArc", fContext);
1417
1418 #ifndef SK_ENABLE_OPTIMIZE_SIZE
1419 GrAAType aaType = this->chooseAAType(aa);
1420 if (aaType == GrAAType::kCoverage) {
1421 const GrShaderCaps* shaderCaps = this->caps()->shaderCaps();
1422 GrOp::Owner op = GrOvalOpFactory::MakeArcOp(fContext,
1423 std::move(paint),
1424 viewMatrix,
1425 arc.fOval,
1426 arc.fStartAngle,
1427 arc.fSweepAngle,
1428 arc.isWedge(),
1429 style,
1430 shaderCaps);
1431 if (op) {
1432 this->addDrawOp(clip, std::move(op));
1433 return;
1434 }
1435 assert_alive(paint);
1436 }
1437 #endif
1438 this->drawShapeUsingPathRenderer(clip,
1439 std::move(paint),
1440 aa,
1441 viewMatrix,
1442 GrStyledShape::MakeArc(arc, style, DoSimplify::kNo));
1443 }
1444
1445 void SurfaceDrawContext::drawImageLattice(const GrClip* clip,
1446 GrPaint&& paint,
1447 const SkMatrix& viewMatrix,
1448 GrSurfaceProxyView view,
1449 SkAlphaType alphaType,
1450 sk_sp<GrColorSpaceXform> csxf,
1451 GrSamplerState::Filter filter,
1452 std::unique_ptr<SkLatticeIter> iter,
1453 const SkRect& dst) {
1454 ASSERT_SINGLE_OWNER
1455 RETURN_IF_ABANDONED
1456 SkDEBUGCODE(this->validate();)
1457 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawImageLattice", fContext);
1458
1459 GrOp::Owner op =
1460 LatticeOp::MakeNonAA(fContext, std::move(paint), viewMatrix, std::move(view),
1461 alphaType, std::move(csxf), filter, std::move(iter), dst);
1462 this->addDrawOp(clip, std::move(op));
1463 }
1464
1465 void SurfaceDrawContext::drawDrawable(std::unique_ptr<SkDrawable::GpuDrawHandler> drawable,
1466 const SkRect& bounds) {
1467 ASSERT_SINGLE_OWNER
1468 RETURN_IF_ABANDONED
1469 SkDEBUGCODE(this->validate();)
1470 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawDrawable", fContext);
1471 GrOp::Owner op(DrawableOp::Make(fContext, std::move(drawable), bounds));
1472 SkASSERT(op);
1473 this->addOp(std::move(op));
1474 }
1475
1476 void SurfaceDrawContext::setLastClip(uint32_t clipStackGenID,
1477 const SkIRect& devClipBounds,
1478 int numClipAnalyticElements) {
1479 auto opsTask = this->getOpsTask();
1480 opsTask->fLastClipStackGenID = clipStackGenID;
1481 opsTask->fLastDevClipBounds = devClipBounds;
1482 opsTask->fLastClipNumAnalyticElements = numClipAnalyticElements;
1483 }
1484
1485 bool SurfaceDrawContext::mustRenderClip(uint32_t clipStackGenID,
1486 const SkIRect& devClipBounds,
1487 int numClipAnalyticElements) {
1488 auto opsTask = this->getOpsTask();
1489 return opsTask->fLastClipStackGenID != clipStackGenID ||
1490 !opsTask->fLastDevClipBounds.contains(devClipBounds) ||
1491 opsTask->fLastClipNumAnalyticElements != numClipAnalyticElements;
1492 }
1493
1494 bool SurfaceDrawContext::waitOnSemaphores(int numSemaphores,
1495 const GrBackendSemaphore waitSemaphores[],
1496 bool deleteSemaphoresAfterWait) {
1497 ASSERT_SINGLE_OWNER
1498 RETURN_FALSE_IF_ABANDONED
1499 SkDEBUGCODE(this->validate();)
1500 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "waitOnSemaphores", fContext);
1501
1502 if (numSemaphores && !this->caps()->backendSemaphoreSupport()) {
1503 return false;
1504 }
1505
1506 auto direct = fContext->asDirectContext();
1507 if (!direct) {
1508 return false;
1509 }
1510
1511 auto resourceProvider = direct->priv().resourceProvider();
1512
1513 GrWrapOwnership ownership =
1514 deleteSemaphoresAfterWait ? kAdopt_GrWrapOwnership : kBorrow_GrWrapOwnership;
1515
1516 std::unique_ptr<std::unique_ptr<GrSemaphore>[]> grSemaphores(
1517 new std::unique_ptr<GrSemaphore>[numSemaphores]);
1518 for (int i = 0; i < numSemaphores; ++i) {
1519 grSemaphores[i] = resourceProvider->wrapBackendSemaphore(waitSemaphores[i],
1520 GrSemaphoreWrapType::kWillWait,
1521 ownership);
1522 }
1523 this->drawingManager()->newWaitRenderTask(this->asSurfaceProxyRef(), std::move(grSemaphores),
1524 numSemaphores);
1525 return true;
1526 }
1527
1528 void SurfaceDrawContext::drawPath(const GrClip* clip,
1529 GrPaint&& paint,
1530 GrAA aa,
1531 const SkMatrix& viewMatrix,
1532 const SkPath& path,
1533 const GrStyle& style) {
1534 ASSERT_SINGLE_OWNER
1535 RETURN_IF_ABANDONED
1536 SkDEBUGCODE(this->validate();)
1537 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawPath", fContext);
1538
1539 GrStyledShape shape(path, style, DoSimplify::kNo);
1540 this->drawShape(clip, std::move(paint), aa, viewMatrix, std::move(shape));
1541 }
1542
1543 void SurfaceDrawContext::drawShape(const GrClip* clip,
1544 GrPaint&& paint,
1545 GrAA aa,
1546 const SkMatrix& viewMatrix,
1547 GrStyledShape&& shape) {
1548 ASSERT_SINGLE_OWNER
1549 RETURN_IF_ABANDONED
1550 SkDEBUGCODE(this->validate();)
1551 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawShape", fContext);
1552
1553 if (shape.isEmpty()) {
1554 if (shape.inverseFilled()) {
1555 this->drawPaint(clip, std::move(paint), viewMatrix);
1556 }
1557 return;
1558 }
1559
1560 // If we get here in drawShape(), we definitely need to use path rendering
1561 this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix, std::move(shape),
1562 /* attemptDrawSimple */ true);
1563 }
1564
1565 static SkIRect get_clip_bounds(const SurfaceDrawContext* sdc, const GrClip* clip) {
1566 return clip ? clip->getConservativeBounds() : SkIRect::MakeWH(sdc->width(), sdc->height());
1567 }
1568
1569 bool SurfaceDrawContext::drawAndStencilPath(const GrHardClip* clip,
1570 const GrUserStencilSettings* ss,
1571 SkRegion::Op op,
1572 bool invert,
1573 GrAA aa,
1574 const SkMatrix& viewMatrix,
1575 const SkPath& path) {
1576 ASSERT_SINGLE_OWNER
1577 RETURN_FALSE_IF_ABANDONED
1578 SkDEBUGCODE(this->validate();)
1579 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawAndStencilPath", fContext);
1580
1581 if (path.isEmpty() && path.isInverseFillType()) {
1582 GrPaint paint;
1583 paint.setCoverageSetOpXPFactory(op, invert);
1584 this->stencilRect(clip, ss, std::move(paint), GrAA::kNo, SkMatrix::I(),
1585 SkRect::Make(this->dimensions()));
1586 return true;
1587 }
1588
1589 // An Assumption here is that path renderer would use some form of tweaking
1590 // the src color (either the input alpha or in the frag shader) to implement
1591 // aa. If we have some future driver-mojo path AA that can do the right
1592 // thing WRT to the blend then we'll need some query on the PR.
1593 GrAAType aaType = this->chooseAAType(aa);
1594 bool hasUserStencilSettings = !ss->isUnused();
1595
1596 SkIRect clipConservativeBounds = get_clip_bounds(this, clip);
1597
1598 GrPaint paint;
1599 paint.setCoverageSetOpXPFactory(op, invert);
1600
1601 GrStyledShape shape(path, GrStyle::SimpleFill());
1602 PathRenderer::CanDrawPathArgs canDrawArgs;
1603 canDrawArgs.fCaps = this->caps();
1604 canDrawArgs.fProxy = this->asRenderTargetProxy();
1605 canDrawArgs.fViewMatrix = &viewMatrix;
1606 canDrawArgs.fShape = &shape;
1607 canDrawArgs.fPaint = &paint;
1608 canDrawArgs.fSurfaceProps = &fSurfaceProps;
1609 canDrawArgs.fClipConservativeBounds = &clipConservativeBounds;
1610 canDrawArgs.fAAType = aaType;
1611 canDrawArgs.fHasUserStencilSettings = hasUserStencilSettings;
1612
1613 using DrawType = PathRendererChain::DrawType;
1614
1615 // Don't allow the SW renderer
1616 auto pr = this->drawingManager()->getPathRenderer(canDrawArgs,
1617 false,
1618 DrawType::kStencilAndColor);
1619 if (!pr) {
1620 return false;
1621 }
1622
1623 PathRenderer::DrawPathArgs args{this->drawingManager()->getContext(),
1624 std::move(paint),
1625 ss,
1626 this,
1627 clip,
1628 &clipConservativeBounds,
1629 &viewMatrix,
1630 &shape,
1631 aaType,
1632 this->colorInfo().isLinearlyBlended()};
1633 pr->drawPath(args);
1634 return true;
1635 }
1636
1637 skgpu::Budgeted SurfaceDrawContext::isBudgeted() const {
1638 ASSERT_SINGLE_OWNER
1639
1640 if (fContext->abandoned()) {
1641 return skgpu::Budgeted::kNo;
1642 }
1643
1644 SkDEBUGCODE(this->validate();)
1645
1646 return this->asSurfaceProxy()->isBudgeted();
1647 }
1648
1649 void SurfaceDrawContext::drawStrokedLine(const GrClip* clip,
1650 GrPaint&& paint,
1651 GrAA aa,
1652 const SkMatrix& viewMatrix,
1653 const SkPoint points[2],
1654 const SkStrokeRec& stroke) {
1655 ASSERT_SINGLE_OWNER
1656
1657 SkASSERT(stroke.getStyle() == SkStrokeRec::kStroke_Style);
1658 SkASSERT(stroke.getWidth() > 0);
1659 // Adding support for round capping would require a
1660 // SurfaceDrawContext::fillRRectWithLocalMatrix entry point
1661 SkASSERT(SkPaint::kRound_Cap != stroke.getCap());
1662
1663 const SkScalar halfWidth = 0.5f * stroke.getWidth();
1664 if (halfWidth <= 0.f) {
1665 // Prevents underflow when stroke width is epsilon > 0 (so technically not a hairline).
1666 // The CTM would need to have a scale near 1/epsilon in order for this to have meaningful
1667 // coverage (although that would likely overflow elsewhere and cause the draw to drop due
1668 // to non-finite bounds). At any other scale, this line is so thin, it's coverage is
1669 // negligible, so discarding the draw is visually equivalent.
1670 return;
1671 }
1672
1673 SkVector parallel = points[1] - points[0];
1674
1675 if (!SkPoint::Normalize(&parallel)) {
1676 parallel.fX = 1.0f;
1677 parallel.fY = 0.0f;
1678 }
1679 parallel *= halfWidth;
1680
1681 SkVector ortho = { parallel.fY, -parallel.fX };
1682 SkPoint p0 = points[0], p1 = points[1];
1683 if (stroke.getCap() == SkPaint::kSquare_Cap) {
1684 // Extra extension for square caps
1685 p0 -= parallel;
1686 p1 += parallel;
1687 }
1688
1689 // If we are using dmsaa or reduced shader mode then attempt to draw with FillRRectOp.
1690 if (this->caps()->drawInstancedSupport() &&
1691 (this->alwaysAntialias() ||
1692 (fContext->priv().caps()->reducedShaderMode() && aa == GrAA::kYes))) {
1693 SkMatrix localMatrix = SkMatrix::MakeAll(p1.fX - p0.fX, ortho.fX, p0.fX,
1694 p1.fY - p0.fY, ortho.fY, p0.fY,
1695 0, 0, 1);
1696 if (auto op = FillRRectOp::Make(fContext,
1697 this->arenaAlloc(),
1698 std::move(paint),
1699 SkMatrix::Concat(viewMatrix, localMatrix),
1700 SkRRect::MakeRect({0,-1,1,1}),
1701 localMatrix,
1702 GrAA::kYes)) {
1703 this->addDrawOp(clip, std::move(op));
1704 return;
1705 }
1706 }
1707
1708 // Order is TL, TR, BR, BL where arbitrarily "down" is p0 to p1 and "right" is positive
1709 SkPoint corners[4] = { p0 - ortho,
1710 p0 + ortho,
1711 p1 + ortho,
1712 p1 - ortho };
1713
1714 GrQuadAAFlags edgeAA = (aa == GrAA::kYes) ? GrQuadAAFlags::kAll : GrQuadAAFlags::kNone;
1715
1716 assert_alive(paint);
1717 this->fillQuadWithEdgeAA(clip, std::move(paint), edgeAA, viewMatrix, corners, nullptr);
1718 }
1719
1720 bool SurfaceDrawContext::drawSimpleShape(const GrClip* clip,
1721 GrPaint* paint,
1722 GrAA aa,
1723 const SkMatrix& viewMatrix,
1724 const GrStyledShape& shape) {
1725 if (!shape.style().hasPathEffect()) {
1726 GrAAType aaType = this->chooseAAType(aa);
1727 SkPoint linePts[2];
1728 SkRRect rrect;
1729 // We can ignore the starting point and direction since there is no path effect.
1730 bool inverted;
1731 if (shape.asLine(linePts, &inverted) && !inverted &&
1732 shape.style().strokeRec().getStyle() == SkStrokeRec::kStroke_Style &&
1733 shape.style().strokeRec().getCap() != SkPaint::kRound_Cap) {
1734 // The stroked line is an oriented rectangle, which looks the same or better (if
1735 // perspective) compared to path rendering. The exception is subpixel/hairline lines
1736 // that are non-AA or MSAA, in which case the default path renderer achieves higher
1737 // quality.
1738 // FIXME(michaelludwig): If the fill rect op could take an external coverage, or checks
1739 // for and outsets thin non-aa rects to 1px, the path renderer could be skipped.
1740 SkScalar coverage;
1741 if (aaType == GrAAType::kCoverage ||
1742 !skcpu::DrawTreatAAStrokeAsHairline(
1743 shape.style().strokeRec().getWidth(), viewMatrix, &coverage)) {
1744 this->drawStrokedLine(clip, std::move(*paint), aa, viewMatrix, linePts,
1745 shape.style().strokeRec());
1746 return true;
1747 }
1748 } else if (shape.asRRect(&rrect, &inverted) && !inverted) {
1749 if (rrect.isRect()) {
1750 this->drawRect(clip, std::move(*paint), aa, viewMatrix, rrect.rect(),
1751 &shape.style());
1752 return true;
1753 } else if (rrect.isOval()) {
1754 this->drawOval(clip, std::move(*paint), aa, viewMatrix, rrect.rect(),
1755 shape.style());
1756 return true;
1757 }
1758 this->drawRRect(clip, std::move(*paint), aa, viewMatrix, rrect, shape.style());
1759 return true;
1760 } else if (GrAAType::kCoverage == aaType &&
1761 shape.style().isSimpleFill() &&
1762 viewMatrix.rectStaysRect() &&
1763 !this->caps()->reducedShaderMode()) {
1764 // TODO: the rectStaysRect restriction could be lifted if we were willing to apply the
1765 // matrix to all the points individually rather than just to the rect
1766 SkRect rects[2];
1767 if (shape.asNestedRects(rects)) {
1768 // Concave AA paths are expensive - try to avoid them for special cases
1769 GrOp::Owner op = ganesh::StrokeRectOp::MakeNested(fContext, std::move(*paint),
1770 viewMatrix, rects);
1771 if (op) {
1772 this->addDrawOp(clip, std::move(op));
1773 return true;
1774 }
1775 // Fall through to let path renderer handle subpixel nested rects with unequal
1776 // stroke widths along X/Y.
1777 }
1778 }
1779 }
1780 return false;
1781 }
1782
1783 void SurfaceDrawContext::drawShapeUsingPathRenderer(const GrClip* clip,
1784 GrPaint&& paint,
1785 GrAA aa,
1786 const SkMatrix& viewMatrix,
1787 GrStyledShape&& shape,
1788 bool attemptDrawSimple) {
1789 ASSERT_SINGLE_OWNER
1790 RETURN_IF_ABANDONED
1791 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "internalDrawPath", fContext);
1792
1793 if (!viewMatrix.isFinite() || !shape.bounds().isFinite()) {
1794 return;
1795 }
1796
1797 SkIRect clipConservativeBounds = get_clip_bounds(this, clip);
1798
1799 // Always allow paths to trigger DMSAA.
1800 GrAAType aaType = fCanUseDynamicMSAA ? GrAAType::kMSAA : this->chooseAAType(aa);
1801
1802 PathRenderer::CanDrawPathArgs canDrawArgs;
1803 canDrawArgs.fCaps = this->caps();
1804 canDrawArgs.fProxy = this->asRenderTargetProxy();
1805 canDrawArgs.fViewMatrix = &viewMatrix;
1806 canDrawArgs.fShape = &shape;
1807 canDrawArgs.fPaint = &paint;
1808 canDrawArgs.fSurfaceProps = &fSurfaceProps;
1809 canDrawArgs.fClipConservativeBounds = &clipConservativeBounds;
1810 canDrawArgs.fHasUserStencilSettings = false;
1811 canDrawArgs.fAAType = aaType;
1812
1813 constexpr static bool kDisallowSWPathRenderer = false;
1814 using DrawType = PathRendererChain::DrawType;
1815
1816 PathRenderer* pr = nullptr;
1817
1818 if (!shape.style().strokeRec().isFillStyle() && !shape.isEmpty()) {
1819 // Give the tessellation path renderer a chance to claim this stroke before we simplify it.
1820 PathRenderer* tess = this->drawingManager()->getTessellationPathRenderer();
1821 if (tess && tess->canDrawPath(canDrawArgs) == PathRenderer::CanDrawPath::kYes) {
1822 pr = tess;
1823 }
1824 }
1825
1826 if (!pr) {
1827 // The shape isn't a stroke that can be drawn directly. Simplify if possible.
1828 shape.simplify();
1829
1830 if (shape.isEmpty() && !shape.inverseFilled()) {
1831 return;
1832 }
1833
1834 if (attemptDrawSimple || shape.simplified()) {
1835 // Usually we enter drawShapeUsingPathRenderer() because the shape+style was too complex
1836 // for dedicated draw ops. However, if GrStyledShape was able to reduce something we
1837 // ought to try again instead of going right to path rendering.
1838 if (this->drawSimpleShape(clip, &paint, aa, viewMatrix, shape)) {
1839 return;
1840 }
1841 }
1842
1843 // Try a 1st time without applying any of the style to the geometry (and barring sw)
1844 pr = this->drawingManager()->getPathRenderer(canDrawArgs, kDisallowSWPathRenderer,
1845 DrawType::kColor);
1846 }
1847
1848 SkScalar styleScale = GrStyle::MatrixToScaleFactor(viewMatrix);
1849 if (styleScale == 0.0f) {
1850 return;
1851 }
1852
1853 if (!pr && shape.style().pathEffect()) {
1854 // It didn't work above, so try again with the path effect applied.
1855 shape = shape.applyStyle(GrStyle::Apply::kPathEffectOnly, styleScale);
1856 if (shape.isEmpty()) {
1857 return;
1858 }
1859 pr = this->drawingManager()->getPathRenderer(canDrawArgs, kDisallowSWPathRenderer,
1860 DrawType::kColor);
1861 }
1862 if (!pr && shape.style().applies()) {
1863 shape = shape.applyStyle(GrStyle::Apply::kPathEffectAndStrokeRec, styleScale);
1864 if (shape.isEmpty()) {
1865 return;
1866 }
1867 pr = this->drawingManager()->getPathRenderer(canDrawArgs, kDisallowSWPathRenderer,
1868 DrawType::kColor);
1869 }
1870
1871 if (!pr) {
1872 // Fall back on SW renderer as a last resort.
1873 if (GrAATypeIsHW(aaType)) {
1874 // No point in trying SW renderer with MSAA.
1875 aaType = GrAAType::kCoverage;
1876 canDrawArgs.fAAType = aaType;
1877 }
1878 // This can only fail if a) AA type is MSAA or the style is not applied (already checked),
1879 // or b) the SW renderer's proxy provider is null, which should never happen.
1880 pr = this->drawingManager()->getSoftwarePathRenderer();
1881 SkASSERT(pr->canDrawPath(canDrawArgs) != PathRenderer::CanDrawPath::kNo);
1882 #if GR_PATH_RENDERER_SPEW
1883 SkDebugf("falling back to: %s\n", pr->name());
1884 #endif
1885 }
1886
1887 PathRenderer::DrawPathArgs args{this->drawingManager()->getContext(),
1888 std::move(paint),
1889 &GrUserStencilSettings::kUnused,
1890 this,
1891 clip,
1892 &clipConservativeBounds,
1893 &viewMatrix,
1894 canDrawArgs.fShape,
1895 aaType,
1896 this->colorInfo().isLinearlyBlended()};
1897 pr->drawPath(args);
1898 }
1899
1900 void SurfaceDrawContext::addDrawOp(const GrClip* clip,
1901 GrOp::Owner op,
1902 const std::function<WillAddOpFn>& willAddFn) {
1903 ASSERT_SINGLE_OWNER
1904 if (fContext->abandoned()) {
1905 return;
1906 }
1907 GrDrawOp* drawOp = (GrDrawOp*)op.get();
1908 SkDEBUGCODE(this->validate();)
1909 SkDEBUGCODE(drawOp->fAddDrawOpCalled = true;)
1910 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "addDrawOp", fContext);
1911
1912 // Setup clip
1913 SkRect bounds;
1914 op_bounds(&bounds, op.get());
1915 GrAppliedClip appliedClip(this->dimensions(), this->asSurfaceProxy()->backingStoreDimensions());
1916 const bool opUsesMSAA = drawOp->usesMSAA();
1917 bool skipDraw = false;
1918 if (clip) {
1919 // Have a complex clip, so defer to its early clip culling
1920 GrAAType aaType;
1921 if (opUsesMSAA) {
1922 aaType = GrAAType::kMSAA;
1923 } else {
1924 aaType = op->hasAABloat() ? GrAAType::kCoverage : GrAAType::kNone;
1925 }
1926 skipDraw = clip->apply(fContext, this, drawOp, aaType,
1927 &appliedClip, &bounds) == GrClip::Effect::kClippedOut;
1928 } else {
1929 // No clipping, so just clip the bounds against the logical render target dimensions
1930 skipDraw = !bounds.intersect(this->asSurfaceProxy()->getBoundsRect());
1931 }
1932
1933 if (skipDraw) {
1934 return;
1935 }
1936
1937 GrClampType clampType = GrColorTypeClampType(this->colorInfo().colorType());
1938 GrProcessorSet::Analysis analysis = drawOp->finalize(*this->caps(), &appliedClip, clampType);
1939
1940 const bool opUsesStencil = drawOp->usesStencil();
1941
1942 // Always trigger DMSAA when there is stencil. This ensures stencil contents get properly
1943 // preserved between render passes, if needed.
1944 const bool drawNeedsMSAA = opUsesMSAA || (fCanUseDynamicMSAA && opUsesStencil);
1945
1946 // Must be called before setDstProxyView so that it sees the final bounds of the op.
1947 op->setClippedBounds(bounds);
1948
1949 // Determine if the Op will trigger the use of a separate DMSAA attachment that requires manual
1950 // resolves.
1951 // TODO: Currently usesAttachmentIfDMSAA checks if this is a textureProxy or not. This check is
1952 // really only for GL which uses a normal texture sampling when using barriers. For Vulkan it
1953 // is possible to use the msaa buffer as an input attachment even if this is not a texture.
1954 // However, support for that is not fully implemented yet in Vulkan. Once it is, this check
1955 // should change to a virtual caps check that returns whether we need to break up an OpsTask
1956 // if it has barriers and we are about to promote to MSAA.
1957 bool usesAttachmentIfDMSAA =
1958 fCanUseDynamicMSAA &&
1959 (!this->caps()->msaaResolvesAutomatically() || !this->asTextureProxy());
1960 bool opRequiresDMSAAAttachment = usesAttachmentIfDMSAA && drawNeedsMSAA;
1961 bool opTriggersDMSAAAttachment =
1962 opRequiresDMSAAAttachment && !this->getOpsTask()->usesMSAASurface();
1963 if (opTriggersDMSAAAttachment) {
1964 // This will be the op that actually triggers use of a DMSAA attachment. Texture barriers
1965 // can't be moved to a DMSAA attachment, so if there already are any on the current opsTask
1966 // then we need to split.
1967 if (this->getOpsTask()->renderPassXferBarriers() & GrXferBarrierFlags::kTexture) {
1968 SkASSERT(!this->getOpsTask()->isColorNoOp());
1969 this->replaceOpsTask()->setCannotMergeBackward();
1970 }
1971 }
1972
1973 GrDstProxyView dstProxyView;
1974 if (analysis.requiresDstTexture()) {
1975 if (!this->setupDstProxyView(drawOp->bounds(), drawNeedsMSAA, &dstProxyView)) {
1976 return;
1977 }
1978 #ifdef SK_DEBUG
1979 if (fCanUseDynamicMSAA && drawNeedsMSAA && !this->caps()->msaaResolvesAutomatically()) {
1980 // Since we aren't literally writing to the render target texture while using a DMSAA
1981 // attachment, we need to resolve that texture before sampling it. Ensure the current
1982 // opsTask got closed off in order to initiate an implicit resolve.
1983 SkASSERT(this->getOpsTask()->isEmpty());
1984 }
1985 #endif
1986 }
1987
1988 auto opsTask = this->getOpsTask();
1989 if (willAddFn) {
1990 willAddFn(op.get(), opsTask->uniqueID());
1991 }
1992
1993 // Note if the op needs stencil. Stencil clipping already called setNeedsStencil for itself, if
1994 // needed.
1995 if (opUsesStencil) {
1996 this->setNeedsStencil();
1997 }
1998
1999 #if GR_GPU_STATS && defined(GPU_TEST_UTILS)
2000 if (fCanUseDynamicMSAA && drawNeedsMSAA) {
2001 if (!opsTask->usesMSAASurface()) {
2002 fContext->priv().dmsaaStats().fNumMultisampleRenderPasses++;
2003 }
2004 fContext->priv().dmsaaStats().fTriggerCounts[op->name()]++;
2005 }
2006 #endif
2007
2008 opsTask->addDrawOp(this->drawingManager(), std::move(op), drawNeedsMSAA, analysis,
2009 std::move(appliedClip), dstProxyView,
2010 GrTextureResolveManager(this->drawingManager()), *this->caps());
2011
2012 #ifdef SK_DEBUG
2013 if (fCanUseDynamicMSAA && drawNeedsMSAA) {
2014 SkASSERT(opsTask->usesMSAASurface());
2015 }
2016 #endif
2017 }
2018
2019 bool SurfaceDrawContext::setupDstProxyView(const SkRect& opBounds,
2020 bool opRequiresMSAA,
2021 GrDstProxyView* dstProxyView) {
2022 // If we are wrapping a vulkan secondary command buffer, we can't make a dst copy because we
2023 // don't actually have a VkImage to make a copy of. Additionally we don't have the power to
2024 // start and stop the render pass in order to make the copy.
2025 if (this->asRenderTargetProxy()->wrapsVkSecondaryCB()) {
2026 return false;
2027 }
2028
2029 // First get the dstSampleFlags as if we will put the draw into the current OpsTask
2030 auto dstSampleFlags = this->caps()->getDstSampleFlagsForProxy(
2031 this->asRenderTargetProxy(), this->getOpsTask()->usesMSAASurface() || opRequiresMSAA);
2032
2033 // If we don't have barriers for this draw then we will definitely be breaking up the OpsTask.
2034 // However, if using dynamic MSAA, the new OpsTask will not have MSAA already enabled on it
2035 // and that may allow us to use texture barriers. So we check if we can use barriers on the new
2036 // ops task and then break it up if so.
2037 if (!(dstSampleFlags & GrDstSampleFlags::kRequiresTextureBarrier) &&
2038 fCanUseDynamicMSAA && this->getOpsTask()->usesMSAASurface() && !opRequiresMSAA) {
2039 auto newFlags =
2040 this->caps()->getDstSampleFlagsForProxy(this->asRenderTargetProxy(),
2041 false/*=opRequiresMSAA*/);
2042 if (newFlags & GrDstSampleFlags::kRequiresTextureBarrier) {
2043 // We can't have an empty ops task if we are in DMSAA and the ops task already returns
2044 // true for usesMSAASurface.
2045 SkASSERT(!this->getOpsTask()->isColorNoOp());
2046 this->replaceOpsTask()->setCannotMergeBackward();
2047 dstSampleFlags = newFlags;
2048 }
2049 }
2050
2051 if (dstSampleFlags & GrDstSampleFlags::kRequiresTextureBarrier) {
2052 // If we require a barrier to sample the dst it means we are sampling the RT itself
2053 // either as a texture or input attachment. In this case we don't need to break up the
2054 // OpsTask.
2055 dstProxyView->setProxyView(this->readSurfaceView());
2056 dstProxyView->setOffset(0, 0);
2057 dstProxyView->setDstSampleFlags(dstSampleFlags);
2058 return true;
2059 }
2060 SkASSERT(dstSampleFlags == GrDstSampleFlags::kNone);
2061
2062 // We are using a different surface from the main color attachment to sample the dst from. If we
2063 // are in DMSAA we can just use the single sampled RT texture itself. Otherwise, we must do a
2064 // copy.
2065 // We do have to check if we ended up here becasue we don't have texture barriers but do have
2066 // msaaResolvesAutomatically (i.e. render-to-msaa-texture). In that case there will be no op or
2067 // barrier between draws to flush the render target before being used as a texture in the next
2068 // draw. So in that case we just fall through to doing a copy.
2069 if (fCanUseDynamicMSAA && opRequiresMSAA && this->asTextureProxy() &&
2070 !this->caps()->msaaResolvesAutomatically() &&
2071 this->caps()->dmsaaResolveCanBeUsedAsTextureInSameRenderPass()) {
2072 this->replaceOpsTaskIfModifiesColor()->setCannotMergeBackward();
2073 dstProxyView->setProxyView(this->readSurfaceView());
2074 dstProxyView->setOffset(0, 0);
2075 dstProxyView->setDstSampleFlags(dstSampleFlags);
2076 return true;
2077 }
2078
2079 // Now we fallback to doing a copy.
2080
2081 GrColorType colorType = this->colorInfo().colorType();
2082 // MSAA consideration: When there is support for reading MSAA samples in the shader we could
2083 // have per-sample dst values by making the copy multisampled.
2084 GrCaps::DstCopyRestrictions restrictions = this->caps()->getDstCopyRestrictions(
2085 this->asRenderTargetProxy(), colorType);
2086
2087 SkIRect copyRect = SkIRect::MakeSize(this->asSurfaceProxy()->backingStoreDimensions());
2088 if (!restrictions.fMustCopyWholeSrc) {
2089 // If we don't need the whole source, restrict to the op's bounds. We add an extra pixel
2090 // of padding to account for AA bloat and the unpredictable rounding of coords near pixel
2091 // centers during rasterization.
2092 SkIRect conservativeDrawBounds = opBounds.roundOut();
2093 conservativeDrawBounds.outset(1, 1);
2094 SkAssertResult(copyRect.intersect(conservativeDrawBounds));
2095 }
2096
2097 SkIPoint dstOffset;
2098 SkBackingFit fit;
2099 if (restrictions.fRectsMustMatch == GrSurfaceProxy::RectsMustMatch::kYes) {
2100 dstOffset = {0, 0};
2101 fit = SkBackingFit::kExact;
2102 } else {
2103 dstOffset = {copyRect.fLeft, copyRect.fTop};
2104 fit = SkBackingFit::kApprox;
2105 }
2106 auto copy = GrSurfaceProxy::Copy(fContext,
2107 this->asSurfaceProxyRef(),
2108 this->origin(),
2109 skgpu::Mipmapped::kNo,
2110 copyRect,
2111 fit,
2112 skgpu::Budgeted::kYes,
2113 /*label=*/{},
2114 restrictions.fRectsMustMatch);
2115 SkASSERT(copy);
2116
2117 dstProxyView->setProxyView({std::move(copy), this->origin(), this->readSwizzle()});
2118 dstProxyView->setOffset(dstOffset);
2119 dstProxyView->setDstSampleFlags(dstSampleFlags);
2120 return true;
2121 }
2122
2123 OpsTask* SurfaceDrawContext::replaceOpsTaskIfModifiesColor() {
2124 if (!this->getOpsTask()->isColorNoOp()) {
2125 this->replaceOpsTask();
2126 }
2127 return this->getOpsTask();
2128 }
2129
2130 } // namespace skgpu::ganesh