【OpenGL】自己实现B-Spline曲线
1.绘制目标
自己实现B-Spline曲线。
2.核心代码
/TO DO///
///基于CdM公式计算B-Spline混合函数///
float bspline(float* knots, int i, int order, float u) {
// 特殊情形:一阶B-splines
if (order == 1) {
if (i == 0)
{
if (u >= knots[i] && u <= knots[i + 1])
{
return 1.0;
}
else
{
return 0.0;
}
}
else if (i >= 1)
{
if (u > knots[i] && u <= knots[i + 1])
{
return 1.0;
}
else
{
return 0.0;
}
}
}
// 一般情形
else {
// 用于存储CdM公式右边和式的第一项和第二项的值
float b1(0.f), b2(0.f);
// 计算CdM公式右边和式的第一项
if (knots[i + order - 1] - knots[i] == 0)
{
if (u - knots[i] == 0)
{
b1 = bspline(knots, i, order - 1, u);
}
else
{
b1 = 0;
}
}
else
{
float x = u - knots[i];
float y = knots[i + order - 1] - knots[i];
b1 = x / y * bspline(knots, i, order - 1, u);
}
// 计算CdM公式右边和式的第二项
if (knots[i + order] - knots[i + 1] == 0)
{
if (knots[i + order] - u == 0)
{
b2 = bspline(knots, i + 1, order - 1, u);
}
else
{
b2 = 0;
}
}
else
{
float x = knots[i + order] - u;
float y = knots[i + order] - knots[i + 1];
b2 = x / y * bspline(knots, i + 1, order - 1, u);
}
return b1 + b2;
}
}
/TO DO///
绘制B-Spline曲线//
void drawBSplineCurve(float* knots, float* controlPoints, int numControlPoints, int order, int numSamples)
{
float a = knots[order - 1];
float num = (knots[numControlPoints] - knots[order - 1]) / numSamples;
glColor3f(0.0f, 0.0f, 1.0f);
glBegin(GL_LINE_STRIP);
for (float j = a; j <= knots[numControlPoints]; j += num)
{
float x = 0, y = 0, z = 0;
for (int i = 0; i < numControlPoints; i++)
{
x = x + controlPoints[i * POINT_DIMS] * bspline(knots, i, order, j);
y = y + controlPoints[i * POINT_DIMS + 1] * bspline(knots, i, order, j);
z = z + controlPoints[i * POINT_DIMS + 2] * bspline(knots, i, order, j);
}
glVertex3f(x, y, z);
}
glEnd();
}
///
/// TO DO ///
///创建OpenGL GLU NURBS 对象并设置采样方法和采样阈值/
NURBS_OBJ = gluNewNurbsRenderer();
gluNurbsProperty(NURBS_OBJ, GLU_SAMPLING_METHOD, GLU_PATH_LENGTH);
gluNurbsProperty(NURBS_OBJ, GLU_SAMPLING_TOLERANCE, 10.0);
/
/// 使用自己实现的函数绘制B-Spline曲线//
drawBSplineCurve(KNOT_ARRAY, CONTROL_POINTS_ARRAY, NUM_POINTS, BSPLINE_ORDER, 200);
3.运行结果