生成三次B样条曲线代码
时间: 2023-06-03 12:06:27 浏览: 196
下面是 C++ 代码实现:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 计算 B-Spline 基函数
double BasisFunc(int i, int k, double t, vector<double>& KnotVec)
{
double ti = KnotVec[i];
double ti1 = KnotVec[i+1];
if (k == 0)
{
if (t >= ti && t <= ti1) return 1;
else return 0;
}
double Nik1 = BasisFunc(i, k-1, t, KnotVec);
double Ni1k1 = BasisFunc(i+1, k-1, t, KnotVec);
double coef1 = (t-ti)/(ti+k-i-1);
double coef2 = (ti+k-i)/double(ti+k-i);
double coef3 = (ti1-t)/(i+k-ti1);
double coef4 = (i+k+1-t)/double(i+k+1-ti1);
double result = coef1*Nik1 + coef2*Ni1k1 + coef3*Nik1 + coef4*Ni1k1;
return result;
}
// 生成 B-Spline 曲线
vector<pair<double, double>> BSpline(int k, vector<double>& ControlPoints, vector<double>& KnotVec)
{
vector<pair<double, double>> Result;
int n = ControlPoints.size()-1;
int m = KnotVec.size()-1;
for (double t=KnotVec[k-1]; t<=KnotVec[n+1]; t+=0.001) // 以 0.001 为步长
{
double x = 0;
double y = 0;
for (int i=0; i<=n; i++)
{
double Bi = BasisFunc(i, k, t, KnotVec);
x += Bi * ControlPoints[i*2];
y += Bi * ControlPoints[i*2+1];
}
Result.push_back(make_pair(x, y));
}
return Result;
}
int main()
{
int k = 3; // 三次 B-Spline 曲线
vector<double> ControlPoints = {1,1, 2,3, 4,-3, 7,4, 10,0}; // 控制点坐标 (x,y)
vector<double> KnotVec = {0, 0, 0, 1, 2, 3, 3, 3}; // 结点矢量
auto Curve = BSpline(k, ControlPoints, KnotVec);
for (auto& p : Curve)
{
cout << "(" << p.first << "," << p.second << ")" << " ";
}
cout << endl;
return 0;
}
```
程序输出的是在给定结点矢量 `KnotVec` 下生成的 B-Spline 曲线的点序列。
阅读全文