## Bezier Curve in Directx10 HLSL Geometry Shader

There are some posts on how to do it (for instance: here Hovewer there is a different approach presented than mine. On this post you convert from polynomial basis to Bernstein basis and then you draw a curve. There are two power computations, which can in extreme situations lead to computational errors due floating point arithmetics. In my code computations are only performed in Bernstein basis. I use de Casteljau algorithm to evaluate interpolated Bernstein point between two succeding Bezier knots. These guarantees that are no errors as a result of following computations Bernstein coefficients at the given interpolated parameter t. The only error is bound to representation of float and does not change through algorithm.

Geometry shader in Directx 10 HLSL that computes geometry for drawing Bezier Curve with maximum degree = 3

[maxvertexcount(100)]

void BezierGS(lineadj VS_OUTPUT input[4],inout LineStream LineOutputStream)

{

float n = 90;

for(float t = 0.0; t<1.0; t = t+ 1.0/n)

{

VS_OUTPUT value = (VS_OUTPUT)0;float4 b = DeCasteljauBezierLine(BernsteinCurveDegree,t);

value.Color = float4(1.0,1.0,1.0,1.0);value.Pos = input[0].Pos*b.x + input[1].Pos * b.y + input[2].Pos*b.z +input[3].Pos*b.w ;

LineOutputStream.Append(value);

}

LineOutputStream.RestartStrip();

if(!BernsteinCurvePolygonVisible)

return;

for(int i=0;i<4;i++)

{

input[i].Color = float4(1.0,0.5,0.5,1.0);

LineOutputStream.Append(input[i]);

}LineOutputStream.RestartStrip();

}

```
```De Casteljau algorthm

float4 DeCasteljauBezierLine(int n,float t)

{

matrix BernsteinCurveBasis={{1.0,0.0,0.0,0.0},

{0.0,0.0,0.0,0.0},

{0.0,0.0,0.0,0.0},

{0.0,0.0,0.0,0.0}};

float u = 1-t;

for(int j=1;j<=n;j++)

{

for(int i=0;i<=j;i++)

{

if(i==0)

{

BernsteinCurveBasis[j][i] = BernsteinCurveBasis[j-1][i]*u;

}

else

{

BernsteinCurveBasis[j][i] = BernsteinCurveBasis[j-1][i]*u + BernsteinCurveBasis[j-1][i-1]*t;

}

}

}

return float4(BernsteinCurveBasis[n][0],BernsteinCurveBasis[n][1],BernsteinCurveBasis[n][2],BernsteinCurveBasis[n][3]);

}

## Leave a Reply