Algorithm Search⌘K

Algorithmcore

Tessendorf FFT ocean synthesis

Also called FFT ocean waves, statistical ocean wave synthesis.

Fill a frequency grid with random amplitudes from an ocean spectrum such as Phillips, advance phases by the dispersion relation, and invert by FFT.

Time
O(N^2 log N) frameO(N^2) setup
Space
O(N^2) extra
Where
N = the number of grid points along one side of the patch
Properties
deterministicnot exactnot needs simulationperiodicreal output
Origin
Jerry Tessendorf, Gary Mastin, Peter Watterberg, John Mareda, 2001

FFT ocean synthesis makes an animated patch of deep ocean as a sum of many thousands of sine waves, one for each point of a frequency grid. Each wave gets a random amplitude whose size comes from an ocean wave spectrum, often the Phillips spectrum, and a speed from the deep water dispersion relation ω2=gk\omega^2 = g k. One inverse fast Fourier transform per frame then gives the heights at all N2N^2 grid points in O(N2log⁡N)O(N^2 \log N) time. Mastin, Watterberg and Mareda (1987) used this idea for images of the sea, and Tessendorf (2001) made it a standard method for ocean surfaces in film and games, with the motion in time and a horizontal "choppy" displacement. There is no simulation: each frame comes from a closed formula, and the patch repeats in space, so it tiles.

In plain words

The sea far from the coast looks like many waves of different lengths that run in different directions and pass through each other. Long waves run faster than short ones. The method picks a large set of wave lengths and directions on a regular grid, gives each one a random size, with more size for the waves that the wind makes most, and lets each wave run at its own speed. To find the height of the water at every point of the grid, it adds up all the waves, and the fast Fourier transform does this sum for all points at once. A small sideways push of each point makes the crests sharper.

The problem

The input is the patch size LL (m), the grid size NN (a power of 2), the wind direction w^\hat w and speed VV (m/s), a spectrum scale AA, gravity g=9.81g = 9.81 m/s², a random seed, the frame times tt and a choppiness λ≥0\lambda \ge 0. The output, for each frame, is the height hh and the horizontal displacement DD at the grid points x=(aL/N,bL/N)x = (aL/N, bL/N), 0≤a,b<N0 \le a, b < N. The wave vectors are k=(2πn′/L,2πm′/L)k = (2\pi n'/L, 2\pi m'/L) for the signed indices −N/2≤n′,m′<N/2-N/2 \le n', m' < N/2, and

h(x,t)=∑kH(k,t) eik⋅x,H(k,t)=h0(k) eiω(k)t+h0(−k)‾ e−iω(k)t,ω(k)=(g∣k∣)1/2.h(x, t) = \sum_k H(k, t)\, e^{i k\cdot x}, \qquad H(k, t) = h_0(k)\, e^{i\omega(k) t} + \overline{h_0(-k)}\, e^{-i\omega(k) t}, \qquad \omega(k) = (g |k|)^{1/2}.

The initial amplitudes are h0(k)=(ξr+iξi)(P(k)/2)1/2h_0(k) = (\xi_r + i\xi_i)(P(k)/2)^{1/2} with independent standard normal ξr,ξi\xi_r, \xi_i. The Phillips spectrum, in the form of Tessendorf, is

P(k)=A e−1/(∣k∣ℓ)2∣k∣4 ∣k^⋅w^∣2,ℓ=V2/g.P(k) = A\, \frac{e^{-1/(|k| \ell)^2}}{|k|^4}\, |\hat k\cdot\hat w|^2, \qquad \ell = V^2/g.

The dispersion relation ω2=gk\omega^2 = g k is the law for small waves on deep water. The Phillips spectrum is a fit, not a law: it approximates the spectrum of a wind sea in deep water, with the ∣k∣−4|k|^{-4} fall of the equilibrium range of Phillips (1958) at short waves, a cut at waves longer than about ℓ\ell, the largest waves that a steady wind of speed VV can raise, and a factor that removes waves that run across the wind. This is one method for fluid simulation for animation.

The algorithm

  1. FFT-OCEAN(L, N, ŵ, V, A, seed, times, λ)
  2. 1for each k on the grid: h₀(k) ← (ξ_r + i ξ_i)(P(k)/2)^½, with ξ from the seeded generator
  3. 2for each frame time t
  4. 3for each k: H(k, t) ← h₀(k) e^{iω(k)t} + conj(h₀(-k)) e^{-iω(k)t}
  5. 4h ← inverse 2D FFT of H
  6. 5D ← inverse 2D FFT of -i λ (k/|k|) H
  7. 6output the points x + D with the heights h

