Shaping functions: the vocabulary for the rest of the course
In Chapter 2 you turned position into shapes, and in Chapter 3 you did arithmetic on colors. Along the way you already met step, smoothstep, fract and mix, mostly as one-liners I asked you to trust. This chapter slows down and goes through them properly, together with sin, cos, fmod, abs, clamp and pow.
These are often called shaping functions. Each one takes a number and bends it: repeats it, folds it, cuts it at a threshold, or curves it. Nearly every effect in the rest of the course (grids in Chapter 5, noise in Chapter 6, transitions in Chapter 7, distance fields in Chapter 8, animation in Chapter 9) is a few of these chained together. If you can predict what each one does to a number, you can read and write almost any shader.
For every function you'll get three things: what it returns, a small table of inputs and outputs, and what it looks like when you feed it a coordinate.
A shader for seeing functions
The fastest way to learn a function is to look at its graph. This shader draws one. It treats uv.x as the input, computes f, and paints a green line wherever the pixel's height matches f:
[[ stitchable ]] half4 plotFunction(float2 position, half4 color, float2 size) {
float2 uv = position / size;
float x = uv.x;
float y = 1.0 - uv.y; // flip so y grows upward, like a graph on paper
float f = smoothstep(0.2, 0.8, x); // swap in any function of x here
// 1.0 on the curve, fading to 0.0 about 1% of the height away from it
float curve = 1.0 - smoothstep(0.0, 0.01, abs(y - f));
// Background shows f as brightness, the curve is drawn in green on top
float3 rgb = mix(float3(f), float3(0.0, 1.0, 0.0), curve);
return half4(half3(rgb), 1.0);
}
Apply it the same way as the earlier chapters, passing the size yourself (SwiftUI doesn't hand it to colorEffect):
content.colorEffect(ShaderLibrary.plotFunction(.float2(proxy.size)))
Two details are worth understanding because you'll reuse them:
- SwiftUI's
positionhas its origin at the top left with y growing downward.1.0 - uv.yturns that around so the bottom of the view is 0 and the top is 1, which is how graphs in a math book look. abs(y - f)is the vertical distance between this pixel and the curve. Pixels with a distance near 0 sit on the curve.1.0 - smoothstep(0.0, 0.01, distance)turns "close to the curve" into 1 and "far" into 0. Challenge 1 uses this same trick.
The graph only shows outputs between 0 and 1. For functions that go negative, like sin, remap them first with * 0.5 + 0.5.
Each section below gives you a line to paste into the float f = ... slot.
The functions one by one
sin and cos: smooth repetition
sin(x) returns a value between -1 and 1 that rises and falls forever, repeating every 2π (about 6.283) units of input.
Where the shape comes from: picture a point moving around a circle of radius 1. Its height above the center, as it goes around, is sin of the angle it has travelled (in radians).
angle x sin(x) point on the circle
0 0.0 right side, level with the center
π/2 ≈ 1.571 1.0 top
π ≈ 3.142 0.0 left side
3π/2 ≈ 4.712 -1.0 bottom
2π ≈ 6.283 0.0 back to the start, and it repeats
Because the point moves around the circle at a steady speed, its height slows down near the top and bottom and moves fastest through the middle. That's why a sine wave has rounded peaks instead of the sharp corners of a triangle wave.
cos(x) is the same wave shifted a quarter turn: it's the point's horizontal position instead of its height, so cos(0) = 1. You'll use the pair together for rotation and for moving things in circles.
1 | .. ..
| . . . .
0 |-.----.----------.----.----.--> x
| . .
-1 | .. ..
0 π/2 π 3π/2 2π
Frequency: how many waves fit across the view
In a shader the input is usually a coordinate, scaled by some number:
float wave = sin(uv.x * 10.0);
uv.x runs from 0 to 1, so the angle runs from 0 to 10. One full wave takes 6.283, so you get 10 / 6.283 ≈ 1.6 waves across the view. The multiplier is not the number of waves. If you want exactly N waves, multiply by N × 2π:
float wave = sin(uv.x * 4.0 * 6.2832); // exactly 4 waves from left to right
In general, sin(x * k) repeats every 2π / k units. That distance is the wavelength.
Mapping -1...1 to a color
A color channel wants 0 to 1, but sin gives -1 to 1. The standard fix is wave * 0.5 + 0.5: multiplying by 0.5 squeezes the range to -0.5...0.5, and adding 0.5 slides it up to 0...1. Without it, the negative half of the wave clips to black and you see only half the pattern.
This is the first example in the Xcode project (sinePattern), and it produces soft vertical stripes:
[[ stitchable ]] half4 sinePattern(float2 position, half4 color, float2 size) {
float2 uv = position / size;
// Create horizontal sine wave
float wave = sin(uv.x * 10.0);
// Convert from [-1,1] to [0,1]
float brightness = wave * 0.5 + 0.5;
return half4(brightness, brightness, brightness, 1.0);
}
The value changes as you move left to right, so the bright and dark bands run top to bottom. Plot it with f = sin(x * 10.0) * 0.5 + 0.5.
fract: a repeating ramp
fract(x) returns the fractional part of x, defined as x - floor(x). The result is always at least 0 and less than 1.
x floor(x) fract(x)
0.0 0 0.0
0.3 0 0.3
1.0 1 0.0
1.7 1 0.7
2.25 2 0.25
-0.25 -1 0.75 (not -0.25: floor rounds down, toward -∞)
-1.3 -2 0.7
Its graph is a sawtooth: it climbs from 0 to 1, drops back to 0, and climbs again.
1 | /| /| /| /
| / | / | / | /
0 | / | / | / | /
+--------------------> x
0 1 2 3 4
Multiply first and you control how many teeth fit in the view. With fract(uv.x * 5.0), the input runs 0 to 5, so you get five ramps, and each one runs 0 to 1 in its own fifth of the view. In 2D, fract(uv * 5.0) gives a 5×5 grid where every cell has its own local coordinates from 0 to 1. A pixel in any cell can't tell which cell it's in from these values, so anything you draw using them appears in every cell.
floor is the partner that tells you which cell you're in:
float2 scaled = uv * 5.0;
float2 cellUV = fract(scaled); // where am I inside my cell? (0 to 1)
float2 cellID = floor(scaled); // which cell am I in? (0, 1, 2, 3 or 4 on each axis)
Take a pixel at uv = (0.45, 0.83). Scaled by 5 that's (2.25, 4.15), so cellID = (2, 4) and cellUV = (0.25, 0.15): a quarter of the way across, near the top of the cell in column 2, row 4. Chapter 5 builds entirely on this split.
Plot it with f = fract(x * 4.0).
fmod: Metal's remainder (there is no mod)
If you're porting a shader from GLSL or Shadertoy, you'll see mod(x, y). Metal has no mod. The closest built-in is fmod(x, y), which returns the remainder after dividing x by y. For positive inputs the two agree:
fmod(5.5, 2.0) = 1.5 5.5 = 2 × 2.0 + 1.5
fmod(0.7, 0.25) = 0.2 0.7 = 2 × 0.25 + 0.2
They disagree on negative inputs. Metal's fmod is defined as x - y * trunc(x / y), and trunc rounds toward zero, so the result takes the sign of x. GLSL's mod uses floor, which always rounds down, so the result takes the sign of y:
x fmod(x, 1.0) GLSL mod(x, 1.0) fract(x)
1.3 0.3 0.3 0.3
0.4 0.4 0.4 0.4
-0.25 -0.25 0.75 0.75
-1.3 -0.3 0.7 0.7
So fmod(x, 1.0) and fract(x) are the same only while x is positive. Negative coordinates come up all the time: centered coordinates (uv - 0.5) are negative on the left half, and anything scrolling with uv.x - time goes negative as time grows. With fmod, the pattern on the negative side runs backwards and you get a visible seam at zero.
When you need the GLSL behavior, write it yourself:
float glslMod(float x, float y) {
return x - y * floor(x / y);
}
For a repeat length of 1, just use fract.
abs: folding negatives over
abs(x) returns x without its sign.
x abs(x)
-1.0 1.0
-0.3 0.3
0.0 0.0
0.6 0.6
On a graph, everything below zero gets folded up above it. Two uses come up constantly.
Distance from a line. abs(uv.x - 0.5) is how far the pixel is from the vertical center line:
uv.x uv.x - 0.5 abs(uv.x - 0.5)
0.0 -0.5 0.5
0.25 -0.25 0.25
0.5 0.0 0.0
0.75 0.25 0.25
1.0 0.5 0.5
As a brightness, that's dark down the middle and brighter toward both edges, a mirror image around the center. Chapter 8's distance fields start from exactly this idea.
Bouncing. abs(sin(x)) flips the negative half of the wave, giving a row of rounded bumps that touch zero with a sharp corner, like a ball bouncing on the floor. Plot it with f = abs(sin(x * 10.0)).
step: a hard threshold
step(edge, x) returns 0.0 if x is less than edge, and 1.0 otherwise. Notice the argument order: the threshold comes first.
step(0.5, x)
x result
0.0 0.0
0.49 0.0
0.5 1.0 (equal counts as "reached")
0.8 1.0
float mask = step(0.5, uv.x); is black on the left half and white on the right half, with a perfectly hard edge.
Because it only returns 0 or 1, you can combine steps like logic:
float right = step(0.5, uv.x); // 1 on the right half
float left = 1.0 - step(0.5, uv.x); // flipped: 1 on the left half
float band = step(0.4, uv.x) - step(0.6, uv.x); // 1 only between 0.4 and 0.6
You can also swap which argument varies. step(abs(uv.x - 0.5), 0.1) asks "is 0.1 at least as big as my distance from the center line?", which is 1 for a strip 0.2 wide down the middle. The waveVisualizer solution draws its curves this way.
The cost of a hard edge is aliasing. A pixel either passes or fails, so diagonal and curved edges come out as visible stair steps. That's what smoothstep is for.
smoothstep: a threshold with a soft edge
smoothstep(edge0, edge1, x) returns 0.0 when x is at or below edge0, 1.0 at or above edge1, and an S-shaped blend in between.
Here's what it does internally, written out as code:
float t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0); // where x sits between the edges, as 0 to 1
return t * t * (3.0 - 2.0 * t); // bend the straight ramp into an S
Tracing smoothstep(0.2, 0.8, 0.35) by hand:
x - edge0 = 0.35 - 0.2 = 0.15edge1 - edge0 = 0.8 - 0.2 = 0.6t = 0.15 / 0.6 = 0.25, already inside 0...1 soclampleaves it alone0.25 × 0.25 × (3.0 - 0.5) = 0.0625 × 2.5 = 0.15625
A plain linear ramp would give 0.25 here. The S curve starts slower than that.
smoothstep(0.2, 0.8, x)
x t result
0.1 0.0 0.0
0.2 0.0 0.0
0.35 0.25 0.156
0.5 0.5 0.5
0.65 0.75 0.844
0.8 1.0 1.0
0.9 1.0 1.0
The polynomial 3t² - 2t³ was chosen because its slope is 0 at both ends. The blend leaves the flat 0 region and arrives at the flat 1 region without a corner, so you don't see a crease where the transition starts or stops. To make up for the slow start and finish, it's steeper than a straight line in the middle (slope 1.5 instead of 1 at t = 0.5). Its curvature does still jump at the two ends; if that ever shows up as a visible band in a very smooth gradient, the "smootherstep" polynomial t * t * t * (t * (6.0 * t - 15.0) + 10.0) fixes it. You'll rarely need it.
The edge order matters in Metal. The Metal Shading Language specification says the result is undefined when edge0 is greater than or equal to edge1. Reversed edges like smoothstep(0.5, 0.4, x) often appear to work on current hardware, but nothing guarantees it. When you want the curve to go from 1 down to 0, write it the defined way:
float inside = 1.0 - smoothstep(0.4, 0.5, radius); // 1 inside radius 0.4, 0 beyond 0.5
The distance between the two edges is the width of the soft zone. For anti-aliasing a shape's edge you want it about one pixel wide. For a deliberate glow or blur you make it wider. The radial pulse example below uses 1.0 - smoothstep(0.4, 0.5, radius) to fade the pattern out over the outer tenth of the view.
Plot it with f = smoothstep(0.2, 0.8, x), then compare against f = step(0.5, x).
mix: blending between two values
mix(a, b, t) returns a + (b - a) * t. At t = 0 you get a, at t = 1 you get b, and in between you get the proportional blend.
mix(10.0, 20.0, t)
t result
0.0 10.0
0.25 12.5
0.5 15.0
1.0 20.0
It works the same way on vectors, one component at a time. Halfway between red and blue:
mix(float3(1, 0, 0), float3(0, 0, 1), 0.5) = float3(0.5, 0.0, 0.5) // purple
mix doesn't decide anything by itself; the interesting part is where t comes from. Feed it a coordinate and you get a gradient. Feed it a smoothstep and you get a soft split between two colors:
float3 warm = float3(1.0, 0.2, 0.1);
float3 cool = float3(0.1, 0.3, 1.0);
float3 gradient = mix(warm, cool, uv.x); // even left-to-right gradient
float3 split = mix(warm, cool, smoothstep(0.45, 0.55, uv.x)); // warm left, cool right, soft seam
This pattern of "compute a 0 to 1 mask with step, smoothstep or a distance, then use it as t in mix" is how most shaders in the rest of the course combine layers.
In Metal, keep t between 0 and 1. The specification says mix is undefined outside that range. Mathematically, t = 1.5 would overshoot past b; if you want that, write the formula out yourself. Otherwise wrap t in saturate (next section).
clamp and saturate: keeping values in range
clamp(x, lo, hi) returns x if it's between lo and hi, otherwise the nearest limit. It's the same as min(max(x, lo), hi).
clamp(x, 0.0, 1.0)
x result
-0.5 0.0
0.3 0.3
1.4 1.0
The 0 to 1 case is so common that Metal has a dedicated function for it: saturate(x). You won't find it in GLSL, but you'll see it in Metal code everywhere.
Use it when an intermediate value can leave the range a later function needs, such as the t you pass to mix, or a brightness you're about to raise to a power. Like smoothstep's edges, the limits must be in order: clamp is undefined if lo is greater than hi.
pow: bending the 0 to 1 range
pow(x, p) returns x raised to the power p. For inputs between 0 and 1 it has a property that makes it useful for shaping: 0 stays 0 and 1 stays 1, only the values in between move.
x pow(x, 2.0) pow(x, 0.5)
0.0 0.0 0.0
0.25 0.0625 0.5
0.5 0.25 0.707
0.75 0.5625 0.866
1.0 1.0 1.0
An exponent above 1 pushes the middle values down, so the curve stays low for a long time and then rises quickly. An exponent below 1 pushes them up, rising fast at first and then leveling off. Raising a falloff to a power is how you make a glow tighter (p above 1) or more spread out (p below 1).
A negative base is a problem. pow(-0.5, 0.5) asks for the square root of a negative number, which has no real answer, so you get NaN and usually a black or garbage pixel. Since sin and centered coordinates go negative, use pow(abs(x), p), and multiply by sign(x) if you need the sign back. The moire solution does exactly that.
The preview shows three curves at once, one per color channel:
Falloff Comparison
Three different power curves displayed as RGB channels - linear (red), quadratic (green), and square root (blue)
[[ stitchable ]] half4 falloffComparison(float2 position, half4 color, float2 size) {
float2 uv = position / size;
// Three different falloff curves
float linear = uv.x;
float quadratic = pow(uv.x, 2.0);
float sqrt = pow(uv.x, 0.5);
// Show each in R, G, B channels
return half4(linear, quadratic, sqrt, 1.0);
}At the left edge all three channels are 0 (black) and at the right edge all three are 1 (white). In between, blue (square root) is always the highest and green (squared) the lowest, so the middle of the strip tints toward blue and purple.
Combining functions
Single functions make stripes and ramps. Things get interesting when you feed the output of one into another, or combine two coordinates.
Interference: multiplying two waves
Interference Pattern
Two sine waves multiplied together create interference patterns - bright where they agree, dark where they disagree
[[ stitchable ]] half4 interferencePattern(float2 position, half4 color, float2 size) {
float2 uv = position / size;
// Two waves at different angles
float wave1 = sin(uv.x * 10.0);
float wave2 = sin(uv.y * 10.0);
// Multiply: where both are positive or both negative = bright
// Where they disagree = dark
float interference = wave1 * wave2;
// This creates a checkerboard of positive/negative values
// Map to 0-1 for visibility
float brightness = interference * 0.5 + 0.5;
return half4(brightness, brightness, brightness, 1.0);
}wave1 changes along x and wave2 along y. Multiplying them follows the sign rules you know: positive times positive and negative times negative are both positive (bright), while mixed signs give a negative product (dark).
sin(uv.x * 10.0) changes sign every π / 10 ≈ 0.314 of the view, so each axis splits into bands at roughly 0.31 and 0.63 and 0.94. Where a positive x band crosses a positive y band, or a negative crosses a negative, you get a bright blob; elsewhere a dark one. The result is a soft checkerboard of round spots, brightest at their centers where both waves peak together.
Phase: making a wave move
Traveling Wave
A sine wave that moves across the screen using phase shift - demonstrates how time creates motion
[[ stitchable ]] half4 travelingWave(float2 position, half4 color, float2 size, float time) {
float2 uv = position / size;
// Phase shift moves the wave
float phase = time * 2.0;
float wave = sin(uv.x * 10.0 - phase);
// Visualize
float brightness = wave * 0.5 + 0.5;
return half4(brightness, brightness, brightness, 1.0);
}The phase is a number added to (or subtracted from) the angle before sin sees it. It doesn't change the shape of the wave, only where along x each peak lands.
Follow one peak. sin peaks when its angle is π/2, so the peak is wherever uv.x * 10.0 - 2.0 * time = 1.571. Solve for uv.x:
uv.x = (1.571 + 2.0 * time) / 10.0
time = 0.0 peak at uv.x = 0.157
time = 1.0 peak at uv.x = 0.357
time = 2.0 peak at uv.x = 0.557
The peak moves right by 0.2 of the view every second, so it crosses the whole view in 5 seconds. Subtracting the phase moves the wave right; adding it moves it left. The multiplier on time sets the speed.
time here is the number of seconds since the view appeared. The Xcode project computes it as date.timeIntervalSince(startDate) inside a timeline and passes it with .float(...). Don't pass Date().timeIntervalSinceReferenceDate directly: that's around 800 million seconds, and at that size a Float can only change in steps of 64 seconds, so the animation freezes. Chapter 9 covers animation timing in detail.
Radial waves: sine of a distance
Radial Pulse
Concentric circular waves radiating from the center, with smooth edge masking for a focused effect
[[ stitchable ]] half4 radialPulse(float2 position, half4 color, float2 size, float time) {
float2 uv = position / size;
float2 center = uv - 0.5;
// Distance creates circular coordinate
float radius = length(center);
// Apply sine to radius instead of x/y
float wave = sin(radius * 30.0 - time * 3.0);
// Smooth edges
float mask = 1.0 - smoothstep(0.4, 0.5, radius);
float brightness = wave * 0.5 + 0.5;
return half4(brightness * mask, brightness * mask, brightness * mask, 1.0);
}The only change from the traveling wave is the input. Instead of uv.x, the wave reads radius, the distance from the center of the view. All pixels at the same distance get the same value, so the stripes become rings. The phase works the same way as before: the rings move outward by 3 / 30 = 0.1 of the view per second.
The last line multiplies by mask, which is 1 inside radius 0.4, fades to 0 by radius 0.5, and stays 0 beyond. That's smoothstep used as a soft circular cutout, and the corners of the view stay black.
Layering waves (a preview of noise)
Complex Wave (Multi-Octave)
Multiple sine waves combined with increasing frequency and decreasing amplitude - a preview of noise generation techniques
[[ stitchable ]] half4 complexWave(float2 position, half4 color, float2 size) {
float2 uv = position / size;
float wave = 0.0;
float amplitude = 1.0;
float frequency = 1.0;
// Add multiple octaves
for(int i = 0; i < 4; i++) {
wave += sin(uv.x * frequency * 10.0) * amplitude;
frequency *= 2.0; // Double frequency
amplitude *= 0.5; // Halve amplitude
}
// Map to roughly 0-1. The sum can reach +/-1.875 (1 + 0.5 + 0.25 + 0.125),
// so the brightest and darkest spots clip.
wave = wave * 0.5 + 0.5;
return half4(wave, wave, wave, 1.0);
}Each pass through the loop adds another sine wave with twice the frequency and half the amplitude of the previous one. Each of these layers is called an octave, borrowing the musical term for a doubling of frequency:
octave frequency multiplier amplitude
1 10 1.0
2 20 0.5
3 40 0.25
4 80 0.125
The first wave sets the broad shape, and each later one adds smaller, fainter wiggles on top. Natural shapes like coastlines and clouds have this property of detail at many scales. Chapter 6 uses the same loop with noise instead of sin to get organic textures.
Common pitfalls
Pitfall 1: stripes running the wrong way
// sin(uv.x): brightness changes left to right, so the stripes are vertical
float wave = sin(uv.x * 10.0);
// sin(uv.y): brightness changes top to bottom, so the stripes are horizontal
float wave = sin(uv.y * 10.0);
The stripes run perpendicular to the coordinate you feed in. If you want vertical bands, the value has to change as you move horizontally, so use uv.x.
Pitfall 2: frequency higher than the pixels can show
Every wave needs at least two pixels (one for the peak, one for the trough) to be drawn at all. This is the Nyquist limit. Above it, neighboring pixels land on unrelated parts of the wave and you get flickering moiré patterns instead of stripes.
// Too high for a small view
float wave = sin(uv.x * 1000.0);
// Comfortable
float wave = sin(uv.x * 10.0);
Work it out for a specific view. sin(uv.x * 1000.0) fits 1000 / 6.283 ≈ 159 waves across. On a 200-point-wide view on a 2x screen, that's 400 pixels, so only 2.5 pixels per wave. That's right at the limit, and it will shimmer as soon as anything moves. Keep several pixels per wave, or fade the pattern out where it gets too dense.
Pitfall 3: mixing up frequency, wavelength, phase and amplitude
// Frequency: how quickly the wave repeats. sin(x * k) repeats every 2π / k units
sin(uv.x * frequency)
// Wavelength: the distance between two peaks, 2π / frequency here.
// Write sin(uv.x * cycles * 6.2832) if you want "cycles" waves across 0 to 1.
// Phase: shifts the wave sideways without changing its shape
sin(uv.x * frequency + phase)
// Amplitude: scales the height of the wave
sin(uv.x * frequency) * amplitude
Challenges
The solutions are in Chapter 4/Chapter4.metal in the Xcode project.
Challenge 1: Wave Mastery

