caryclark@google.com | 639df89 | 2012-01-10 21:46:10 +0000 | [diff] [blame^] | 1 | #include "CubicIntersection.h" |
| 2 | |
| 3 | //http://planetmath.org/encyclopedia/CubicEquation.html |
| 4 | /* the roots of x^3 + ax^2 + bx + c are |
| 5 | j = -2a^3 + 9ab - 27c |
| 6 | k = sqrt((2a^3 - 9ab + 27c)^2 + 4(-a^2 + 3b)^3) |
| 7 | t1 = -a/3 + cuberoot((j + k) / 54) + cuberoot((j - k) / 54) |
| 8 | t2 = -a/3 - ( 1 + i*cuberoot(3))/2 * cuberoot((j + k) / 54) |
| 9 | + (-1 + i*cuberoot(3))/2 * cuberoot((j - k) / 54) |
| 10 | t3 = -a/3 + (-1 + i*cuberoot(3))/2 * cuberoot((j + k) / 54) |
| 11 | - ( 1 + i*cuberoot(3))/2 * cuberoot((j - k) / 54) |
| 12 | */ |
| 13 | |
| 14 | |
| 15 | static bool is_unit_interval(double x) { |
| 16 | return x > 0 && x < 1; |
| 17 | } |
| 18 | |
| 19 | const double PI = 4 * atan(1); |
| 20 | |
| 21 | // from SkGeometry.cpp |
| 22 | int cubic_roots(const double coeff[4], double tValues[3]) { |
| 23 | if (approximately_zero(coeff[0])) // we're just a quadratic |
| 24 | { |
| 25 | return quadratic_roots(&coeff[1], tValues); |
| 26 | } |
| 27 | double inva = 1 / coeff[0]; |
| 28 | double a = coeff[1] * inva; |
| 29 | double b = coeff[2] * inva; |
| 30 | double c = coeff[3] * inva; |
| 31 | double a2 = a * a; |
| 32 | double Q = (a2 - b * 3) / 9; |
| 33 | double R = (2 * a2 * a - 9 * a * b + 27 * c) / 54; |
| 34 | double Q3 = Q * Q * Q; |
| 35 | double R2MinusQ3 = R * R - Q3; |
| 36 | double adiv3 = a / 3; |
| 37 | double* roots = tValues; |
| 38 | double r; |
| 39 | |
| 40 | if (R2MinusQ3 < 0) // we have 3 real roots |
| 41 | { |
| 42 | double theta = acos(R / sqrt(Q3)); |
| 43 | double neg2RootQ = -2 * sqrt(Q); |
| 44 | |
| 45 | r = neg2RootQ * cos(theta / 3) - adiv3; |
| 46 | if (is_unit_interval(r)) |
| 47 | *roots++ = r; |
| 48 | |
| 49 | r = neg2RootQ * cos((theta + 2 * PI) / 3) - adiv3; |
| 50 | if (is_unit_interval(r)) |
| 51 | *roots++ = r; |
| 52 | |
| 53 | r = neg2RootQ * cos((theta - 2 * PI) / 3) - adiv3; |
| 54 | if (is_unit_interval(r)) |
| 55 | *roots++ = r; |
| 56 | } |
| 57 | else // we have 1 real root |
| 58 | { |
| 59 | double A = fabs(R) + sqrt(R2MinusQ3); |
| 60 | A = cube_root(A); |
| 61 | if (R > 0) { |
| 62 | A = -A; |
| 63 | } |
| 64 | if (A != 0) { |
| 65 | A += Q / A; |
| 66 | } |
| 67 | r = A - adiv3; |
| 68 | if (is_unit_interval(r)) |
| 69 | *roots++ = r; |
| 70 | } |
| 71 | return (int)(roots - tValues); |
| 72 | } |