Skip to content

Mandelbulb

Video Lecture

Section Video Links
Mandelbulb Mandelbulb Mandelbulb 

 (Pay Per View)

You can use PayPal to purchase a one time viewing of this video for $1.49 USD.

Pay Per View Terms

  • One viewing session of this video will cost the equivalent of $1.49 USD in your currency.
  • After successful purchase, the video will automatically start playing.
  • You can pause, replay and go fullscreen as many times as needed in one single session for up to an hour.
  • Do not refresh the browser since it will invalidate the session.
  • If you want longer-term access to all videos, consider purchasing full access through Udemy or YouTube Memberships instead.
  • This Pay Per View option does not permit downloading this video for later viewing or sharing.
  • All videos are Copyright © 2019-2025 Sean Bradley, all rights reserved.

Description

We will practice concepts that we've already scene, but use a fractal algorithm known as the Mandelbulb.

Working Example

<>

The Mandelbulb Algorithm

  1. Start with a 3D position (x, y, z).

    This is the position we are testing to see if it belongs to the fractal.

  2. Initialize variables

    1. Make a copy of this position.
    2. Set a "derivative accumulator" (dr) to 1. This keeps track of how distances stretch as we iterate.
  3. Repeat for several iterations. (usually 8–12 times, or until we "escape")

    1. Measure the distance from the origin. r = length(z)
    2. Escape check. If r > 2, we know we are outside the fractal and can stop early.
    3. Update the derivative accumulator. This step is used later to estimate how far we are from the fractal surface.
    4. Convert to spherical coordinates. Think a point on a sphere:
      • r = how far from the center
      • θ = theta. The angle from the vertical axis (like latitude)
      • φ = phi. The angle around the vertical axis (like longitude)
    5. Scale by the fractal power
      • Raise r to a power (e.g. r^8)
      • Multiply the angles θ and φ by the same power.
    6. Convert the scaled (r, θ, φ) back into 3D (cartesian) coordinates (x, y, z)
    7. Add to the original position. p.addAssign(position)

  4. After the loop, calculate the final distance estimate.

    return log(r).mul(r).div(dr).mul(0.5)

    This gives us a good guess of how far we are from the nearest surface of the Mandelbulb, which lets us raymarch efficiently.

Start Scripts

./src/SDFScene.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import * as THREE from 'three/webgpu'
import {
  Break,
  float,
  If,
  Loop,
  normalize,
  uniform,
  vec2,
  vec3,
  Fn,
  positionLocal,
  abs,
  sin,
  cos,
  time,
  ShaderNodeObject
} from 'three/tsl'
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js'
import ShadowMarcher from './ShadowMarcher'
import AmbientOcclusion from './AmbientOcclusion'
import { atmosphericScattering } from './AtmosphericScattering'
import Mandelbulb from './Mandelbulb'

export default class SDFScene {
  private static options = {
    maxSteps: 256,
    surfaceDistance: 0.0001,
    cameraNear: 0.1,
    cameraFar: 100.0
  }

  private static maxSteps = uniform(this.options.maxSteps)
  private static surfaceDistance = uniform(this.options.surfaceDistance)
  private static cameraNear = uniform(this.options.cameraNear)
  private static cameraFar = uniform(this.options.cameraFar)

  private static scene = Fn(([position]: [ShaderNodeObject<THREE.Node>]) => {
    return vec2(Mandelbulb.scene(position), 0).toVar()
  })

  private static getNormal = Fn(
    ([position, distance]: [ShaderNodeObject<THREE.Node>, ShaderNodeObject<THREE.Node>]) => {
      const offset = vec2(0.0025, 0)

      return normalize(
        distance.sub(
          vec3(
            this.scene(position.sub(offset.xyy)).x,
            this.scene(position.sub(offset.yxy)).x,
            this.scene(position.sub(offset.yyx)).x
          )
        )
      )
    }
  )

  static render = Fn(([rayOrigin_immutable]: [ShaderNodeObject<THREE.Node>]) => {
    const rayOrigin = rayOrigin_immutable.toVar()

    const p = positionLocal

    const rayDirection = normalize(p).toVar()

    const t = time //.div(5)
    //const lightPosition = vec3(0, 50, this.cameraFar.negate())
    //const lightPosition = vec3(0, sin(t).mul(30).add(43), this.cameraFar.negate())
    const lightPosition = vec3(sin(t).mul(this.cameraFar), 50, cos(t).mul(this.cameraFar))
    //const lightPosition = vec3(sin(t).mul(this.cameraFar), sin(t).mul(40).add(50), cos(t).mul(this.cameraFar))
    const lightDirection = normalize(lightPosition.sub(p)).toVar()

    const skyColour = atmosphericScattering(p, normalize(lightPosition)).toVar()
    const finalColour = skyColour.toVar()

    const accumulatedDistance = float(this.cameraNear).toVar()

    const distance = vec2(0).toVar()
    const position = vec3(0).toVar()

    Loop({ start: 0, end: this.maxSteps, condition: '<' }, () => {
      position.assign(rayOrigin.add(rayDirection.mul(accumulatedDistance)))
      distance.assign(this.scene(position))

      If(abs(distance.x).lessThan(this.surfaceDistance).or(accumulatedDistance.greaterThan(this.cameraFar)), () => {
        Break()
      })

      accumulatedDistance.addAssign(distance.x.mul(0.6))
    })

    const normal = this.getNormal(position, distance.x).toVar()

    If(accumulatedDistance.lessThan(this.cameraFar), () => {
      finalColour.assign(Mandelbulb.render(position, normal, rayDirection, lightPosition, lightDirection))
    })

    return finalColour
  })

