Procedural Patterns

From one pattern to a whole grid

In Chapter 4 you met fract() as a way to repeat space: fract(uv * 10.0) turns one 0 to 1 square into a 10×10 grid of small 0 to 1 squares. That alone gives you wallpaper, the same tile everywhere. This chapter adds the piece that makes grids interesting: knowing which tile a pixel is in, so each tile can look or behave differently.

With that one extra piece you can build checkerboards, stripes, tiles that pick a random design, Truchet mazes, Voronoi cells, honeycombs and warped grids. All of them follow the same recipe:

  1. Scale the coordinates so the view holds N cells.
  2. Split each coordinate into "which cell" (floor) and "where inside the cell" (fract).
  3. Draw something using the local position, and vary it using the cell ID.

Remember the factory from Chapter 1, where every worker (pixel) runs the same instructions without talking to the others? A grid shader works the same way. Each pixel works out its own cell and its own position inside that cell, and draws accordingly. No pixel knows anything about the other cells.

Repeating space with fract and floor

Tracing one pixel through the grid

Here are the two lines you'll write at the top of almost every shader in this chapter:

float2 grid = fract(uv * 10.0);      // Local: Where am I in my cell? (0-1)
float2 cellID = floor(uv * 10.0);    // Global: Which cell am I in? (0-9, 0-9)

Let's follow one pixel through them. Say the view is 400×400 points and we use an 8×8 grid (uv * 8.0, as most examples in this chapter do). Each cell is then 400 / 8 = 50 points wide. Take the pixel at position = (130, 270):

position          = (130, 270)
uv = position / size = (130/400, 270/400)  = (0.325, 0.675)
uv * 8.0          = (2.6, 5.4)
floor(uv * 8.0)   = (2.0, 5.0)   -> cellID: column 2, row 5
fract(uv * 8.0)   = (0.6, 0.4)   -> grid:   60% across, 40% down inside that cell

Counting starts at 0 and, because SwiftUI's y axis points down, row 5 is the sixth row from the top. Notice that floor and fract add back up to the scaled value: (2, 5) + (0.6, 0.4) = (2.6, 5.4). You haven't thrown any information away. You've split one number into a coarse part and a fine part.

Now move along the same row and watch what happens:

position.x   uv.x    uv.x * 8   floor   fract
   130       0.325     2.6        2      0.6
   140       0.350     2.8        2      0.8
   149       0.3725    2.98       2      0.98
   150       0.375     3.0        3      0.0    <- crossed into the next cell
   180       0.450     3.6        3      0.6    <- same local x as position 130

As x grows, fract climbs from 0 towards 1, then snaps back to 0 at each cell border, while floor steps up by one. Pixels 130 and 180 sit exactly one cell apart (50 points), so they get the same local coordinates and different cell IDs:

uv.x * 8:  0         1         2         3         4
           |---------|---------|---------|---------|
floor:     0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3
fract:     0 ......1 0 ......1 0 ......1 0 ......1

That gives you the rule the whole chapter is built on:

  • Anything you compute only from grid comes out identical in every cell. Draw a circle with length(grid - 0.5) < 0.3 and you get 64 identical circles. For our pixel, grid - 0.5 = (0.1, -0.1), its length is about 0.14, so it's inside its cell's circle, and so is pixel 180 in the next cell over.
  • Anything you feed cellID into can differ from cell to cell: a color, a size, a speed, which shape to draw.

Stripes and checkerboards

Stripes are the 1D version: repeat along one axis, then split each repeat in half with step.

float stripes  = step(0.5, fract(uv.x * 10.0));            // 10 vertical stripes
float diagonal = step(0.5, fract((uv.x + uv.y) * 10.0));   // diagonal stripes

uv.x + uv.y is constant along lines running at 45°, so repeating it gives diagonal bands.

A checkerboard is the first pattern that needs the cell ID. Neighboring cells must alternate, and the cheapest test for that is whether cellID.x + cellID.y is even or odd:

float2 cellID = floor(uv * 8.0);
float checker = fmod(cellID.x + cellID.y, 2.0);   // 0 or 1, alternating

Our traced pixel is in cell (2, 5): 2 + 5 = 7, odd, so checker is 1. Its neighbor in cell (3, 5) gives 8, even, so 0. Step one cell in any direction and the sum changes by exactly one, which flips the result.

A different random value per cell