Line L1 runs once. It draws two normal numbers for each grid point, so a fixed seed gives the same ocean each time. The code sets h0h_0 to 0 on the row and the column of the index N/2N/2, where kk and −k-k fall on the same grid point; this keeps the displacement of line L5 real, and it is a choice of this code. Line L3 moves each wave forward in time: the factor eiωte^{i\omega t} turns its phase at the rate of the dispersion relation, and the second term is the partner wave that makes H(−k)=H(k)‾H(-k) = \overline{H(k)}. That symmetry makes the height real. Line L4 is the inverse 2D DFT, done by a 1D FFT on each row and then on each column, with no factor 1/N21/N^2. Line L5 is optional: it moves each point toward the crests and away from the troughs, which makes the crests sharp and the troughs flat, as a Gerstner wave does. The code writes its own radix-2 FFT, and the test compares it with a direct sum.

Example

Take L=100L = 100 m, V=10V = 10 m/s (so ℓ=10.19\ell = 10.19 m), the wind along xx, A=3⋅10−6A = 3\cdot 10^{-6}, seed 3, and t=0t = 0. For each NN, the table gives the largest imaginary part of the computed height, the largest difference from a direct evaluation of the sum, the measured root mean square height, the expected value (∑k2P(k))1/2(\sum_k 2P(k))^{1/2} from the proof, and the time of one height field in this pure Python code.

NN max ∣Im⁡h∣\lvert\operatorname{Im} h\rvert (m) max difference from the direct sum (m) measured RMS height (m) expected RMS height (m) FFT time (s) direct sum time (s)
8 3.5e-16 1.3e-15 0.535 0.475 0.0001 0.002
16 3.7e-16 2.2e-15 0.533 0.504 0.0005 0.029
32 3.6e-16 4.0e-15 0.622 0.510 0.002 0.88
64 7.3e-16 not run 0.769 0.512 0.014 not run

The imaginary part is rounding only, and the FFT gives the same heights as the direct sum. The measured RMS height of one random ocean differs from the expected value because a few long waves near the peak of the spectrum carry most of the energy. The direct sum costs N4N^4 terms, so it is several hundred times slower at N=32N = 32.

One wave of wavelength 10 m has k=0.628319k = 0.628319 rad/m, ω=2.482701\omega = 2.482701 rad/s, the period 2.5307862.530786 s and the phase speed ω/k=3.951342\omega/k = 3.951342 m/s. On this patch it is the wave of index 10, and it needs N≥32N \ge 32.

Correctness

The proof shows these facts in exact arithmetic, and the tests check them:

  • FFT. The radix-2 FFT of the code equals the DFT.
  • Real height. H(−k,t)=H(k,t)‾H(-k, t) = \overline{H(k, t)} for every kk and tt, so the inverse DFT is real. With the Nyquist row and column set to 0, the displacement is real too.
  • The sum. At the grid points, the inverse 2D DFT of line L4 equals the sum ∑kH(k,t)eik⋅x\sum_k H(k, t) e^{ik\cdot x} with the signed wave vectors.
  • One wave. A single h0(k)h_0(k) gives the height 2Re⁡(h0(k)ei(k⋅x+ωt))2\operatorname{Re}(h_0(k) e^{i(k\cdot x + \omega t)}), a cosine wave that runs at the speed ω/∣k∣\omega/|k|.
  • Statistics. The mean height is 0, and the expected square height is ∑k2P(k)\sum_k 2P(k) at every point and every time.

Whether the result looks like a real sea is not a claim of this page; it depends on the spectrum.

Proof: The FFT, the real height and the statistics of FFT ocean synthesisfull

We use the notation of the page, with exact arithmetic. The grid indices are 0≤n,m<N0 \le n, m < N with NN a power of 2, and the signed index is n′=nn' = n for n<N/2n < N/2 and n′=n−Nn' = n - N otherwise, so n′≡n(modN)n' \equiv n \pmod N. The wave vector of (n,m)(n, m) is knm=(2πn′/L,2πm′/L)k_{nm} = (2\pi n'/L, 2\pi m'/L), and −k-k means the index ((−n) mod N,(−m) mod N)((-n) \bmod N, (-m) \bmod N). For every index pair except the Nyquist row and column (n=N/2n = N/2 or m=N/2m = N/2), k−n,−m=−knmk_{-n,-m} = -k_{nm}. On the Nyquist row and column the code sets h0=0h_0 = 0, so H=0H = 0 there by line L3. The grid points are xab=(aL/N,bL/N)x_{ab} = (aL/N, bL/N).

