Skip to content

Adding Water

Video Lecture

Section Video Links
Adding Water Adding Water Adding Water

Description

We will add a water layer. We could use the FBM algorithm to create a water effect, but we will use a faster algorithm called a Gerstner wave, also known as a trochoidal wave.

Working Example

<>

Start Scripts

./src/Land.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
import { abs, clamp, cos, dot, float, Fn, If, Loop, mat2, mix, sin, smoothstep, uniform, vec3 } from 'three/tsl'
import * as THREE from 'three/webgpu'
import AmbientOcclusion from './AmbientOcclusion'
import ShadowMarcher from './ShadowMarcher'
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js'

export default class Land {
  private static options = {
    octaves: 8,
    lacunarity: 2.15,
    gain: 0.35,
    factorA: 0.19,
    colour1: new THREE.Color(0xdfff00).convertLinearToSRGB(),
    colour2: new THREE.Color(0xffffff).convertLinearToSRGB()
  }

  private static octaves = uniform(this.options.octaves)
  private static lacunarity = uniform(this.options.lacunarity)
  private static gain = uniform(this.options.gain)
  private static factorA = uniform(this.options.factorA)
  private static colour1 = uniform(this.options.colour1)
  private static colour2 = uniform(this.options.colour2)

  // @ts-ignore
  private static noise = Fn(([position]) => {
    return sin(position.x).add(sin(position.y))
  })

  // @ts-ignore
  private static rotate = Fn(([radians]) => {
    const a = sin(radians)
    const b = cos(radians)
    return mat2(b, a.negate(), a, b)
  })

  // @ts-ignore
  private static fbm = Fn(([position]) => {
    const p = position.xz.toVar()
    const accumulator = float(0.0).toVar()
    const amplitude = float(this.gain).toVar()

    Loop({ start: 0, end: this.octaves, condition: '<' }, () => {
      accumulator.addAssign(amplitude.mul(this.noise(p)))
      amplitude.mulAssign(this.gain)
      p.mulAssign(this.lacunarity.mul(this.rotate(this.factorA)))
    })

    return accumulator
  })

  //@ts-ignore
  static scene = Fn(([position]) => {
    const p = position.mul(0.5)

    const height = this.fbm(p).mul(2.2)

    // height.assign(height.mul(cos(p.x.mul(0.25))))
    // height.assign(height.mul(cos(p.z.mul(0.25))))
    // height.mulAssign(3.3)
    // height.subAssign(0.1)

    return p.y.sub(height)
  })

  //@ts-ignore
  static render = Fn(([position, normal, rayDirection, lightPosition, lightDirection, scene]) => {
    const colour = this.colour1.toVar()

    const steepness = float(abs(normal.y).oneMinus()).toVar()
    colour.assign(mix(colour, this.colour2, smoothstep(0.1, 0.7, steepness)))
    colour.assign(mix(colour, this.colour2, smoothstep(0, 1.0, position.y.sub(2))))

    const diffuse = clamp(dot(normal, lightDirection), 0, 1).toVar()
    diffuse.mulAssign(ShadowMarcher.render(position.add(normal.mul(0.001)), vec3(lightDirection), scene))
    diffuse.mulAssign(AmbientOcclusion.render(position, normal, scene))

    return colour.mul(diffuse)
  })

  static setGUI(gui: GUI) {
    const folder = gui.addFolder('Land')
    folder
      .add(this.options, 'octaves', 0, 10, 1)
      .name('Octaves')
      .onChange((v) => {
        this.octaves.value = v
      })
    folder
      .add(this.options, 'lacunarity', 1, 10, 0.01)
      .name('Lacunarity')
      .onChange((v) => {
        this.lacunarity.value = v
      })
    folder
      .add(this.options, 'gain', 0.01, 1.99, 0.01)
      .name('Gain')
      .onChange((v) => {
        this.gain.value = v
      })
    folder
      .add(this.options, 'factorA', 0, Math.PI / 2, 0.01)
      .name('Factor A')
      .onChange((v) => {
        this.factorA.value = v
      })

    folder.addColor(this.options, 'colour1').name('Colour 1')
    folder.addColor(this.options, 'colour2').name('Colour 2')

    folder.close()
  }
}

