Creating 2D geometry from a line strip

During development of an old prototype that never saw the light, I found the need to create some 2D geometry from a set of points that form a line.

After searching for any algorithm that could make what I needed, with no success, I decided to develop my own.

The algorithm is very simple, it just takes a rope and a width and creates a set of vertices tha form a TriangleStrip to be rendered on screen.
[sourcecode language=’csharp’]
///

/// Triangulates a line, returning a list of vertices that form a triangle strip
///

/// List of points that form the line /// Desired with of the geometry /// list of vertices that form a triangle strip
public static List Process(ReadOnlyCollection contour,float width)
{
List result = new List();
Vector2 normal = Vector2.Zero ;
// Generate vertices for each point in the line
for (int i = 0; i < contour.Count; i++) { // First and last are special cases, the normal is calculated right away if (i == contour.Count - 1) normal = GameMath.Normal(contour[i] - contour[i - 1]); else if (i == 0) normal = GameMath.Normal(contour[1] - contour[0]); else { // For the rest of points, determine the normal as the middle angle between the direction of the previous and next segments. Vector2 delta1 = contour[i] - contour[i - 1]; Vector2 delta2 = contour[i + 1] - contour[i]; if ((delta1.Length()!=0)&&(delta2.Length()!=0)) { delta1.Normalize(); delta2.Normalize(); normal = GameMath.Normal(delta1 + delta2); } } // Add two vertices to the vertex list result.Add(contour[i] - normal * width / 2f); result.Add(contour[i] + normal * width / 2f); } return result; } ///

/// Returns one normal of the 2D vector
///

/// ///
public static Vector2 Normal(Vector2 line)
{
float x = line.X; float y = line.Y;
Vector2 normal = new Vector2();
if (x != 0)
{
normal.X = -y / x;
normal.Y = 1 / (float)Math.Sqrt(normal.X * normal.X + 1);
normal.Normalize();
}
else if (y != 0)
{
normal.Y = 0;
normal.X = (line.Y<0) ? 1 : -1; } else { normal.X = 1; normal.Y = 0; } if (x < 0) { normal *= -1; } return normal; } [/sourcecode] That code is well enough to generate a credible line in almost all situations. As for UVs, what I did was assign the even vertices the value (X,0) and odd vertices (X,1), where X is the distance elapsed since the line start.

Tags: , ,