1/*
2 * Copyright 2017 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/ccpr/GrCoverageCountingPathRenderer.h"
9
10#include "include/pathops/SkPathOps.h"
11#include "src/gpu/GrCaps.h"
12#include "src/gpu/GrProxyProvider.h"
13#include "src/gpu/GrRenderTargetContext.h"
14#include "src/gpu/ccpr/GrCCClipProcessor.h"
15#include "src/gpu/ccpr/GrCCDrawPathsOp.h"
16#include "src/gpu/ccpr/GrCCPathCache.h"
17
18using PathInstance = GrCCPathProcessor::Instance;
19
20bool GrCoverageCountingPathRenderer::IsSupported(const GrCaps& caps, CoverageType* coverageType) {
21 const GrShaderCaps& shaderCaps = *caps.shaderCaps();
22 GrBackendFormat defaultA8Format = caps.getDefaultBackendFormat(GrColorType::kAlpha_8,
23 GrRenderable::kYes);
24 if (caps.driverDisableCCPR() || !shaderCaps.integerSupport() ||
25 !caps.drawInstancedSupport() || !shaderCaps.floatIs32Bits() ||
26 !defaultA8Format.isValid() || // This checks both texturable and renderable
27 !caps.halfFloatVertexAttributeSupport()) {
28 return false;
29 }
30
31 GrBackendFormat defaultAHalfFormat = caps.getDefaultBackendFormat(GrColorType::kAlpha_F16,
32 GrRenderable::kYes);
33 if (caps.allowCoverageCounting() &&
34 defaultAHalfFormat.isValid()) { // This checks both texturable and renderable
35 if (coverageType) {
36 *coverageType = CoverageType::kFP16_CoverageCount;
37 }
38 return true;
39 }
40
41 if (!caps.driverDisableMSAACCPR() &&
42 caps.internalMultisampleCount(defaultA8Format) > 1 &&
43 caps.sampleLocationsSupport() &&
44 shaderCaps.sampleMaskSupport()) {
45 if (coverageType) {
46 *coverageType = CoverageType::kA8_Multisample;
47 }
48 return true;
49 }
50
51 return false;
52}
53
54sk_sp<GrCoverageCountingPathRenderer> GrCoverageCountingPathRenderer::CreateIfSupported(
55 const GrCaps& caps, AllowCaching allowCaching, uint32_t contextUniqueID) {
56 CoverageType coverageType;
57 if (IsSupported(caps, &coverageType)) {
58 return sk_sp<GrCoverageCountingPathRenderer>(new GrCoverageCountingPathRenderer(
59 coverageType, allowCaching, contextUniqueID));
60 }
61 return nullptr;
62}
63
64GrCoverageCountingPathRenderer::GrCoverageCountingPathRenderer(
65 CoverageType coverageType, AllowCaching allowCaching, uint32_t contextUniqueID)
66 : fCoverageType(coverageType) {
67 if (AllowCaching::kYes == allowCaching) {
68 fPathCache = std::make_unique<GrCCPathCache>(contextUniqueID);
69 }
70}
71
72GrCCPerOpsTaskPaths* GrCoverageCountingPathRenderer::lookupPendingPaths(uint32_t opsTaskID) {
73 auto it = fPendingPaths.find(opsTaskID);
74 if (fPendingPaths.end() == it) {
75 sk_sp<GrCCPerOpsTaskPaths> paths = sk_make_sp<GrCCPerOpsTaskPaths>();
76 it = fPendingPaths.insert(std::make_pair(opsTaskID, std::move(paths))).first;
77 }
78 return it->second.get();
79}
80
81GrPathRenderer::CanDrawPath GrCoverageCountingPathRenderer::onCanDrawPath(
82 const CanDrawPathArgs& args) const {
83 const GrStyledShape& shape = *args.fShape;
84 // We use "kCoverage", or analytic AA, no mater what the coverage type of our atlas: Even if the
85 // atlas is multisampled, that resolves into analytic coverage before we draw the path to the
86 // main canvas.
87 if (GrAAType::kCoverage != args.fAAType || shape.style().hasPathEffect() ||
88 args.fViewMatrix->hasPerspective() || shape.inverseFilled()) {
89 return CanDrawPath::kNo;
90 }
91
92 SkPath path;
93 shape.asPath(&path);
94
95 const SkStrokeRec& stroke = shape.style().strokeRec();
96 switch (stroke.getStyle()) {
97 case SkStrokeRec::kFill_Style: {
98 SkRect devBounds;
99 args.fViewMatrix->mapRect(&devBounds, path.getBounds());
100
101 SkIRect clippedIBounds;
102 devBounds.roundOut(&clippedIBounds);
103 if (!clippedIBounds.intersect(*args.fClipConservativeBounds)) {
104 // The path is completely clipped away. Our code will eventually notice this before
105 // doing any real work.
106 return CanDrawPath::kYes;
107 }
108
109 int64_t numPixels = sk_64_mul(clippedIBounds.height(), clippedIBounds.width());
110 if (path.countVerbs() > 1000 && path.countPoints() > numPixels) {
111 // This is a complicated path that has more vertices than pixels! Let's let the SW
112 // renderer have this one: It will probably be faster and a bitmap will require less
113 // total memory on the GPU than CCPR instance buffers would for the raw path data.
114 return CanDrawPath::kNo;
115 }
116
117 if (numPixels > 256 * 256) {
118 // Large paths can blow up the atlas fast. And they are not ideal for a two-pass
119 // rendering algorithm. Give the simpler direct renderers a chance before we commit
120 // to drawing it.
121 return CanDrawPath::kAsBackup;
122 }
123
124 if (args.fShape->hasUnstyledKey() && path.countVerbs() > 50) {
125 // Complex paths do better cached in an SDF, if the renderer will accept them.
126 return CanDrawPath::kAsBackup;
127 }
128
129 return CanDrawPath::kYes;
130 }
131
132 case SkStrokeRec::kStroke_Style:
133 if (!args.fViewMatrix->isSimilarity()) {
134 // The stroker currently only supports rigid-body transfoms for the stroke lines
135 // themselves. This limitation doesn't affect hairlines since their stroke lines are
136 // defined relative to device space.
137 return CanDrawPath::kNo;
138 }
139 [[fallthrough]];
140 case SkStrokeRec::kHairline_Style: {
141 if (CoverageType::kFP16_CoverageCount != fCoverageType) {
142 // Stroking is not yet supported in MSAA atlas mode.
143 return CanDrawPath::kNo;
144 }
145 float inflationRadius;
146 GetStrokeDevWidth(*args.fViewMatrix, stroke, &inflationRadius);
147 if (!(inflationRadius <= kMaxBoundsInflationFromStroke)) {
148 // Let extremely wide strokes be converted to fill paths and drawn by the CCPR
149 // filler instead. (Cast the logic negatively in order to also catch r=NaN.)
150 return CanDrawPath::kNo;
151 }
152 SkASSERT(!SkScalarIsNaN(inflationRadius));
153 if (SkPathPriv::ConicWeightCnt(path)) {
154 // The stroker does not support conics yet.
155 return CanDrawPath::kNo;
156 }
157 return CanDrawPath::kYes;
158 }
159
160 case SkStrokeRec::kStrokeAndFill_Style:
161 return CanDrawPath::kNo;
162 }
163
164 SK_ABORT("Invalid stroke style.");
165}
166
167bool GrCoverageCountingPathRenderer::onDrawPath(const DrawPathArgs& args) {
168 SkASSERT(!fFlushing);
169
170 auto op = GrCCDrawPathsOp::Make(args.fContext, *args.fClipConservativeBounds, *args.fViewMatrix,
171 *args.fShape, std::move(args.fPaint));
172 this->recordOp(std::move(op), args);
173 return true;
174}
175
176void GrCoverageCountingPathRenderer::recordOp(std::unique_ptr<GrCCDrawPathsOp> op,
177 const DrawPathArgs& args) {
178 if (op) {
179 auto addToOwningPerOpsTaskPaths = [this](GrOp* op, uint32_t opsTaskID) {
180 op->cast<GrCCDrawPathsOp>()->addToOwningPerOpsTaskPaths(
181 sk_ref_sp(this->lookupPendingPaths(opsTaskID)));
182 };
183 args.fRenderTargetContext->addDrawOp(args.fClip, std::move(op),
184 addToOwningPerOpsTaskPaths);
185 }
186}
187
188std::unique_ptr<GrFragmentProcessor> GrCoverageCountingPathRenderer::makeClipProcessor(
189 std::unique_ptr<GrFragmentProcessor> inputFP, uint32_t opsTaskID,
190 const SkPath& deviceSpacePath, const SkIRect& accessRect, const GrCaps& caps) {
191 SkASSERT(!fFlushing);
192
193 uint32_t key = deviceSpacePath.getGenerationID();
194 if (CoverageType::kA8_Multisample == fCoverageType) {
195 // We only need to consider fill rule in MSAA mode. In coverage count mode Even/Odd and
196 // Nonzero both reference the same coverage count mask.
197 key = (key << 1) | (uint32_t)GrFillRuleForSkPath(deviceSpacePath);
198 }
199 GrCCClipPath& clipPath =
200 this->lookupPendingPaths(opsTaskID)->fClipPaths[key];
201 if (!clipPath.isInitialized()) {
202 // This ClipPath was just created during lookup. Initialize it.
203 const SkRect& pathDevBounds = deviceSpacePath.getBounds();
204 if (std::max(pathDevBounds.height(), pathDevBounds.width()) > kPathCropThreshold) {
205 // The path is too large. Crop it or analytic AA can run out of fp32 precision.
206 SkPath croppedPath;
207 int maxRTSize = caps.maxRenderTargetSize();
208 CropPath(deviceSpacePath, SkIRect::MakeWH(maxRTSize, maxRTSize), &croppedPath);
209 clipPath.init(croppedPath, accessRect, fCoverageType, caps);
210 } else {
211 clipPath.init(deviceSpacePath, accessRect, fCoverageType, caps);
212 }
213 } else {
214 clipPath.addAccess(accessRect);
215 }
216
217 auto isCoverageCount = GrCCClipProcessor::IsCoverageCount(
218 CoverageType::kFP16_CoverageCount == fCoverageType);
219 auto mustCheckBounds = GrCCClipProcessor::MustCheckBounds(
220 !clipPath.pathDevIBounds().contains(accessRect));
221 return std::make_unique<GrCCClipProcessor>(
222 std::move(inputFP), caps, &clipPath, isCoverageCount, mustCheckBounds);
223}
224
225void GrCoverageCountingPathRenderer::preFlush(
226 GrOnFlushResourceProvider* onFlushRP, const uint32_t* opsTaskIDs, int numOpsTaskIDs) {
227 using DoCopiesToA8Coverage = GrCCDrawPathsOp::DoCopiesToA8Coverage;
228 SkASSERT(!fFlushing);
229 SkASSERT(fFlushingPaths.empty());
230 SkDEBUGCODE(fFlushing = true);
231
232 if (fPathCache) {
233 fPathCache->doPreFlushProcessing();
234 }
235
236 if (fPendingPaths.empty()) {
237 return; // Nothing to draw.
238 }
239
240 GrCCPerFlushResourceSpecs specs;
241 int maxPreferredRTSize = onFlushRP->caps()->maxPreferredRenderTargetSize();
242 specs.fCopyAtlasSpecs.fMaxPreferredTextureSize = std::min(2048, maxPreferredRTSize);
243 SkASSERT(0 == specs.fCopyAtlasSpecs.fMinTextureSize);
244 specs.fRenderedAtlasSpecs.fMaxPreferredTextureSize = maxPreferredRTSize;
245 specs.fRenderedAtlasSpecs.fMinTextureSize = std::min(512, maxPreferredRTSize);
246
247 // Move the per-opsTask paths that are about to be flushed from fPendingPaths to fFlushingPaths,
248 // and count them up so we can preallocate buffers.
249 fFlushingPaths.reserve(numOpsTaskIDs);
250 for (int i = 0; i < numOpsTaskIDs; ++i) {
251 auto iter = fPendingPaths.find(opsTaskIDs[i]);
252 if (fPendingPaths.end() == iter) {
253 continue; // No paths on this opsTask.
254 }
255
256 fFlushingPaths.push_back(std::move(iter->second));
257 fPendingPaths.erase(iter);
258
259 for (GrCCDrawPathsOp* op : fFlushingPaths.back()->fDrawOps) {
260 op->accountForOwnPaths(fPathCache.get(), onFlushRP, &specs);
261 }
262 for (const auto& clipsIter : fFlushingPaths.back()->fClipPaths) {
263 clipsIter.second.accountForOwnPath(&specs);
264 }
265 }
266
267 if (specs.isEmpty()) {
268 return; // Nothing to draw.
269 }
270
271 // Determine if there are enough reusable paths from last flush for it to be worth our time to
272 // copy them to cached atlas(es).
273 int numCopies = specs.fNumCopiedPaths[GrCCPerFlushResourceSpecs::kFillIdx] +
274 specs.fNumCopiedPaths[GrCCPerFlushResourceSpecs::kStrokeIdx];
275 auto doCopies = DoCopiesToA8Coverage(numCopies > 100 ||
276 specs.fCopyAtlasSpecs.fApproxNumPixels > 256 * 256);
277 if (numCopies && DoCopiesToA8Coverage::kNo == doCopies) {
278 specs.cancelCopies();
279 }
280
281 auto resources = sk_make_sp<GrCCPerFlushResources>(onFlushRP, fCoverageType, specs);
282 if (!resources->isMapped()) {
283 return; // Some allocation failed.
284 }
285
286 // Layout the atlas(es) and parse paths.
287 for (const auto& flushingPaths : fFlushingPaths) {
288 for (GrCCDrawPathsOp* op : flushingPaths->fDrawOps) {
289 op->setupResources(fPathCache.get(), onFlushRP, resources.get(), doCopies);
290 }
291 for (auto& clipsIter : flushingPaths->fClipPaths) {
292 clipsIter.second.renderPathInAtlas(resources.get(), onFlushRP);
293 }
294 }
295
296 if (fPathCache) {
297 // Purge invalidated textures from previous atlases *before* calling finalize(). That way,
298 // the underlying textures objects can be freed up and reused for the next atlases.
299 fPathCache->purgeInvalidatedAtlasTextures(onFlushRP);
300 }
301
302 // Allocate resources and then render the atlas(es).
303 if (!resources->finalize(onFlushRP)) {
304 return;
305 }
306
307 // Commit flushing paths to the resources once they are successfully completed.
308 for (auto& flushingPaths : fFlushingPaths) {
309 SkASSERT(!flushingPaths->fFlushResources);
310 flushingPaths->fFlushResources = resources;
311 }
312}
313
314void GrCoverageCountingPathRenderer::postFlush(GrDeferredUploadToken, const uint32_t* opsTaskIDs,
315 int numOpsTaskIDs) {
316 SkASSERT(fFlushing);
317
318 if (!fFlushingPaths.empty()) {
319 // In DDL mode these aren't guaranteed to be deleted so we must clear out the perFlush
320 // resources manually.
321 for (auto& flushingPaths : fFlushingPaths) {
322 flushingPaths->fFlushResources = nullptr;
323 }
324
325 // We wait to erase these until after flush, once Ops and FPs are done accessing their data.
326 fFlushingPaths.reset();
327 }
328
329 SkDEBUGCODE(fFlushing = false);
330}
331
332void GrCoverageCountingPathRenderer::purgeCacheEntriesOlderThan(
333 GrProxyProvider* proxyProvider, const GrStdSteadyClock::time_point& purgeTime) {
334 if (fPathCache) {
335 fPathCache->purgeEntriesOlderThan(proxyProvider, purgeTime);
336 }
337}
338
339void GrCoverageCountingPathRenderer::CropPath(const SkPath& path, const SkIRect& cropbox,
340 SkPath* out) {
341 SkPath cropboxPath;
342 cropboxPath.addRect(SkRect::Make(cropbox));
343 if (!Op(cropboxPath, path, kIntersect_SkPathOp, out)) {
344 // This can fail if the PathOps encounter NaN or infinities.
345 out->reset();
346 }
347 out->setIsVolatile(true);
348}
349
350float GrCoverageCountingPathRenderer::GetStrokeDevWidth(const SkMatrix& m,
351 const SkStrokeRec& stroke,
352 float* inflationRadius) {
353 float strokeDevWidth;
354 if (stroke.isHairlineStyle()) {
355 strokeDevWidth = 1;
356 } else {
357 SkASSERT(SkStrokeRec::kStroke_Style == stroke.getStyle());
358 SkASSERT(m.isSimilarity()); // Otherwise matrixScaleFactor = m.getMaxScale().
359 float matrixScaleFactor = SkVector::Length(m.getScaleX(), m.getSkewY());
360 strokeDevWidth = stroke.getWidth() * matrixScaleFactor;
361 }
362 if (inflationRadius) {
363 // Inflate for a minimum stroke width of 1. In some cases when the stroke is less than 1px
364 // wide, we may inflate it to 1px and instead reduce the opacity.
365 *inflationRadius = SkStrokeRec::GetInflationRadius(
366 stroke.getJoin(), stroke.getMiter(), stroke.getCap(), std::max(strokeDevWidth, 1.f));
367 }
368 return strokeDevWidth;
369}
370