./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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import {
  Break,
  cos,
  float,
  If,
  Loop,
  normalize,
  sin,
  time,
  uniform,
  vec2,
  vec3,
  Fn,
  positionLocal,
  reflect,
  mix,
  exp,
  int,
  abs
} from 'three/tsl'
import { atmosphericScattering } from './AtmosphericScattering'
import Land from './Land'
import ShadowMarcher from './ShadowMarcher'
import AmbientOcclusion from './AmbientOcclusion'
import Fog from './Fog'
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js'
// import Ocean from './Ocean'
// import Fresnel from './Fresnel'

export default class SDFScene {
  private static options = {
    maxSteps: 384,
    surfaceDistance: 0.001,
    cameraNear: 0.01,
    cameraFar: 192.0,
    reflectivity: 0.5
  }

  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 reflectivity = uniform(this.options.reflectivity)

  // @ts-ignore
  private static scene = Fn(([position]) => {
    const land = Land.scene(position)

    //const ocean = Ocean.scene(position)

    const distance = vec2(land, 0).toVar()
    // If(distance.x.greaterThan(ocean), () => {
    //   distance.assign(vec2(ocean, 1))
    // })

    return distance
  })

  // @ts-ignore
  private static getNormal = Fn(([position, distance]) => {
    const offset = vec2(0.0001, 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
        )
      )
    )
  })

  // @ts-ignore
  static render = Fn(([rayOrigin_immutable]) => {
    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))

    const skyColour = atmosphericScattering(p, normalize(lightPosition)).toVar()
    //const skyColour = atmosphericScattering(vec3(p.x, abs(p.y), p.z), normalize(lightPosition)).toVar()
    const finalColour = skyColour.toVar()

    //const reflectivityFactor = float(1.0).toVar()

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

    //const maxReflections = int(1).toVar()
    //Loop({ start: 0, end: maxReflections, condition: '<=' }, () => {
    accumulatedDistance.assign(0)
    const distance = vec2(0).toVar()
    const position = vec3(0).toVar()

    // @ts-ignore
    Loop({ start: 0, end: this.maxSteps }, () => {
      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)
      //fogDistance.addAssign(distance.x)
    })

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

    If(accumulatedDistance.lessThan(this.cameraFar), () => {
      //If(distance.y.equal(0), () => {
      // land
      finalColour.assign(Land.render(position, normal, rayDirection, lightPosition, lightDirection, this.scene))
      // finalColour.assign(
      //   mix(
      //     finalColour,
      //     Land.render(position, normal, rayDirection, lightPosition, lightDirection, this.scene),
      //     reflectivityFactor
      //   )
      // )

      //maxReflections.assign(0) //do not calc reflections on land layer
      //})
      // .Else(() => {
      //   // ocean
      //   //normal.assign(mix(vec3(0, 1, 0), normal, exp(accumulatedDistance.pow(3).mul(-0.005))))

      //   // finalColour.assign(
      //   //   Ocean.render(finalColour, position, normal, rayDirection, lightPosition, lightDirection, this.scene)
      //   // )

      //   rayOrigin.assign(position.add(normal.mul(this.surfaceDistance)))
      //   rayDirection.assign(reflect(rayDirection, normal))
      //   //reflectivityFactor.assign(this.reflectivity)
      // })

      // fog
      finalColour.assign(Fog.render(skyColour, finalColour, accumulatedDistance))
      //finalColour.assign(Fog.render(skyColour, finalColour, fogDistance))
    })
    //})

    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
      .add(this.options, 'reflectivity', 0, 1, 0.01)
      .name('Reflectivity')
      .onChange((v) => {
        this.reflectivity.value = v
      })
    folder.close()

    ShadowMarcher.setGUI(gui)
    AmbientOcclusion.setGUI(gui)
    Land.setGUI(gui)
    //Ocean.setGUI(gui)
    //Fresnel.setGUI(gui)
    Fog.setGUI(gui)
  }
}

