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

前端 未结 5 1328
有刺的猬
有刺的猬 2020-11-30 18:53

I\'d like to implement a Bézier curve. I\'ve done this in C# before, but I\'m totally unfamiliar with the C++ libraries. How should I go about creating a quadratic curve?

5条回答
  •  自闭症患者
    2020-11-30 19:08

    Here is a general implementation for a curve with any number of points.

    vec2 getBezierPoint( vec2* points, int numPoints, float t ) {
        vec2* tmp = new vec2[numPoints];
        memcpy(tmp, points, numPoints * sizeof(vec2));
        int i = numPoints - 1;
        while (i > 0) {
            for (int k = 0; k < i; k++)
                tmp[k] = tmp[k] + t * ( tmp[k+1] - tmp[k] );
            i--;
        }
        vec2 answer = tmp[0];
        delete[] tmp;
        return answer;
    }
    

    Note that it uses heap memory for a temporary array which is not all that efficient. If you only need to deal with a fixed number of points you could hard-code the numPoints value and use stack memory instead.

    Of course, the above assumes you have a vec2 structure and operators for it like this:

    struct vec2 {
        float x, y;
        vec2(float x, float y) : x(x), y(y) {}
    };
    
    vec2 operator + (vec2 a, vec2 b) {
        return vec2(a.x + b.x, a.y + b.y);
    }
    
    vec2 operator - (vec2 a, vec2 b) {
        return vec2(a.x - b.x, a.y - b.y);
    }
    
    vec2 operator * (float s, vec2 a) {
        return vec2(s * a.x, s * a.y);
    }
    

提交回复
热议问题