Claudio Ferraro
Claudio Ferraro

Reputation: 4721

Optimize the parameterization algorithm of a cubic bezier curve

Except using look-up tables, is there another way to optimize the parameterization algorithm of a cubic Bézier curve like this? (5000 steps for a good parameterization is simply too much for a slower PC, as I need to call this function many times in 1 second):

function parameterizeCurve(path, partArc, initialT)
{
   // curve length is already known and globally defined
   // brute force
   var STEPS = 5000; // > precision
   var t = 1 / STEPS;
   var aX=0;
   var aY=0;
   var bX=path[0], bY=path[1];
   var dX=0, dY=0;
   var dS = 0;
   var sumArc = 0;
   var arrT = new Array(Math.round(partArc)); 
   var z = 1;
   arrT[0] = -1;

   var oldpartArc = partArc;
   partArc = partArc - initialT;

   var j = 0;

   for (var i=0; i<STEPS; j = j + t) {
      aX = bezierPoint(j, path[0], path[2], path[4], path[6]);
      aY = bezierPoint(j, path[1], path[3], path[5], path[7]);

      dX = aX - bX;
      dY = aY - bY;
      // deltaS. Pitagora
      dS = Math.sqrt((dX * dX) + (dY * dY));
      sumArc = sumArc + dS;
      if (sumArc >= partArc) {
         arrT[z] = j; // save current t
         z++;
         sumArc = 0;
         partArc = oldpartArc;
      }
      bX = aX;
      bY = aY;
      i++;
   }

   return arrT;
}


    function bezierPoint(t, o1, c1, c2, e1) {
        var C1 = (e1 - (3.0 * c2) + (3.0 * c1) - o1);
        var C2 = ((3.0 * c2) - (6.0 * c1) + (3.0 * o1));
        var C3 = ((3.0 * c1) - (3.0 * o1));
        var C4 = (o1);

        return ((C1*t*t*t) + (C2*t*t) + (C3*t) + C4)
    }

Upvotes: 2

Views: 948

Answers (1)

Rahul Banerjee
Rahul Banerjee

Reputation: 2363

If I've guessed correctly, you're trying to come up with a cubic Bezier curve parameterization that moves at a constant speed along the curve.

So, why do you need 5000 steps? The minimum one can move along a curve is one pixel. A Bezier stays within the convex hull of its four control points, so the length of the curve will be less than that of the polyline P0 -> P1 -> P2 -> P3. So find that length in pixels, and use it (instead of 5000).

Let me know if that speeds things up enough.

Upvotes: 1

Related Questions