The FFT

Claim 1. For NN a power of 2, fft(a) returns Aq=∑j<NajωNjqA_q = \sum_{j<N} a_j \omega_N^{jq} with ωN=e−2πi/N\omega_N = e^{-2\pi i/N}, and with ωN=e+2πi/N\omega_N = e^{+2\pi i/N} for the inverse.

Proof. For N=1N = 1 the code returns aa. For N>1N > 1, split the sum into the even and odd jj: Aq=Eq+ωNqOqA_q = E_q + \omega_N^q O_q and Aq+N/2=Eq−ωNqOqA_{q + N/2} = E_q - \omega_N^q O_q for q<N/2q < N/2, where EE and OO are the DFTs of length N/2N/2 of the even and odd entries, because ωN2=ωN/2\omega_N^2 = \omega_{N/2} and ωNN/2=−1\omega_N^{N/2} = -1. The bit reversal puts the even entries in the first half and the odd entries in the second half, each half again in bit reversed order. By induction on the length, after the passes with block sizes up to N/2N/2, the two halves hold EE and OO. The last pass, with block size NN, computes Eq±wOqE_q \pm w O_q with w=ωNqw = \omega_N^q for q=0,…,N/2−1q = 0, \dots, N/2 - 1, which is the split above. □\square

The 2D transform of the code applies Claim 1 to each row and then to each column, which is the 2D DFT ∑n,mGnm ωN±(na+mb)\sum_{n, m} G_{nm}\, \omega_N^{\pm(na + mb)} because the 2D kernel is the product of two 1D kernels.

The height is real

Claim 2. H(−k,t)=H(k,t)‾H(-k, t) = \overline{H(k, t)} for every index and every tt.

Proof. ω\omega depends on ∣k∣|k| only, and ∣k−n,−m∣=∣knm∣|k_{-n,-m}| = |k_{nm}| on every index. So H(−k,t)=h0(−k)eiωt+h0(k)‾ e−iωtH(-k, t) = h_0(-k) e^{i\omega t} + \overline{h_0(k)}\, e^{-i\omega t}, and H(k,t)‾=h0(k)‾ e−iωt+h0(−k)eiωt\overline{H(k, t)} = \overline{h_0(k)}\, e^{-i\omega t} + h_0(-k) e^{i\omega t}. These are equal. □\square

Claim 3. At the grid points, the inverse 2D DFT of line L4 equals h(xab,t)=∑kH(k,t)eik⋅xabh(x_{ab}, t) = \sum_k H(k, t) e^{i k\cdot x_{ab}}, and this value is real.

Proof. eiknm⋅xab=e2πi(n′a+m′b)/N=e2πi(na+mb)/Ne^{i k_{nm}\cdot x_{ab}} = e^{2\pi i (n'a + m'b)/N} = e^{2\pi i (na + mb)/N} because n′≡nn' \equiv n and m′≡m(modN)m' \equiv m \pmod N, so the sum is the inverse DFT of Claim 1 with no factor. For its conjugate, h‾=∑n,mHnm‾ e−2πi(na+mb)/N\overline{h} = \sum_{n, m} \overline{H_{nm}}\, e^{-2\pi i(na + mb)/N}. Put n→(−n) mod Nn \to (-n) \bmod N and m→(−m) mod Nm \to (-m) \bmod N, a bijection of the indices: by Claim 2 the term becomes Hnme2πi(na+mb)/NH_{nm} e^{2\pi i(na + mb)/N}, so h‾=h\overline h = h. □\square

Claim 4. The displacement of line L5 is real.

Proof. Let S(k)=−iλ(k/∣k∣)H(k)S(k) = -i\lambda (k/|k|) H(k) for k≠0k \ne 0 and S(0)=0S(0) = 0. Off the Nyquist row and column, k−n,−m=−knmk_{-n,-m} = -k_{nm}, so S(−k)=iλ(k/∣k∣)H(k)‾=S(k)‾S(-k) = i\lambda (k/|k|)\overline{H(k)} = \overline{S(k)} by Claim 2. On the Nyquist row and column, H=0H = 0, so S=0S = 0 at both kk and −k-k. So SS has the symmetry of Claim 2 in each component, and the argument of Claim 3 makes its inverse DFT real. □\square

One wave

