Article index:
Today some GLSL code to draw a circle, a disc and a fake sphere. And to make circles and discs more appealing, the background pixels take their RGB values from this geeky Captain America woman.
The demos have been coded with GLSL Hacker and you can find all source codes in the Code Sample Pack under the GLSL_Disc_Circle_FakeSphere/ folder.
All the demos follow the same principle: a GLSL program is executed during the rendering of a simple textured quad.
As usual, the GLSL programs are not specific to GLSL Hacker. You can use them in any OpenGL/WebGL application with minor changes only.
1 – Simple Circle in GLSL
Here is the complete OpenGL 2.1 (GLSL 1.20) GLSL program that draws a circle defined by a radius,
a center and a border size:
Vertex shader:
#version 120 void main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; gl_TexCoord[0] = gl_MultiTexCoord0; }
Fragment shader:
#version 120 uniform sampler2D tex0; uniform float border; // 0.01 uniform float circle_radius; // 0.5 uniform vec4 circle_color; // vec4(1.0, 1.0, 1.0, 1.0) uniform vec2 circle_center; // vec2(0.5, 0.5) void main (void) { vec2 uv = gl_TexCoord[0].xy; vec4 bkg_color = texture2D(tex0,uv * vec2(1.0, -1.0)); // Offset uv with the center of the circle. uv -= circle_center; float dist = sqrt(dot(uv, uv)); if ( (dist > (circle_radius+border)) || (dist < (circle_radius-border)) ) gl_FragColor = bkg_color; else gl_FragColor = circle_color; }
Article index:
You can anti-alias the fake sphere’s edges by modifying the alpha channel with a smoothstep function. The one used in the Disc demo should do the trick, just adjust the values so it won’t be so thick.
Thanks Nathan. I quickly ported the fake sphere demo without thinking to the antialiasing and as you said, the smoothstep function can help to antialiase.