./src/AtmosphericScattering.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
import {
  clamp,
  mix,
  vec3,
  length,
  normalize,
  exp,
  smoothstep,
  Fn,
} from 'three/tsl'

// @ts-ignore
export const atmosphericScattering = Fn(([position, direction]) => {
  const topColour = vec3(0.1, 0.2, 0.5).mul(2)
  const midColour = vec3(1.0, 0.4, 0.2)
  const bottomColour = vec3(0.0, 0.0, 0.133)

  const t = clamp(position.y.mul(0.5).add(0.5), 0.0, 1.0) // Horizon-based gradient
  const skyColour = mix(
    mix(bottomColour, vec3(0.75, 0.85, 0.95), t).mul(3),
    vec3(0),
    t.mul(1.25)
  )

  const radius = 0.005
  const distance = length(position.sub(normalize(direction)))
  const sun = exp(distance.negate().mul(distance.div(radius)))
  skyColour.addAssign(vec3(1.0, 0.8, 0.5).mul(sun))

  // Mie scattering (orange glow near the sun)
  const mie = exp(distance.mul(3.0).pow(2.0).negate()).mul(0.5)
  const mieColor = vec3(midColour).mul(mie)
  skyColour.addAssign(mieColor.mul(1.5))

  // Rayleigh scattering (blue tint in the upper sky)
  const rayleigh = exp(position.y.mul(2.5)).mul(0.3)
  const rayleighColor = rayleigh.mul(topColour)
  skyColour.addAssign(rayleighColor)

  // Night Transition
  const nightFactor = smoothstep(-0.1, 0.1, direction.y)
  skyColour.mulAssign(nightFactor)

  return skyColour
})

./src/Ocean.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import { clamp, cos, dot, float, Fn, If, normalize, sqrt, time, uniform, vec2 } from 'three/tsl'
import * as THREE from 'three/webgpu'
import ShadowMarcher from './ShadowMarcher'
import Fresnel from './Fresnel'
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js'

export default class Ocean {
  private static options = {
    waveDirection: [0, 33, 66],
    waveSteepness: [0.02, 0.02, 0.02],
    waveLength: [0.2, 0.1, 0.05],
    waterColour: new THREE.Color(0x415474).convertLinearToSRGB()
  }

  private static waveA = uniform(
    new THREE.Vector4(
      Math.sin((this.options.waveDirection[0] * Math.PI) / 180),
      Math.cos((this.options.waveDirection[0] * Math.PI) / 180),
      this.options.waveSteepness[0],
      this.options.waveLength[0]
    )
  )
  private static waveB = uniform(
    new THREE.Vector4(
      Math.sin((this.options.waveDirection[1] * Math.PI) / 180),
      Math.cos((this.options.waveDirection[1] * Math.PI) / 180),
      this.options.waveSteepness[1],
      this.options.waveLength[1]
    )
  )
  private static waveC = uniform(
    new THREE.Vector4(
      Math.sin((this.options.waveDirection[2] * Math.PI) / 180),
      Math.cos((this.options.waveDirection[2] * Math.PI) / 180),
      this.options.waveSteepness[2],
      this.options.waveLength[2]
    )
  )

  private static waterColour = uniform(this.options.waterColour)

  //@ts-ignore
  private static gerstnerWave = Fn(([wave, p]) => {
    const steepness = wave.z
    const wavelength = wave.w
    const k = float(Math.PI * 2).div(wavelength)
    const c = sqrt(float(9.8).div(k))
    const d = normalize(wave.xy)
    const f = k.mul(d.dot(vec2(p.x, p.z)).sub(c.mul(time.div(2))))
    const a = steepness.div(k)

    return d.y.mul(a.mul(cos(f)))
  })

  //@ts-ignore
  static scene = Fn(([position]) => {
    const p = position.toVar()

    const gridPoint = position.toVar()

    p.addAssign(this.gerstnerWave(this.waveA, gridPoint))
    p.addAssign(this.gerstnerWave(this.waveB, gridPoint))
    p.addAssign(this.gerstnerWave(this.waveC, gridPoint))

    return p.y
  })