Claim 5. If h0h_0 is 0 except at one index kk off the Nyquist row and column with k≠0k \ne 0, then h(x,t)=2Re⁡(h0(k)ei(k⋅x+ωt))h(x, t) = 2\operatorname{Re}(h_0(k) e^{i(k\cdot x + \omega t)}), a cosine wave that runs in the direction −k^-\hat k at the speed ω/∣k∣=(g/∣k∣)1/2\omega/|k| = (g/|k|)^{1/2}.

Proof. Only H(k)=h0(k)eiωtH(k) = h_0(k) e^{i\omega t} and H(−k)=h0(k)‾ e−iωtH(-k) = \overline{h_0(k)}\, e^{-i\omega t} are not 0. With k−n,−m=−kk_{-n,-m} = -k, the sum is h0(k)ei(k⋅x+ωt)+h0(k)ei(k⋅x+ωt)‾h_0(k) e^{i(k\cdot x + \omega t)} + \overline{h_0(k) e^{i(k\cdot x + \omega t)}}, which is twice the real part. The phase k⋅x+ωtk\cdot x + \omega t is constant on points that move with the velocity −(ω/∣k∣)k^-(\omega/|k|)\hat k. □\square

In the same way, each h0(k)h_0(k) gives a wave in the direction −k^-\hat k, and each h0(−k)‾\overline{h_0(-k)} term gives one in the direction k^\hat k.

Statistics

Claim 6. The mean of hh over the grid points is 0, and for every grid point and every tt, E[h(x,t)]=0E[h(x, t)] = 0 and E[h(x,t)2]=∑k2P(k)E[h(x, t)^2] = \sum_k 2P(k), summed over the indices off the Nyquist row and column.

Proof. P(0)=0P(0) = 0, so h0(0)=0h_0(0) = 0 and H(0)=0H(0) = 0; the mean over the grid is N−2∑a,bh=H(0)=0N^{-2}\sum_{a, b} h = H(0) = 0, since ∑ae2πina/N=0\sum_{a} e^{2\pi i na/N} = 0 for n≠0n \ne 0. The values h0(k)h_0(k) are independent for different indices, with E[h0]=0E[h_0] = 0, E[∣h0∣2]=P2E[ξr2+ξi2]=PE[|h_0|^2] = \frac{P}{2}E[\xi_r^2 + \xi_i^2] = P and E[h02]=P2E[ξr2−ξi2+2iξrξi]=0E[h_0^2] = \frac P2 E[\xi_r^2 - \xi_i^2 + 2i\xi_r\xi_i] = 0. So E[h]=0E[h] = 0. Since hh is real, h2=hh‾=∑k,k′H(k)H(k′)‾ ei(k−k′)⋅xh^2 = h\overline h = \sum_{k, k'} H(k)\overline{H(k')}\, e^{i(k - k')\cdot x}. If k′≠±kk' \ne \pm k, H(k)H(k) and H(k′)H(k') depend on disjoint sets of independent values with mean 0, so E[H(k)H(k′)‾]=0E[H(k)\overline{H(k')}] = 0. If k′=k≠0k' = k \ne 0, E∣H(k)∣2=E∣h0(k)∣2+E∣h0(−k)∣2+2Re⁡(E[h0(k)h0(−k)]e2iωt)=P(k)+P(−k)=2P(k)E|H(k)|^2 = E|h_0(k)|^2 + E|h_0(-k)|^2 + 2\operatorname{Re}(E[h_0(k) h_0(-k)] e^{2i\omega t}) = P(k) + P(-k) = 2P(k), because h0(k)h_0(k) and h0(−k)h_0(-k) are independent with mean 0 and PP is even. If k′=−k≠kk' = -k \ne k, then H(−k)‾=H(k)\overline{H(-k)} = H(k) and E[H(k)2]=E[h0(k)2]e2iωt+2E[h0(k)h0(−k)‾]+E[h0(−k)‾2]e−2iωt=0E[H(k)^2] = E[h_0(k)^2] e^{2i\omega t} + 2E[h_0(k)\overline{h_0(-k)}] + E[\overline{h_0(-k)}^2] e^{-2i\omega t} = 0. So only the terms k′=kk' = k remain, and they give ∑k2P(k)\sum_k 2P(k), with no dependence on xx or tt. □\square

The peak of the spectrum

Claim 7. Along the wind (k^=w^\hat k = \hat w), PP is largest at ∣k∣=1/(2 ℓ)|k| = 1/(\sqrt 2\,\ell).

Proof. With κ=∣k∣\kappa = |k|, ln⁡P=ln⁡A−1/(κℓ)2−4ln⁡κ\ln P = \ln A - 1/(\kappa\ell)^2 - 4\ln\kappa, whose derivative 2/(κ3ℓ2)−4/κ2/(\kappa^3\ell^2) - 4/\kappa is positive for κ2<1/(2ℓ2)\kappa^2 < 1/(2\ell^2) and negative after. ■\blacksquare

