• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2006 The Android Open Source Project
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/core/SkGeometry.h"
9 
10 #include "include/core/SkMatrix.h"
11 #include "include/core/SkPoint3.h"
12 #include "include/core/SkRect.h"
13 #include "include/private/base/SkDebug.h"
14 #include "include/private/base/SkFloatingPoint.h"
15 #include "include/private/base/SkTPin.h"
16 #include "include/private/base/SkTo.h"
17 #include "src/base/SkBezierCurves.h"
18 #include "src/base/SkCubics.h"
19 #include "src/base/SkVx.h"
20 #include "src/core/SkPointPriv.h"
21 
22 #include <algorithm>
23 #include <array>
24 #include <cmath>
25 #include <cstddef>
26 #include <cstdint>
27 
28 namespace {
29 
30 using float2 = skvx::float2;
31 using float4 = skvx::float4;
32 
to_vector(const float2 & x)33 SkVector to_vector(const float2& x) {
34     SkVector vector;
35     x.store(&vector);
36     return vector;
37 }
38 
39 ////////////////////////////////////////////////////////////////////////
40 
is_not_monotonic(SkScalar a,SkScalar b,SkScalar c)41 int is_not_monotonic(SkScalar a, SkScalar b, SkScalar c) {
42     SkScalar ab = a - b;
43     SkScalar bc = b - c;
44     if (ab < 0) {
45         bc = -bc;
46     }
47     return ab == 0 || bc < 0;
48 }
49 
50 ////////////////////////////////////////////////////////////////////////
51 
valid_unit_divide(SkScalar numer,SkScalar denom,SkScalar * ratio)52 int valid_unit_divide(SkScalar numer, SkScalar denom, SkScalar* ratio) {
53     SkASSERT(ratio);
54 
55     if (numer < 0) {
56         numer = -numer;
57         denom = -denom;
58     }
59 
60     if (denom == 0 || numer == 0 || numer >= denom) {
61         return 0;
62     }
63 
64     SkScalar r = numer / denom;
65     if (SkScalarIsNaN(r)) {
66         return 0;
67     }
68     SkASSERTF(r >= 0 && r < SK_Scalar1, "numer %f, denom %f, r %f", numer, denom, r);
69     if (r == 0) { // catch underflow if numer <<<< denom
70         return 0;
71     }
72     *ratio = r;
73     return 1;
74 }
75 
76 // Just returns its argument, but makes it easy to set a break-point to know when
77 // SkFindUnitQuadRoots is going to return 0 (an error).
return_check_zero(int value)78 int return_check_zero(int value) {
79     if (value == 0) {
80         return 0;
81     }
82     return value;
83 }
84 
85 } // namespace
86 
87 /** From Numerical Recipes in C.
88 
89     Q = -1/2 (B + sign(B) sqrt[B*B - 4*A*C])
90     x1 = Q / A
91     x2 = C / Q
92 */
SkFindUnitQuadRoots(SkScalar A,SkScalar B,SkScalar C,SkScalar roots[2])93 int SkFindUnitQuadRoots(SkScalar A, SkScalar B, SkScalar C, SkScalar roots[2]) {
94     SkASSERT(roots);
95 
96     if (A == 0) {
97         return return_check_zero(valid_unit_divide(-C, B, roots));
98     }
99 
100     SkScalar* r = roots;
101 
102     // use doubles so we don't overflow temporarily trying to compute R
103     double dr = (double)B * B - 4 * (double)A * C;
104     if (dr < 0) {
105         return return_check_zero(0);
106     }
107     dr = sqrt(dr);
108     SkScalar R = SkDoubleToScalar(dr);
109     if (!SkScalarIsFinite(R)) {
110         return return_check_zero(0);
111     }
112 
113     SkScalar Q = (B < 0) ? -(B-R)/2 : -(B+R)/2;
114     r += valid_unit_divide(Q, A, r);
115     r += valid_unit_divide(C, Q, r);
116     if (r - roots == 2) {
117         if (roots[0] > roots[1]) {
118             using std::swap;
119             swap(roots[0], roots[1]);
120         } else if (roots[0] == roots[1]) { // nearly-equal?
121             r -= 1; // skip the double root
122         }
123     }
124     return return_check_zero((int)(r - roots));
125 }
126 
127 ///////////////////////////////////////////////////////////////////////////////
128 ///////////////////////////////////////////////////////////////////////////////
129 
SkEvalQuadAt(const SkPoint src[3],SkScalar t,SkPoint * pt,SkVector * tangent)130 void SkEvalQuadAt(const SkPoint src[3], SkScalar t, SkPoint* pt, SkVector* tangent) {
131     SkASSERT(src);
132     SkASSERT(t >= 0 && t <= SK_Scalar1);
133 
134     if (pt) {
135         *pt = SkEvalQuadAt(src, t);
136     }
137     if (tangent) {
138         *tangent = SkEvalQuadTangentAt(src, t);
139     }
140 }
141 
SkEvalQuadAt(const SkPoint src[3],SkScalar t)142 SkPoint SkEvalQuadAt(const SkPoint src[3], SkScalar t) {
143     return to_point(SkQuadCoeff(src).eval(t));
144 }
145 
SkEvalQuadTangentAt(const SkPoint src[3],SkScalar t)146 SkVector SkEvalQuadTangentAt(const SkPoint src[3], SkScalar t) {
147     // The derivative equation is 2(b - a +(a - 2b +c)t). This returns a
148     // zero tangent vector when t is 0 or 1, and the control point is equal
149     // to the end point. In this case, use the quad end points to compute the tangent.
150     if ((t == 0 && src[0] == src[1]) || (t == 1 && src[1] == src[2])) {
151         return src[2] - src[0];
152     }
153     SkASSERT(src);
154     SkASSERT(t >= 0 && t <= SK_Scalar1);
155 
156     float2 P0 = from_point(src[0]);
157     float2 P1 = from_point(src[1]);
158     float2 P2 = from_point(src[2]);
159 
160     float2 B = P1 - P0;
161     float2 A = P2 - P1 - B;
162     float2 T = A * t + B;
163 
164     return to_vector(T + T);
165 }
166 
interp(const float2 & v0,const float2 & v1,const float2 & t)167 static inline float2 interp(const float2& v0,
168                             const float2& v1,
169                             const float2& t) {
170     return v0 + (v1 - v0) * t;
171 }
172 
SkChopQuadAt(const SkPoint src[3],SkPoint dst[5],SkScalar t)173 void SkChopQuadAt(const SkPoint src[3], SkPoint dst[5], SkScalar t) {
174     SkASSERT(t > 0 && t < SK_Scalar1);
175 
176     float2 p0 = from_point(src[0]);
177     float2 p1 = from_point(src[1]);
178     float2 p2 = from_point(src[2]);
179     float2 tt(t);
180 
181     float2 p01 = interp(p0, p1, tt);
182     float2 p12 = interp(p1, p2, tt);
183 
184     dst[0] = to_point(p0);
185     dst[1] = to_point(p01);
186     dst[2] = to_point(interp(p01, p12, tt));
187     dst[3] = to_point(p12);
188     dst[4] = to_point(p2);
189 }
190 
SkChopQuadAtHalf(const SkPoint src[3],SkPoint dst[5])191 void SkChopQuadAtHalf(const SkPoint src[3], SkPoint dst[5]) {
192     SkChopQuadAt(src, dst, 0.5f);
193 }
194 
SkMeasureAngleBetweenVectors(SkVector a,SkVector b)195 float SkMeasureAngleBetweenVectors(SkVector a, SkVector b) {
196     float cosTheta = sk_ieee_float_divide(a.dot(b), sqrtf(a.dot(a) * b.dot(b)));
197     // Pin cosTheta such that if it is NaN (e.g., if a or b was 0), then we return acos(1) = 0.
198     cosTheta = std::max(std::min(1.f, cosTheta), -1.f);
199     return acosf(cosTheta);
200 }
201 
SkFindBisector(SkVector a,SkVector b)202 SkVector SkFindBisector(SkVector a, SkVector b) {
203     std::array<SkVector, 2> v;
204     if (a.dot(b) >= 0) {
205         // a,b are within +/-90 degrees apart.
206         v = {a, b};
207     } else if (a.cross(b) >= 0) {
208         // a,b are >90 degrees apart. Find the bisector of their interior normals instead. (Above 90
209         // degrees, the original vectors start cancelling each other out which eventually becomes
210         // unstable.)
211         v[0].set(-a.fY, +a.fX);
212         v[1].set(+b.fY, -b.fX);
213     } else {
214         // a,b are <-90 degrees apart. Find the bisector of their interior normals instead. (Below
215         // -90 degrees, the original vectors start cancelling each other out which eventually
216         // becomes unstable.)
217         v[0].set(+a.fY, -a.fX);
218         v[1].set(-b.fY, +b.fX);
219     }
220     // Return "normalize(v[0]) + normalize(v[1])".
221     skvx::float2 x0_x1{v[0].fX, v[1].fX};
222     skvx::float2 y0_y1{v[0].fY, v[1].fY};
223     auto invLengths = 1.0f / sqrt(x0_x1 * x0_x1 + y0_y1 * y0_y1);
224     x0_x1 *= invLengths;
225     y0_y1 *= invLengths;
226     return SkPoint{x0_x1[0] + x0_x1[1], y0_y1[0] + y0_y1[1]};
227 }
228 
SkFindQuadMidTangent(const SkPoint src[3])229 float SkFindQuadMidTangent(const SkPoint src[3]) {
230     // Tangents point in the direction of increasing T, so tan0 and -tan1 both point toward the
231     // midtangent. The bisector of tan0 and -tan1 is orthogonal to the midtangent:
232     //
233     //     n dot midtangent = 0
234     //
235     SkVector tan0 = src[1] - src[0];
236     SkVector tan1 = src[2] - src[1];
237     SkVector bisector = SkFindBisector(tan0, -tan1);
238 
239     // The midtangent can be found where (F' dot bisector) = 0:
240     //
241     //   0 = (F'(T) dot bisector) = |2*T 1| * |p0 - 2*p1 + p2| * |bisector.x|
242     //                                        |-2*p0 + 2*p1  |   |bisector.y|
243     //
244     //                     = |2*T 1| * |tan1 - tan0| * |nx|
245     //                                 |2*tan0     |   |ny|
246     //
247     //                     = 2*T * ((tan1 - tan0) dot bisector) + (2*tan0 dot bisector)
248     //
249     //   T = (tan0 dot bisector) / ((tan0 - tan1) dot bisector)
250     float T = sk_ieee_float_divide(tan0.dot(bisector), (tan0 - tan1).dot(bisector));
251     if (!(T > 0 && T < 1)) {  // Use "!(positive_logic)" so T=nan will take this branch.
252         T = .5;  // The quadratic was a line or near-line. Just chop at .5.
253     }
254 
255     return T;
256 }
257 
258 /** Quad'(t) = At + B, where
259     A = 2(a - 2b + c)
260     B = 2(b - a)
261     Solve for t, only if it fits between 0 < t < 1
262 */
SkFindQuadExtrema(SkScalar a,SkScalar b,SkScalar c,SkScalar tValue[1])263 int SkFindQuadExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar tValue[1]) {
264     /*  At + B == 0
265         t = -B / A
266     */
267     return valid_unit_divide(a - b, a - b - b + c, tValue);
268 }
269 
flatten_double_quad_extrema(SkScalar coords[14])270 static inline void flatten_double_quad_extrema(SkScalar coords[14]) {
271     coords[2] = coords[6] = coords[4];
272 }
273 
274 /*  Returns 0 for 1 quad, and 1 for two quads, either way the answer is
275  stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
276  */
SkChopQuadAtYExtrema(const SkPoint src[3],SkPoint dst[5])277 int SkChopQuadAtYExtrema(const SkPoint src[3], SkPoint dst[5]) {
278     SkASSERT(src);
279     SkASSERT(dst);
280 
281     SkScalar a = src[0].fY;
282     SkScalar b = src[1].fY;
283     SkScalar c = src[2].fY;
284 
285     if (is_not_monotonic(a, b, c)) {
286         SkScalar    tValue;
287         if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
288             SkChopQuadAt(src, dst, tValue);
289             flatten_double_quad_extrema(&dst[0].fY);
290             return 1;
291         }
292         // if we get here, we need to force dst to be monotonic, even though
293         // we couldn't compute a unit_divide value (probably underflow).
294         b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
295     }
296     dst[0].set(src[0].fX, a);
297     dst[1].set(src[1].fX, b);
298     dst[2].set(src[2].fX, c);
299     return 0;
300 }
301 
302 /*  Returns 0 for 1 quad, and 1 for two quads, either way the answer is
303     stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
304  */
SkChopQuadAtXExtrema(const SkPoint src[3],SkPoint dst[5])305 int SkChopQuadAtXExtrema(const SkPoint src[3], SkPoint dst[5]) {
306     SkASSERT(src);
307     SkASSERT(dst);
308 
309     SkScalar a = src[0].fX;
310     SkScalar b = src[1].fX;
311     SkScalar c = src[2].fX;
312 
313     if (is_not_monotonic(a, b, c)) {
314         SkScalar tValue;
315         if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
316             SkChopQuadAt(src, dst, tValue);
317             flatten_double_quad_extrema(&dst[0].fX);
318             return 1;
319         }
320         // if we get here, we need to force dst to be monotonic, even though
321         // we couldn't compute a unit_divide value (probably underflow).
322         b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
323     }
324     dst[0].set(a, src[0].fY);
325     dst[1].set(b, src[1].fY);
326     dst[2].set(c, src[2].fY);
327     return 0;
328 }
329 
330 //  F(t)    = a (1 - t) ^ 2 + 2 b t (1 - t) + c t ^ 2
331 //  F'(t)   = 2 (b - a) + 2 (a - 2b + c) t
332 //  F''(t)  = 2 (a - 2b + c)
333 //
334 //  A = 2 (b - a)
335 //  B = 2 (a - 2b + c)
336 //
337 //  Maximum curvature for a quadratic means solving
338 //  Fx' Fx'' + Fy' Fy'' = 0
339 //
340 //  t = - (Ax Bx + Ay By) / (Bx ^ 2 + By ^ 2)
341 //
SkFindQuadMaxCurvature(const SkPoint src[3])342 SkScalar SkFindQuadMaxCurvature(const SkPoint src[3]) {
343     SkScalar    Ax = src[1].fX - src[0].fX;
344     SkScalar    Ay = src[1].fY - src[0].fY;
345     SkScalar    Bx = src[0].fX - src[1].fX - src[1].fX + src[2].fX;
346     SkScalar    By = src[0].fY - src[1].fY - src[1].fY + src[2].fY;
347 
348     SkScalar numer = -(Ax * Bx + Ay * By);
349     SkScalar denom = Bx * Bx + By * By;
350     if (denom < 0) {
351         numer = -numer;
352         denom = -denom;
353     }
354     if (numer <= 0) {
355         return 0;
356     }
357     if (numer >= denom) {  // Also catches denom=0.
358         return 1;
359     }
360     SkScalar t = numer / denom;
361     SkASSERT((0 <= t && t < 1) || SkScalarIsNaN(t));
362     return t;
363 }
364 
SkChopQuadAtMaxCurvature(const SkPoint src[3],SkPoint dst[5])365 int SkChopQuadAtMaxCurvature(const SkPoint src[3], SkPoint dst[5]) {
366     SkScalar t = SkFindQuadMaxCurvature(src);
367     if (t > 0 && t < 1) {
368         SkChopQuadAt(src, dst, t);
369         return 2;
370     } else {
371         memcpy(dst, src, 3 * sizeof(SkPoint));
372         return 1;
373     }
374 }
375 
SkConvertQuadToCubic(const SkPoint src[3],SkPoint dst[4])376 void SkConvertQuadToCubic(const SkPoint src[3], SkPoint dst[4]) {
377     float2 scale(SkDoubleToScalar(2.0 / 3.0));
378     float2 s0 = from_point(src[0]);
379     float2 s1 = from_point(src[1]);
380     float2 s2 = from_point(src[2]);
381 
382     dst[0] = to_point(s0);
383     dst[1] = to_point(s0 + (s1 - s0) * scale);
384     dst[2] = to_point(s2 + (s1 - s2) * scale);
385     dst[3] = to_point(s2);
386 }
387 
388 //////////////////////////////////////////////////////////////////////////////
389 ///// CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS /////
390 //////////////////////////////////////////////////////////////////////////////
391 
eval_cubic_derivative(const SkPoint src[4],SkScalar t)392 static SkVector eval_cubic_derivative(const SkPoint src[4], SkScalar t) {
393     SkQuadCoeff coeff;
394     float2 P0 = from_point(src[0]);
395     float2 P1 = from_point(src[1]);
396     float2 P2 = from_point(src[2]);
397     float2 P3 = from_point(src[3]);
398 
399     coeff.fA = P3 + 3 * (P1 - P2) - P0;
400     coeff.fB = times_2(P2 - times_2(P1) + P0);
401     coeff.fC = P1 - P0;
402     return to_vector(coeff.eval(t));
403 }
404 
eval_cubic_2ndDerivative(const SkPoint src[4],SkScalar t)405 static SkVector eval_cubic_2ndDerivative(const SkPoint src[4], SkScalar t) {
406     float2 P0 = from_point(src[0]);
407     float2 P1 = from_point(src[1]);
408     float2 P2 = from_point(src[2]);
409     float2 P3 = from_point(src[3]);
410     float2 A = P3 + 3 * (P1 - P2) - P0;
411     float2 B = P2 - times_2(P1) + P0;
412 
413     return to_vector(A * t + B);
414 }
415 
SkEvalCubicAt(const SkPoint src[4],SkScalar t,SkPoint * loc,SkVector * tangent,SkVector * curvature)416 void SkEvalCubicAt(const SkPoint src[4], SkScalar t, SkPoint* loc,
417                    SkVector* tangent, SkVector* curvature) {
418     SkASSERT(src);
419     SkASSERT(t >= 0 && t <= SK_Scalar1);
420 
421     if (loc) {
422         *loc = to_point(SkCubicCoeff(src).eval(t));
423     }
424     if (tangent) {
425         // The derivative equation returns a zero tangent vector when t is 0 or 1, and the
426         // adjacent control point is equal to the end point. In this case, use the
427         // next control point or the end points to compute the tangent.
428         if ((t == 0 && src[0] == src[1]) || (t == 1 && src[2] == src[3])) {
429             if (t == 0) {
430                 *tangent = src[2] - src[0];
431             } else {
432                 *tangent = src[3] - src[1];
433             }
434             if (!tangent->fX && !tangent->fY) {
435                 *tangent = src[3] - src[0];
436             }
437         } else {
438             *tangent = eval_cubic_derivative(src, t);
439         }
440     }
441     if (curvature) {
442         *curvature = eval_cubic_2ndDerivative(src, t);
443     }
444 }
445 
446 /** Cubic'(t) = At^2 + Bt + C, where
447     A = 3(-a + 3(b - c) + d)
448     B = 6(a - 2b + c)
449     C = 3(b - a)
450     Solve for t, keeping only those that fit betwee 0 < t < 1
451 */
SkFindCubicExtrema(SkScalar a,SkScalar b,SkScalar c,SkScalar d,SkScalar tValues[2])452 int SkFindCubicExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar d,
453                        SkScalar tValues[2]) {
454     // we divide A,B,C by 3 to simplify
455     SkScalar A = d - a + 3*(b - c);
456     SkScalar B = 2*(a - b - b + c);
457     SkScalar C = b - a;
458 
459     return SkFindUnitQuadRoots(A, B, C, tValues);
460 }
461 
462 // This does not return b when t==1, but it otherwise seems to get better precision than
463 // "a*(1 - t) + b*t" for things like chopping cubics on exact cusp points.
464 // The responsibility falls on the caller to check that t != 1 before calling.
465 template<int N, typename T>
unchecked_mix(const skvx::Vec<N,T> & a,const skvx::Vec<N,T> & b,const skvx::Vec<N,T> & t)466 inline static skvx::Vec<N,T> unchecked_mix(const skvx::Vec<N,T>& a, const skvx::Vec<N,T>& b,
467                                            const skvx::Vec<N,T>& t) {
468     return (b - a)*t + a;
469 }
470 
SkChopCubicAt(const SkPoint src[4],SkPoint dst[7],SkScalar t)471 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[7], SkScalar t) {
472     SkASSERT(0 <= t && t <= 1);
473 
474     if (t == 1) {
475         memcpy(dst, src, sizeof(SkPoint) * 4);
476         dst[4] = dst[5] = dst[6] = src[3];
477         return;
478     }
479 
480     float2 p0 = skvx::bit_pun<float2>(src[0]);
481     float2 p1 = skvx::bit_pun<float2>(src[1]);
482     float2 p2 = skvx::bit_pun<float2>(src[2]);
483     float2 p3 = skvx::bit_pun<float2>(src[3]);
484     float2 T = t;
485 
486     float2 ab = unchecked_mix(p0, p1, T);
487     float2 bc = unchecked_mix(p1, p2, T);
488     float2 cd = unchecked_mix(p2, p3, T);
489     float2 abc = unchecked_mix(ab, bc, T);
490     float2 bcd = unchecked_mix(bc, cd, T);
491     float2 abcd = unchecked_mix(abc, bcd, T);
492 
493     dst[0] = skvx::bit_pun<SkPoint>(p0);
494     dst[1] = skvx::bit_pun<SkPoint>(ab);
495     dst[2] = skvx::bit_pun<SkPoint>(abc);
496     dst[3] = skvx::bit_pun<SkPoint>(abcd);
497     dst[4] = skvx::bit_pun<SkPoint>(bcd);
498     dst[5] = skvx::bit_pun<SkPoint>(cd);
499     dst[6] = skvx::bit_pun<SkPoint>(p3);
500 }
501 
SkChopCubicAt(const SkPoint src[4],SkPoint dst[10],float t0,float t1)502 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[10], float t0, float t1) {
503     SkASSERT(0 <= t0 && t0 <= t1 && t1 <= 1);
504 
505     if (t1 == 1) {
506         SkChopCubicAt(src, dst, t0);
507         dst[7] = dst[8] = dst[9] = src[3];
508         return;
509     }
510 
511     // Perform both chops in parallel using 4-lane SIMD.
512     float4 p00, p11, p22, p33, T;
513     p00.lo = p00.hi = skvx::bit_pun<float2>(src[0]);
514     p11.lo = p11.hi = skvx::bit_pun<float2>(src[1]);
515     p22.lo = p22.hi = skvx::bit_pun<float2>(src[2]);
516     p33.lo = p33.hi = skvx::bit_pun<float2>(src[3]);
517     T.lo = t0;
518     T.hi = t1;
519 
520     float4 ab = unchecked_mix(p00, p11, T);
521     float4 bc = unchecked_mix(p11, p22, T);
522     float4 cd = unchecked_mix(p22, p33, T);
523     float4 abc = unchecked_mix(ab, bc, T);
524     float4 bcd = unchecked_mix(bc, cd, T);
525     float4 abcd = unchecked_mix(abc, bcd, T);
526     float4 middle = unchecked_mix(abc, bcd, skvx::shuffle<2,3,0,1>(T));
527 
528     dst[0] = skvx::bit_pun<SkPoint>(p00.lo);
529     dst[1] = skvx::bit_pun<SkPoint>(ab.lo);
530     dst[2] = skvx::bit_pun<SkPoint>(abc.lo);
531     dst[3] = skvx::bit_pun<SkPoint>(abcd.lo);
532     middle.store(dst + 4);
533     dst[6] = skvx::bit_pun<SkPoint>(abcd.hi);
534     dst[7] = skvx::bit_pun<SkPoint>(bcd.hi);
535     dst[8] = skvx::bit_pun<SkPoint>(cd.hi);
536     dst[9] = skvx::bit_pun<SkPoint>(p33.hi);
537 }
538 
SkChopCubicAt(const SkPoint src[4],SkPoint dst[],const SkScalar tValues[],int tCount)539 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[],
540                    const SkScalar tValues[], int tCount) {
541     SkASSERT(std::all_of(tValues, tValues + tCount, [](SkScalar t) { return t >= 0 && t <= 1; }));
542     SkASSERT(std::is_sorted(tValues, tValues + tCount));
543 
544     if (dst) {
545         if (tCount == 0) { // nothing to chop
546             memcpy(dst, src, 4*sizeof(SkPoint));
547         } else {
548             int i = 0;
549             for (; i < tCount - 1; i += 2) {
550                 // Do two chops at once.
551                 float2 tt = float2::Load(tValues + i);
552                 if (i != 0) {
553                     float lastT = tValues[i - 1];
554                     tt = skvx::pin((tt - lastT) / (1 - lastT), float2(0), float2(1));
555                 }
556                 SkChopCubicAt(src, dst, tt[0], tt[1]);
557                 src = dst = dst + 6;
558             }
559             if (i < tCount) {
560                 // Chop the final cubic if there was an odd number of chops.
561                 SkASSERT(i + 1 == tCount);
562                 float t = tValues[i];
563                 if (i != 0) {
564                     float lastT = tValues[i - 1];
565                     t = SkTPin(sk_ieee_float_divide(t - lastT, 1 - lastT), 0.f, 1.f);
566                 }
567                 SkChopCubicAt(src, dst, t);
568             }
569         }
570     }
571 }
572 
SkChopCubicAtHalf(const SkPoint src[4],SkPoint dst[7])573 void SkChopCubicAtHalf(const SkPoint src[4], SkPoint dst[7]) {
574     SkChopCubicAt(src, dst, 0.5f);
575 }
576 
SkMeasureNonInflectCubicRotation(const SkPoint pts[4])577 float SkMeasureNonInflectCubicRotation(const SkPoint pts[4]) {
578     SkVector a = pts[1] - pts[0];
579     SkVector b = pts[2] - pts[1];
580     SkVector c = pts[3] - pts[2];
581     if (a.isZero()) {
582         return SkMeasureAngleBetweenVectors(b, c);
583     }
584     if (b.isZero()) {
585         return SkMeasureAngleBetweenVectors(a, c);
586     }
587     if (c.isZero()) {
588         return SkMeasureAngleBetweenVectors(a, b);
589     }
590     // Postulate: When no points are colocated and there are no inflection points in T=0..1, the
591     // rotation is: 360 degrees, minus the angle [p0,p1,p2], minus the angle [p1,p2,p3].
592     return 2*SK_ScalarPI - SkMeasureAngleBetweenVectors(a,-b) - SkMeasureAngleBetweenVectors(b,-c);
593 }
594 
fma(const skvx::float4 & f,float m,const skvx::float4 & a)595 static skvx::float4 fma(const skvx::float4& f, float m, const skvx::float4& a) {
596     return skvx::fma(f, skvx::float4(m), a);
597 }
598 
599 // Finds the root nearest 0.5. Returns 0.5 if the roots are undefined or outside 0..1.
solve_quadratic_equation_for_midtangent(float a,float b,float c,float discr)600 static float solve_quadratic_equation_for_midtangent(float a, float b, float c, float discr) {
601     // Quadratic formula from Numerical Recipes in C:
602     float q = -.5f * (b + copysignf(sqrtf(discr), b));
603     // The roots are q/a and c/q. Pick the midtangent closer to T=.5.
604     float _5qa = -.5f*q*a;
605     float T = fabsf(q*q + _5qa) < fabsf(a*c + _5qa) ? sk_ieee_float_divide(q,a)
606                                                     : sk_ieee_float_divide(c,q);
607     if (!(T > 0 && T < 1)) {  // Use "!(positive_logic)" so T=NaN will take this branch.
608         // Either the curve is a flat line with no rotation or FP precision failed us. Chop at .5.
609         T = .5;
610     }
611     return T;
612 }
613 
solve_quadratic_equation_for_midtangent(float a,float b,float c)614 static float solve_quadratic_equation_for_midtangent(float a, float b, float c) {
615     return solve_quadratic_equation_for_midtangent(a, b, c, b*b - 4*a*c);
616 }
617 
SkFindCubicMidTangent(const SkPoint src[4])618 float SkFindCubicMidTangent(const SkPoint src[4]) {
619     // Tangents point in the direction of increasing T, so tan0 and -tan1 both point toward the
620     // midtangent. The bisector of tan0 and -tan1 is orthogonal to the midtangent:
621     //
622     //     bisector dot midtangent == 0
623     //
624     SkVector tan0 = (src[0] == src[1]) ? src[2] - src[0] : src[1] - src[0];
625     SkVector tan1 = (src[2] == src[3]) ? src[3] - src[1] : src[3] - src[2];
626     SkVector bisector = SkFindBisector(tan0, -tan1);
627 
628     // Find the T value at the midtangent. This is a simple quadratic equation:
629     //
630     //     midtangent dot bisector == 0, or using a tangent matrix C' in power basis form:
631     //
632     //                   |C'x  C'y|
633     //     |T^2  T  1| * |.    .  | * |bisector.x| == 0
634     //                   |.    .  |   |bisector.y|
635     //
636     // The coeffs for the quadratic equation we need to solve are therefore:  C' * bisector
637     static const skvx::float4 kM[4] = {skvx::float4(-1,  2, -1,  0),
638                                        skvx::float4( 3, -4,  1,  0),
639                                        skvx::float4(-3,  2,  0,  0)};
640     auto C_x = fma(kM[0], src[0].fX,
641                fma(kM[1], src[1].fX,
642                fma(kM[2], src[2].fX, skvx::float4(src[3].fX, 0,0,0))));
643     auto C_y = fma(kM[0], src[0].fY,
644                fma(kM[1], src[1].fY,
645                fma(kM[2], src[2].fY, skvx::float4(src[3].fY, 0,0,0))));
646     auto coeffs = C_x * bisector.x() + C_y * bisector.y();
647 
648     // Now solve the quadratic for T.
649     float T = 0;
650     float a=coeffs[0], b=coeffs[1], c=coeffs[2];
651     float discr = b*b - 4*a*c;
652     if (discr > 0) {  // This will only be false if the curve is a line.
653         return solve_quadratic_equation_for_midtangent(a, b, c, discr);
654     } else {
655         // This is a 0- or 360-degree flat line. It doesn't have single points of midtangent.
656         // (tangent == midtangent at every point on the curve except the cusp points.)
657         // Chop in between both cusps instead, if any. There can be up to two cusps on a flat line,
658         // both where the tangent is perpendicular to the starting tangent:
659         //
660         //     tangent dot tan0 == 0
661         //
662         coeffs = C_x * tan0.x() + C_y * tan0.y();
663         a = coeffs[0];
664         b = coeffs[1];
665         if (a != 0) {
666             // We want the point in between both cusps. The midpoint of:
667             //
668             //     (-b +/- sqrt(b^2 - 4*a*c)) / (2*a)
669             //
670             // Is equal to:
671             //
672             //     -b / (2*a)
673             T = -b / (2*a);
674         }
675         if (!(T > 0 && T < 1)) {  // Use "!(positive_logic)" so T=NaN will take this branch.
676             // Either the curve is a flat line with no rotation or FP precision failed us. Chop at
677             // .5.
678             T = .5;
679         }
680         return T;
681     }
682 }
683 
flatten_double_cubic_extrema(SkScalar coords[14])684 static void flatten_double_cubic_extrema(SkScalar coords[14]) {
685     coords[4] = coords[8] = coords[6];
686 }
687 
688 /** Given 4 points on a cubic bezier, chop it into 1, 2, 3 beziers such that
689     the resulting beziers are monotonic in Y. This is called by the scan
690     converter.  Depending on what is returned, dst[] is treated as follows:
691     0   dst[0..3] is the original cubic
692     1   dst[0..3] and dst[3..6] are the two new cubics
693     2   dst[0..3], dst[3..6], dst[6..9] are the three new cubics
694     If dst == null, it is ignored and only the count is returned.
695 */
SkChopCubicAtYExtrema(const SkPoint src[4],SkPoint dst[10])696 int SkChopCubicAtYExtrema(const SkPoint src[4], SkPoint dst[10]) {
697     SkScalar    tValues[2];
698     int         roots = SkFindCubicExtrema(src[0].fY, src[1].fY, src[2].fY,
699                                            src[3].fY, tValues);
700 
701     SkChopCubicAt(src, dst, tValues, roots);
702     if (dst && roots > 0) {
703         // we do some cleanup to ensure our Y extrema are flat
704         flatten_double_cubic_extrema(&dst[0].fY);
705         if (roots == 2) {
706             flatten_double_cubic_extrema(&dst[3].fY);
707         }
708     }
709     return roots;
710 }
711 
SkChopCubicAtXExtrema(const SkPoint src[4],SkPoint dst[10])712 int SkChopCubicAtXExtrema(const SkPoint src[4], SkPoint dst[10]) {
713     SkScalar    tValues[2];
714     int         roots = SkFindCubicExtrema(src[0].fX, src[1].fX, src[2].fX,
715                                            src[3].fX, tValues);
716 
717     SkChopCubicAt(src, dst, tValues, roots);
718     if (dst && roots > 0) {
719         // we do some cleanup to ensure our Y extrema are flat
720         flatten_double_cubic_extrema(&dst[0].fX);
721         if (roots == 2) {
722             flatten_double_cubic_extrema(&dst[3].fX);
723         }
724     }
725     return roots;
726 }
727 
728 /** http://www.faculty.idc.ac.il/arik/quality/appendixA.html
729 
730     Inflection means that curvature is zero.
731     Curvature is [F' x F''] / [F'^3]
732     So we solve F'x X F''y - F'y X F''y == 0
733     After some canceling of the cubic term, we get
734     A = b - a
735     B = c - 2b + a
736     C = d - 3c + 3b - a
737     (BxCy - ByCx)t^2 + (AxCy - AyCx)t + AxBy - AyBx == 0
738 */
SkFindCubicInflections(const SkPoint src[4],SkScalar tValues[2])739 int SkFindCubicInflections(const SkPoint src[4], SkScalar tValues[2]) {
740     SkScalar    Ax = src[1].fX - src[0].fX;
741     SkScalar    Ay = src[1].fY - src[0].fY;
742     SkScalar    Bx = src[2].fX - 2 * src[1].fX + src[0].fX;
743     SkScalar    By = src[2].fY - 2 * src[1].fY + src[0].fY;
744     SkScalar    Cx = src[3].fX + 3 * (src[1].fX - src[2].fX) - src[0].fX;
745     SkScalar    Cy = src[3].fY + 3 * (src[1].fY - src[2].fY) - src[0].fY;
746 
747     return SkFindUnitQuadRoots(Bx*Cy - By*Cx,
748                                Ax*Cy - Ay*Cx,
749                                Ax*By - Ay*Bx,
750                                tValues);
751 }
752 
SkChopCubicAtInflections(const SkPoint src[4],SkPoint dst[10])753 int SkChopCubicAtInflections(const SkPoint src[4], SkPoint dst[10]) {
754     SkScalar    tValues[2];
755     int         count = SkFindCubicInflections(src, tValues);
756 
757     if (dst) {
758         if (count == 0) {
759             memcpy(dst, src, 4 * sizeof(SkPoint));
760         } else {
761             SkChopCubicAt(src, dst, tValues, count);
762         }
763     }
764     return count + 1;
765 }
766 
767 // Assumes the third component of points is 1.
768 // Calcs p0 . (p1 x p2)
calc_dot_cross_cubic(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2)769 static double calc_dot_cross_cubic(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2) {
770     const double xComp = (double) p0.fX * ((double) p1.fY - (double) p2.fY);
771     const double yComp = (double) p0.fY * ((double) p2.fX - (double) p1.fX);
772     const double wComp = (double) p1.fX * (double) p2.fY - (double) p1.fY * (double) p2.fX;
773     return (xComp + yComp + wComp);
774 }
775 
776 // Returns a positive power of 2 that, when multiplied by n, and excepting the two edge cases listed
777 // below, shifts the exponent of n to yield a magnitude somewhere inside [1..2).
778 // Returns 2^1023 if abs(n) < 2^-1022 (including 0).
779 // Returns NaN if n is Inf or NaN.
previous_inverse_pow2(double n)780 inline static double previous_inverse_pow2(double n) {
781     uint64_t bits;
782     memcpy(&bits, &n, sizeof(double));
783     bits = ((1023llu*2 << 52) + ((1llu << 52) - 1)) - bits; // exp=-exp
784     bits &= (0x7ffllu) << 52; // mantissa=1.0, sign=0
785     memcpy(&n, &bits, sizeof(double));
786     return n;
787 }
788 
write_cubic_inflection_roots(double t0,double s0,double t1,double s1,double * t,double * s)789 inline static void write_cubic_inflection_roots(double t0, double s0, double t1, double s1,
790                                                 double* t, double* s) {
791     t[0] = t0;
792     s[0] = s0;
793 
794     // This copysign/abs business orients the implicit function so positive values are always on the
795     // "left" side of the curve.
796     t[1] = -copysign(t1, t1 * s1);
797     s[1] = -fabs(s1);
798 
799     // Ensure t[0]/s[0] <= t[1]/s[1] (s[1] is negative from above).
800     if (copysign(s[1], s[0]) * t[0] > -fabs(s[0]) * t[1]) {
801         using std::swap;
802         swap(t[0], t[1]);
803         swap(s[0], s[1]);
804     }
805 }
806 
SkClassifyCubic(const SkPoint P[4],double t[2],double s[2],double d[4])807 SkCubicType SkClassifyCubic(const SkPoint P[4], double t[2], double s[2], double d[4]) {
808     // Find the cubic's inflection function, I = [T^3  -3T^2  3T  -1] dot D. (D0 will always be 0
809     // for integral cubics.)
810     //
811     // See "Resolution Independent Curve Rendering using Programmable Graphics Hardware",
812     // 4.2 Curve Categorization:
813     //
814     // https://www.microsoft.com/en-us/research/wp-content/uploads/2005/01/p1000-loop.pdf
815     double A1 = calc_dot_cross_cubic(P[0], P[3], P[2]);
816     double A2 = calc_dot_cross_cubic(P[1], P[0], P[3]);
817     double A3 = calc_dot_cross_cubic(P[2], P[1], P[0]);
818 
819     double D3 = 3 * A3;
820     double D2 = D3 - A2;
821     double D1 = D2 - A2 + A1;
822 
823     // Shift the exponents in D so the largest magnitude falls somewhere in 1..2. This protects us
824     // from overflow down the road while solving for roots and KLM functionals.
825     double Dmax = std::max(std::max(fabs(D1), fabs(D2)), fabs(D3));
826     double norm = previous_inverse_pow2(Dmax);
827     D1 *= norm;
828     D2 *= norm;
829     D3 *= norm;
830 
831     if (d) {
832         d[3] = D3;
833         d[2] = D2;
834         d[1] = D1;
835         d[0] = 0;
836     }
837 
838     // Now use the inflection function to classify the cubic.
839     //
840     // See "Resolution Independent Curve Rendering using Programmable Graphics Hardware",
841     // 4.4 Integral Cubics:
842     //
843     // https://www.microsoft.com/en-us/research/wp-content/uploads/2005/01/p1000-loop.pdf
844     if (0 != D1) {
845         double discr = 3*D2*D2 - 4*D1*D3;
846         if (discr > 0) { // Serpentine.
847             if (t && s) {
848                 double q = 3*D2 + copysign(sqrt(3*discr), D2);
849                 write_cubic_inflection_roots(q, 6*D1, 2*D3, q, t, s);
850             }
851             return SkCubicType::kSerpentine;
852         } else if (discr < 0) { // Loop.
853             if (t && s) {
854                 double q = D2 + copysign(sqrt(-discr), D2);
855                 write_cubic_inflection_roots(q, 2*D1, 2*(D2*D2 - D3*D1), D1*q, t, s);
856             }
857             return SkCubicType::kLoop;
858         } else { // Cusp.
859             if (t && s) {
860                 write_cubic_inflection_roots(D2, 2*D1, D2, 2*D1, t, s);
861             }
862             return SkCubicType::kLocalCusp;
863         }
864     } else {
865         if (0 != D2) { // Cusp at T=infinity.
866             if (t && s) {
867                 write_cubic_inflection_roots(D3, 3*D2, 1, 0, t, s); // T1=infinity.
868             }
869             return SkCubicType::kCuspAtInfinity;
870         } else { // Degenerate.
871             if (t && s) {
872                 write_cubic_inflection_roots(1, 0, 1, 0, t, s); // T0=T1=infinity.
873             }
874             return 0 != D3 ? SkCubicType::kQuadratic : SkCubicType::kLineOrPoint;
875         }
876     }
877 }
878 
bubble_sort(T array[],int count)879 template <typename T> void bubble_sort(T array[], int count) {
880     for (int i = count - 1; i > 0; --i)
881         for (int j = i; j > 0; --j)
882             if (array[j] < array[j-1])
883             {
884                 T   tmp(array[j]);
885                 array[j] = array[j-1];
886                 array[j-1] = tmp;
887             }
888 }
889 
890 /**
891  *  Given an array and count, remove all pair-wise duplicates from the array,
892  *  keeping the existing sorting, and return the new count
893  */
collaps_duplicates(SkScalar array[],int count)894 static int collaps_duplicates(SkScalar array[], int count) {
895     for (int n = count; n > 1; --n) {
896         if (array[0] == array[1]) {
897             for (int i = 1; i < n; ++i) {
898                 array[i - 1] = array[i];
899             }
900             count -= 1;
901         } else {
902             array += 1;
903         }
904     }
905     return count;
906 }
907 
908 #ifdef SK_DEBUG
909 
910 #define TEST_COLLAPS_ENTRY(array)   array, std::size(array)
911 
test_collaps_duplicates()912 static void test_collaps_duplicates() {
913     static bool gOnce;
914     if (gOnce) { return; }
915     gOnce = true;
916     const SkScalar src0[] = { 0 };
917     const SkScalar src1[] = { 0, 0 };
918     const SkScalar src2[] = { 0, 1 };
919     const SkScalar src3[] = { 0, 0, 0 };
920     const SkScalar src4[] = { 0, 0, 1 };
921     const SkScalar src5[] = { 0, 1, 1 };
922     const SkScalar src6[] = { 0, 1, 2 };
923     const struct {
924         const SkScalar* fData;
925         int fCount;
926         int fCollapsedCount;
927     } data[] = {
928         { TEST_COLLAPS_ENTRY(src0), 1 },
929         { TEST_COLLAPS_ENTRY(src1), 1 },
930         { TEST_COLLAPS_ENTRY(src2), 2 },
931         { TEST_COLLAPS_ENTRY(src3), 1 },
932         { TEST_COLLAPS_ENTRY(src4), 2 },
933         { TEST_COLLAPS_ENTRY(src5), 2 },
934         { TEST_COLLAPS_ENTRY(src6), 3 },
935     };
936     for (size_t i = 0; i < std::size(data); ++i) {
937         SkScalar dst[3];
938         memcpy(dst, data[i].fData, data[i].fCount * sizeof(dst[0]));
939         int count = collaps_duplicates(dst, data[i].fCount);
940         SkASSERT(data[i].fCollapsedCount == count);
941         for (int j = 1; j < count; ++j) {
942             SkASSERT(dst[j-1] < dst[j]);
943         }
944     }
945 }
946 #endif
947 
SkScalarCubeRoot(SkScalar x)948 static SkScalar SkScalarCubeRoot(SkScalar x) {
949     return SkScalarPow(x, 0.3333333f);
950 }
951 
952 /*  Solve coeff(t) == 0, returning the number of roots that
953     lie withing 0 < t < 1.
954     coeff[0]t^3 + coeff[1]t^2 + coeff[2]t + coeff[3]
955 
956     Eliminates repeated roots (so that all tValues are distinct, and are always
957     in increasing order.
958 */
solve_cubic_poly(const SkScalar coeff[4],SkScalar tValues[3])959 static int solve_cubic_poly(const SkScalar coeff[4], SkScalar tValues[3]) {
960     if (SkScalarNearlyZero(coeff[0])) {  // we're just a quadratic
961         return SkFindUnitQuadRoots(coeff[1], coeff[2], coeff[3], tValues);
962     }
963 
964     SkScalar a, b, c, Q, R;
965 
966     {
967         SkASSERT(coeff[0] != 0);
968 
969         SkScalar inva = SkScalarInvert(coeff[0]);
970         a = coeff[1] * inva;
971         b = coeff[2] * inva;
972         c = coeff[3] * inva;
973     }
974     Q = (a*a - b*3) / 9;
975     R = (2*a*a*a - 9*a*b + 27*c) / 54;
976 
977     SkScalar Q3 = Q * Q * Q;
978     SkScalar R2MinusQ3 = R * R - Q3;
979     SkScalar adiv3 = a / 3;
980 
981     if (R2MinusQ3 < 0) { // we have 3 real roots
982         // the divide/root can, due to finite precisions, be slightly outside of -1...1
983         SkScalar theta = SkScalarACos(SkTPin(R / SkScalarSqrt(Q3), -1.0f, 1.0f));
984         SkScalar neg2RootQ = -2 * SkScalarSqrt(Q);
985 
986         tValues[0] = SkTPin(neg2RootQ * SkScalarCos(theta/3) - adiv3, 0.0f, 1.0f);
987         tValues[1] = SkTPin(neg2RootQ * SkScalarCos((theta + 2*SK_ScalarPI)/3) - adiv3, 0.0f, 1.0f);
988         tValues[2] = SkTPin(neg2RootQ * SkScalarCos((theta - 2*SK_ScalarPI)/3) - adiv3, 0.0f, 1.0f);
989         SkDEBUGCODE(test_collaps_duplicates();)
990 
991         // now sort the roots
992         bubble_sort(tValues, 3);
993         return collaps_duplicates(tValues, 3);
994     } else {              // we have 1 real root
995         SkScalar A = SkScalarAbs(R) + SkScalarSqrt(R2MinusQ3);
996         A = SkScalarCubeRoot(A);
997         if (R > 0) {
998             A = -A;
999         }
1000         if (A != 0) {
1001             A += Q / A;
1002         }
1003         tValues[0] = SkTPin(A - adiv3, 0.0f, 1.0f);
1004         return 1;
1005     }
1006 }
1007 
1008 /*  Looking for F' dot F'' == 0
1009 
1010     A = b - a
1011     B = c - 2b + a
1012     C = d - 3c + 3b - a
1013 
1014     F' = 3Ct^2 + 6Bt + 3A
1015     F'' = 6Ct + 6B
1016 
1017     F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
1018 */
formulate_F1DotF2(const SkScalar src[],SkScalar coeff[4])1019 static void formulate_F1DotF2(const SkScalar src[], SkScalar coeff[4]) {
1020     SkScalar    a = src[2] - src[0];
1021     SkScalar    b = src[4] - 2 * src[2] + src[0];
1022     SkScalar    c = src[6] + 3 * (src[2] - src[4]) - src[0];
1023 
1024     coeff[0] = c * c;
1025     coeff[1] = 3 * b * c;
1026     coeff[2] = 2 * b * b + c * a;
1027     coeff[3] = a * b;
1028 }
1029 
1030 /*  Looking for F' dot F'' == 0
1031 
1032     A = b - a
1033     B = c - 2b + a
1034     C = d - 3c + 3b - a
1035 
1036     F' = 3Ct^2 + 6Bt + 3A
1037     F'' = 6Ct + 6B
1038 
1039     F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
1040 */
SkFindCubicMaxCurvature(const SkPoint src[4],SkScalar tValues[3])1041 int SkFindCubicMaxCurvature(const SkPoint src[4], SkScalar tValues[3]) {
1042     SkScalar coeffX[4], coeffY[4];
1043     int      i;
1044 
1045     formulate_F1DotF2(&src[0].fX, coeffX);
1046     formulate_F1DotF2(&src[0].fY, coeffY);
1047 
1048     for (i = 0; i < 4; i++) {
1049         coeffX[i] += coeffY[i];
1050     }
1051 
1052     int numRoots = solve_cubic_poly(coeffX, tValues);
1053     // now remove extrema where the curvature is zero (mins)
1054     // !!!! need a test for this !!!!
1055     return numRoots;
1056 }
1057 
SkChopCubicAtMaxCurvature(const SkPoint src[4],SkPoint dst[13],SkScalar tValues[3])1058 int SkChopCubicAtMaxCurvature(const SkPoint src[4], SkPoint dst[13],
1059                               SkScalar tValues[3]) {
1060     SkScalar    t_storage[3];
1061 
1062     if (tValues == nullptr) {
1063         tValues = t_storage;
1064     }
1065 
1066     SkScalar roots[3];
1067     int rootCount = SkFindCubicMaxCurvature(src, roots);
1068 
1069     // Throw out values not inside 0..1.
1070     int count = 0;
1071     for (int i = 0; i < rootCount; ++i) {
1072         if (0 < roots[i] && roots[i] < 1) {
1073             tValues[count++] = roots[i];
1074         }
1075     }
1076 
1077     if (dst) {
1078         if (count == 0) {
1079             memcpy(dst, src, 4 * sizeof(SkPoint));
1080         } else {
1081             SkChopCubicAt(src, dst, tValues, count);
1082         }
1083     }
1084     return count + 1;
1085 }
1086 
1087 // Returns a constant proportional to the dimensions of the cubic.
1088 // Constant found through experimentation -- maybe there's a better way....
calc_cubic_precision(const SkPoint src[4])1089 static SkScalar calc_cubic_precision(const SkPoint src[4]) {
1090     return (SkPointPriv::DistanceToSqd(src[1], src[0]) + SkPointPriv::DistanceToSqd(src[2], src[1])
1091             + SkPointPriv::DistanceToSqd(src[3], src[2])) * 1e-8f;
1092 }
1093 
1094 // Returns true if both points src[testIndex], src[testIndex+1] are in the same half plane defined
1095 // by the line segment src[lineIndex], src[lineIndex+1].
on_same_side(const SkPoint src[4],int testIndex,int lineIndex)1096 static bool on_same_side(const SkPoint src[4], int testIndex, int lineIndex) {
1097     SkPoint origin = src[lineIndex];
1098     SkVector line = src[lineIndex + 1] - origin;
1099     SkScalar crosses[2];
1100     for (int index = 0; index < 2; ++index) {
1101         SkVector testLine = src[testIndex + index] - origin;
1102         crosses[index] = line.cross(testLine);
1103     }
1104     return crosses[0] * crosses[1] >= 0;
1105 }
1106 
1107 // Return location (in t) of cubic cusp, if there is one.
1108 // Note that classify cubic code does not reliably return all cusp'd cubics, so
1109 // it is not called here.
SkFindCubicCusp(const SkPoint src[4])1110 SkScalar SkFindCubicCusp(const SkPoint src[4]) {
1111     // When the adjacent control point matches the end point, it behaves as if
1112     // the cubic has a cusp: there's a point of max curvature where the derivative
1113     // goes to zero. Ideally, this would be where t is zero or one, but math
1114     // error makes not so. It is not uncommon to create cubics this way; skip them.
1115     if (src[0] == src[1]) {
1116         return -1;
1117     }
1118     if (src[2] == src[3]) {
1119         return -1;
1120     }
1121     // Cubics only have a cusp if the line segments formed by the control and end points cross.
1122     // Detect crossing if line ends are on opposite sides of plane formed by the other line.
1123     if (on_same_side(src, 0, 2) || on_same_side(src, 2, 0)) {
1124         return -1;
1125     }
1126     // Cubics may have multiple points of maximum curvature, although at most only
1127     // one is a cusp.
1128     SkScalar maxCurvature[3];
1129     int roots = SkFindCubicMaxCurvature(src, maxCurvature);
1130     for (int index = 0; index < roots; ++index) {
1131         SkScalar testT = maxCurvature[index];
1132         if (0 >= testT || testT >= 1) {  // no need to consider max curvature on the end
1133             continue;
1134         }
1135         // A cusp is at the max curvature, and also has a derivative close to zero.
1136         // Choose the 'close to zero' meaning by comparing the derivative length
1137         // with the overall cubic size.
1138         SkVector dPt = eval_cubic_derivative(src, testT);
1139         SkScalar dPtMagnitude = SkPointPriv::LengthSqd(dPt);
1140         SkScalar precision = calc_cubic_precision(src);
1141         if (dPtMagnitude < precision) {
1142             // All three max curvature t values may be close to the cusp;
1143             // return the first one.
1144             return testT;
1145         }
1146     }
1147     return -1;
1148 }
1149 
close_enough_to_zero(double x)1150 static bool close_enough_to_zero(double x) {
1151     return std::fabs(x) < 0.00001;
1152 }
1153 
first_axis_intersection(const double coefficients[8],bool yDirection,double axisIntercept,double * solution)1154 static bool first_axis_intersection(const double coefficients[8], bool yDirection,
1155                                     double axisIntercept, double* solution) {
1156     auto [A, B, C, D] = SkBezierCubic::ConvertToPolynomial(coefficients, yDirection);
1157     D -= axisIntercept;
1158     double roots[3] = {0, 0, 0};
1159     int count = SkCubics::RootsValidT(A, B, C, D, roots);
1160     if (count == 0) {
1161         return false;
1162     }
1163     // Verify that at least one of the roots is accurate.
1164     for (int i = 0; i < count; i++) {
1165         if (close_enough_to_zero(SkCubics::EvalAt(A, B, C, D, roots[i]))) {
1166             *solution = roots[i];
1167             return true;
1168         }
1169     }
1170     // None of the roots returned by our normal cubic solver were correct enough
1171     // (e.g. https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=55732)
1172     // So we need to fallback to a more accurate solution.
1173     count = SkCubics::BinarySearchRootsValidT(A, B, C, D, roots);
1174     if (count == 0) {
1175         return false;
1176     }
1177     for (int i = 0; i < count; i++) {
1178         if (close_enough_to_zero(SkCubics::EvalAt(A, B, C, D, roots[i]))) {
1179             *solution = roots[i];
1180             return true;
1181         }
1182     }
1183     return false;
1184 }
1185 
SkChopMonoCubicAtY(const SkPoint src[4],SkScalar y,SkPoint dst[7])1186 bool SkChopMonoCubicAtY(const SkPoint src[4], SkScalar y, SkPoint dst[7]) {
1187     double coefficients[8] = {src[0].fX, src[0].fY, src[1].fX, src[1].fY,
1188                               src[2].fX, src[2].fY, src[3].fX, src[3].fY};
1189     double solution = 0;
1190     if (first_axis_intersection(coefficients, true, y, &solution)) {
1191         double cubicPair[14];
1192         SkBezierCubic::Subdivide(coefficients, solution, cubicPair);
1193         for (int i = 0; i < 7; i ++) {
1194             dst[i].fX = sk_double_to_float(cubicPair[i*2]);
1195             dst[i].fY = sk_double_to_float(cubicPair[i*2 + 1]);
1196         }
1197         return true;
1198     }
1199     return false;
1200 }
1201 
SkChopMonoCubicAtX(const SkPoint src[4],SkScalar x,SkPoint dst[7])1202 bool SkChopMonoCubicAtX(const SkPoint src[4], SkScalar x, SkPoint dst[7]) {
1203     double coefficients[8] = {src[0].fX, src[0].fY, src[1].fX, src[1].fY,
1204                                   src[2].fX, src[2].fY, src[3].fX, src[3].fY};
1205     double solution = 0;
1206     if (first_axis_intersection(coefficients, false, x, &solution)) {
1207         double cubicPair[14];
1208         SkBezierCubic::Subdivide(coefficients, solution, cubicPair);
1209         for (int i = 0; i < 7; i ++) {
1210             dst[i].fX = sk_double_to_float(cubicPair[i*2]);
1211             dst[i].fY = sk_double_to_float(cubicPair[i*2 + 1]);
1212         }
1213         return true;
1214     }
1215     return false;
1216 }
1217 
1218 ///////////////////////////////////////////////////////////////////////////////
1219 //
1220 // NURB representation for conics.  Helpful explanations at:
1221 //
1222 // http://citeseerx.ist.psu.edu/viewdoc/
1223 //   download?doi=10.1.1.44.5740&rep=rep1&type=ps
1224 // and
1225 // http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/NURBS/RB-conics.html
1226 //
1227 // F = (A (1 - t)^2 + C t^2 + 2 B (1 - t) t w)
1228 //     ------------------------------------------
1229 //         ((1 - t)^2 + t^2 + 2 (1 - t) t w)
1230 //
1231 //   = {t^2 (P0 + P2 - 2 P1 w), t (-2 P0 + 2 P1 w), P0}
1232 //     ------------------------------------------------
1233 //             {t^2 (2 - 2 w), t (-2 + 2 w), 1}
1234 //
1235 
1236 // F' = 2 (C t (1 + t (-1 + w)) - A (-1 + t) (t (-1 + w) - w) + B (1 - 2 t) w)
1237 //
1238 //  t^2 : (2 P0 - 2 P2 - 2 P0 w + 2 P2 w)
1239 //  t^1 : (-2 P0 + 2 P2 + 4 P0 w - 4 P1 w)
1240 //  t^0 : -2 P0 w + 2 P1 w
1241 //
1242 //  We disregard magnitude, so we can freely ignore the denominator of F', and
1243 //  divide the numerator by 2
1244 //
1245 //    coeff[0] for t^2
1246 //    coeff[1] for t^1
1247 //    coeff[2] for t^0
1248 //
conic_deriv_coeff(const SkScalar src[],SkScalar w,SkScalar coeff[3])1249 static void conic_deriv_coeff(const SkScalar src[],
1250                               SkScalar w,
1251                               SkScalar coeff[3]) {
1252     const SkScalar P20 = src[4] - src[0];
1253     const SkScalar P10 = src[2] - src[0];
1254     const SkScalar wP10 = w * P10;
1255     coeff[0] = w * P20 - P20;
1256     coeff[1] = P20 - 2 * wP10;
1257     coeff[2] = wP10;
1258 }
1259 
conic_find_extrema(const SkScalar src[],SkScalar w,SkScalar * t)1260 static bool conic_find_extrema(const SkScalar src[], SkScalar w, SkScalar* t) {
1261     SkScalar coeff[3];
1262     conic_deriv_coeff(src, w, coeff);
1263 
1264     SkScalar tValues[2];
1265     int roots = SkFindUnitQuadRoots(coeff[0], coeff[1], coeff[2], tValues);
1266     SkASSERT(0 == roots || 1 == roots);
1267 
1268     if (1 == roots) {
1269         *t = tValues[0];
1270         return true;
1271     }
1272     return false;
1273 }
1274 
1275 // We only interpolate one dimension at a time (the first, at +0, +3, +6).
p3d_interp(const SkScalar src[7],SkScalar dst[7],SkScalar t)1276 static void p3d_interp(const SkScalar src[7], SkScalar dst[7], SkScalar t) {
1277     SkScalar ab = SkScalarInterp(src[0], src[3], t);
1278     SkScalar bc = SkScalarInterp(src[3], src[6], t);
1279     dst[0] = ab;
1280     dst[3] = SkScalarInterp(ab, bc, t);
1281     dst[6] = bc;
1282 }
1283 
ratquad_mapTo3D(const SkPoint src[3],SkScalar w,SkPoint3 dst[3])1284 static void ratquad_mapTo3D(const SkPoint src[3], SkScalar w, SkPoint3 dst[3]) {
1285     dst[0].set(src[0].fX * 1, src[0].fY * 1, 1);
1286     dst[1].set(src[1].fX * w, src[1].fY * w, w);
1287     dst[2].set(src[2].fX * 1, src[2].fY * 1, 1);
1288 }
1289 
project_down(const SkPoint3 & src)1290 static SkPoint project_down(const SkPoint3& src) {
1291     return {src.fX / src.fZ, src.fY / src.fZ};
1292 }
1293 
1294 // return false if infinity or NaN is generated; caller must check
chopAt(SkScalar t,SkConic dst[2]) const1295 bool SkConic::chopAt(SkScalar t, SkConic dst[2]) const {
1296     SkPoint3 tmp[3], tmp2[3];
1297 
1298     ratquad_mapTo3D(fPts, fW, tmp);
1299 
1300     p3d_interp(&tmp[0].fX, &tmp2[0].fX, t);
1301     p3d_interp(&tmp[0].fY, &tmp2[0].fY, t);
1302     p3d_interp(&tmp[0].fZ, &tmp2[0].fZ, t);
1303 
1304     dst[0].fPts[0] = fPts[0];
1305     dst[0].fPts[1] = project_down(tmp2[0]);
1306     dst[0].fPts[2] = project_down(tmp2[1]); dst[1].fPts[0] = dst[0].fPts[2];
1307     dst[1].fPts[1] = project_down(tmp2[2]);
1308     dst[1].fPts[2] = fPts[2];
1309 
1310     // to put in "standard form", where w0 and w2 are both 1, we compute the
1311     // new w1 as sqrt(w1*w1/w0*w2)
1312     // or
1313     // w1 /= sqrt(w0*w2)
1314     //
1315     // However, in our case, we know that for dst[0]:
1316     //     w0 == 1, and for dst[1], w2 == 1
1317     //
1318     SkScalar root = SkScalarSqrt(tmp2[1].fZ);
1319     dst[0].fW = tmp2[0].fZ / root;
1320     dst[1].fW = tmp2[2].fZ / root;
1321     SkASSERT(sizeof(dst[0]) == sizeof(SkScalar) * 7);
1322     SkASSERT(0 == offsetof(SkConic, fPts[0].fX));
1323     return SkScalarsAreFinite(&dst[0].fPts[0].fX, 7 * 2);
1324 }
1325 
chopAt(SkScalar t1,SkScalar t2,SkConic * dst) const1326 void SkConic::chopAt(SkScalar t1, SkScalar t2, SkConic* dst) const {
1327     if (0 == t1 || 1 == t2) {
1328         if (0 == t1 && 1 == t2) {
1329             *dst = *this;
1330             return;
1331         } else {
1332             SkConic pair[2];
1333             if (this->chopAt(t1 ? t1 : t2, pair)) {
1334                 *dst = pair[SkToBool(t1)];
1335                 return;
1336             }
1337         }
1338     }
1339     SkConicCoeff coeff(*this);
1340     float2 tt1(t1);
1341     float2 aXY = coeff.fNumer.eval(tt1);
1342     float2 aZZ = coeff.fDenom.eval(tt1);
1343     float2 midTT((t1 + t2) / 2);
1344     float2 dXY = coeff.fNumer.eval(midTT);
1345     float2 dZZ = coeff.fDenom.eval(midTT);
1346     float2 tt2(t2);
1347     float2 cXY = coeff.fNumer.eval(tt2);
1348     float2 cZZ = coeff.fDenom.eval(tt2);
1349     float2 bXY = times_2(dXY) - (aXY + cXY) * 0.5f;
1350     float2 bZZ = times_2(dZZ) - (aZZ + cZZ) * 0.5f;
1351     dst->fPts[0] = to_point(aXY / aZZ);
1352     dst->fPts[1] = to_point(bXY / bZZ);
1353     dst->fPts[2] = to_point(cXY / cZZ);
1354     float2 ww = bZZ / sqrt(aZZ * cZZ);
1355     dst->fW = ww[0];
1356 }
1357 
evalAt(SkScalar t) const1358 SkPoint SkConic::evalAt(SkScalar t) const {
1359     return to_point(SkConicCoeff(*this).eval(t));
1360 }
1361 
evalTangentAt(SkScalar t) const1362 SkVector SkConic::evalTangentAt(SkScalar t) const {
1363     // The derivative equation returns a zero tangent vector when t is 0 or 1,
1364     // and the control point is equal to the end point.
1365     // In this case, use the conic endpoints to compute the tangent.
1366     if ((t == 0 && fPts[0] == fPts[1]) || (t == 1 && fPts[1] == fPts[2])) {
1367         return fPts[2] - fPts[0];
1368     }
1369     float2 p0 = from_point(fPts[0]);
1370     float2 p1 = from_point(fPts[1]);
1371     float2 p2 = from_point(fPts[2]);
1372     float2 ww(fW);
1373 
1374     float2 p20 = p2 - p0;
1375     float2 p10 = p1 - p0;
1376 
1377     float2 C = ww * p10;
1378     float2 A = ww * p20 - p20;
1379     float2 B = p20 - C - C;
1380 
1381     return to_vector(SkQuadCoeff(A, B, C).eval(t));
1382 }
1383 
evalAt(SkScalar t,SkPoint * pt,SkVector * tangent) const1384 void SkConic::evalAt(SkScalar t, SkPoint* pt, SkVector* tangent) const {
1385     SkASSERT(t >= 0 && t <= SK_Scalar1);
1386 
1387     if (pt) {
1388         *pt = this->evalAt(t);
1389     }
1390     if (tangent) {
1391         *tangent = this->evalTangentAt(t);
1392     }
1393 }
1394 
subdivide_w_value(SkScalar w)1395 static SkScalar subdivide_w_value(SkScalar w) {
1396     return SkScalarSqrt(SK_ScalarHalf + w * SK_ScalarHalf);
1397 }
1398 
chop(SkConic * SK_RESTRICT dst) const1399 void SkConic::chop(SkConic * SK_RESTRICT dst) const {
1400     float2 scale = SkScalarInvert(SK_Scalar1 + fW);
1401     SkScalar newW = subdivide_w_value(fW);
1402 
1403     float2 p0 = from_point(fPts[0]);
1404     float2 p1 = from_point(fPts[1]);
1405     float2 p2 = from_point(fPts[2]);
1406     float2 ww(fW);
1407 
1408     float2 wp1 = ww * p1;
1409     float2 m = (p0 + times_2(wp1) + p2) * scale * 0.5f;
1410     SkPoint mPt = to_point(m);
1411     if (!mPt.isFinite()) {
1412         double w_d = fW;
1413         double w_2 = w_d * 2;
1414         double scale_half = 1 / (1 + w_d) * 0.5;
1415         mPt.fX = SkDoubleToScalar((fPts[0].fX + w_2 * fPts[1].fX + fPts[2].fX) * scale_half);
1416         mPt.fY = SkDoubleToScalar((fPts[0].fY + w_2 * fPts[1].fY + fPts[2].fY) * scale_half);
1417     }
1418     dst[0].fPts[0] = fPts[0];
1419     dst[0].fPts[1] = to_point((p0 + wp1) * scale);
1420     dst[0].fPts[2] = dst[1].fPts[0] = mPt;
1421     dst[1].fPts[1] = to_point((wp1 + p2) * scale);
1422     dst[1].fPts[2] = fPts[2];
1423 
1424     dst[0].fW = dst[1].fW = newW;
1425 }
1426 
1427 /*
1428  *  "High order approximation of conic sections by quadratic splines"
1429  *      by Michael Floater, 1993
1430  */
1431 #define AS_QUAD_ERROR_SETUP                                         \
1432     SkScalar a = fW - 1;                                            \
1433     SkScalar k = a / (4 * (2 + a));                                 \
1434     SkScalar x = k * (fPts[0].fX - 2 * fPts[1].fX + fPts[2].fX);    \
1435     SkScalar y = k * (fPts[0].fY - 2 * fPts[1].fY + fPts[2].fY);
1436 
computeAsQuadError(SkVector * err) const1437 void SkConic::computeAsQuadError(SkVector* err) const {
1438     AS_QUAD_ERROR_SETUP
1439     err->set(x, y);
1440 }
1441 
asQuadTol(SkScalar tol) const1442 bool SkConic::asQuadTol(SkScalar tol) const {
1443     AS_QUAD_ERROR_SETUP
1444     return (x * x + y * y) <= tol * tol;
1445 }
1446 
1447 // Limit the number of suggested quads to approximate a conic
1448 #define kMaxConicToQuadPOW2     5
1449 
computeQuadPOW2(SkScalar tol) const1450 int SkConic::computeQuadPOW2(SkScalar tol) const {
1451     if (tol < 0 || !SkScalarIsFinite(tol) || !SkPointPriv::AreFinite(fPts, 3)) {
1452         return 0;
1453     }
1454 
1455     AS_QUAD_ERROR_SETUP
1456 
1457     SkScalar error = SkScalarSqrt(x * x + y * y);
1458     int pow2;
1459     for (pow2 = 0; pow2 < kMaxConicToQuadPOW2; ++pow2) {
1460         if (error <= tol) {
1461             break;
1462         }
1463         error *= 0.25f;
1464     }
1465     // float version -- using ceil gives the same results as the above.
1466     if ((false)) {
1467         SkScalar err = SkScalarSqrt(x * x + y * y);
1468         if (err <= tol) {
1469             return 0;
1470         }
1471         SkScalar tol2 = tol * tol;
1472         if (tol2 == 0) {
1473             return kMaxConicToQuadPOW2;
1474         }
1475         SkScalar fpow2 = SkScalarLog2((x * x + y * y) / tol2) * 0.25f;
1476         int altPow2 = SkScalarCeilToInt(fpow2);
1477         if (altPow2 != pow2) {
1478             SkDebugf("pow2 %d altPow2 %d fbits %g err %g tol %g\n", pow2, altPow2, fpow2, err, tol);
1479         }
1480         pow2 = altPow2;
1481     }
1482     return pow2;
1483 }
1484 
1485 // This was originally developed and tested for pathops: see SkOpTypes.h
1486 // returns true if (a <= b <= c) || (a >= b >= c)
between(SkScalar a,SkScalar b,SkScalar c)1487 static bool between(SkScalar a, SkScalar b, SkScalar c) {
1488     return (a - b) * (c - b) <= 0;
1489 }
1490 
subdivide(const SkConic & src,SkPoint pts[],int level)1491 static SkPoint* subdivide(const SkConic& src, SkPoint pts[], int level) {
1492     SkASSERT(level >= 0);
1493 
1494     if (0 == level) {
1495         memcpy(pts, &src.fPts[1], 2 * sizeof(SkPoint));
1496         return pts + 2;
1497     } else {
1498         SkConic dst[2];
1499         src.chop(dst);
1500         const SkScalar startY = src.fPts[0].fY;
1501         SkScalar endY = src.fPts[2].fY;
1502         if (between(startY, src.fPts[1].fY, endY)) {
1503             // If the input is monotonic and the output is not, the scan converter hangs.
1504             // Ensure that the chopped conics maintain their y-order.
1505             SkScalar midY = dst[0].fPts[2].fY;
1506             if (!between(startY, midY, endY)) {
1507                 // If the computed midpoint is outside the ends, move it to the closer one.
1508                 SkScalar closerY = SkTAbs(midY - startY) < SkTAbs(midY - endY) ? startY : endY;
1509                 dst[0].fPts[2].fY = dst[1].fPts[0].fY = closerY;
1510             }
1511             if (!between(startY, dst[0].fPts[1].fY, dst[0].fPts[2].fY)) {
1512                 // If the 1st control is not between the start and end, put it at the start.
1513                 // This also reduces the quad to a line.
1514                 dst[0].fPts[1].fY = startY;
1515             }
1516             if (!between(dst[1].fPts[0].fY, dst[1].fPts[1].fY, endY)) {
1517                 // If the 2nd control is not between the start and end, put it at the end.
1518                 // This also reduces the quad to a line.
1519                 dst[1].fPts[1].fY = endY;
1520             }
1521             // Verify that all five points are in order.
1522             SkASSERT(between(startY, dst[0].fPts[1].fY, dst[0].fPts[2].fY));
1523             SkASSERT(between(dst[0].fPts[1].fY, dst[0].fPts[2].fY, dst[1].fPts[1].fY));
1524             SkASSERT(between(dst[0].fPts[2].fY, dst[1].fPts[1].fY, endY));
1525         }
1526         --level;
1527         pts = subdivide(dst[0], pts, level);
1528         return subdivide(dst[1], pts, level);
1529     }
1530 }
1531 
chopIntoQuadsPOW2(SkPoint pts[],int pow2) const1532 int SkConic::chopIntoQuadsPOW2(SkPoint pts[], int pow2) const {
1533     SkASSERT(pow2 >= 0);
1534     *pts = fPts[0];
1535     SkDEBUGCODE(SkPoint* endPts);
1536     if (pow2 == kMaxConicToQuadPOW2) {  // If an extreme weight generates many quads ...
1537         SkConic dst[2];
1538         this->chop(dst);
1539         // check to see if the first chop generates a pair of lines
1540         if (SkPointPriv::EqualsWithinTolerance(dst[0].fPts[1], dst[0].fPts[2]) &&
1541                 SkPointPriv::EqualsWithinTolerance(dst[1].fPts[0], dst[1].fPts[1])) {
1542             pts[1] = pts[2] = pts[3] = dst[0].fPts[1];  // set ctrl == end to make lines
1543             pts[4] = dst[1].fPts[2];
1544             pow2 = 1;
1545             SkDEBUGCODE(endPts = &pts[5]);
1546             goto commonFinitePtCheck;
1547         }
1548     }
1549     SkDEBUGCODE(endPts = ) subdivide(*this, pts + 1, pow2);
1550 commonFinitePtCheck:
1551     const int quadCount = 1 << pow2;
1552     const int ptCount = 2 * quadCount + 1;
1553     SkASSERT(endPts - pts == ptCount);
1554     if (!SkPointPriv::AreFinite(pts, ptCount)) {
1555         // if we generated a non-finite, pin ourselves to the middle of the hull,
1556         // as our first and last are already on the first/last pts of the hull.
1557         for (int i = 1; i < ptCount - 1; ++i) {
1558             pts[i] = fPts[1];
1559         }
1560     }
1561     return 1 << pow2;
1562 }
1563 
findMidTangent() const1564 float SkConic::findMidTangent() const {
1565     // Tangents point in the direction of increasing T, so tan0 and -tan1 both point toward the
1566     // midtangent. The bisector of tan0 and -tan1 is orthogonal to the midtangent:
1567     //
1568     //     bisector dot midtangent = 0
1569     //
1570     SkVector tan0 = fPts[1] - fPts[0];
1571     SkVector tan1 = fPts[2] - fPts[1];
1572     SkVector bisector = SkFindBisector(tan0, -tan1);
1573 
1574     // Start by finding the tangent function's power basis coefficients. These define a tangent
1575     // direction (scaled by some uniform value) as:
1576     //                                                |T^2|
1577     //     Tangent_Direction(T) = dx,dy = |A  B  C| * |T  |
1578     //                                    |.  .  .|   |1  |
1579     //
1580     // The derivative of a conic has a cumbersome order-4 denominator. However, this isn't necessary
1581     // if we are only interested in a vector in the same *direction* as a given tangent line. Since
1582     // the denominator scales dx and dy uniformly, we can throw it out completely after evaluating
1583     // the derivative with the standard quotient rule. This leaves us with a simpler quadratic
1584     // function that we use to find a tangent.
1585     SkVector A = (fPts[2] - fPts[0]) * (fW - 1);
1586     SkVector B = (fPts[2] - fPts[0]) - (fPts[1] - fPts[0]) * (fW*2);
1587     SkVector C = (fPts[1] - fPts[0]) * fW;
1588 
1589     // Now solve for "bisector dot midtangent = 0":
1590     //
1591     //                            |T^2|
1592     //     bisector * |A  B  C| * |T  | = 0
1593     //                |.  .  .|   |1  |
1594     //
1595     float a = bisector.dot(A);
1596     float b = bisector.dot(B);
1597     float c = bisector.dot(C);
1598     return solve_quadratic_equation_for_midtangent(a, b, c);
1599 }
1600 
findXExtrema(SkScalar * t) const1601 bool SkConic::findXExtrema(SkScalar* t) const {
1602     return conic_find_extrema(&fPts[0].fX, fW, t);
1603 }
1604 
findYExtrema(SkScalar * t) const1605 bool SkConic::findYExtrema(SkScalar* t) const {
1606     return conic_find_extrema(&fPts[0].fY, fW, t);
1607 }
1608 
chopAtXExtrema(SkConic dst[2]) const1609 bool SkConic::chopAtXExtrema(SkConic dst[2]) const {
1610     SkScalar t;
1611     if (this->findXExtrema(&t)) {
1612         if (!this->chopAt(t, dst)) {
1613             // if chop can't return finite values, don't chop
1614             return false;
1615         }
1616         // now clean-up the middle, since we know t was meant to be at
1617         // an X-extrema
1618         SkScalar value = dst[0].fPts[2].fX;
1619         dst[0].fPts[1].fX = value;
1620         dst[1].fPts[0].fX = value;
1621         dst[1].fPts[1].fX = value;
1622         return true;
1623     }
1624     return false;
1625 }
1626 
chopAtYExtrema(SkConic dst[2]) const1627 bool SkConic::chopAtYExtrema(SkConic dst[2]) const {
1628     SkScalar t;
1629     if (this->findYExtrema(&t)) {
1630         if (!this->chopAt(t, dst)) {
1631             // if chop can't return finite values, don't chop
1632             return false;
1633         }
1634         // now clean-up the middle, since we know t was meant to be at
1635         // an Y-extrema
1636         SkScalar value = dst[0].fPts[2].fY;
1637         dst[0].fPts[1].fY = value;
1638         dst[1].fPts[0].fY = value;
1639         dst[1].fPts[1].fY = value;
1640         return true;
1641     }
1642     return false;
1643 }
1644 
computeTightBounds(SkRect * bounds) const1645 void SkConic::computeTightBounds(SkRect* bounds) const {
1646     SkPoint pts[4];
1647     pts[0] = fPts[0];
1648     pts[1] = fPts[2];
1649     int count = 2;
1650 
1651     SkScalar t;
1652     if (this->findXExtrema(&t)) {
1653         this->evalAt(t, &pts[count++]);
1654     }
1655     if (this->findYExtrema(&t)) {
1656         this->evalAt(t, &pts[count++]);
1657     }
1658     bounds->setBounds(pts, count);
1659 }
1660 
computeFastBounds(SkRect * bounds) const1661 void SkConic::computeFastBounds(SkRect* bounds) const {
1662     bounds->setBounds(fPts, 3);
1663 }
1664 
1665 #if 0  // unimplemented
1666 bool SkConic::findMaxCurvature(SkScalar* t) const {
1667     // TODO: Implement me
1668     return false;
1669 }
1670 #endif
1671 
TransformW(const SkPoint pts[3],SkScalar w,const SkMatrix & matrix)1672 SkScalar SkConic::TransformW(const SkPoint pts[3], SkScalar w, const SkMatrix& matrix) {
1673     if (!matrix.hasPerspective()) {
1674         return w;
1675     }
1676 
1677     SkPoint3 src[3], dst[3];
1678 
1679     ratquad_mapTo3D(pts, w, src);
1680 
1681     matrix.mapHomogeneousPoints(dst, src, 3);
1682 
1683     // w' = sqrt(w1*w1/w0*w2)
1684     // use doubles temporarily, to handle small numer/denom
1685     double w0 = dst[0].fZ;
1686     double w1 = dst[1].fZ;
1687     double w2 = dst[2].fZ;
1688     return sk_double_to_float(sqrt(sk_ieee_double_divide(w1 * w1, w0 * w2)));
1689 }
1690 
BuildUnitArc(const SkVector & uStart,const SkVector & uStop,SkRotationDirection dir,const SkMatrix * userMatrix,SkConic dst[kMaxConicsForArc])1691 int SkConic::BuildUnitArc(const SkVector& uStart, const SkVector& uStop, SkRotationDirection dir,
1692                           const SkMatrix* userMatrix, SkConic dst[kMaxConicsForArc]) {
1693     // rotate by x,y so that uStart is (1.0)
1694     SkScalar x = SkPoint::DotProduct(uStart, uStop);
1695     SkScalar y = SkPoint::CrossProduct(uStart, uStop);
1696 
1697     SkScalar absY = SkScalarAbs(y);
1698 
1699     // check for (effectively) coincident vectors
1700     // this can happen if our angle is nearly 0 or nearly 180 (y == 0)
1701     // ... we use the dot-prod to distinguish between 0 and 180 (x > 0)
1702     if (absY <= SK_ScalarNearlyZero && x > 0 && ((y >= 0 && kCW_SkRotationDirection == dir) ||
1703                                                  (y <= 0 && kCCW_SkRotationDirection == dir))) {
1704         return 0;
1705     }
1706 
1707     if (dir == kCCW_SkRotationDirection) {
1708         y = -y;
1709     }
1710 
1711     // We decide to use 1-conic per quadrant of a circle. What quadrant does [xy] lie in?
1712     //      0 == [0  .. 90)
1713     //      1 == [90 ..180)
1714     //      2 == [180..270)
1715     //      3 == [270..360)
1716     //
1717     int quadrant = 0;
1718     if (0 == y) {
1719         quadrant = 2;        // 180
1720         SkASSERT(SkScalarAbs(x + SK_Scalar1) <= SK_ScalarNearlyZero);
1721     } else if (0 == x) {
1722         SkASSERT(absY - SK_Scalar1 <= SK_ScalarNearlyZero);
1723         quadrant = y > 0 ? 1 : 3; // 90 : 270
1724     } else {
1725         if (y < 0) {
1726             quadrant += 2;
1727         }
1728         if ((x < 0) != (y < 0)) {
1729             quadrant += 1;
1730         }
1731     }
1732 
1733     const SkPoint quadrantPts[] = {
1734         { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }
1735     };
1736     const SkScalar quadrantWeight = SK_ScalarRoot2Over2;
1737 
1738     int conicCount = quadrant;
1739     for (int i = 0; i < conicCount; ++i) {
1740         dst[i].set(&quadrantPts[i * 2], quadrantWeight);
1741     }
1742 
1743     // Now compute any remaing (sub-90-degree) arc for the last conic
1744     const SkPoint finalP = { x, y };
1745     const SkPoint& lastQ = quadrantPts[quadrant * 2];  // will already be a unit-vector
1746     const SkScalar dot = SkVector::DotProduct(lastQ, finalP);
1747     SkASSERT(0 <= dot && dot <= SK_Scalar1 + SK_ScalarNearlyZero);
1748 
1749     if (dot < 1) {
1750         SkVector offCurve = { lastQ.x() + x, lastQ.y() + y };
1751         // compute the bisector vector, and then rescale to be the off-curve point.
1752         // we compute its length from cos(theta/2) = length / 1, using half-angle identity we get
1753         // length = sqrt(2 / (1 + cos(theta)). We already have cos() when to computed the dot.
1754         // This is nice, since our computed weight is cos(theta/2) as well!
1755         //
1756         const SkScalar cosThetaOver2 = SkScalarSqrt((1 + dot) / 2);
1757         offCurve.setLength(SkScalarInvert(cosThetaOver2));
1758         if (!SkPointPriv::EqualsWithinTolerance(lastQ, offCurve)) {
1759             dst[conicCount].set(lastQ, offCurve, finalP, cosThetaOver2);
1760             conicCount += 1;
1761         }
1762     }
1763 
1764     // now handle counter-clockwise and the initial unitStart rotation
1765     SkMatrix    matrix;
1766     matrix.setSinCos(uStart.fY, uStart.fX);
1767     if (dir == kCCW_SkRotationDirection) {
1768         matrix.preScale(SK_Scalar1, -SK_Scalar1);
1769     }
1770     if (userMatrix) {
1771         matrix.postConcat(*userMatrix);
1772     }
1773     for (int i = 0; i < conicCount; ++i) {
1774         matrix.mapPoints(dst[i].fPts, 3);
1775     }
1776     return conicCount;
1777 }
1778