  //@ts-ignore
  static render = Fn(([baseColour, position, normal, rayDirection, lightPosition, lightDirection, scene]) => {
    //const diffuse = clamp(dot(normal, lightDirection), 0, 1).toVar()
    //diffuse.mulAssign(ShadowMarcher.render(position.add(normal.mul(0.001)), lightDirection, scene))
    //diffuse.mulAssign(Fresnel.render(rayDirection.negate(), normal))

    return baseColour//.mul(this.waterColour)//.mul(diffuse)
  })

  static setGUI(gui: GUI) {
    const folder = gui.addFolder('Ocean')
    folder.addColor(this.options, 'waterColour').name('Colour')

    const folderA = folder.addFolder('Wave A')
    folderA
      .add(this.options.waveDirection, 0, 0, 359)
      .name('Direction')
      .onChange((v) => {
        const x = (v * Math.PI) / 180
        this.waveA.value.x = Math.sin(x)
        this.waveA.value.y = Math.cos(x)
      })
    folderA
      .add(this.options.waveSteepness, 0, 0, 1, 0.01)
      .name('Steepness')
      .onChange((v) => {
        this.waveA.value.z = v
      })
    folderA
      .add(this.options.waveLength, 0, 1, 10)
      .name('Wavelength')
      .onChange((v) => {
        this.waveA.value.w = v
      })
    folderA.close()

    const folderB = folder.addFolder('Wave B')
    folderB
      .add(this.options.waveDirection, 1, 0, 359)
      .name('Direction')
      .onChange((v) => {
        const x = (v * Math.PI) / 180
        this.waveB.value.x = Math.sin(x)
        this.waveB.value.y = Math.cos(x)
      })
    folderB
      .add(this.options.waveSteepness, 1, 0, 1, 0.01)
      .name('Steepness')
      .onChange((v) => {
        this.waveB.value.z = v
      })
    folderB
      .add(this.options.waveLength, 1, 1, 10)
      .name('Wavelength')
      .onChange((v) => {
        this.waveB.value.w = v
      })
    folderB.close()

    const folderC = folder.addFolder('Wave C')
    folderC
      .add(this.options.waveDirection, 2, 0, 359)
      .name('Direction')
      .onChange((v) => {
        const x = (v * Math.PI) / 180
        this.waveC.value.x = Math.sin(x)
        this.waveC.value.y = Math.cos(x)
      })
    folderC
      .add(this.options.waveSteepness, 2, 0, 1, 0.01)
      .name('Steepness')
      .onChange((v) => {
        this.waveC.value.z = v
      })
    folderC
      .add(this.options.waveLength, 2, 1, 10)
      .name('Wavelength')
      .onChange((v) => {
        this.waveC.value.w = v
      })
    folderC.close()

    folder.close()
  }
}

./src/Fresnel.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
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js'
import { uniform, Fn, dot, pow, sub } from 'three/tsl'

export default class Fresnel {
  private static options = {
    power: 1
    //bias: 0,
    //scale: 1
  }

  private static power = uniform(this.options.power)
  // private static bias = uniform(this.options.bias)
  // private static scale = uniform(this.options.scale)

  // @ts-ignore
  static render = Fn(([viewDirection, normal]) => {
    return dot(viewDirection, normal).oneMinus().pow(this.power)
    //return this.bias.add(this.scale).mul(dot(viewDirection, normal).oneMinus().pow(power))
  })

  static setGUI(gui: GUI) {
    const folder = gui.addFolder('Fresnel')
    folder
      .add(this.options, 'power', 0, 10, 0.001)
      .name('Power')
      .onChange((v) => {
        this.power.value = v
      })

    folder.close()
  }
}

Final Scripts

./src/Land.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
import { abs, clamp, cos, dot, float, Fn, If, Loop, mat2, mix, sin, smoothstep, uniform, vec3 } from 'three/tsl'
import * as THREE from 'three/webgpu'
import AmbientOcclusion from './AmbientOcclusion'
import ShadowMarcher from './ShadowMarcher'
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js'

