I'm trying to write a GLSL fragment shader that renders a reference grid on a flat ground plane. I'm using BabylonJS to create a WebGL application.
The code can be seen in action here:
http://www.babylonjs.com/cyos/#IBHRN#2
#extension GL_OES_standard_derivatives : enable
precision highp float;
varying vec2 vUV;
void main(void) {
float divisions = 10.0;
float thickness = 0.01;
float delta = 0.05 / 2.0;
float x = fract(vUV.x / (1.0 / divisions));
float xdelta = fwidth(x) * 2.5;
x = smoothstep(x - xdelta, x + xdelta, thickness);
float y = fract(vUV.y / (1.0 / divisions));
float ydelta = fwidth(y) * 2.5;
y = smoothstep(y - ydelta, y + ydelta, thickness);
float c = clamp(x + y, 0.1, 1.0);
gl_FragColor = vec4(c, c, c, 1.0);
}
The result isn't super smooth yet, and I'm wondering how I can get rid of the ridges in the lines, and end up with perfectly, anti-aliased lines.
This fragment shader code should work as expected:
#extension GL_OES_standard_derivatives : enable
precision highp float;
varying vec2 vUV;
void main(void) {
float divisions = 10.0;
float thickness = 0.04;
float delta = 0.05 / 2.0;
float x = fract(vUV.x * divisions);
x = min(x, 1.0 - x);
float xdelta = fwidth(x);
x = smoothstep(x - xdelta, x + xdelta, thickness);
float y = fract(vUV.y * divisions);
y = min(y, 1.0 - y);
float ydelta = fwidth(y);
y = smoothstep(y - ydelta, y + ydelta, thickness);
float c =clamp(x + y, 0.0, 1.0);
gl_FragColor = vec4(c, c, c, 1.0);
}
I added the expression
x = min(x, 1.0 - x);
to make the value of x (and also y) symmetrical around the centers of the edges. Since the original code was directly using the "fract" function's output, it was jumping between large and small values around the edges centers, which created the sharp corners.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With