To make cells differ in a less regular way, you want a "random" number per cell. Shaders have no random() function (Chapter 6 explains why and takes this function apart line by line), so the standard trick is a hash: a function that scrambles its input into a value that looks random.

float random(float2 st) {
    return fract(sin(dot(st, float2(12.9898, 78.233))) * 43758.5453);
}

The output is deterministic: the same input always gives the same value between 0 and 1. That's exactly what you want here. Pass it cellID, and every pixel in cell (2, 5) gets the same number, so the whole cell agrees on one color or one choice, while cell (3, 5) gets a different number. If you passed uv instead, every pixel would get its own value and you'd see static.

You'll see the hash written inline in the examples below instead of as a helper function. Either works. If you write the helper, put it in the .metal file above the [[ stitchable ]] function that calls it.

Rotating the grid or the cells

You know the rotation formula from Chapter 2. Wrapped in a helper, it looks like this:

float2 rotate(float2 p, float angle) {
    float s = sin(angle);
    float c = cos(angle);
    return float2(p.x * c - p.y * s, p.x * s + p.y * c);
}

// Rotate first, then repeat: the whole grid is tilted
float2 tiltedGrid = fract(rotate(uv, angle) * 5.0);

// Repeat first, then rotate around each cell's center: every cell spins in place
float2 spinningCells = rotate(fract(uv * 5.0) - 0.5, angle);

The order matters because each operation works on whatever coordinates it receives:

  • Rotating before fract turns the whole coordinate system, so the grid lines themselves come out tilted. (rotate(uv, angle) spins around uv (0, 0), the top-left corner of the view. Use uv - 0.5 to spin around the center instead.)
  • Rotating after fract leaves the grid lines where they are and turns the coordinates inside each cell, so the content of every cell rotates while the tiles stay put.

The - 0.5 in the second line is important. The formula rotates around (0, 0), and after fract that point is each cell's top-left corner. Subtracting 0.5 first moves (0, 0) to the cell's center, so the shape spins in place instead of swinging around the corner. The result runs from -0.5 to 0.5, so draw with it accordingly (a circle is length(spinningCells) < 0.3, with no extra - 0.5).

Polar coordinates for radial patterns

Chapter 4 used length() to build circular waves from a distance. The other half of polar coordinates is the angle, and it lets you repeat things around a point the way fract repeats them along a line:

float2 p = fract(uv * 6.0) - 0.5;     // center of each cell is (0, 0)
float angle = atan2(p.y, p.x);        // -π to π
float radius = length(p);
float petals = cos(angle * 6.0) * 0.5 + 0.5;    // 6 bumps per full turn
float shape = step(radius, 0.2 + 0.2 * petals); // 1 inside the flower

atan2(y, x) gives the angle of the point around the cell's center. Multiplying the angle by 6 before cos makes the cosine repeat six times per full turn, so the radius limit 0.2 + 0.2 * petals bulges out six times: a six-petal flower in every cell. Change 6 to 8 and you get eight petals.

Two details to know. Because y points down in SwiftUI, increasing angles go clockwise on screen. And atan2 jumps from π to -π on the left side of the center. With a whole-number multiplier the cosine has the same value on both sides of that jump, so you never see it. With something like angle * 5.5 you'll get a visible seam there.

Example: a grid of cells that behave differently

Here's everything above in one shader. Each cell of an 8×8 grid uses its hash value to pick one of three animations and uses its ID to pick a color.

Living Mosaic

A grid where each cell randomly chooses between pulsing circles, rotating crosses, or moving stripes - each with unique colors and timing