export default class Land {
  private static options = {
    octaves: 8,
    lacunarity: 2.15,
    gain: 0.35,
    factorA: 0.19,
    colour1: new THREE.Color(0xdfff00).convertLinearToSRGB(),
    colour2: new THREE.Color(0xffffff).convertLinearToSRGB()
  }

  private static octaves = uniform(this.options.octaves)
  private static lacunarity = uniform(this.options.lacunarity)
  private static gain = uniform(this.options.gain)
  private static factorA = uniform(this.options.factorA)
  private static colour1 = uniform(this.options.colour1)
  private static colour2 = uniform(this.options.colour2)

  // @ts-ignore
  private static noise = Fn(([position]) => {
    return sin(position.x).add(sin(position.y))
  })

  // @ts-ignore
  private static rotate = Fn(([radians]) => {
    const a = sin(radians)
    const b = cos(radians)
    return mat2(b, a.negate(), a, b)
  })

  // @ts-ignore
  private static fbm = Fn(([position]) => {
    const p = position.xz.toVar()
    const accumulator = float(0.0).toVar()
    const amplitude = float(this.gain).toVar()

    Loop({ start: 0, end: this.octaves, condition: '<' }, () => {
      accumulator.addAssign(amplitude.mul(this.noise(p)))
      amplitude.mulAssign(this.gain)
      p.mulAssign(this.lacunarity.mul(this.rotate(this.factorA)))
    })

    return accumulator
  })

  //@ts-ignore
  static scene = Fn(([position]) => {
    const p = position.mul(0.5)

    const height = this.fbm(p)

    height.assign(height.mul(cos(p.x.mul(0.25))))
    height.assign(height.mul(cos(p.z.mul(0.25))))
    height.mulAssign(3.3)
    height.subAssign(0.1)

    return p.y.sub(height)
  })

  //@ts-ignore
  static render = Fn(([position, normal, rayDirection, lightPosition, lightDirection, scene]) => {
    const colour = this.colour1.toVar()

    const steepness = float(abs(normal.y).oneMinus()).toVar()
    colour.assign(mix(colour, this.colour2, smoothstep(0.1, 0.7, steepness)))
    colour.assign(mix(colour, this.colour2, smoothstep(0, 1.0, position.y.sub(2))))

    const diffuse = clamp(dot(normal, lightDirection), 0, 1).toVar()
    diffuse.mulAssign(ShadowMarcher.render(position.add(normal.mul(0.001)), vec3(lightDirection), scene))
    diffuse.mulAssign(AmbientOcclusion.render(position, normal, scene))

    return colour.mul(diffuse)
  })

  static setGUI(gui: GUI) {
    const folder = gui.addFolder('Land')
    folder
      .add(this.options, 'octaves', 0, 10, 1)
      .name('Octaves')
      .onChange((v) => {
        this.octaves.value = v
      })
    folder
      .add(this.options, 'lacunarity', 1, 10, 0.01)
      .name('Lacunarity')
      .onChange((v) => {
        this.lacunarity.value = v
      })
    folder
      .add(this.options, 'gain', 0.01, 1.99, 0.01)
      .name('Gain')
      .onChange((v) => {
        this.gain.value = v
      })
    folder
      .add(this.options, 'factorA', 0, Math.PI / 2, 0.01)
      .name('Factor A')
      .onChange((v) => {
        this.factorA.value = v
      })

    folder.addColor(this.options, 'colour1').name('Colour 1')
    folder.addColor(this.options, 'colour2').name('Colour 2')

    folder.close()
  }
}

./src/Ocean.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import { clamp, cos, dot, float, Fn, If, normalize, sqrt, time, uniform, vec2 } from 'three/tsl'
import * as THREE from 'three/webgpu'
import ShadowMarcher from './ShadowMarcher'
import Fresnel from './Fresnel'
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js'

export default class Ocean {
  private static options = {
    waveDirection: [0, 33, 66],
    waveSteepness: [0.02, 0.02, 0.02],
    waveLength: [0.2, 0.1, 0.05],
    waterColour: new THREE.Color(0x415474).convertLinearToSRGB()
  }