Complexity

Line L1 costs O(N2)O(N^2) once. Each frame costs O(N2)O(N^2) for line L3 and O(N2log⁡N)O(N^2 \log N) for each 2D FFT of lines L4 and L5: NN row transforms and NN column transforms of length NN. The memory is O(N2)O(N^2). A direct sum would cost O(N4)O(N^4) per frame. The FFTs are the main cost, and they run well on a GPU.

Properties

  • Periodic. The height is periodic with the period LL in xx and in yy, because every wave vector is a multiple of 2π/L2\pi/L (proved). The patch tiles with no seam, but the repetition can show from far away.
  • No simulation. Each frame comes from h0h_0 and tt alone, so any frame can be made at once, in any order (proved from the formula).
  • Dispersion. Each wave runs at the deep water phase speed (g/∣k∣)1/2(g/|k|)^{1/2}, so long waves overtake short ones (a law of the model).
  • Stationary statistics. The expected square height does not depend on tt (proved). One random ocean still changes its RMS height a little in time (measured).
  • Both directions. P(k)=P(−k)P(k) = P(-k), so the code makes as many waves that run against the wind as with it (proved from the formula).
  • Peak. Along the wind, PP is largest at ∣k∣ℓ=1/2|k|\ell = 1/\sqrt 2, the wavelength 2π2 ℓ2\pi\sqrt 2\, \ell, which is 90.6 m for V=10V = 10 m/s (proved).

Variants and improvements

  • Other spectra. Measured ocean spectra such as JONSWAP or Pierson-Moskowitz in place of Phillips give other shapes of the sea. Each is a fit to measurements.
  • Finite depth. ω2=gktanh⁡(kd)\omega^2 = g k \tanh(k d) for the depth dd slows the long waves. The code has this as an option of its dispersion function.
  • Looping in time. Rounding each ω\omega to a multiple of 2π/T2\pi/T makes the animation repeat with the period TT.
  • Small wave cut. A factor e−∣k∣2s2e^{-|k|^2 s^2} removes waves much shorter than ss; the code has it as the option small.
  • One direction. Setting P(k)=0P(k) = 0 for k^⋅w^<0\hat k\cdot\hat w < 0 removes the waves that run against the wind.
  • Cascades. Several patches of different sizes, added together, hide the repetition of one patch.
  • Normals and foam. The slope ∇h\nabla h is one more inverse FFT of ikHi k H. The Jacobian of x↦x+Dx \mapsto x + D falls below 0 where the choppy surface folds, which is a common place to put foam.

When to use it

Use FFT ocean synthesis for open deep water seen from a ship, a plane or a shore far away, where the waves are not affected by objects. For a few wave trains with direct control, Gerstner waves are simpler. For water that reacts to objects or to a coast, use height field water or the shallow water equations, maybe on top of this method.

Pitfalls

  • Height not real. If line L3 uses only h0(k)eiωth_0(k) e^{i\omega t}, without the partner term, HH is not Hermitian and the inverse FFT has a large imaginary part.
  • Wrong wave vectors. The FFT stores the negative frequencies in the upper half of the indices. Using the index nn in place of n−Nn - N for n≥N/2n \ge N/2 in lines L1 and L3 gives wrong speeds and wrong directions.
  • The Nyquist row. At the index N/2N/2, kk and −k-k are the same grid point, and the factor −ik/∣k∣-ik/|k| of line L5 is not odd there, so the displacement gets an imaginary part. Set h0h_0 to 0 there, as the code does.
  • Scale of the FFT. Some FFT libraries divide the inverse by N2N^2. Then the amplitudes in line L1 must be multiplied by N2N^2, or the waves are far too small.
  • Too much chop. A large λ\lambda in line L5 folds the surface over itself near the crests.
  • Patch size and wind speed do not match. The longest wave on the patch is LL and the shortest is 2L/N2L/N. If the peak wavelength 2π2 ℓ2\pi\sqrt 2\,\ell of line L1 is longer than LL, the main waves of the spectrum are not on the grid.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

