0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036
0037
0038
0039
0040
0041
0042
0043
0044
0045
0046
0047
0048
0049
0050
0051
0052
0053
0054
0055
0056
0057
0058
0059
0060
0061
0062
0063
0064
0065
0066
0067
0068
0069
0070
0071
0072
0073
0074
0075
0076
0077
0078
0079
0080
0081
0082
0083
0084
0085
0086
0087
0088
0089
0090
/* 
 *  Given Bezier curve:
 *
 *    |               |
 *    A          C    |
 *    |*.      .''**-.D
 *    |  *----*       |
 *    0---------B-----1
 *
 * With the constraints:
 *    Ax = 0
 *    Dx = 1
 *    0 <= Bx <= 1
 *    0 <= Cx <= 1
 *
 * It has the parametric formula for point P along the curve, at time 0<=t<=1:
 *    P(t) = t^3 (1+3B-3C) + t^2(-6B+3C) + t(3B)
 *
 * We would like to have an explicit function: Py(x)
 *
 * This requires rearranging, solving the cubic, then passing it to the 
 * parametric function. 
 *
 *    F(t,x) = t^3(1+3Bx-3Cx) + t^2(-6Bx+3Cx) + t(3Bx) - x
 *    solve F(t,x) = 0 for t.
 *
 * A full cubic rootfind will waste time deciding on if there is 1 or 3 real 
 * roots, involving trig or complex numbers etc.
 *
 * We're only looking for the one (guaranteed) root within the unit interval.
 * I've chosen to use the Illinois method which is a bracketed option, and 
 * makes sure we get a real value without risk of diverging.
 *
 *    t = Illinois( F, 0, 1 )
 *
 * Since our bracket starts as the unit interval, the first iteration is very
 * quick to compute the cubics at each end, since t0 is 0, and t1 is 1. Few
 * iterations are needed, no more than 10 for our purposes of animation curves,
 * for sane curves, it will early exit around 3-4.
 *
 */

f32 explicit_bezier( f32 A[2], f32 B[2], f32 C[2], f32 D[2], f32 x )
{
   f32 dAxDx = D[0]-A[0],
       unitBx = (B[0] - A[0]) / dAxDx,
       unitCx = (C[0] - A[0]) / dAxDx,

       /* cubic coefficients */
       a =  3.0f*unitBx - 3.0f*unitCx + 1.0f,
       b = -6.0f*unitBx + 3.0f*unitCx,
       c =  3.0f*unitBx,
       d = -(x - A[0]) / dAxDx,

        t0 = 0.0f,
       Ft0 = d,
        t1 = 1.0f,
       Ft1 = a+b+c+d,
        tc, Ftcx;

   /* Illinois method to find root */
   for( u32 j=0; j<8; j ++ )
   {
      tc = t1 - Ft1*(t1-t0)/(Ft1-Ft0);
      Ftcx = tc*tc*tc*a + tc*tc*b + tc*c + d;

      if( fabsf(Ftcx) < 0.00001f )
         break;
      
      if( Ft1*Ftcx < 0.0f )
      {
         t0 = t1;
         Ft0 = Ft1;
      }
      else
         Ft0 *= 0.5f;

      t1 = tc;
      Ft1 = Ftcx;
   }

   /* Evaluate parametric bezier */
   f32 t2 = tc*tc,
       t3 = tc*tc*tc;
   
   return  D[1] * t3
         + C[1] * (-3.0f*t3 + 3.0f*t2)
         + B[1] * ( 3.0f*t3 - 6.0f*t2 + 3.0f*tc)
         + A[1] * (-1.0f*t3 + 3.0f*t2 - 3.0f*tc + 1.0f);
}