Create waveVisualizer that draws three waves as thin lines, each in its own color channel:
- red: a sine wave
- green: the same wave with double the frequency
- blue: the same wave with half the amplitude
Use the plotting technique from the start of the chapter. Compute each wave's height, shift and scale it so it fits inside the view, and light the pixel when abs(y - waveHeight) is small. Adding the three lines into R, G and B lets you see where they overlap (red and green together show as yellow, for example). The solution also adds a faint grid with step(0.98, fract(uv.x * 10.0)) so you can count waves.
Challenge 2: Fract Exploration

Create gridExplorer that:
- uses
fract()to create a 5×5 grid - colors each cell differently based on its grid position
Hint: floor(uv * 5.0) gives you the cell coordinates. Turn them into one number per cell with cellID.x + cellID.y * 5.0 (0 to 24), then feed that number into three sin calls with different phase offsets to get a red, green and blue value. Use cellUV to darken a thin border around each cell.
Challenge 3: Smoothstep Animation

Create breathingCircle (the Xcode solution is named organicPulse) that:
- shows a circle that grows and shrinks
- uses
smoothstepfor soft edges - uses
sin(time)to control the radius
The shape is 1.0 - smoothstep(radius - 0.02, radius + 0.02, dist), with radius changing over time. Remember that sin goes negative, so add it to a base radius: 0.3 + sin(time) * 0.05.
Bonus: make it pulse with a heartbeat rhythm. A plain sin is too even. pow(abs(sin(time * 3.0)), 8.0) stays near 0 most of the time and spikes to 1 briefly about once a second, which reads as a beat. The solution takes a different route: it adds four sine waves at unrelated speeds (1.0, 2.3, 0.7 and 3.1), so the rhythm never quite repeats.
Challenge 4: Function Composition

