Simple Fractals

10 / 18
Learn to create simple fractal patterns and understand the application of recursion and self-similarity concepts in shaders.

Scale up coordinates by 2 and wrap with fract on each iteration — detail keeps appearing at smaller and smaller scales. The core loop is:

Let’s break down how iteration produces self-similarity.


Scale + fract = self-similarity

Each loop iteration does two things:

  1. pos *= 2.0 — zoom into coordinate space by 2x; one big cell becomes four smaller cells
  2. pos = fract(pos) - 0.5 — take the fractional part and re-center, resetting each cell to its own [-0.5, 0.5] space

After one zoom, the same pattern appears at half the size. After four zooms, four scales of the same pattern stack on top of each other, creating the impression of infinite detail — that’s what a fractal is.


Decreasing weights

Iteration 1 adds 1/2 (50%), iteration 2 adds 1/4 (25%), iteration 3 adds 1/8 (12.5%), iteration 4 adds 1/16 (6.25%). The largest circles dominate the overall shape; finer details contribute less and less. The result is a clear large structure with progressively richer detail.


Animated pulse

A sine wave based on time and distance from center adds a rippling animation that gives the static pattern some life.


Try changing it

ChangeEffect
Change loop count from 4 to 2Less detail, coarser pattern
Change loop count to 6More levels, richer detail
Change pow(2.0, ...) to pow(1.5, ...)Detail levels get more weight
Change the 2.0 scale factor to 3.0More cells per zoom, denser pattern

Exercise

The exercise has the loop and circle drawing already in place. The initial pattern accumulation just needs to start from zero. Make sure pattern starts at 0.0 before the loop so the fractal accumulates correctly.

Answer Breakdown

Each iteration zooms in and wraps coordinates with fract, making the same circle motif appear at 4 different scales. circle / pow(2.0, float(i+1)) ensures larger-scale circles dominate: the first iteration contributes 50%, the fourth only 6.25%. After four passes, pattern is near 1 where circles appear and near 0 in empty space.

Try changing smoothstep(0.1, 0.3, dist) to smoothstep(0.05, 0.25, dist) to make each circle more solid, and watch how the fractal density changes.

GLSL Code Editor

Correct Code Preview

Current Code Preview