1 /*
2 * Copyright 2020 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 #ifndef tessellate_WangsFormula_DEFINED
9 #define tessellate_WangsFormula_DEFINED
10
11 #include "include/core/SkMatrix.h"
12 #include "include/core/SkPoint.h"
13 #include "include/core/SkString.h"
14 #include "include/private/SkFloatingPoint.h"
15 #include "src/gpu/tessellate/Tessellation.h"
16
17 #define AI SK_MAYBE_UNUSED SK_ALWAYS_INLINE
18
19 // Wang's formula gives the minimum number of evenly spaced (in the parametric sense) line segments
20 // that a bezier curve must be chopped into in order to guarantee all lines stay within a distance
21 // of "1/precision" pixels from the true curve. Its definition for a bezier curve of degree "n" is
22 // as follows:
23 //
24 // maxLength = max([length(p[i+2] - 2p[i+1] + p[i]) for (0 <= i <= n-2)])
25 // numParametricSegments = sqrt(maxLength * precision * n*(n - 1)/8)
26 //
27 // (Goldman, Ron. (2003). 5.6.3 Wang's Formula. "Pyramid Algorithms: A Dynamic Programming Approach
28 // to Curves and Surfaces for Geometric Modeling". Morgan Kaufmann Publishers.)
29 namespace skgpu::wangs_formula {
30
31 // Returns the value by which to multiply length in Wang's formula. (See above.)
length_term(float precision)32 template<int Degree> constexpr float length_term(float precision) {
33 return (Degree * (Degree - 1) / 8.f) * precision;
34 }
length_term_pow2(float precision)35 template<int Degree> constexpr float length_term_pow2(float precision) {
36 return ((Degree * Degree) * ((Degree - 1) * (Degree - 1)) / 64.f) * (precision * precision);
37 }
38
root4(float x)39 AI float root4(float x) {
40 return sqrtf(sqrtf(x));
41 }
42
43 // Returns nextlog2(sqrt(x)):
44 //
45 // log2(sqrt(x)) == log2(x^(1/2)) == log2(x)/2 == log2(x)/log2(4) == log4(x)
46 //
nextlog4(float x)47 AI int nextlog4(float x) {
48 return (sk_float_nextlog2(x) + 1) >> 1;
49 }
50
51 // Returns nextlog2(sqrt(sqrt(x))):
52 //
53 // log2(sqrt(sqrt(x))) == log2(x^(1/4)) == log2(x)/4 == log2(x)/log2(16) == log16(x)
54 //
nextlog16(float x)55 AI int nextlog16(float x) {
56 return (sk_float_nextlog2(x) + 3) >> 2;
57 }
58
59 // Represents the upper-left 2x2 matrix of an affine transform for applying to vectors:
60 //
61 // VectorXform(p1 - p0) == M * float3(p1, 1) - M * float3(p0, 1)
62 //
63 class VectorXform {
64 public:
65 using float2 = skvx::Vec<2, float>;
66 using float4 = skvx::Vec<4, float>;
VectorXform()67 AI explicit VectorXform() : fType(Type::kIdentity) {}
VectorXform(const SkMatrix & m)68 AI explicit VectorXform(const SkMatrix& m) { *this = m; }
69 AI VectorXform& operator=(const SkMatrix& m) {
70 SkASSERT(!m.hasPerspective());
71 if (m.getType() & SkMatrix::kAffine_Mask) {
72 fType = Type::kAffine;
73 fScaleXSkewY = {m.getScaleX(), m.getSkewY()};
74 fSkewXScaleY = {m.getSkewX(), m.getScaleY()};
75 fScaleXYXY = {m.getScaleX(), m.getScaleY(), m.getScaleX(), m.getScaleY()};
76 fSkewXYXY = {m.getSkewX(), m.getSkewY(), m.getSkewX(), m.getSkewY()};
77 } else if (m.getType() & SkMatrix::kScale_Mask) {
78 fType = Type::kScale;
79 fScaleXY = {m.getScaleX(), m.getScaleY()};
80 fScaleXYXY = {m.getScaleX(), m.getScaleY(), m.getScaleX(), m.getScaleY()};
81 } else {
82 SkASSERT(!(m.getType() & ~SkMatrix::kTranslate_Mask));
83 fType = Type::kIdentity;
84 }
85 return *this;
86 }
operator()87 AI float2 operator()(float2 vector) const {
88 switch (fType) {
89 case Type::kIdentity:
90 return vector;
91 case Type::kScale:
92 return fScaleXY * vector;
93 case Type::kAffine:
94 return fScaleXSkewY * float2(vector[0]) + fSkewXScaleY * vector[1];
95 }
96 SkUNREACHABLE;
97 }
operator()98 AI float4 operator()(float4 vectors) const {
99 switch (fType) {
100 case Type::kIdentity:
101 return vectors;
102 case Type::kScale:
103 return vectors * fScaleXYXY;
104 case Type::kAffine:
105 return fScaleXYXY * vectors + fSkewXYXY * vectors.yxwz();
106 }
107 SkUNREACHABLE;
108 }
109 private:
110 enum class Type { kIdentity, kScale, kAffine } fType;
111 union { float2 fScaleXY, fScaleXSkewY; };
112 float2 fSkewXScaleY;
113 float4 fScaleXYXY;
114 float4 fSkewXYXY;
115 };
116
117 // Returns Wang's formula, raised to the 4th power, specialized for a quadratic curve.
118 AI float quadratic_pow4(float precision,
119 const SkPoint pts[],
120 const VectorXform& vectorXform = VectorXform()) {
121 float2 p0 = skvx::bit_pun<float2>(pts[0]);
122 float2 p1 = skvx::bit_pun<float2>(pts[1]);
123 float2 p2 = skvx::bit_pun<float2>(pts[2]);
124 float2 v = -2*p1 + p0 + p2;
125 v = vectorXform(v);
126 float2 vv = v*v;
127 return (vv[0] + vv[1]) * length_term_pow2<2>(precision);
128 }
129
130 // Returns Wang's formula specialized for a quadratic curve.
131 AI float quadratic(float precision,
132 const SkPoint pts[],
133 const VectorXform& vectorXform = VectorXform()) {
134 return root4(quadratic_pow4(precision, pts, vectorXform));
135 }
136
137 // Returns the log2 value of Wang's formula specialized for a quadratic curve, rounded up to the
138 // next int.
139 AI int quadratic_log2(float precision,
140 const SkPoint pts[],
141 const VectorXform& vectorXform = VectorXform()) {
142 // nextlog16(x) == ceil(log2(sqrt(sqrt(x))))
143 return nextlog16(quadratic_pow4(precision, pts, vectorXform));
144 }
145
146 // Returns Wang's formula, raised to the 4th power, specialized for a cubic curve.
147 AI float cubic_pow4(float precision,
148 const SkPoint pts[],
149 const VectorXform& vectorXform = VectorXform()) {
150 float4 p01 = float4::Load(pts);
151 float4 p12 = float4::Load(pts + 1);
152 float4 p23 = float4::Load(pts + 2);
153 float4 v = -2*p12 + p01 + p23;
154 v = vectorXform(v);
155 float4 vv = v*v;
156 return std::max(vv[0] + vv[1], vv[2] + vv[3]) * length_term_pow2<3>(precision);
157 }
158
159 // Returns Wang's formula specialized for a cubic curve.
160 AI float cubic(float precision,
161 const SkPoint pts[],
162 const VectorXform& vectorXform = VectorXform()) {
163 return root4(cubic_pow4(precision, pts, vectorXform));
164 }
165
166 // Returns the log2 value of Wang's formula specialized for a cubic curve, rounded up to the next
167 // int.
168 AI int cubic_log2(float precision,
169 const SkPoint pts[],
170 const VectorXform& vectorXform = VectorXform()) {
171 // nextlog16(x) == ceil(log2(sqrt(sqrt(x))))
172 return nextlog16(cubic_pow4(precision, pts, vectorXform));
173 }
174
175 // Returns the maximum number of line segments a cubic with the given device-space bounding box size
176 // would ever need to be divided into, raised to the 4th power. This is simply a special case of the
177 // cubic formula where we maximize its value by placing control points on specific corners of the
178 // bounding box.
worst_case_cubic_pow4(float precision,float devWidth,float devHeight)179 AI float worst_case_cubic_pow4(float precision, float devWidth, float devHeight) {
180 float kk = length_term_pow2<3>(precision);
181 return 4*kk * (devWidth * devWidth + devHeight * devHeight);
182 }
183
184 // Returns the maximum number of line segments a cubic with the given device-space bounding box size
185 // would ever need to be divided into.
worst_case_cubic(float precision,float devWidth,float devHeight)186 AI float worst_case_cubic(float precision, float devWidth, float devHeight) {
187 return root4(worst_case_cubic_pow4(precision, devWidth, devHeight));
188 }
189
190 // Returns the maximum log2 number of line segments a cubic with the given device-space bounding box
191 // size would ever need to be divided into.
worst_case_cubic_log2(float precision,float devWidth,float devHeight)192 AI int worst_case_cubic_log2(float precision, float devWidth, float devHeight) {
193 // nextlog16(x) == ceil(log2(sqrt(sqrt(x))))
194 return nextlog16(worst_case_cubic_pow4(precision, devWidth, devHeight));
195 }
196
197 // Returns Wang's formula specialized for a conic curve, raised to the second power.
198 // Input points should be in projected space.
199 //
200 // This is not actually due to Wang, but is an analogue from (Theorem 3, corollary 1):
201 // J. Zheng, T. Sederberg. "Estimating Tessellation Parameter Intervals for
202 // Rational Curves and Surfaces." ACM Transactions on Graphics 19(1). 2000.
203 AI float conic_pow2(float precision,
204 const SkPoint pts[],
205 float w,
206 const VectorXform& vectorXform = VectorXform()) {
207 float2 p0 = vectorXform(skvx::bit_pun<float2>(pts[0]));
208 float2 p1 = vectorXform(skvx::bit_pun<float2>(pts[1]));
209 float2 p2 = vectorXform(skvx::bit_pun<float2>(pts[2]));
210
211 // Compute center of bounding box in projected space
212 const float2 C = 0.5f * (skvx::min(skvx::min(p0, p1), p2) + skvx::max(skvx::max(p0, p1), p2));
213
214 // Translate by -C. This improves translation-invariance of the formula,
215 // see Sec. 3.3 of cited paper
216 p0 -= C;
217 p1 -= C;
218 p2 -= C;
219
220 // Compute max length
221 const float max_len = sqrtf(std::max(dot(p0, p0), std::max(dot(p1, p1), dot(p2, p2))));
222
223 // Compute forward differences
224 const float2 dp = -2*w*p1 + p0 + p2;
225 const float dw = fabsf(-2 * w + 2);
226
227 // Compute numerator and denominator for parametric step size of linearization. Here, the
228 // epsilon referenced from the cited paper is 1/precision.
229 const float rp_minus_1 = std::max(0.f, max_len * precision - 1);
230 const float numer = sqrtf(dot(dp, dp)) * precision + rp_minus_1 * dw;
231 const float denom = 4 * std::min(w, 1.f);
232
233 // Number of segments = sqrt(numer / denom).
234 // This assumes parametric interval of curve being linearized is [t0,t1] = [0, 1].
235 // If not, the number of segments is (tmax - tmin) / sqrt(denom / numer).
236 return numer / denom;
237 }
238
239 // Returns the value of Wang's formula specialized for a conic curve.
240 AI float conic(float tolerance,
241 const SkPoint pts[],
242 float w,
243 const VectorXform& vectorXform = VectorXform()) {
244 return sqrtf(conic_pow2(tolerance, pts, w, vectorXform));
245 }
246
247 // Returns the log2 value of Wang's formula specialized for a conic curve, rounded up to the next
248 // int.
249 AI int conic_log2(float tolerance,
250 const SkPoint pts[],
251 float w,
252 const VectorXform& vectorXform = VectorXform()) {
253 // nextlog4(x) == ceil(log2(sqrt(x)))
254 return nextlog4(conic_pow2(tolerance, pts, w, vectorXform));
255 }
256
257 // Emits an SKSL function that calculates Wang's formula for the given set of 4 points. The points
258 // represent a cubic if w < 0, or if w >= 0, a conic defined by the first 3 points.
as_sksl()259 SK_MAYBE_UNUSED inline static SkString as_sksl() {
260 SkString code;
261 code.appendf(R"(
262 // Returns the length squared of the largest forward difference from Wang's cubic formula.
263 float wangs_formula_max_fdiff_pow2(float2 p0, float2 p1, float2 p2, float2 p3,
264 float2x2 matrix) {
265 float2 d0 = matrix * (fma(float2(-2), p1, p2) + p0);
266 float2 d1 = matrix * (fma(float2(-2), p2, p3) + p1);
267 return max(dot(d0,d0), dot(d1,d1));
268 }
269 float wangs_formula_cubic(float _precision_, float2 p0, float2 p1, float2 p2, float2 p3,
270 float2x2 matrix) {
271 float m = wangs_formula_max_fdiff_pow2(p0, p1, p2, p3, matrix);
272 return max(ceil(sqrt(%f * _precision_ * sqrt(m))), 1.0);
273 }
274 float wangs_formula_cubic_log2(float _precision_, float2 p0, float2 p1, float2 p2, float2 p3,
275 float2x2 matrix) {
276 float m = wangs_formula_max_fdiff_pow2(p0, p1, p2, p3, matrix);
277 return ceil(log2(max(%f * _precision_ * _precision_ * m, 1.0)) * .25);
278 })", length_term<3>(1), length_term_pow2<3>(1));
279
280 code.appendf(R"(
281 float wangs_formula_conic_pow2(float _precision_, float2 p0, float2 p1, float2 p2, float w) {
282 // Translate the bounding box center to the origin.
283 float2 C = (min(min(p0, p1), p2) + max(max(p0, p1), p2)) * 0.5;
284 p0 -= C;
285 p1 -= C;
286 p2 -= C;
287
288 // Compute max length.
289 float m = sqrt(max(max(dot(p0,p0), dot(p1,p1)), dot(p2,p2)));
290
291 // Compute forward differences.
292 float2 dp = fma(float2(-2.0 * w), p1, p0) + p2;
293 float dw = abs(fma(-2.0, w, 2.0));
294
295 // Compute numerator and denominator for parametric step size of linearization. Here, the
296 // epsilon referenced from the cited paper is 1/precision.
297 float rp_minus_1 = max(0.0, fma(m, _precision_, -1.0));
298 float numer = length(dp) * _precision_ + rp_minus_1 * dw;
299 float denom = 4 * min(w, 1.0);
300
301 return numer/denom;
302 }
303 float wangs_formula_conic(float _precision_, float2 p0, float2 p1, float2 p2, float w) {
304 float n2 = wangs_formula_conic_pow2(_precision_, p0, p1, p2, w);
305 return max(ceil(sqrt(n2)), 1.0);
306 }
307 float wangs_formula_conic_log2(float _precision_, float2 p0, float2 p1, float2 p2, float w) {
308 float n2 = wangs_formula_conic_pow2(_precision_, p0, p1, p2, w);
309 return ceil(log2(max(n2, 1.0)) * .5);
310 })");
311
312 return code;
313 }
314
315 } // namespace skgpu::wangs_formula
316
317 #undef AI
318
319 #endif // tessellate_WangsFormula_DEFINED
320