How to efficiently draw dashed lines

The polygonal line(not a simple straight line) vertex array is known.[x1,y1,x2,y2,x3,y3...]

I find there are probably two ways

1.Calculates the vertex data of the dashed line from the original vertex above by interpolation algorithm, then draw new vertices

2.Calculates the distance from each vertex to the first vertex, then calculates the remainder of the distance and the dotted line segment in the fragment shader


Is there a better way to reduce the amount of computation in vertex arrays?

Accepted Reply

Hello


I'd say:

3) Add "distance along continuous line" to your vertex data. Let's say your original data looks like this:

(0,0), (0,2), (0,2), (1,2), (3,7), (3,8) (that is, your have two segment line first, and then separate segment)

This is what your enhanced data will look like:

(0,0,0), (0,2,2), (0,2,2), (1,2,3), distance resets here because not continuous (3,7,0), (3,8,1) and so on. You can do it on the CPU before data upload, as it isn't good candidate for parallel computations.


Now, in your vertex shader just pass that distanceAlongTheLine to fragment shader, so that it gets properly interpolated between begin/end of the segment. Then your can trigger line on and off like that:

// assuming that there is vec4 variable containing final color
int segmentNumber = int(distanceAlongTheLine/segmentLength);
// alternate alpha between even and odd segments
color.w = (segmentNumber & 1) ? 1.0f : 0.0f;

That should do the trick. Remember that your distanceAlongTheLine gets simply carried over from vertex data, so if you want pixels there you got to convert.

Hope that helps

Michal

Replies

Hello


I'd say:

3) Add "distance along continuous line" to your vertex data. Let's say your original data looks like this:

(0,0), (0,2), (0,2), (1,2), (3,7), (3,8) (that is, your have two segment line first, and then separate segment)

This is what your enhanced data will look like:

(0,0,0), (0,2,2), (0,2,2), (1,2,3), distance resets here because not continuous (3,7,0), (3,8,1) and so on. You can do it on the CPU before data upload, as it isn't good candidate for parallel computations.


Now, in your vertex shader just pass that distanceAlongTheLine to fragment shader, so that it gets properly interpolated between begin/end of the segment. Then your can trigger line on and off like that:

// assuming that there is vec4 variable containing final color
int segmentNumber = int(distanceAlongTheLine/segmentLength);
// alternate alpha between even and odd segments
color.w = (segmentNumber & 1) ? 1.0f : 0.0f;

That should do the trick. Remember that your distanceAlongTheLine gets simply carried over from vertex data, so if you want pixels there you got to convert.

Hope that helps

Michal