  private static waveA = uniform(
    new THREE.Vector4(
      Math.sin((this.options.waveDirection[0] * Math.PI) / 180),
      Math.cos((this.options.waveDirection[0] * Math.PI) / 180),
      this.options.waveSteepness[0],
      this.options.waveLength[0]
    )
  )
  private static waveB = uniform(
    new THREE.Vector4(
      Math.sin((this.options.waveDirection[1] * Math.PI) / 180),
      Math.cos((this.options.waveDirection[1] * Math.PI) / 180),
      this.options.waveSteepness[1],
      this.options.waveLength[1]
    )
  )
  private static waveC = uniform(
    new THREE.Vector4(
      Math.sin((this.options.waveDirection[2] * Math.PI) / 180),
      Math.cos((this.options.waveDirection[2] * Math.PI) / 180),
      this.options.waveSteepness[2],
      this.options.waveLength[2]
    )
  )

  private static waterColour = uniform(this.options.waterColour)

  //@ts-ignore
  private static gerstnerWave = Fn(([wave, p]) => {
    const steepness = wave.z
    const wavelength = wave.w
    const k = float(Math.PI * 2).div(wavelength)
    const c = sqrt(float(9.8).div(k))
    const d = normalize(wave.xy)
    const f = k.mul(d.dot(vec2(p.x, p.z)).sub(c.mul(time.div(2))))
    const a = steepness.div(k)

    return d.y.mul(a.mul(cos(f)))
  })

  //@ts-ignore
  static scene = Fn(([position]) => {
    const p = position.toVar()

    const gridPoint = position.toVar()

    p.addAssign(this.gerstnerWave(this.waveA, gridPoint))
    p.addAssign(this.gerstnerWave(this.waveB, gridPoint))
    p.addAssign(this.gerstnerWave(this.waveC, gridPoint))

    return p.y
  })

  //@ts-ignore
  static render = Fn(([baseColour, position, normal, rayDirection, lightPosition, lightDirection, scene]) => {
    const diffuse = clamp(dot(normal, lightDirection), 0, 1).toVar()
    diffuse.mulAssign(ShadowMarcher.render(position.add(normal.mul(0.001)), lightDirection, scene))
    diffuse.mulAssign(Fresnel.render(rayDirection.negate(), normal))

    return baseColour.mul(this.waterColour).mul(diffuse)
  })

  static setGUI(gui: GUI) {
    const folder = gui.addFolder('Ocean')
    folder.addColor(this.options, 'waterColour').name('Colour')

    const folderA = folder.addFolder('Wave A')
    folderA
      .add(this.options.waveDirection, 0, 0, 359)
      .name('Direction')
      .onChange((v) => {
        const x = (v * Math.PI) / 180
        this.waveA.value.x = Math.sin(x)
        this.waveA.value.y = Math.cos(x)
      })
    folderA
      .add(this.options.waveSteepness, 0, 0, 1, 0.01)
      .name('Steepness')
      .onChange((v) => {
        this.waveA.value.z = v
      })
    folderA
      .add(this.options.waveLength, 0, 1, 10)
      .name('Wavelength')
      .onChange((v) => {
        this.waveA.value.w = v
      })
    folderA.close()

    const folderB = folder.addFolder('Wave B')
    folderB
      .add(this.options.waveDirection, 1, 0, 359)
      .name('Direction')
      .onChange((v) => {
        const x = (v * Math.PI) / 180
        this.waveB.value.x = Math.sin(x)
        this.waveB.value.y = Math.cos(x)
      })
    folderB
      .add(this.options.waveSteepness, 1, 0, 1, 0.01)
      .name('Steepness')
      .onChange((v) => {
        this.waveB.value.z = v
      })
    folderB
      .add(this.options.waveLength, 1, 1, 10)
      .name('Wavelength')
      .onChange((v) => {
        this.waveB.value.w = v
      })
    folderB.close()

    const folderC = folder.addFolder('Wave C')
    folderC
      .add(this.options.waveDirection, 2, 0, 359)
      .name('Direction')
      .onChange((v) => {
        const x = (v * Math.PI) / 180
        this.waveC.value.x = Math.sin(x)
        this.waveC.value.y = Math.cos(x)
      })
    folderC
      .add(this.options.waveSteepness, 2, 0, 1, 0.01)
      .name('Steepness')
      .onChange((v) => {
        this.waveC.value.z = v
      })
    folderC
      .add(this.options.waveLength, 2, 1, 10)
      .name('Wavelength')
      .onChange((v) => {
        this.waveC.value.w = v
      })
    folderC.close()

    folder.close()
  }
}