[[ stitchable ]] half4 livingMosaic(float2 position, half4 color, float2 size, float time) {
  // Convert to UV coordinates (see Chapter 2 for detailed explanation)
  float2 uv = position / size;

  // Create grid
  float gridSize = 8.0;
  float2 grid = fract(uv * gridSize);
  float2 cellID = floor(uv * gridSize);

  // Unique random per cell
  float cellRandom = fract(sin(dot(cellID, float2(12.9898, 78.233))) * 43758.5453);

  // Each cell has different behavior based on its random value
  float pattern = 0.0;

  if (cellRandom < 0.33) {
      // Circles that pulse
      float2 center = grid - 0.5;
      float pulse = sin(time * 2.0 + cellRandom * 6.28) * 0.1 + 0.3;
      pattern = 1.0 - smoothstep(pulse - 0.05, pulse, length(center));
  }
  else if (cellRandom < 0.66) {
      // Rotating crosses
      float angle = time + cellRandom * 6.28;
      float2 rotGrid = float2(
          grid.x * cos(angle) - grid.y * sin(angle),
          grid.x * sin(angle) + grid.y * cos(angle)
      );
      float cross = min(
          smoothstep(0.4, 0.45, abs(rotGrid.x - 0.5)),
          smoothstep(0.4, 0.45, abs(rotGrid.y - 0.5))
      );
      pattern = 1.0 - cross;
  }
  else {
      // Diagonal stripes
      float stripes = sin((grid.x + grid.y) * 10.0 + time * 3.0) * 0.5 + 0.5;
      pattern = stripes;
  }

  // Color based on cell position
  half3 cellColor = half3(
      sin(cellID.x * 0.3 + 1.0),
      sin(cellID.y * 0.3 + 2.0),
      sin(cellID.x * cellID.y * 0.1 + 3.0)
  ) * 0.5 + 0.5;

  return half4(pattern * cellColor.r, pattern * cellColor.g, pattern * cellColor.b, 1.0);
}
SwiftUI Metal Shader

Things worth noticing:

  • size and time are arguments you pass from Swift. colorEffect doesn't supply them. The Xcode project passes .float2(geometryProxy.size) and .float(date.timeIntervalSince(startDate)), the time elapsed since the view appeared. position is in points, so position / size runs from 0 to 1 across the view.
  • The hash gives values spread fairly evenly between 0 and 1, so the thresholds 0.33 and 0.66 split the cells into three groups of roughly equal size.
  • cellRandom * 6.28 adds a different phase to each cell's animation. Without it, every pulsing circle would grow and shrink in sync.
  • The color comes straight from cellID, through sin(...) * 0.5 + 0.5 to map -1...1 into 0...1, so neighboring cells drift gradually through colors across the grid.
  • The rotating branch rotates grid without subtracting 0.5 first, so it spins around each cell's top-left corner, and the shape sweeps across the cell instead of turning in place. Compare that with the - 0.5 version in the rotation section and in Challenge 1.

Patterns built on the same grid

Truchet tiles

A Truchet pattern uses one tile design and only one random decision per cell: rotate the tile by 90° or not. The result looks like a continuous maze of curves.

Truchet Magic

Randomly rotated quarter-circle tiles that magically form continuous connected paths - mathematical elegance in action

[[ stitchable ]] half4 truchetMagic(float2 position, half4 color, float2 size) {
  float2 uv = position / size;

  float2 grid = fract(uv * 8.0);
  float2 cellID = floor(uv * 8.0);

  // Random rotation per cell
  float rand = fract(sin(dot(cellID, float2(12.9898, 78.233))) * 43758.5453);

  // Rotate grid coordinates 90° (around the cell center) for about half the cells
  if (rand > 0.5) {
      grid = float2(1.0 - grid.y, grid.x);
  }

  // Draw quarter circles in opposite corners
  // Arc around the top-left corner (y points down in SwiftUI)
  float arc1 = length(grid);
  // Arc around the bottom-right corner
  float arc2 = length(grid - float2(1.0, 1.0));

  // Create the line pattern (where the arcs should be)
  float lineWidth = 0.03;
  float line = 0.0;

  // First arc (radius 0.5, centered at 0,0)
  if (abs(arc1 - 0.5) < lineWidth) {
      line = 1.0;
  }

  // Second arc (radius 0.5, centered at 1,1)
  if (abs(arc2 - 0.5) < lineWidth) {
      line = 1.0;
  }

  return half4(line, line, line, 1.0);
}
SwiftUI Metal Shader

Each tile has two quarter circles of radius 0.5: one centered on the top-left corner, one on the bottom-right. abs(arc1 - 0.5) < lineWidth is true for pixels whose distance from the corner is within 0.03 of 0.5, which draws a thin ring, and only the quarter inside the cell is visible.

The line grid = float2(1.0 - grid.y, grid.x) rotates the tile's coordinates by 90°. Plug in the corner (0, 0) and you get (1, 0), so in rotated cells the arcs sit around the top-right and bottom-left corners instead.

Why do the curves always connect? A radius-0.5 arc around a corner meets the two edges next to that corner exactly at their midpoints. Two arcs on opposite corners together touch the midpoint of all four edges, in either orientation. Neighboring cells share an edge, and therefore share its midpoint, so a curve leaving one tile always arrives where the next tile has a curve waiting.

