Book of Shaders: Noisy Distance
GLSL Study 3
May 16th, 2022
Shaders really start getting interesting when you start implementing randomness. The Noise section of The Book of Shaders includes some vague challenges about "using noise with distance." I assumed that this meant using some overlapping to create the illusion of a rough edges.
Here's a simple demonstration of a reusable function. You multiply the larger circle and make the solid circle slight smaller than the radius input.
float rough_circle(in vec2 _st, float radius){
float noiseScale= 90;
vec2 noise_st = _st * noiseScale;
float _noise = noise(noise_st);
float circle1 = circle(_st, radius);
float circle2 = circle(_st, radius - (0.01));
float color = (circle1 * _noise) + circle2;
return color;
}
This Noise Chapter also challenged you to animate this shape. I usually make a normalized time value between 0 and 1 with this:
float sin_time = sin(u_time) * 0.5 + 0.5;
Then I have a continuous linear *u_time* and a oscillating *sin_time.* Here's the final result:
uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;
// 2D Random
float random (in vec2 st) {
return fract(sin(dot(st.xy,
vec2(12.9898,78.233)))
* 43758.5453123);
}
float circle(in vec2 _st, float radius){
return 1.0 -
smoothstep(radius-0.2, radius, length(_st));
}
float time_value = sin(u_time) * 0.5 + 0.5;
// 2D Noise based on Morgan McGuire @morgan3d
// https://www.shadertoy.com/view/4dS3Wd
float noise (in vec2 st) {
vec2 i = floor(st);
vec2 f = fract(st);
// Four corners in 2D of a tile
float a = random(i);
float b = random(i + vec2(1.0, 0.0));
float c = random(i + vec2(0.0, 1.0));
float d = random(i + vec2(1.0, 1.0));
// Smooth Interpolation
// Cubic Hermine Curve. Same as SmoothStep()
vec2 u = f*f*(3.0-2.0*f);
// u = smoothstep(0.,1.,f);
// Mix 4 coorners percentages
return mix(a, b, u.x) +
(c - a)* u.y * (1.0 - u.x) +
(d - b) * u.x * u.y;
}
float rough_circle(in vec2 _st, float radius){
float noiseScale= 90.*(time_value + 0.5);
float time_scale = 0.0001;
vec2 moving_st = vec2(_st.x, _st.y + (u_time*time_scale*0.3)+1.0);
vec2 noise_st = moving_st * noiseScale;
float _noise = noise(noise_st);
float circle1 = circle(_st, radius);
float circle2 = circle(_st, radius - (0.1*time_value));
float color = (circle1 * _noise) + circle2;
return color;
}
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
st -= 0.5;
float color = 1.0-step(rough_circle(st, 0.5), time_value);
gl_FragColor = vec4(vec3(color), 1.0);
}