PDA

View Full Version : Draw circle in shader



rulfen
05-02-2011, 06:56 AM
Hi, I would like to draw a circle in a GLSL shader when the render window is not square. In my solution the circle turns into an ellipse when the window size is not square (ex. 640x480 instead of 512x512)



vec2 p = gl_FragCoord.xy / screenDim_.xy;
vec2 circleCenter = vec2(0.5,0.5);
float dist = length(p - circleCenter _);
float circle = smoothstep(circleRadius_,circleRadius_ - 0.05,dist);

I have tried setting



vec2 p = gl_FragCoord.xy / screenDim_.x;
but then the circle is not positioned correctly

Thanks!

StefanG
05-03-2011, 11:48 AM
You could scale your vector from the midpoint to the fragment differently in x and y to adjust for the aspect ratio, but a cleaner way would be to do the computations in unscaled fragment coordinates, without doing any scaling:

vec2 midpoint = screenDim_.xy * 0.5;
float radius = min(screenDim_.x, screenDim_.y) * circleRadius_;
float dist = length(gl_FragCoord.xy - midpoint);
circle = smoothstep(radius-1.0, radius+1.0, dist);

Several advantages here. The max() function handles a tall and narrow window as well as a low and wide one. The smoothstep gets a step width in fragment coordinates, which creates an anti-aliasing that is independent on the viewport resolution.

Happy hacking!

rulfen
05-05-2011, 12:05 AM
Thanks, yea it works both to scale the vector and to compute it with unscaled coords.