Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GLSL to render a smooth reference grid on a plane

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.

GLSL fragment shader result

like image 261
josef.van.niekerk Avatar asked Jul 08 '15 19:07

josef.van.niekerk


1 Answers

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.

like image 197
volzotan Avatar answered Nov 11 '22 19:11

volzotan