The edges here are hard (if instead of smoothstep), so they'll look jagged. Swapping in 1.0 - smoothstep(lineWidth - 0.01, lineWidth, abs(arc1 - 0.5)) is a good exercise.

Voronoi cells

A Voronoi pattern scatters one seed point in each cell and colors every pixel by whichever seed is closest. The result looks like biological cells, cracked mud or a giraffe's coat.

Voronoi Organic

Animated cellular pattern where each pixel belongs to the closest randomly placed seed point - mimics natural cell structures

[[ stitchable ]] half4 voronoiOrganic(float2 position, half4 color, float2 size, float time) {
  float2 uv = position / size;
  float2 scaledUV = uv * 5.0;

  float2 gridID = floor(scaledUV);
  float2 gridUV = fract(scaledUV);

  float minDist1 = 10.0;  // Closest
  float minDist2 = 10.0;  // Second closest
  float2 closestID;

  // Check 3x3 grid of neighbors
  for (int y = -1; y <= 1; y++) {
      for (int x = -1; x <= 1; x++) {
          float2 neighbor = float2(x, y);
          float2 cellID = gridID + neighbor;

          // Animated random point in each cell
          float2 pointOffset = float2(
              fract(sin(dot(cellID, float2(12.9898, 78.233))) * 43758.5453),
              fract(sin(dot(cellID, float2(78.233, 12.9898))) * 43758.5453)
          );

          // Add subtle animation
          pointOffset += sin(time * 2.0 + pointOffset * 6.28) * 0.1;

          float2 point = neighbor + pointOffset;
          float dist = length(point - gridUV);

          if (dist < minDist1) {
              minDist2 = minDist1;
              minDist1 = dist;
              closestID = cellID;
          } else if (dist < minDist2) {
              minDist2 = dist;
          }
      }
  }

  // Color based on cell
  half3 cellColor = half3(
      fract(sin(closestID.x * 12.9898) * 43758.5453),
      fract(sin(closestID.y * 78.233) * 43758.5453),
      fract(sin(dot(closestID, float2(45.678, 98.765))) * 43758.5453)
  );

  return half4(cellColor, 1.0);
}
SwiftUI Metal Shader

Step by step:

  1. Each grid cell gets one seed point. Two hashes of the cell ID give its x and y offset inside the cell, both between 0 and 1. A small sin(time ...) term makes the seeds drift by up to 0.1.
  2. A pixel can't check every seed in the image, so it checks only its own cell and the eight around it (the -1...1 loops). Each seed stays inside or very close to its own cell, so the nearest seed is almost always in that 3×3 block, which is why this is the standard search size.
  3. The positions are measured in the pixel's local frame: neighbor + pointOffset is where that neighbor's seed sits relative to the current cell's corner, and gridUV is where the pixel sits, so length(point - gridUV) is the distance between them.
  4. The loop keeps the smallest distance and the ID of the cell that owns that seed. All pixels sharing the same closest seed get the same closestID, hash it into the same color, and form one region.

The shader also tracks minDist2, the second-closest distance, but doesn't use it. It's there for you to experiment with: minDist2 - minDist1 is close to zero along the borders between regions, so step(0.05, minDist2 - minDist1) draws dark outlines around every cell.

Hexagons and warped grids

Hexagonal grids

Square grids are easy because floor and fract work on each axis separately. Hexagons don't line up with the x and y axes, so they need a trick. The centers of a hex grid can be split into two ordinary rectangular grids, each with spacing (1, √3), offset from each other by half a step in both directions. For each pixel, find the nearest center in each of the two grids and keep whichever is closer. That center's hexagon is the one the pixel is in.

Hexagonal Honey

Perfect hexagonal grid pattern like honeycomb - demonstrates optimal space packing as used by bees in nature