fft_ocean_synthesis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fft-ocean-synthesis/. The authors are listed in prov/6YE8FD.jsonl.
"""FFT ocean synthesis in the style of Tessendorf (2001), on an N by N grid.

The patch has the side length L (m) and is periodic. The wave vector of the
index (n, m) is k = (2 pi n' / L, 2 pi m' / L), where n' = n for n < N/2 and
n' = n - N otherwise (the order of the FFT). The height is

    h(x, t) = sum_k H(k, t) exp(i k . x),
    H(k, t) = h0(k) exp(i w(k) t) + conj(h0(-k)) exp(-i w(k) t),

with the deep water dispersion w(k) = (g |k|)^(1/2) and the initial
amplitudes h0(k) = (xi_r + i xi_i) (P(k) / 2)^(1/2) from two standard normal
numbers and the Phillips spectrum P. Because H(-k) = conj(H(k)), the height is
real. The sum has no factor 1/N^2, as in the notes of Tessendorf.

This file sets h0 to 0 on the Nyquist row and column (n = N/2 or m = N/2),
so that the choppy displacement is real too. This is a choice of this file.
"""

import cmath
import math

G = 9.81


def fft(a, inverse=False):
    """The radix-2 DFT of a list of complex numbers whose length is a power of 2.

    Forward: A_k = sum_n a_n exp(-2 pi i n k / N). Inverse: the same with
    exp(+2 pi i n k / N), with no factor 1/N. Returns a new list.
    """
    n = len(a)
    if n & (n - 1):
        raise ValueError("the length must be a power of 2")
    out = list(a)
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            out[i], out[j] = out[j], out[i]
    sign = 1.0 if inverse else -1.0
    size = 2
    while size <= n:
        w_step = cmath.exp(sign * 2j * math.pi / size)
        half = size // 2
        for start in range(0, n, size):
            w = 1.0 + 0.0j
            for k in range(start, start + half):
                t = w * out[k + half]
                out[k + half] = out[k] - t
                out[k] = out[k] + t
                w *= w_step
        size *= 2
    return out


def fft2(grid, inverse=False):
    """The 2D DFT of an N by N list of lists, by 1D transforms of the rows and then of the columns."""
    rows = [fft(row, inverse) for row in grid]
    cols = [fft([rows[i][j] for i in range(len(rows))], inverse) for j in range(len(rows[0]))]
    return [[cols[j][i] for j in range(len(cols))] for i in range(len(rows))]


def wave_index(n, size):
    """The signed index n' of the FFT order."""
    return n if n < size // 2 else n - size


def wave_vector(n, m, size, length):
    return (2.0 * math.pi * wave_index(n, size) / length, 2.0 * math.pi * wave_index(m, size) / length)


def dispersion(k, g=G, depth=None):
    """The angular frequency w of a wave with the wave number k: (g k)^(1/2) in deep water, (g k tanh(k d))^(1/2) at depth d."""
    if depth is None:
        return math.sqrt(g * k)
    return math.sqrt(g * k * math.tanh(k * depth))


def phillips(kx, ky, amplitude, wind, speed, g=G, small=0.0):
    """The Phillips spectrum A exp(-1 / (k L)^2) / k^4 |k_hat . w_hat|^2, with L = V^2 / g.

    wind is the wind direction (any length), speed the wind speed V (m/s).
    small > 0 multiplies by exp(-k^2 small^2) to remove waves much shorter than small.
    P(0) = 0.
    """
    k2 = kx * kx + ky * ky
    if k2 == 0.0:
        return 0.0
    big_l = speed * speed / g
    wn = math.hypot(wind[0], wind[1])
    cos = (kx * wind[0] + ky * wind[1]) / (math.sqrt(k2) * wn)
    return amplitude * math.exp(-1.0 / (k2 * big_l * big_l)) / (k2 * k2) * cos * cos * math.exp(-k2 * small * small)


def initial_amplitudes(rng, size, length, amplitude, wind, speed, g=G, small=0.0):
    """h0(k) = (xi_r + i xi_i) (P(k) / 2)^(1/2) for each index, with standard normal xi from rng.gauss."""
    h0 = [[0j] * size for _ in range(size)]
    for n in range(size):
        for m in range(size):
            xr, xi = rng.gauss(0.0, 1.0), rng.gauss(0.0, 1.0)
            if n == size // 2 or m == size // 2:
                continue
            kx, ky = wave_vector(n, m, size, length)
            p = phillips(kx, ky, amplitude, wind, speed, g, small)
            h0[n][m] = complex(xr, xi) * math.sqrt(p / 2.0)
    return h0


