Debian Codegraph @

src/gpu/tessellate/Tessellation.cpp

raw
1 /*
2 * Copyright 2021 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 #include "src/gpu/tessellate/Tessellation.h"
8
9 #include "include/core/SkPath.h"
10 #include "include/core/SkPathBuilder.h"
11 #include "include/core/SkPathTypes.h"
12 #include "include/core/SkRect.h"
13 #include "include/private/base/SkFloatingPoint.h"
14 #include "include/private/base/SkTArray.h"
15 #include "src/base/SkUtils.h"
16 #include "src/base/SkVx.h"
17 #include "src/core/SkGeometry.h"
18 #include "src/core/SkPathPriv.h"
19 #include "src/gpu/tessellate/CullTest.h"
20 #include "src/gpu/tessellate/WangsFormula.h"
21
22 using namespace skia_private;
23
24 namespace skgpu::tess {
25
26 namespace {
27
28 using float2 = skvx::float2;
29 using float4 = skvx::float4;
30
31 // This value only protects us against getting stuck in infinite recursion due to fp32 precision
32 // issues. Mathematically, every curve should reduce to manageable visible sections in O(log N)
33 // chops, where N is the the magnitude of its control points.
34 //
35 // But, to define a protective upper bound, a cubic can enter or exit the viewport as many as 6
36 // times. So we may need to refine the curve (via binary search chopping at T=.5) up to 6 times.
37 //
38 // Furthermore, chopping a cubic at T=.5 may only reduce its length by 1/8 (.5^3), so we may require
39 // up to 6 chops in order to reduce the length by 1/2.
40 constexpr static int kMaxChopsPerCurve = 128/*magnitude of +fp32_max - -fp32_max*/ *
41 6/*max number of chops to reduce the length by half*/ *
42 6/*max number of viewport boundary crosses*/;
43
44 // Writes a new path, chopping as necessary so no verbs require more segments than
45 // kMaxTessellationSegmentsPerCurve. Curves completely outside the viewport are flattened into
46 // lines.
47 class PathChopper {
48 public:
49 PathChopper(float tessellationPrecision, const SkMatrix& matrix, const SkRect& viewport)
50 : fTessellationPrecision(tessellationPrecision)
51 , fCullTest(viewport, matrix)
52 , fVectorXform(matrix) {
53 fBuilder.setIsVolatile(true);
54 }
55
56 SkPath detachPath(SkPathFillType ft) {
57 fBuilder.setFillType(ft);
58 return fBuilder.detach();
59 }
60
61 void moveTo(SkPoint p) { fBuilder.moveTo(p); }
62 void lineTo(const SkPoint p[2]) { fBuilder.lineTo(p[1]); }
63 void close() { fBuilder.close(); }
64
65 void quadTo(const SkPoint quad[3]) {
66 SkASSERT(fPointStack.empty());
67 // Use a heap stack to recursively chop the quad into manageable, on-screen segments.
68 fPointStack.push_back_n(3, quad);
69 int numChops = 0;
70 while (!fPointStack.empty()) {
71 const SkPoint* p = fPointStack.end() - 3;
72 if (!fCullTest.areVisible3(p)) {
73 fBuilder.lineTo(p[2]);
74 } else {
75 float n4 = wangs_formula::quadratic_p4(fTessellationPrecision, p, fVectorXform);
76 if (n4 > kMaxSegmentsPerCurve_p4 && numChops < kMaxChopsPerCurve) {
77 SkPoint chops[5];
78 SkChopQuadAtHalf(p, chops);
79 fPointStack.pop_back_n(3);
80 fPointStack.push_back_n(3, chops+2);
81 fPointStack.push_back_n(3, chops);
82 ++numChops;
83 continue;
84 }
85 fBuilder.quadTo(p[1], p[2]);
86 }
87 fPointStack.pop_back_n(3);
88 }
89 }
90
91 void conicTo(const SkPoint conic[3], float weight) {
92 SkASSERT(fPointStack.empty());
93 SkASSERT(fWeightStack.empty());
94 // Use a heap stack to recursively chop the conic into manageable, on-screen segments.
95 fPointStack.push_back_n(3, conic);
96 fWeightStack.push_back(weight);
97 int numChops = 0;
98 while (!fPointStack.empty()) {
99 const SkPoint* p = fPointStack.end() - 3;
100 float w = fWeightStack.back();
101 if (!fCullTest.areVisible3(p)) {
102 fBuilder.lineTo(p[2]);
103 } else {
104 float n2 = wangs_formula::conic_p2(fTessellationPrecision, p, w, fVectorXform);
105 if (n2 > kMaxSegmentsPerCurve_p2 && numChops < kMaxChopsPerCurve) {
106 SkConic chops[2];
107 if (!SkConic(p,w).chopAt(.5, chops)) {
108 SkPoint line[2] = {p[0], p[2]};
109 this->lineTo(line);
110 continue;
111 }
112 fPointStack.pop_back_n(3);
113 fWeightStack.pop_back();
114 fPointStack.push_back_n(3, chops[1].fPts);
115 fWeightStack.push_back(chops[1].fW);
116 fPointStack.push_back_n(3, chops[0].fPts);
117 fWeightStack.push_back(chops[0].fW);
118 ++numChops;
119 continue;
120 }
121 fBuilder.conicTo(p[1], p[2], w);
122 }
123 fPointStack.pop_back_n(3);
124 fWeightStack.pop_back();
125 }
126 SkASSERT(fWeightStack.empty());
127 }
128
129 void cubicTo(const SkPoint cubic[4]) {
130 SkASSERT(fPointStack.empty());
131 // Use a heap stack to recursively chop the cubic into manageable, on-screen segments.
132 fPointStack.push_back_n(4, cubic);
133 int numChops = 0;
134 while (!fPointStack.empty()) {
135 SkPoint* p = fPointStack.end() - 4;
136 if (!fCullTest.areVisible4(p)) {
137 fBuilder.lineTo(p[3]);
138 } else {
139 float n4 = wangs_formula::cubic_p4(fTessellationPrecision, p, fVectorXform);
140 if (n4 > kMaxSegmentsPerCurve_p4 && numChops < kMaxChopsPerCurve) {
141 SkPoint chops[7];
142 SkChopCubicAtHalf(p, chops);
143 fPointStack.pop_back_n(4);
144 fPointStack.push_back_n(4, chops+3);
145 fPointStack.push_back_n(4, chops);
146 ++numChops;
147 continue;
148 }
149 fBuilder.cubicTo(p[1], p[2], p[3]);
150 }
151 fPointStack.pop_back_n(4);
152 }
153 }
154
155 private:
156 const float fTessellationPrecision;
157 const CullTest fCullTest;
158 const wangs_formula::VectorXform fVectorXform;
159 SkPathBuilder fBuilder;
160
161 // Used for stack-based recursion (instead of using the runtime stack).
162 STArray<8, SkPoint> fPointStack;
163 STArray<2, float> fWeightStack;
164 };
165
166 } // namespace
167
168 SkPath PreChopPathCurves(float tessellationPrecision,
169 const SkPath& path,
170 const SkMatrix& matrix,
171 const SkRect& viewport) {
172 // If the viewport is exceptionally large, we could end up blowing out memory with an unbounded
173 // number of of chops. Therefore, we require that the viewport is manageable enough that a fully
174 // contained curve can be tessellated in kMaxTessellationSegmentsPerCurve or fewer. (Any larger
175 // and that amount of pixels wouldn't fit in memory anyway.)
176 SkASSERT(wangs_formula::worst_case_cubic(
177 tessellationPrecision,
178 viewport.width(),
179 viewport.height()) <= kMaxSegmentsPerCurve);
180 PathChopper chopper(tessellationPrecision, matrix, viewport);
181 for (auto [verb, p, w] : SkPathPriv::Iterate(path)) {
182 switch (verb) {
183 case SkPathVerb::kMove:
184 chopper.moveTo(p[0]);
185 break;
186 case SkPathVerb::kLine:
187 chopper.lineTo(p);
188 break;
189 case SkPathVerb::kQuad:
190 chopper.quadTo(p);
191 break;
192 case SkPathVerb::kConic:
193 chopper.conicTo(p, *w);
194 break;
195 case SkPathVerb::kCubic:
196 chopper.cubicTo(p);
197 break;
198 case SkPathVerb::kClose:
199 chopper.close();
200 break;
201 }
202 }
203 // Must preserve the input path's fill type (see crbug.com/1472747)
204 return chopper.detachPath(path.getFillType());
205 }
206
207 int FindCubicConvex180Chops(const SkPoint pts[], float T[2], bool* areCusps) {
208 SkASSERT(pts);
209 SkASSERT(T);
210 SkASSERT(areCusps);
211
212 // If a chop falls within a distance of "kEpsilon" from 0 or 1, throw it out. Tangents become
213 // unstable when we chop too close to the boundary. This works out because the tessellation
214 // shaders don't allow more than 2^10 parametric segments, and they snap the beginning and
215 // ending edges at 0 and 1. So if we overstep an inflection or point of 180-degree rotation by a
216 // fraction of a tessellation segment, it just gets snapped.
217 constexpr static float kEpsilon = 1.f / (1 << 11);
218 // Floating-point representation of "1 - 2*kEpsilon".
219 constexpr static uint32_t kIEEE_one_minus_2_epsilon = (127 << 23) - 2 * (1 << (24 - 11));
220 // Unfortunately we don't have a way to static_assert this, but we can runtime assert that the
221 // kIEEE_one_minus_2_epsilon bits are correct.
222 SkASSERT(sk_bit_cast<float>(kIEEE_one_minus_2_epsilon) == 1 - 2*kEpsilon);
223
224 float2 p0 = sk_bit_cast<float2>(pts[0]);
225 float2 p1 = sk_bit_cast<float2>(pts[1]);
226 float2 p2 = sk_bit_cast<float2>(pts[2]);
227 float2 p3 = sk_bit_cast<float2>(pts[3]);
228
229 // Find the cubic's power basis coefficients. These define the bezier curve as:
230 //
231 // |T^3|
232 // Cubic(T) = x,y = |A 3B 3C| * |T^2| + P0
233 // |. . .| |T |
234 //
235 // And the tangent direction (scaled by a uniform 1/3) will be:
236 //
237 // |T^2|
238 // Tangent_Direction(T) = dx,dy = |A 2B C| * |T |
239 // |. . .| |1 |
240 //
241 float2 C = p1 - p0;
242 float2 D = p2 - p1;
243 float2 E = p3 - p0;
244 float2 B = D - C;
245 float2 A = -3*D + E;
246
247 // Now find the cubic's inflection function. There are inflections where F' x F'' == 0.
248 // We formulate this as a quadratic equation: F' x F'' == aT^2 + bT + c == 0.
249 // See: https://www.microsoft.com/en-us/research/wp-content/uploads/2005/01/p1000-loop.pdf
250 // NOTE: We only need the roots, so a uniform scale factor does not affect the solution.
251 float a = cross(A,B);
252 float b = cross(A,C);
253 float c = cross(B,C);
254 float b_over_minus_2 = -.5f * b;
255 float discr_over_4 = b_over_minus_2*b_over_minus_2 - a*c;
256
257 // If -cuspThreshold <= discr_over_4 <= cuspThreshold, it means the two roots are within
258 // kEpsilon of one another (in parametric space). This is close enough for our purposes to
259 // consider them a single cusp.
260 float cuspThreshold = a * (kEpsilon/2);
261 cuspThreshold *= cuspThreshold;
262
263 if (discr_over_4 < -cuspThreshold) {
264 // The curve does not inflect or cusp. This means it might rotate more than 180 degrees
265 // instead. Chop were rotation == 180 deg. (This is the 2nd root where the tangent is
266 // parallel to tan0.)
267 //
268 // Tangent_Direction(T) x tan0 == 0
269 // (AT^2 x tan0) + (2BT x tan0) + (C x tan0) == 0
270 // (A x C)T^2 + (2B x C)T + (C x C) == 0 [[because tan0 == P1 - P0 == C]]
271 // bT^2 + 2cT + 0 == 0 [[because A x C == b, B x C == c]]
272 // T = [0, -2c/b]
273 //
274 // NOTE: if C == 0, then C != tan0. But this is fine because the curve is definitely
275 // convex-180 if any points are colocated, and T[0] will equal NaN which returns 0 chops.
276 *areCusps = false;
277 float root = sk_ieee_float_divide(c, b_over_minus_2);
278 // Is "root" inside the range [kEpsilon, 1 - kEpsilon)?
279 if (sk_bit_cast<uint32_t>(root - kEpsilon) < kIEEE_one_minus_2_epsilon) {
280 T[0] = root;
281 return 1;
282 }
283 return 0;
284 }
285
286 *areCusps = (discr_over_4 <= cuspThreshold);
287 if (*areCusps) {
288 // The two roots are close enough that we can consider them a single cusp.
289 if (a != 0 || b_over_minus_2 != 0 || c != 0) {
290 // Pick the average of both roots.
291 float root = sk_ieee_float_divide(b_over_minus_2, a);
292 // Is "root" inside the range [kEpsilon, 1 - kEpsilon)?
293 if (sk_bit_cast<uint32_t>(root - kEpsilon) < kIEEE_one_minus_2_epsilon) {
294 T[0] = root;
295 return 1;
296 }
297 return 0;
298 }
299
300 // The curve is a flat line. The standard inflection function doesn't detect cusps from flat
301 // lines. Find cusps by searching instead for points where the tangent is perpendicular to
302 // tan0. This will find any cusp point.
303 //
304 // dot(tan0, Tangent_Direction(T)) == 0
305 //
306 // |T^2|
307 // tan0 * |A 2B C| * |T | == 0
308 // |. . .| |1 |
309 //
310 float2 tan0 = skvx::if_then_else(C != 0, C, p2 - p0);
311 a = dot(tan0, A);
312 b_over_minus_2 = -dot(tan0, B);
313 c = dot(tan0, C);
314 discr_over_4 = b_over_minus_2*b_over_minus_2 - a*c;
315 if (discr_over_4 < -cuspThreshold) {
316 // With the updated discriminant, this line actually wouldn't have cusps (e.g. it never
317 // turns back on itself).
318 return 0;
319 }
320
321 discr_over_4 = std::max(discr_over_4, 0.f);
322 }
323
324 // Solve our quadratic equation to find where to chop. See the quadratic formula from
325 // Numerical Recipes in C.
326 float q = sqrtf(discr_over_4);
327 q = copysignf(q, b_over_minus_2);
328 q = q + b_over_minus_2;
329 float2 roots = float2{q,c} / float2{a,q};
330
331 auto inside = (roots > kEpsilon) & (roots < (1 - kEpsilon));
332 if (inside[0]) {
333 if (inside[1] && roots[0] != roots[1]) {
334 if (roots[0] > roots[1]) {
335 roots = skvx::shuffle<1,0>(roots); // Sort.
336 }
337 roots.store(T);
338 return 2;
339 }
340 T[0] = roots[0];
341 return 1;
342 }
343 if (inside[1]) {
344 T[0] = roots[1];
345 return 1;
346 }
347 return 0;
348 }
349
350 } // namespace skgpu::tess