c++mathinterpolationspline

How do I implement a Bézier curve in C++?


I'd like to implement a Bézier curve. How should I go about creating a quadratic curve?

void printQuadCurve(float delta, Vector2f p0, Vector2f p1, Vector2f p2);

Clearly we'd need to use linear interpolation, but does this exist in the standard math library? If not, where can I find it?

I'm using Linux.


Solution

  • Recently I ran across the same question and wanted to implemented it on my own. This image from Wikipedia helped me:

    http://upload.wikimedia.org/wikipedia/commons/3/35/Bezier_quadratic_anim.gif

    The following code shows how to compute a quadratic bezier.

    int interpolate( int from , int to , float percent )
    {
        int difference = to - from;
        return from + ( difference * percent );
    }    
    
    for( float i = 0 ; i < 1 ; i += 0.01 )
    {
        // The Green Line
        xa = interpolate( x1 , x2 , i );
        ya = interpolate( y1 , y2 , i );
        xb = interpolate( x2 , x3 , i );
        yb = interpolate( y2 , y3 , i );
    
        // The Black Dot
        x = interpolate( xa , xb , i );
        y = interpolate( ya , yb , i );
        
        drawPixel( x , y , COLOR_RED );
    }
    

    With (x1|y1), (x2|y2) and (x3|y3) being P0, P1 and P2 in the image. Just for showing the basic idea...

    For the ones who ask for the cubic bezier, it just works analogue (also from Wikipedia):

    http://upload.wikimedia.org/wikipedia/commons/a/a3/Bezier_cubic_anim.gif

    This answer provides Code for it.