def spectrum_at(h0, size, length, t, g=G):
    """H(k, t) = h0(k) exp(i w t) + conj(h0(-k)) exp(-i w t) for each index."""
    out = [[0j] * size for _ in range(size)]
    for n in range(size):
        for m in range(size):
            kx, ky = wave_vector(n, m, size, length)
            w = dispersion(math.hypot(kx, ky), g)
            e = cmath.exp(1j * w * t)
            out[n][m] = h0[n][m] * e + h0[(-n) % size][(-m) % size].conjugate() * e.conjugate()
    return out


def height_field(h0, size, length, t, g=G):
    """The complex heights at the grid points x = (a L / N, b L / N). The imaginary part is 0 up to rounding."""
    spec = spectrum_at(h0, size, length, t, g)  # @line L3
    return fft2(spec, inverse=True)  # @line L4


def choppy_displacement(h0, size, length, t, lam=1.0, g=G):
    """The horizontal displacement D(x) = sum_k -i lam (k / |k|) H(k, t) exp(i k . x), as two complex grids."""
    spec = spectrum_at(h0, size, length, t, g)
    sx = [[0j] * size for _ in range(size)]
    sy = [[0j] * size for _ in range(size)]
    for n in range(size):
        for m in range(size):
            kx, ky = wave_vector(n, m, size, length)
            k = math.hypot(kx, ky)
            if k > 0.0:
                sx[n][m] = -1j * lam * kx / k * spec[n][m]
                sy[n][m] = -1j * lam * ky / k * spec[n][m]
    return fft2(sx, inverse=True), fft2(sy, inverse=True)  # @line L5


def synthesize(rng, size, length, amplitude, wind, speed, times, lam=1.0, g=G):
    """The ocean patch at each time in times: a list of (height, dx, dy) real grids."""
    h0 = initial_amplitudes(rng, size, length, amplitude, wind, speed, g)  # @line L1
    frames = []
    for t in times:  # @line L2
        h = height_field(h0, size, length, t, g)
        dx, dy = choppy_displacement(h0, size, length, t, lam, g)
        frames.append(([[z.real for z in row] for row in h], [[z.real for z in row] for row in dx],
                       [[z.real for z in row] for row in dy]))  # @line L6
    return frames
test_fft_ocean_synthesis.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fft-ocean-synthesis/. The authors are listed in prov/6YE8FD.jsonl.
import cmath
import math
import random
import unittest

import fft_ocean_synthesis as fo

SIZE = 16
LENGTH = 100.0
WIND = (1.0, 0.5)
SPEED = 10.0
AMP = 1e-3


def direct_dft(a, inverse=False):
    n = len(a)
    s = 1.0 if inverse else -1.0
    return [sum(a[j] * cmath.exp(s * 2j * math.pi * j * k / n) for j in range(n)) for k in range(n)]


def direct_height(spec, size, length, x, y):
    total = 0j
    for n in range(size):
        for m in range(size):
            kx, ky = fo.wave_vector(n, m, size, length)
            total += spec[n][m] * cmath.exp(1j * (kx * x + ky * y))
    return total


class TestFFT(unittest.TestCase):
    def test_fft_equals_direct_dft(self):
        rng = random.Random(1)
        for n in (1, 2, 4, 8, 32):
            a = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
            for inverse in (False, True):
                fast = fo.fft(a, inverse)
                slow = direct_dft(a, inverse)
                self.assertLess(max(abs(p - q) for p, q in zip(fast, slow)), 1e-12)
        self.assertEqual([abs(z) for z in fo.fft([1, 0, 0, 0])], [1.0] * 4)

    def test_fft_round_trip(self):
        rng = random.Random(2)
        a = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(64)]
        back = [z / 64 for z in fo.fft(fo.fft(a), inverse=True)]
        self.assertLess(max(abs(p - q) for p, q in zip(a, back)), 1e-12)

    def test_bad_length(self):
        with self.assertRaises(ValueError):
            fo.fft([0j] * 6)