[[ stitchable ]] half4 hexagonalHoney(float2 position, half4 color, float2 size) {
  float2 uv = position / size;

  // Aspect correction
  float aspect = size.x / size.y;
  uv.x *= aspect;

  // Scale
  float2 p = uv * 10.0;

  // Hexagonal grid math
  float2 hex = float2(1.0, 1.73205); // 1, sqrt(3)
  float2 a = fmod(p, hex) - hex * 0.5;
  float2 b = fmod(p - hex * 0.5, hex) - hex * 0.5;

  // Find closest hexagon center
  float2 gv = (dot(a, a) < dot(b, b)) ? a : b;

  // Hexagon distance: the larger of the distances to the edge directions (0° and 60°)
  float2 absGv = abs(gv);
  float d = max(dot(absGv, float2(0.5, 0.866025)), absGv.x);

  // Create honeycomb walls: 1 inside the cell, 0 on the wall
  // (edges in increasing order; reversed edges are undefined in Metal)
  float walls = 1.0 - smoothstep(0.40, 0.45, d);

  // Honey color inside cells, dark walls
  half3 honeyColor = half3(1.0, 0.85, 0.0);
  half3 wallColor = half3(0.4, 0.2, 0.0);

  half3 finalColor = mix(wallColor, honeyColor, walls);

  return half4(finalColor.r, finalColor.g, finalColor.b, 1.0);
}
SwiftUI Metal Shader

How the pieces map to that idea:

  • fmod(p, hex) - hex * 0.5 is the same move as fract(uv) - 0.5, but with a cell that is 1 wide and √3 tall. It gives the offset from the pixel to the nearest center of the first grid. b does the same for the second grid, shifted by half a cell.
  • dot(a, a) is the squared length of a. Comparing squared lengths picks the closer center without computing two square roots.
  • gv is now the pixel's offset from its own hexagon's center, the hex equivalent of grid - 0.5.
  • A circle would use length(gv). A hexagon has flat sides, so its "distance" is the largest of the pixel's distances along the directions perpendicular to the edges. abs() folds all six edges onto two, the vertical edge (measured by absGv.x) and the slanted one (measured by the dot product with the direction at 60°), and max keeps the larger. Pixels where d is below 0.4 are honey, pixels above 0.45 are wall, and 1.0 - smoothstep(0.40, 0.45, d) blends between them. Writing it as smoothstep(0.45, 0.40, d) looks equivalent, but Metal leaves smoothstep undefined when the first edge isn't smaller than the second, so always flip the result instead of the edges.

fmod is safe here because p is never negative. Once coordinates can go negative, for example after uv - 0.5, switch to the floor-based glslMod helper from Chapter 4 (see the first validation question below).

The Xcode project solves the same problem a different way: the hexagonGrid shader in Chapter5.metal converts to axial hex coordinates and uses round() to find the center. Open it and compare the two approaches.

Domain warping

Every grid so far has perfectly straight rows. Domain warping bends them: before you build the pattern, you nudge the coordinates by a smooth function of position, and the pattern follows the bent coordinates.

Domain Warp Pattern

Organic-looking circles created by warping coordinate space with sine waves - breaks mechanical grid regularity

[[ stitchable ]] half4 domainWarpPattern(float2 position, half4 color, float2 size, float time) {
  float2 uv = position / size;

  // First pattern to warp space
  float2 q = float2(
      sin(uv.x * 4.0 + time * 0.3),
      cos(uv.y * 4.0 + time * 0.2)
  ) * 0.1;

  // Warp the coordinates
  float2 warpedUV = uv + q;

  // Apply pattern to warped space
  float2 grid = fract(warpedUV * 8.0);
  float2 center = grid - 0.5;

  float circles = 1.0 - smoothstep(0.2, 0.25, length(center));

  // Radial brightness wave moving outward from the center (modulates color, doesn't warp)
  float warp2 = sin(length(uv - 0.5) * 10.0 - time) * 0.5 + 0.5;

  float r = circles * warp2;
  float g = circles * warp2 * 0.7;
  float b = circles * warp2 * 0.5;

  return half4(r, g, b, 1.0);
}
SwiftUI Metal Shader

q is an offset of at most 0.1 in each direction, and it changes smoothly across the view and over time. The grid has 8 cells across, so each cell is 0.125 wide in uv units, and an offset of 0.1 moves a circle by up to 80% of a cell. Nearby pixels get almost the same offset, so circles stay round-ish, but circles far apart get pushed in different directions, and the rows wobble. warp2 is a separate effect: rings of brightness that move outward from the center and dim some circles more than others.

Chapter 6 uses the same idea with noise instead of sine waves, which is where domain warping starts to look like marble and smoke.

Common mistakes

Stretched cells on non-square views

// WRONG - Squares become rectangles!
float2 grid = fract(uv * 10.0);

// CORRECT - Perfect squares regardless of screen shape
float aspectRatio = size.x / size.y;
float2 grid = fract(float2(uv.x * aspectRatio, uv.y) * 10.0);

