blob: 482a1ef78495d921dc709606a2ca9d08ab5454e5 [file] [log] [blame]
Chris Daltonb832ce62020-01-06 19:49:37 -07001/*
2 * Copyright 2019 Google LLC.
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
Chris Dalton0a22b1e2020-03-26 11:52:15 -06008#include "src/gpu/tessellate/GrTessellationPathRenderer.h"
Chris Daltonb832ce62020-01-06 19:49:37 -07009
Chris Daltonb96995d2020-06-04 16:44:29 -060010#include "include/pathops/SkPathOps.h"
Chris Daltond2dc8dd2020-05-19 16:32:02 -060011#include "src/core/SkIPoint16.h"
Chris Daltonb832ce62020-01-06 19:49:37 -070012#include "src/core/SkPathPriv.h"
13#include "src/gpu/GrClip.h"
14#include "src/gpu/GrMemoryPool.h"
15#include "src/gpu/GrRecordingContextPriv.h"
16#include "src/gpu/GrRenderTargetContext.h"
Chris Daltonc3b67eb2020-02-10 21:09:58 -070017#include "src/gpu/GrSurfaceContextPriv.h"
Michael Ludwig2686d692020-04-17 20:21:37 +000018#include "src/gpu/geometry/GrStyledShape.h"
Chris Daltonc3b67eb2020-02-10 21:09:58 -070019#include "src/gpu/ops/GrFillRectOp.h"
Chris Dalton4e998532020-02-10 11:06:42 -070020#include "src/gpu/tessellate/GrDrawAtlasPathOp.h"
Chris Daltonb832ce62020-01-06 19:49:37 -070021#include "src/gpu/tessellate/GrTessellatePathOp.h"
Chris Daltonb96995d2020-06-04 16:44:29 -060022#include "src/gpu/tessellate/GrWangsFormula.h"
Chris Daltonb832ce62020-01-06 19:49:37 -070023
Chris Dalton4e998532020-02-10 11:06:42 -070024constexpr static SkISize kAtlasInitialSize{512, 512};
25constexpr static int kMaxAtlasSize = 2048;
26
Chris Daltond2dc8dd2020-05-19 16:32:02 -060027// The atlas is only used for small-area paths, which means at least one dimension of every path is
28// guaranteed to be quite small. So if we transpose tall paths, then every path will have a small
29// height, which lends very well to efficient pow2 atlas packing.
30constexpr static auto kAtlasAlgorithm = GrDynamicAtlas::RectanizerAlgorithm::kPow2;
31
32// Ensure every path in the atlas falls in or below the 128px high rectanizer band.
33constexpr static int kMaxAtlasPathHeight = 128;
34
Chris Daltonb96995d2020-06-04 16:44:29 -060035GrTessellationPathRenderer::GrTessellationPathRenderer(const GrCaps& caps)
36 : fAtlas(GrColorType::kAlpha_8, GrDynamicAtlas::InternalMultisample::kYes,
37 kAtlasInitialSize, std::min(kMaxAtlasSize, caps.maxPreferredRenderTargetSize()),
38 caps, kAtlasAlgorithm) {
39 this->initAtlasFlags(*caps.shaderCaps());
40}
41
42void GrTessellationPathRenderer::initAtlasFlags(const GrShaderCaps& shaderCaps) {
43 fStencilAtlasFlags = OpFlags::kStencilOnly | OpFlags::kDisableHWTessellation;
44 fMaxAtlasPathWidth = fAtlas.maxAtlasSize() / 2;
45 // The atlas usually does better with hardware tessellation. If hardware tessellation is
46 // supported, we choose a max atlas path width that is guaranteed to never require more
47 // tessellation segments than are supported by the hardware.
48 if (!shaderCaps.tessellationSupport()) {
49 return;
50 }
51 // Since we limit the area of paths in the atlas to kMaxAtlasPathHeight^2, taller paths can't
52 // get very wide anyway. Find the tallest path whose width is limited by
53 // GrWangsFormula::worst_case_cubic() rather than the max area constraint, and use that for our
54 // max atlas path width.
55 //
56 // Solve the following equation for w:
57 //
58 // GrWangsFormula::worst_case_cubic(kLinearizationIntolerance, w, kMaxAtlasPathHeight^2 / w)
59 // == maxTessellationSegments
60 //
61 float k = GrWangsFormula::cubic_k(kLinearizationIntolerance);
62 float h = kMaxAtlasPathHeight;
63 float s = shaderCaps.maxTessellationSegments();
64 // Quadratic formula from Numerical Recipes in C:
65 //
66 // q = -1/2 [b + sign(b) sqrt(b*b - 4*a*c)]
67 // x1 = q/a
68 // x2 = c/q
69 //
70 // float a = 1; // 'a' is always 1 in our specific equation.
71 float b = -s*s*s*s / (4*k*k); // Always negative.
72 float c = h*h*h*h; // Always positive.
73 float det = b*b - 4*1*c;
74 if (det <= 0) {
75 // maxTessellationSegments is too small for any path whose area == kMaxAtlasPathHeight^2.
76 // (This is unexpected because the GL spec mandates a minimum of 64 segments.)
77 SkDebugf("WARNING: maxTessellationSegments seems too low. (%i)\n",
78 shaderCaps.maxTessellationSegments());
79 return;
80 }
81 float q = -.5f * (b - std::sqrt(det)); // Always positive.
82 // The two roots represent the width^2 and height^2 of the tallest rectangle that is limited by
83 // GrWangsFormula::worst_case_cubic().
84 float r0 = q; // Always positive.
85 float r1 = c/q; // Always positive.
86 float worstCaseWidth = std::sqrt(std::max(r0, r1));
87#ifdef SK_DEBUG
88 float worstCaseHeight = std::sqrt(std::min(r0, r1));
89 // Verify the above equation worked as expected. It should have found a width and height whose
90 // area == kMaxAtlasPathHeight^2.
91 SkASSERT(SkScalarNearlyEqual(worstCaseHeight * worstCaseWidth, h*h, 1));
92 // Verify GrWangsFormula::worst_case_cubic() still works as we expect. The worst case number of
93 // segments for this bounding box should be maxTessellationSegments.
94 SkASSERT(SkScalarNearlyEqual(GrWangsFormula::worst_case_cubic(
95 kLinearizationIntolerance, worstCaseWidth, worstCaseHeight), s, 1));
96#endif
97 fStencilAtlasFlags &= ~OpFlags::kDisableHWTessellation;
98 fMaxAtlasPathWidth = std::min(fMaxAtlasPathWidth, (int)worstCaseWidth);
Chris Dalton4e998532020-02-10 11:06:42 -070099}
100
Chris Dalton0a22b1e2020-03-26 11:52:15 -0600101GrPathRenderer::CanDrawPath GrTessellationPathRenderer::onCanDrawPath(
Chris Daltonb832ce62020-01-06 19:49:37 -0700102 const CanDrawPathArgs& args) const {
Chris Dalton0f6bb8a2020-01-15 09:40:54 -0700103 if (!args.fShape->style().isSimpleFill() || args.fShape->inverseFilled() ||
104 args.fViewMatrix->hasPerspective()) {
Chris Daltonb832ce62020-01-06 19:49:37 -0700105 return CanDrawPath::kNo;
106 }
107 if (GrAAType::kCoverage == args.fAAType) {
108 SkASSERT(1 == args.fProxy->numSamples());
109 if (!args.fProxy->canUseMixedSamples(*args.fCaps)) {
110 return CanDrawPath::kNo;
111 }
112 }
113 SkPath path;
114 args.fShape->asPath(&path);
115 if (SkPathPriv::ConicWeightCnt(path)) {
116 return CanDrawPath::kNo;
117 }
118 return CanDrawPath::kYes;
119}
120
Chris Dalton0a22b1e2020-03-26 11:52:15 -0600121bool GrTessellationPathRenderer::onDrawPath(const DrawPathArgs& args) {
Chris Dalton4e998532020-02-10 11:06:42 -0700122 GrRenderTargetContext* renderTargetContext = args.fRenderTargetContext;
123 GrOpMemoryPool* pool = args.fContext->priv().opMemoryPool();
Chris Daltonb96995d2020-06-04 16:44:29 -0600124 const GrShaderCaps& shaderCaps = *args.fContext->priv().caps()->shaderCaps();
125
Chris Daltonb832ce62020-01-06 19:49:37 -0700126 SkPath path;
127 args.fShape->asPath(&path);
128
Chris Daltonb96995d2020-06-04 16:44:29 -0600129 SkRect devBounds;
130 args.fViewMatrix->mapRect(&devBounds, path.getBounds());
131
Chris Dalton4e998532020-02-10 11:06:42 -0700132 // See if the path is small and simple enough to atlas instead of drawing directly.
133 //
134 // NOTE: The atlas uses alpha8 coverage even for msaa render targets. We could theoretically
135 // render the sample mask to an integer texture, but such a scheme would probably require
136 // GL_EXT_post_depth_coverage, which appears to have low adoption.
137 SkIRect devIBounds;
Chris Daltond2dc8dd2020-05-19 16:32:02 -0600138 SkIPoint16 locationInAtlas;
139 bool transposedInAtlas;
Chris Daltonb96995d2020-06-04 16:44:29 -0600140 if (this->tryAddPathToAtlas(*args.fContext->priv().caps(), *args.fViewMatrix, path, devBounds,
Chris Daltond2dc8dd2020-05-19 16:32:02 -0600141 args.fAAType, &devIBounds, &locationInAtlas, &transposedInAtlas)) {
Chris Daltonb96995d2020-06-04 16:44:29 -0600142#ifdef SK_DEBUG
143 // If using hardware tessellation in the atlas, make sure the max number of segments is
144 // sufficient for this path. fMaxAtlasPathWidth should have been tuned for this to always be
145 // the case.
146 if (!(fStencilAtlasFlags & OpFlags::kDisableHWTessellation)) {
147 int worstCaseNumSegments = GrWangsFormula::worst_case_cubic(kLinearizationIntolerance,
148 devIBounds.width(),
149 devIBounds.height());
150 SkASSERT(worstCaseNumSegments <= shaderCaps.maxTessellationSegments());
151 }
152#endif
Chris Dalton4e998532020-02-10 11:06:42 -0700153 auto op = pool->allocate<GrDrawAtlasPathOp>(
154 renderTargetContext->numSamples(), sk_ref_sp(fAtlas.textureProxy()),
Chris Daltond2dc8dd2020-05-19 16:32:02 -0600155 devIBounds, locationInAtlas, transposedInAtlas, *args.fViewMatrix,
Michael Ludwig7c12e282020-05-29 09:54:07 -0400156 std::move(args.fPaint));
157 renderTargetContext->addDrawOp(args.fClip, std::move(op));
Chris Dalton4e998532020-02-10 11:06:42 -0700158 return true;
159 }
Chris Daltonb832ce62020-01-06 19:49:37 -0700160
Chris Daltonb96995d2020-06-04 16:44:29 -0600161 auto drawPathFlags = OpFlags::kNone;
162
163 // Find the worst-case log2 number of line segments that a curve in this path might need to be
164 // divided into.
165 int worstCaseResolveLevel = GrWangsFormula::worst_case_cubic_log2(kLinearizationIntolerance,
166 devBounds.width(),
167 devBounds.height());
168 if (worstCaseResolveLevel > kMaxResolveLevel) {
169 // The path is too large for our internal indirect draw shaders. Crop it to the viewport.
170 SkPath viewport;
171 viewport.addRect(SkRect::MakeIWH(renderTargetContext->width(),
172 renderTargetContext->height()).makeOutset(1, 1));
173 // Perform the crop in device space so it's a simple rect-path intersection.
174 path.transform(*args.fViewMatrix);
175 if (!Op(viewport, path, kIntersect_SkPathOp, &path)) {
176 // The crop can fail if the PathOps encounter NaN or infinities. Return true
177 // because drawing nothing is acceptable behavior for FP overflow.
178 return true;
179 }
180 // Transform the path back to its own local space.
181 SkMatrix inverse;
182 if (!args.fViewMatrix->invert(&inverse)) {
183 return true; // Singular view matrix. Nothing would have drawn anyway. Return true.
184 }
185 path.transform(inverse);
186 path.setIsVolatile(true);
187 args.fViewMatrix->mapRect(&devBounds, path.getBounds());
188 worstCaseResolveLevel = GrWangsFormula::worst_case_cubic_log2(kLinearizationIntolerance,
189 devBounds.width(),
190 devBounds.height());
191 // kMaxResolveLevel should be large enough to tessellate paths the size of any screen we
192 // might encounter.
193 SkASSERT(worstCaseResolveLevel <= kMaxResolveLevel);
194 }
195
196 if ((1 << worstCaseResolveLevel) > shaderCaps.maxTessellationSegments()) {
197 // The path is too large for hardware tessellation; a curve in this bounding box could
198 // potentially require more segments than are supported by the hardware. Fall back on
199 // indirect draws.
200 drawPathFlags |= OpFlags::kDisableHWTessellation;
201 }
202
203 auto op = pool->allocate<GrTessellatePathOp>(*args.fViewMatrix, path, std::move(args.fPaint),
204 args.fAAType, drawPathFlags);
Michael Ludwig7c12e282020-05-29 09:54:07 -0400205 renderTargetContext->addDrawOp(args.fClip, std::move(op));
Chris Dalton4e998532020-02-10 11:06:42 -0700206 return true;
207}
208
Chris Dalton0a22b1e2020-03-26 11:52:15 -0600209bool GrTessellationPathRenderer::tryAddPathToAtlas(
Chris Daltonb96995d2020-06-04 16:44:29 -0600210 const GrCaps& caps, const SkMatrix& viewMatrix, const SkPath& path, const SkRect& devBounds,
211 GrAAType aaType, SkIRect* devIBounds, SkIPoint16* locationInAtlas,
212 bool* transposedInAtlas) {
Chris Dalton4e998532020-02-10 11:06:42 -0700213 if (!caps.multisampleDisableSupport() && GrAAType::kNone == aaType) {
214 return false;
215 }
216
Chris Daltond2dc8dd2020-05-19 16:32:02 -0600217 // Atlas paths require their points to be transformed on the CPU and copied into an "uber path".
218 // Check if this path has too many points to justify this extra work.
219 if (path.countPoints() > 200) {
Chris Dalton4e998532020-02-10 11:06:42 -0700220 return false;
221 }
222
Chris Daltond2dc8dd2020-05-19 16:32:02 -0600223 // Transpose tall paths in the atlas. Since we limit ourselves to small-area paths, this
224 // guarantees that every atlas entry has a small height, which lends very well to efficient pow2
225 // atlas packing.
Chris Daltonb96995d2020-06-04 16:44:29 -0600226 devBounds.roundOut(devIBounds);
Chris Daltond2dc8dd2020-05-19 16:32:02 -0600227 int maxDimenstion = devIBounds->width();
228 int minDimension = devIBounds->height();
229 *transposedInAtlas = minDimension > maxDimenstion;
230 if (*transposedInAtlas) {
231 std::swap(minDimension, maxDimenstion);
232 }
233
234 // Check if the path is too large for an atlas. Since we use "minDimension" for height in the
235 // atlas, limiting to kMaxAtlasPathHeight^2 pixels guarantees height <= kMaxAtlasPathHeight.
236 if (maxDimenstion * minDimension > kMaxAtlasPathHeight * kMaxAtlasPathHeight ||
Chris Daltonb96995d2020-06-04 16:44:29 -0600237 maxDimenstion > fMaxAtlasPathWidth) {
Chris Dalton4e998532020-02-10 11:06:42 -0700238 return false;
239 }
240
Chris Daltond2dc8dd2020-05-19 16:32:02 -0600241 if (!fAtlas.addRect(maxDimenstion, minDimension, locationInAtlas)) {
Chris Dalton4e998532020-02-10 11:06:42 -0700242 return false;
243 }
244
245 SkMatrix atlasMatrix = viewMatrix;
Chris Daltond2dc8dd2020-05-19 16:32:02 -0600246 if (*transposedInAtlas) {
247 std::swap(atlasMatrix[0], atlasMatrix[3]);
248 std::swap(atlasMatrix[1], atlasMatrix[4]);
249 float tx=atlasMatrix.getTranslateX(), ty=atlasMatrix.getTranslateY();
250 atlasMatrix.setTranslateX(ty - devIBounds->y() + locationInAtlas->x());
251 atlasMatrix.setTranslateY(tx - devIBounds->x() + locationInAtlas->y());
252 } else {
253 atlasMatrix.postTranslate(locationInAtlas->x() - devIBounds->x(),
254 locationInAtlas->y() - devIBounds->y());
255 }
Chris Dalton4e998532020-02-10 11:06:42 -0700256
257 // Concatenate this path onto our uber path that matches its fill and AA types.
258 SkPath* uberPath = this->getAtlasUberPath(path.getFillType(), GrAAType::kNone != aaType);
Chris Daltond2dc8dd2020-05-19 16:32:02 -0600259 uberPath->moveTo(locationInAtlas->x(), locationInAtlas->y()); // Implicit moveTo(0,0).
Chris Dalton4e998532020-02-10 11:06:42 -0700260 uberPath->addPath(path, atlasMatrix);
Chris Daltonb832ce62020-01-06 19:49:37 -0700261 return true;
262}
263
Chris Dalton0a22b1e2020-03-26 11:52:15 -0600264void GrTessellationPathRenderer::onStencilPath(const StencilPathArgs& args) {
Chris Daltonb832ce62020-01-06 19:49:37 -0700265 SkPath path;
266 args.fShape->asPath(&path);
267
268 GrAAType aaType = (GrAA::kYes == args.fDoStencilMSAA) ? GrAAType::kMSAA : GrAAType::kNone;
269
Chris Daltonf9aea7f2020-01-21 11:19:26 -0700270 auto op = args.fContext->priv().opMemoryPool()->allocate<GrTessellatePathOp>(
Chris Daltonb96995d2020-06-04 16:44:29 -0600271 *args.fViewMatrix, path, GrPaint(), aaType, OpFlags::kStencilOnly);
Michael Ludwig7c12e282020-05-29 09:54:07 -0400272 args.fRenderTargetContext->addDrawOp(args.fClip, std::move(op));
Chris Daltonb832ce62020-01-06 19:49:37 -0700273}
Chris Dalton4e998532020-02-10 11:06:42 -0700274
Chris Dalton0a22b1e2020-03-26 11:52:15 -0600275void GrTessellationPathRenderer::preFlush(GrOnFlushResourceProvider* onFlushRP,
276 const uint32_t* opsTaskIDs, int numOpsTaskIDs) {
Chris Dalton4e998532020-02-10 11:06:42 -0700277 if (!fAtlas.drawBounds().isEmpty()) {
278 this->renderAtlas(onFlushRP);
279 fAtlas.reset(kAtlasInitialSize, *onFlushRP->caps());
280 }
281 for (SkPath& path : fAtlasUberPaths) {
282 path.reset();
283 }
284}
285
286constexpr static GrUserStencilSettings kTestStencil(
287 GrUserStencilSettings::StaticInit<
288 0x0000,
289 GrUserStencilTest::kNotEqual,
290 0xffff,
291 GrUserStencilOp::kKeep,
292 GrUserStencilOp::kKeep,
293 0xffff>());
294
295constexpr static GrUserStencilSettings kTestAndResetStencil(
296 GrUserStencilSettings::StaticInit<
297 0x0000,
298 GrUserStencilTest::kNotEqual,
299 0xffff,
300 GrUserStencilOp::kZero,
301 GrUserStencilOp::kKeep,
302 0xffff>());
303
Chris Dalton0a22b1e2020-03-26 11:52:15 -0600304void GrTessellationPathRenderer::renderAtlas(GrOnFlushResourceProvider* onFlushRP) {
Chris Dalton4e998532020-02-10 11:06:42 -0700305 auto rtc = fAtlas.instantiate(onFlushRP);
306 if (!rtc) {
307 return;
308 }
309
310 // Add ops to stencil the atlas paths.
311 for (auto antialias : {false, true}) {
312 for (auto fillType : {SkPathFillType::kWinding, SkPathFillType::kEvenOdd}) {
313 SkPath* uberPath = this->getAtlasUberPath(fillType, antialias);
314 if (uberPath->isEmpty()) {
315 continue;
316 }
317 uberPath->setFillType(fillType);
318 GrAAType aaType = (antialias) ? GrAAType::kMSAA : GrAAType::kNone;
319 auto op = onFlushRP->opMemoryPool()->allocate<GrTessellatePathOp>(
Chris Daltonb96995d2020-06-04 16:44:29 -0600320 SkMatrix::I(), *uberPath, GrPaint(), aaType, fStencilAtlasFlags);
Michael Ludwig7c12e282020-05-29 09:54:07 -0400321 rtc->addDrawOp(nullptr, std::move(op));
Chris Dalton4e998532020-02-10 11:06:42 -0700322 }
323 }
324
Chris Daltonc3b67eb2020-02-10 21:09:58 -0700325 // Finally, draw a fullscreen rect to convert our stencilled paths into alpha coverage masks.
326 auto fillRectFlags = GrFillRectOp::InputFlags::kNone;
Chris Dalton4e998532020-02-10 11:06:42 -0700327
Chris Daltonc3b67eb2020-02-10 21:09:58 -0700328 // This will be the final op in the renderTargetContext. So if Ganesh is planning to discard the
329 // stencil values anyway, then we might not actually need to reset the stencil values back to 0.
330 bool mustResetStencil = !onFlushRP->caps()->discardStencilValuesAfterRenderPass();
331
332 if (rtc->numSamples() <= 1) {
333 // We are mixed sampled. We need to enable conservative raster and ensure stencil values get
334 // reset in order to avoid artifacts along the diagonal of the atlas.
335 fillRectFlags |= GrFillRectOp::InputFlags::kConservativeRaster;
336 mustResetStencil = true;
337 }
338
339 SkRect coverRect = SkRect::MakeIWH(fAtlas.drawBounds().width(), fAtlas.drawBounds().height());
340 const GrUserStencilSettings* stencil;
341 if (mustResetStencil) {
342 // Outset the cover rect in case there are T-junctions in the path bounds.
343 coverRect.outset(1, 1);
344 stencil = &kTestAndResetStencil;
345 } else {
346 stencil = &kTestStencil;
347 }
348
349 GrQuad coverQuad(coverRect);
350 DrawQuad drawQuad{coverQuad, coverQuad, GrQuadAAFlags::kAll};
351
Chris Dalton4e998532020-02-10 11:06:42 -0700352 GrPaint paint;
353 paint.setColor4f(SK_PMColor4fWHITE);
Chris Daltonc3b67eb2020-02-10 21:09:58 -0700354
355 auto coverOp = GrFillRectOp::Make(rtc->surfPriv().getContext(), std::move(paint),
356 GrAAType::kMSAA, &drawQuad, stencil, fillRectFlags);
Michael Ludwig7c12e282020-05-29 09:54:07 -0400357 rtc->addDrawOp(nullptr, std::move(coverOp));
Chris Dalton4e998532020-02-10 11:06:42 -0700358
359 if (rtc->asSurfaceProxy()->requiresManualMSAAResolve()) {
360 onFlushRP->addTextureResolveTask(sk_ref_sp(rtc->asTextureProxy()),
361 GrSurfaceProxy::ResolveFlags::kMSAA);
362 }
363}