Create moire that:
- builds a grid pattern from
sin(x * 30.0) * sin(y * 30.0) - builds the same pattern again from coordinates rotated by a small angle (the solution uses 15°)
- multiplies the two together
Two nearly identical grids laid over each other produce large, slow interference bands, called moiré, like the patterns you see in overlapping fabric. To rotate around the center of the view, subtract 0.5, apply the rotation formula from Chapter 2, then add 0.5 back. The solution then boosts contrast with pow(abs(m), 0.5) * sign(m) and tints the result.
Challenge 5: Distortion Introduction

Create ripple using distortionEffect. This is the first time you'll use a shader that doesn't return a color. A distortion shader receives a pixel's position and returns a float2: the position in the original view to read the color from. Return position unchanged and nothing moves. Return a point slightly to the left and the content appears shifted right.
[[ stitchable ]] float2 ripple(float2 position, float2 size, float time) {
float2 uv = position / size;
float2 center = uv - 0.5;
float dist = length(center);
float wave = sin(dist * 20.0 - time * 3.0) * 0.02;
// Return the position to sample from: pushed toward or away from the center
return position + center * wave * size.x;
}
Notice there's no color parameter: a distortion shader only moves pixels, it doesn't compute colors. center points from the middle of the view to this pixel, so adding a multiple of it samples further out (when wave is positive) or further in (when it's negative), and the rings of sin(dist * 20.0 - time * 3.0) travel outward just like the radial pulse.
On the Swift side, distortionEffect needs a maxSampleOffset: the furthest any pixel will read from its own position. SwiftUI uses it to know how much of the surrounding content to make available. Here the offset is at most about 0.71 × 0.02 × the view width, under 3 points for a 200-point view. The Xcode project passes a generous 200 × 200:
content.distortionEffect(
ShaderLibrary.ripple(
.float2(geometryProxy.size),
.float(date.timeIntervalSince(startDate))
),
maxSampleOffset: .init(width: 200, height: 200)
)
Apply it over an image so you can see the content bend.
Want the Challenges Solutions?
Get the full Xcode project with solutions to all challenges, bonus examples, and clean, runnable code.
Get the Full Project →Validation Questions
Before proceeding to Chapter 5:
- Why does
sin()create smooth waves instead of sharp triangles?
Sine is the height of a point moving around a circle at constant speed. Near the top and bottom of the circle the point is moving mostly sideways, so its height changes slowly, and the peaks come out rounded. A triangle wave changes at a constant rate and then reverses instantly, which gives sharp corners.
- What happens when you multiply two sine waves together?
You get an interference pattern. Where both waves have the same sign the product is positive (bright), and where their signs differ it's negative (dark). Multiplying a wave along x by a wave along y gives a soft checkerboard of spots.
- How does
fract(uv * 5)create 5 copies of space?
Multiplying by 5 stretches the coordinates to run from 0 to 5. fract() keeps only the part after the decimal point, so each stretch from 0 to 1, 1 to 2, and so on maps back to 0 to 1. Along one axis that's 5 copies; with a 2D uv it's a 5×5 grid of 25 cells, each with its own local 0 to 1 coordinates. floor(uv * 5) tells you which copy you're in.
- Why use
smoothstep(0.4, 0.6, x)instead ofstep(0.5, x)?
step() jumps from 0 to 1 at a single value, so on curved or diagonal edges every pixel is either fully in or fully out, and you see jagged stair steps. smoothstep() blends from 0 to 1 across a range, here 0.4 to 0.6, which removes the stair steps. The width of that range controls how soft the edge is: about one pixel wide for clean anti-aliasing, wider for a deliberate blur or glow. Keep the first edge smaller than the second; Metal doesn't define the result otherwise.
- What's the relationship between frequency and wavelength?
They're inversely related. For sin(x * k), one full wave takes 2π / k units, so doubling k halves the wavelength. If you write the frequency in cycles, as in sin(x * cycles * 6.2832), the wavelength is simply 1 / cycles.
- How would you create a wave that speeds up over time?
Make the phase grow faster than linearly: sin(uv.x * frequency - time * time * acceleration). With a phase of time * speed, the wave moves at a constant rate. With time * time, the phase advances a little more each second than the second before, so the wave accelerates. Increasing the frequency over time with sin(uv.x * (baseFrequency + time * rate)) does something different: it packs more and more waves into the view.
Debugging deep patterns
When a combination doesn't look the way you expect, put the individual pieces into separate channels and look at them side by side:
// Visualize function ranges
return half4(
sin(uv.x * 5.0) * 0.5 + 0.5, // Red: sine
fract(uv.x * 5.0), // Green: fract
smoothstep(0.4, 0.6, uv.x), // Blue: smoothstep
1.0
);
If a channel is solid black or white everywhere, that value is outside 0 to 1, and you need to remap it or check your math. You can also paste any intermediate value into the plotFunction shader to see its exact graph.
Further Exploration
- Fourier analysis: any repeating signal can be built by adding sine waves of different frequencies, which is the idea behind the octave loop.
- Signal processing: the same sampling and aliasing rules, including the Nyquist limit, apply to audio and any other sampled signal.
- Natural patterns: reaction-diffusion, fluid motion and crystal growth produce shapes you can approximate with these functions.
- Distortion effects:
distortionEffectwith any of the functions in this chapter (tryfractorstepin place ofsin).
Next Chapter Preview: You've learned how individual functions create patterns. Chapter 5 uses fract(), floor() and fmod(), plus a simple hash for per-cell randomness, to build repeating designs: Truchet tiles, Voronoi cells, hexagonal grids, and domain-warped patterns.