uv runs from 0 to 1 on both axes whatever the view's shape. On a 400×200 view, uv * 10.0 gives 10 cells across 400 points and 10 cells down 200 points, so each cell is 40×20 points. Multiplying uv.x by the aspect ratio (2 here) stretches the x range to 0...2, which gives 20 cells across, each 20×20 points.

Correlated random values

// WRONG - randX only depends on the column, randY only on the row,
// and with the same multiplier randX at cell (3, 5) equals randY at cell (5, 3)
float randX = fract(sin(cellID.x * 12.9898) * 43758.5453);
float randY = fract(sin(cellID.y * 12.9898) * 43758.5453);

// CORRECT - Each value hashes the full cell ID, with unrelated constants
float randX = fract(sin(dot(cellID, float2(127.1, 311.7))) * 43758.5453);
float randY = fract(sin(dot(cellID, float2(269.5, 183.3))) * 43758.5453);

The first version has two problems. Every cell in a column shares the same randX, which shows up as vertical stripes of identical behavior. And because both lines use the same multiplier, the values are mirrored across the diagonal. Hash the whole cellID with a dot, and use a different constant vector for each value you need.

Swapping the two numbers isn't enough either. The Voronoi example uses float2(12.9898, 78.233) for x and float2(78.233, 12.9898) for y, which means the seed in cell (a, b) is the mirror image of the seed in cell (b, a). Look closely at that preview and you'll find the cell shapes mirrored across the diagonal. Constants with no relation to each other, like the ones above, avoid it.

Checking too many neighbors