class TestOcean(unittest.TestCase):
    def setUp(self):
        self.h0 = fo.initial_amplitudes(random.Random(7), SIZE, LENGTH, AMP, WIND, SPEED)

    def test_dispersion_check_values(self):
        k = 2 * math.pi / 10.0
        w = fo.dispersion(k, 9.81)
        self.assertAlmostEqual(k, 0.628319, places=6)
        self.assertAlmostEqual(w, 2.482701, places=6)
        self.assertAlmostEqual(2 * math.pi / w, 2.530786, places=6)
        self.assertAlmostEqual(w / k, 3.951342, places=6)
        self.assertAlmostEqual(fo.dispersion(k, 9.81, depth=1000.0), w, places=12)
        self.assertLess(fo.dispersion(k, 9.81, depth=1.0), w)

    def test_spectrum_is_hermitian(self):
        for t in (0.0, 1.3, 17.0):
            spec = fo.spectrum_at(self.h0, SIZE, LENGTH, t)
            for n in range(SIZE):
                for m in range(SIZE):
                    other = spec[(-n) % SIZE][(-m) % SIZE].conjugate()
                    self.assertLess(abs(spec[n][m] - other), 1e-15 + 1e-12 * abs(spec[n][m]))

    def test_height_is_real_and_equals_direct_sum(self):
        for t in (0.0, 2.5):
            spec = fo.spectrum_at(self.h0, SIZE, LENGTH, t)
            h = fo.height_field(self.h0, SIZE, LENGTH, t)
            self.assertGreater(max(abs(z.real) for row in h for z in row), 0.05)
            self.assertLess(max(abs(z.imag) for row in h for z in row), 1e-12)
            for a in range(SIZE):
                for b in range(SIZE):
                    x, y = a * LENGTH / SIZE, b * LENGTH / SIZE
                    self.assertLess(abs(h[a][b] - direct_height(spec, SIZE, LENGTH, x, y)), 1e-12)

    def test_choppy_displacement_is_real(self):
        dx, dy = fo.choppy_displacement(self.h0, SIZE, LENGTH, 3.0, lam=0.8)
        self.assertLess(max(abs(z.imag) for g in (dx, dy) for row in g for z in row), 1e-12)
        self.assertGreater(max(abs(z.real) for row in dx for z in row), 0.01)

    def test_single_mode_is_a_moving_cosine(self):
        n, m = 3, 1
        a = complex(0.2, -0.1)
        h0 = [[0j] * SIZE for _ in range(SIZE)]
        h0[n][m] = a
        kx, ky = fo.wave_vector(n, m, SIZE, LENGTH)
        w = fo.dispersion(math.hypot(kx, ky))
        for t in (0.0, 0.7, 4.0):
            h = fo.height_field(h0, SIZE, LENGTH, t)
            for i in range(SIZE):
                for j in range(SIZE):
                    x, y = i * LENGTH / SIZE, j * LENGTH / SIZE
                    want = 2 * (a * cmath.exp(1j * (kx * x + ky * y + w * t))).real
                    self.assertAlmostEqual(h[i][j].real, want, places=12)

    def test_phillips(self):
        self.assertEqual(fo.phillips(0.0, 0.0, 1.0, WIND, SPEED), 0.0)
        self.assertAlmostEqual(fo.phillips(-0.5, 1.0, 1.0, WIND, SPEED), 0.0, places=15)
        p = fo.phillips(0.3, 0.1, 1.0, WIND, SPEED)
        self.assertAlmostEqual(p, fo.phillips(-0.3, -0.1, 1.0, WIND, SPEED), places=15)
        self.assertLess(fo.phillips(0.3, 0.1, 1.0, WIND, SPEED, small=1.0), p)

    def test_seed_and_frames(self):
        f1 = fo.synthesize(random.Random(5), 8, 50.0, AMP, WIND, SPEED, [0.0, 1.0])
        f2 = fo.synthesize(random.Random(5), 8, 50.0, AMP, WIND, SPEED, [0.0, 1.0])
        self.assertEqual(f1, f2)
        self.assertEqual(len(f1), 2)
        mean = sum(sum(row) for row in f1[1][0]) / 64
        self.assertLess(abs(mean), 1e-12)


if __name__ == "__main__":
    unittest.main()

History

Mastin, Watterberg and Mareda (1987) made images of the sea by filtering white noise with an ocean wave spectrum and then inverting it with an FFT. Tessendorf wrote the method in the form used today in his SIGGRAPH course notes "Simulating Ocean Water", with the Phillips spectrum, the time evolution by the dispersion relation and the choppy displacement. The notes appeared in several versions; this page cites the 2001 version. The method is now a common way to make ocean surfaces in films and games.

References

  1. Simulating Ocean Water, the sections on the statistical wave model, the Phillips spectrum, the time evolution and choppy waves
  2. Gary Mastin, Peter Watterberg and John Mareda, Fourier synthesis of ocean scenes, IEEE Computer Graphics and Applications 7(3), 16-23, 1987, the whole paper (white noise filtered by an ocean wave spectrum and inverted by FFT)
  3. O. M. Phillips, The equilibrium range in the spectrum of wind-generated waves, Journal of Fluid Mechanics 4(4), 426-434, 1958, the equilibrium range of the spectrum (general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.frame
  • a full proof of time.setup
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example