  static setGUI(gui: GUI) {
    const folder = gui.addFolder('SDF Scene')
    folder
      .add(this.options, 'maxSteps', 1, 512, 1)
      .name('Raymarch Max Steps')
      .onChange((v) => {
        this.maxSteps.value = v
      })
    folder
      .add(this.options, 'surfaceDistance', 0, 0.01, 0.0001)
      .name('Surface Distance')
      .onChange((v) => {
        this.surfaceDistance.value = v
      })
    folder
      .add(this.options, 'cameraNear', 0.0001, 10, 0.1)
      .name('Camera Near')
      .onChange((v) => {
        this.cameraNear.value = v
      })
    folder
      .add(this.options, 'cameraFar', 1, 512, 0.1)
      .name('Camera Far')
      .onChange((v) => {
        this.cameraFar.value = v
      })
    folder.close()

    Mandelbulb.setGUI(gui)
    ShadowMarcher.setGUI(gui)
    AmbientOcclusion.setGUI(gui)
  }
}

./src/Mandelbulb.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
import * as THREE from 'three/webgpu'
import {
  clamp,
  cos,
  dot,
  float,
  Fn,
  sin,
  uniform,
  vec3,
  length,
  Loop,
  If,
  Break,
  acos,
  atan,
  pow,
  log,
  reflect,
  normalize,
  mix,
  ShaderNodeObject
} from 'three/tsl'
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js'
import AmbientOcclusion from './AmbientOcclusion'
import ShadowMarcher from './ShadowMarcher'
import { atmosphericScattering } from './AtmosphericScattering'

export default class Mandelbulb {
  private static options = {
    power: 8,
    iterations: 8
  }

  private static power = uniform(this.options.power)
  private static iterations = uniform(this.options.iterations)

  static scene = Fn(([position]: [ShaderNodeObject<THREE.Node>]) => {
    const p = position.toVar()

    const r = float(0).toVar()
    const dr = float(1).toVar()

    Loop({ start: 0, end: this.iterations, condition: '<' }, () => {
      r.assign(length(p))

      If(r.greaterThan(2), () => {
        Break()
      })

      // Update the derivative accumulator based on radius
      const r_pow = r.pow(this.power.sub(1.0))
      dr.assign(r_pow.mul(this.power).mul(dr).add(1.0))

      // Convert to spherical coordinates
      const theta = acos(clamp(p.z.div(r), -1.0, 1.0))
      const phi = atan(p.y, p.x)

      // Scale by the fractal power
      const pr = r.pow(this.power)
      theta.mulAssign(this.power)
      phi.mulAssign(this.power)

      // Convert back to cartesian
      p.assign(pr.mul(vec3(sin(theta).mul(cos(phi)), sin(theta).mul(sin(phi)), cos(theta))))

      // Add to original position
      p.addAssign(position)
    })

    return log(r).mul(r).div(dr).mul(0.5)
  })

  static render = Fn(
    ([position, normal, rayDirection, lightPosition, lightDirection]: [
      ShaderNodeObject<THREE.Node>,
      ShaderNodeObject<THREE.Node>,
      ShaderNodeObject<THREE.Node>,
      ShaderNodeObject<THREE.Node>,
      ShaderNodeObject<THREE.Node>
    ]) => {
      const diffuse = clamp(dot(normal, lightDirection), 0, 1)
      const shadow = ShadowMarcher.render(position.add(normal.mul(0.001)), lightDirection, this.scene)
      const colour = atmosphericScattering(reflect(rayDirection, normal), normalize(lightPosition))
      colour.assign(mix(colour.mul(shadow), diffuse.mul(normal).mul(0.25).add(1), shadow))
      colour.mulAssign(AmbientOcclusion.render(position, normal, this.scene))

      return colour
    }
  )

  static setGUI(gui: GUI) {
    const folder = gui.addFolder('MandelBulb')
    folder
      .add(this.options, 'power', 2, 20, 0.1)
      .name('Power')
      .onChange((v) => {
        this.power.value = v
      })
    folder
      .add(this.options, 'iterations', 1, 20, 1)
      .name('Iterations')
      .onChange((v) => {
        this.iterations.value = v
      })
    //folder.close()
  }
}

./src/main.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import './style.css'
import * as THREE from 'three/webgpu'
import { uniform } from 'three/tsl'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { GUI } from 'three/addons/libs/lil-gui.module.min.js'
import adjustDPR from './AdaptiveDPR'
import SDFScene from './SDFScene'

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(
  53,
  window.innerWidth / window.innerHeight,
  0.1,
  10
)
camera.position.set(1, 1, 2.25)

const renderer = new THREE.WebGPURenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
renderer.setAnimationLoop(animate)
renderer.setPixelRatio(0.25) // start low for slower cards

window.addEventListener('resize', function () {
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
})

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true

const gui = new GUI()

SDFScene.setGUI(gui)

const camPos = uniform(new THREE.Vector3())

scene.backgroundNode = SDFScene.render(camPos.toVar())

const clock = new THREE.Clock()
let delta = 0

function animate() {
  delta = clock.getDelta()
  adjustDPR(renderer, delta) //Adaptive DPR

  controls.update()

  camPos.value.copy(camera.position)

  renderer.render(scene, camera)
}

ShadowMarcher Settings

Property Value
softness 10
intensity 0.15
maxSteps 32
near 0.01
far 64
surfaceDistance 0.001

Ambient Occlusion Settings

Property Value
samples 4
spread 0.015
factor 0.005

Mandelbulb (wikipedia)

Spherical coordinate system (wikipedia)