// WRONG - Checking too many cells kills performance
for (int y = -5; y <= 5; y++) {
    for (int x = -5; x <= 5; x++) {  // 121 iterations per pixel!

// CORRECT - Minimum necessary neighbors
for (int y = -1; y <= 1; y++) {
    for (int x = -1; x <= 1; x++) {  // Only 9 iterations

Every pixel runs the loop, so the cost multiplies by the number of pixels. Search only as far as a seed can actually be. With one seed per cell that stays near its cell, that's the 3×3 block.

Challenges

Challenge 1: Checkerboard Plus

Checkerboard Plus Example

Create an animated 8×8 checkerboard where one set of squares draws a rotating cross and the other set draws a pulsing circle.

Use fmod(cellID.x + cellID.y, 2.0) to decide which set a cell belongs to. For the cross, subtract 0.5 from the local coordinates, rotate them by an angle that grows with time, and light up pixels where either rotated coordinate is close to 0. For the circle, vary the radius with sin(time). The solution draws the circles at half brightness so the two sets read as "light" and "dark" squares.

Challenge 2: Islamic Geometric Pattern

Islamic Geometric Pattern Example

Create a repeating tile pattern with 8-fold symmetry, in the spirit of mosque tilework.

Work in centered cell coordinates (fract(p) - 0.5) and use polar coordinates. cos(angle * 4.0) gives four lobes, pointing along the axes. Add lines along the two diagonals (abs(gv.x - gv.y) and abs(gv.x + gv.y) are small near them) to fill in the other four directions. Make the lobes long enough to reach the cell edges, and they'll join up with the neighboring tiles.

Challenge 3: Animated Ball Along Path

Animated Ball Along Path Example

Draw a zigzag path and a ball that travels along it.

A zigzag is a triangle wave: abs(fmod(x * 4.0, 2.0) - 1.0) goes 1 → 0 → 1 → 0 in straight lines. For example, at x = 0.1 it's abs(0.4 - 1.0) = 0.6, at x = 0.25 it's 0, at x = 0.5 it's 1. Map that to a y range with mix, then draw the path where the pixel's y is close to the path's y at the same x. For the ball, pick its x from time (fmod(time * 0.25, 1.0) crosses the view every 4 seconds) and run that x through the same function to get its y.

Measuring abs(uv.y - pathY) is a vertical distance, so steep parts of the path look thinner than flat parts. That's fine for this challenge.

The Xcode project also includes a bonus version, spiralBall, that sends the ball along a spiral using polar coordinates.

Challenge 4: Reaction-Diffusion Approximation

Reaction-Diffusion Example

Fake the look of organic growth by layering Voronoi distance fields at several scales.

Take the Voronoi loop, but keep only the distance to the nearest seed and turn it into a soft blob with smoothstep. Run it at 4, 8, 12 and 16 cells across, add the layers together with smaller weights for the finer ones, then threshold the sum with a narrow smoothstep to get crisp, merging shapes. Let the seeds drift slowly with time.

Challenge 5: Quasicrystal Pattern

Quasicrystal Pattern Example

Create a Penrose-like pattern with 5-fold symmetry.

No square or hexagonal grid can have 5-fold rotational symmetry, so fract and floor won't get you there. Use waves instead. Pick five directions spaced 72° apart (2π/5), project the centered position onto each with dot, take a sine of each projection, and add the five waves together. Their interference gives a pattern that never exactly repeats but looks the same after every 72° turn. Run fract on the sum to get sharp contour bands, and animate by adding time inside the sines.

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

  1. What's the mathematical relationship between fract() and fmod()?

fract(x) returns x - floor(x), which always lands between 0 and 1. fmod(x, 1.0) returns x - trunc(x), which keeps the sign of x. For positive numbers they agree: both give 0.7 for 3.7. For negative numbers they don't: fract(-0.3) is 0.7 but fmod(-0.3, 1.0) is -0.3. Negative coordinates appear as soon as you center them with uv - 0.5, so use fract for repeating space, or the glslMod helper from Chapter 4 (x - y * floor(x / y)) when the period isn't 1.

  1. How do you ensure each grid cell has unique but deterministic randomness?

Feed the cell ID (from floor(uv * gridSize)) into a hash function like fract(sin(dot(cellID, float2(12.9898, 78.233))) * 43758.5453). Every pixel in a cell has the same ID, so they all get the same value. Different cells have different IDs, so they get different values, and the same cell gets the same value every frame.

  1. Why do truchet tiles create continuous patterns despite being randomly oriented?

Each tile has two radius-0.5 arcs centered on opposite corners, and each arc meets the two edges next to its corner at their midpoints. So in either orientation the tile has a line ending at the midpoint of all four edges. Neighboring tiles share edges, and with them the midpoints, so every line continues into the next tile.

  1. What's the key insight behind voronoi patterns?

Each cell owns one seed point at a random position, and each pixel belongs to whichever seed is closest. Because seeds stay in or near their own cell, a pixel only has to check its own cell and the eight around it to find that seed. Coloring by the closest seed's cell ID gives each region one flat color.

  1. How does domain warping create organic-looking patterns?

You offset the coordinates by a smooth function (sine waves here, noise in Chapter 6) before building the pattern. The pattern itself is still a regular grid, but it's drawn in bent coordinates, so its rows and circles wobble and stop looking machine-made.

  1. Why are hexagonal grids optimal for certain natural patterns?

Of all the ways to divide a flat surface into cells of equal area, the hexagonal grid uses the least total wall length. That's why bees, whose walls cost wax, end up with hexagons. Hexagons also have six neighbors at equal distance, where a square grid has four edge neighbors and four diagonal ones further away.

Debug Visualization Tricks

// Visualize your grid structure
float2 cellID = floor(uv * 10.0);
float debugColor = fract(sin(dot(cellID, float2(12.9898, 78.233))) * 43758.5453);
return half4(debugColor, fract(debugColor * 3.14), fract(debugColor * 7.0), 1.0);

// Show grid boundaries
float2 grid = fract(uv * 10.0);
float boundary = step(0.95, grid.x) + step(0.95, grid.y);
return half4(boundary, 0.0, 0.0, 1.0);

The first snippet paints every cell a flat random color, which tells you at a glance whether your cell IDs are what you expect (if two neighboring cells share a color, they share an ID). The second draws a red line along the right and bottom edge of every cell, so you can see where cell borders fall relative to your shapes.

Further Exploration

  • Penrose tilings: tilings with 5-fold symmetry that never repeat
  • Wang tiles: tiles with colored edges that must match their neighbors, used to build large non-repeating textures
  • L-systems: string-rewriting rules that grow plants and fractals
  • Cellular automata: grids where each cell's next state depends on its neighbors, like Conway's Game of Life

Next Chapter Preview: Everything in this chapter is regular: grids, hashes per cell, waves. Natural materials have smooth, irregular variation instead. Chapter 6 introduces noise functions, which give you randomness that changes smoothly from pixel to pixel. You'll take the hash function apart, build value and gradient noise (the idea Ken Perlin won a technical Academy Award for), and use them for clouds, marble and wood.