Fragment Shader Shapes
You'll draw circles and boxes with nothing but a full-screen pixel program, a distance function and smoothstep, then run the same shader in a window you opened yourself.
About
A fragment shader runs once for every pixel, all at the same time, which is a different way of thinking from loops. You can't draw a line from here to there, so you ask each pixel how far it is from the shape and color it by the answer. Shadertoy runs in a browser for free and is the fastest place to try this, but the badge ends with the same code running on two triangles in your own window, fed by uniforms you set. The edge trick that makes everything look good is smoothstep over about one pixel's width, and the beginner tell is a hard, stepped edge.
At a glance
- Per requirement
- 15 XP
- Completion bonus
- 75 XP
- Requirements
- 5
- Takes
- One evening
- Skill level
- Beginner (done it a few times)
- Cost
- Free
- Supplies
- Nothing special
- Where
- At home
- Other people
- On your own
Requirements
-
1
Draw a circle with a signed distance function and an antialiased edge. The length of the pixel position minus the center, minus the radius, gives you a number that's negative inside and positive outside. Use smoothstep across a width of one pixel, which you get from fwidth or from one over the resolution, to blend the edge. Take a screenshot zoomed in on the edge. Photo
-
2
Combine a box and a circle with union, subtraction and intersection. Union is the minimum of two distances, subtraction is the maximum of one and the negative of the other, and intersection is the maximum of both. Draw all three side by side. Take a screenshot showing the three results. Photo
-
3
Fix the aspect ratio and animate with a time uniform. Divide the pixel coordinate by the height rather than the width so a circle stays round in a wide window. Then move or pulse the shape using time. Film a few seconds of it. Video
-
4
Repeat a shape across the screen with one line of math. Use fract or mod on the coordinate to tile space, so one circle becomes a grid of them with no loop at all. Take a screenshot of the grid. Photo
-
5
Rebuild the sketch in your own window outside the browser. Draw two triangles that cover the screen, pass resolution and time as uniforms, and run your shader there. Take a screenshot of it running in a native window or on your own web page, not on Shadertoy. Photo