02 Drawing shapes with math
SDF: distances with a sign
Give distances a sign and you can unite, intersect and subtract shapes.
ExerciseTune values
Make a crescent moon
Runs once per pixelDrag numbers, or edit the code
void main() {
vec2 p = (gl_FragCoord.xy - 0.5 * uResolution) / min(uResolution.x, uResolution.y);
float a = length(p - vec2(-0.300 / 2.0, 0.0)) - 0.220;
float b = length(p - vec2( 0.300 / 2.0, 0.0)) - 0.220;
float d = min(a, b);
float inside = 1.0 - step(0.0, d);
float contour = 0.5 + 0.5 * cos(d * 100.0);
vec3 color = mix(vec3(0.06, 0.10, 0.14), vec3(0.48, 0.83, 0.69), inside) * (0.6 + 0.4 * contour);
color += vec3(1.0 - smoothstep(0.0, 0.006, abs(d)));
gl_FragColor = vec4(color, 1.0);
}JS sidegl.uniform2f(uResolution, …, …)
Signed distance: below 0 is inside, 0 is on the edge. min unites, max intersects, max(a, −b) subtracts.
Try it
- Switch through the three combinations
- Open the pixel debugger and check that d is negative inside the circle