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