./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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import {
  Break,
  cos,
  float,
  If,
  Loop,
  normalize,
  sin,
  time,
  uniform,
  vec2,
  vec3,
  Fn,
  positionLocal,
  reflect,
  mix,
  exp,
  int,
  abs
} from 'three/tsl'
import { atmosphericScattering } from './AtmosphericScattering'
import Land from './Land'
import ShadowMarcher from './ShadowMarcher'
import AmbientOcclusion from './AmbientOcclusion'
import Fog from './Fog'
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js'
import Ocean from './Ocean'
import Fresnel from './Fresnel'

export default class SDFScene {
  private static options = {
    maxSteps: 384,
    surfaceDistance: 0.005,
    cameraNear: 0.01,
    cameraFar: 192.0,
    reflectivity: 0.5
  }

  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 reflectivity = uniform(this.options.reflectivity)

  // @ts-ignore
  private static scene = Fn(([position]) => {
    const land = Land.scene(position)

    const ocean = Ocean.scene(position)

    const distance = vec2(land, 0).toVar()
    If(distance.x.greaterThan(ocean), () => {
      distance.assign(vec2(ocean, 1))
    })

    return distance
  })

  // @ts-ignore
  private static getNormal = Fn(([position, distance]) => {
    const offset = vec2(0.0001, 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
        )
      )
    )
  })

  // @ts-ignore
  static render = Fn(([rayOrigin_immutable]) => {
    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))

    const skyColour = atmosphericScattering(vec3(p.x, abs(p.y), p.z), normalize(lightPosition)).toVar()
    const finalColour = skyColour.toVar()

    const reflectivityFactor = float(1.0).toVar()

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

    const maxReflections = int(1).toVar()
    Loop({ start: 0, end: maxReflections, condition: '<=' }, () => {
      accumulatedDistance.assign(0)
      const distance = vec2(0).toVar()
      const position = vec3(0).toVar()

      // @ts-ignore
      Loop({ start: 0, end: this.maxSteps }, () => {
        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)
        fogDistance.addAssign(distance.x)
      })

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

      If(accumulatedDistance.lessThan(this.cameraFar), () => {
        If(distance.y.equal(0), () => {
          // land
          finalColour.assign(
            mix(
              finalColour,
              Land.render(position, normal, rayDirection, lightPosition, lightDirection, this.scene),
              reflectivityFactor
            )
          )

          maxReflections.assign(0) //do not calc reflections on land layer
        }).Else(() => {
          // ocean
          normal.assign(mix(vec3(0, 1, 0), normal, exp(accumulatedDistance.pow(3).mul(-0.005))))

          finalColour.assign(
            Ocean.render(finalColour, position, normal, rayDirection, lightPosition, lightDirection, this.scene)
          )

          rayOrigin.assign(position.add(normal.mul(this.surfaceDistance)))
          rayDirection.assign(reflect(rayDirection, normal))
          reflectivityFactor.assign(this.reflectivity)
        })

        // fog
        finalColour.assign(Fog.render(skyColour, finalColour, fogDistance))
      })
    })

    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
      .add(this.options, 'reflectivity', 0, 1, 0.01)
      .name('Reflectivity')
      .onChange((v) => {
        this.reflectivity.value = v
      })
    folder.close()

    ShadowMarcher.setGUI(gui)
    AmbientOcclusion.setGUI(gui)
    Land.setGUI(gui)
    Ocean.setGUI(gui)
    Fresnel.setGUI(gui)
    Fog.setGUI(gui)
  }
}

FBM Ocean