I'm trying to write a geometry shader to replace glLineWidth
behavior. I want to draw lines with a customizable width (doing this with a uniform suffices for now). The lines should always have the same thickness, regardless of the camera projection or distance to where the lines are.
Based on a lot of googling, I've come up with the following geometry shader:
#version 330
layout (lines) in;
layout (triangle_strip, max_vertices = 4) out;
uniform mat4 u_model_matrix;
uniform mat4 u_view_matrix;
uniform mat4 u_projection_matrix;
uniform float u_thickness = 4; // just a test default
void main()
{
float r = u_thickness / 2;
mat4 mv = u_view_matrix * u_model_matrix;
vec4 p1 = mv * gl_in[0].gl_Position;
vec4 p2 = mv * gl_in[1].gl_Position;
vec2 dir = normalize(p2.xy - p1.xy);
vec2 normal = vec2(dir.y, -dir.x);
vec4 offset1, offset2;
offset1 = vec4(normal * r, 0, 0);
offset2 = vec4(normal * r, 0, 0);
vec4 coords[4];
coords[0] = p1 + offset1;
coords[1] = p1 - offset1;
coords[2] = p2 + offset2;
coords[3] = p2 - offset2;
for (int i = 0; i < 4; ++i) {
coords[i] = u_projection_matrix * coords[i];
gl_Position = coords[i];
EmitVertex();
}
EndPrimitive();
}
For completeness, here is the vertex shader:
#version 330
in vec4 a_position;
void main() {
gl_Position = a_position;
}
... and my fragment shader:
#version 330
uniform vec4 u_color = vec4(1, 0, 1, 1);
out vec4 fragColor;
void main() {
fragColor = u_color;
}
I can't get the math to work in all situations. With an orthogonal camera, the above works fine:
But with a perspective camera, the problem is that the line is not a fixed size. It gets bigger and smaller relative to how far away the object is.
I expected the line the be the same size using a perspective camera as well. What am I doing wrong?