DEV Community

Roblox Gerstner waves: getting the water height at a world point

If you render Gerstner waves and then ask "how high is the water at (x, z)", you get two different answers. The maths is usually correct in both places. The problem is that the mesh moves sideways and the query does not.

This is about Luau and Roblox, but it holds for any engine with a choppy wave mesh and a separate water-height query.

One caveat before the code: this is not a secret. A 2021 DevForum answer says it plainly: the formula "doesn't just return a new Y value. It also returns new X and Z values. When you ignore the X and Z values, it will appear out of sync." People have known for years. What keeps the bug alive is that ocean modules, including good ones, ship a height sample that reads the undisplaced point anyway, and a boat that bobs one beat late does not look like a maths error.

Two surfaces, one sea

A Gerstner vertex is displaced from a base point p0 = (x, z):

theta_i = k_i * (D_i.x * x + D_i.z * z) - omega_i * t + phase_i

y' = sum( A_i * sin(theta_i) )

x' = x + sum( D_i.x * A_i * cos(theta_i) )

z' = z + sum( D_i.z * A_i * cos(theta_i) )

Note what every term is evaluated at: p0, the undisplaced point. The vertex you see at x' came from somewhere else. The sideways push is the vertical cosine term rotated onto the horizontal axis.

So when something asks for the surface height at a world point X, Z, and the code plugs X, Z straight into the phase sum, it answers with the wave that used to be there. The rendered sea and the queried sea are two different seas.

Why this survives code review

The size of the error is proportional to the steepness term Q * A. At zero choppiness it is exactly zero, and the two surfaces agree perfectly. This is why the bug is everywhere: on the calm test ocean it does not exist.

Turn the chop up and it appears, but it appears as a shift, not as a constant offset.

  • The error peaks where cos(theta) = ±1, which is at crests and troughs.
  • Its horizontal direction follows each wave's direction, so mixed directions scatter it.
  • On screen it does not read as a bug. It reads as a boat that bobs one beat late, or a hull that sits a little deep on one tack and a little high on the other, depending on which way it is pointing.

In a codebase I audited, the worst case worked out to about 0.45 studs at the steepest setting. Small enough to look like tuning. Large enough that every float in the game is wrong at the same time.

The fix: invert the displacement

You want the base point p0 that ends up at the world point. That is p0 = X - D(p0), which you can solve by fixed-point iteration. Four iterations is the usual choice. Four is also where a quiet bug lives.

The contraction rate of the iteration is the local compression of the map, so distance to a fold sets the number of passes you need. Ten passes cut the error to about 35% of what it was at contraction 0.9, and leave 90% of it at 0.99. Hitting a fixed target takes roughly ten times as many passes at 0.99 as at 0.9. A count tuned on a calm test ocean returns a plausible p that is simply wrong where the crest is. Check the contraction per step and fail loudly, rather than trusting the result of a fixed number of passes.

-- waves: { k, omega, A, phase, dx, dz, Q }
local function heightAt(waves, t, X, Z, iterations)
  local px, pz = X, Z
  local height = 0
  for _ = 1, iterations or 4 do
    height = 0
    local dx, dz = 0, 0
    for i = 1, #waves do
      local w = waves[i]
      local theta = w.k * (w.dx * px + w.dz * pz) - w.omega * t + w.phase
      height += w.A * math.sin(theta)
      dx += w.Q * w.A * w.dx * math.cos(theta)
      dz += w.Q * w.A * w.dz * math.cos(theta)
    end
    px, pz = X - dx, Z - dz
  end
  return height
end

One property matters more than the code: the iteration only converges while the horizontal map does not fold, and a fold is exactly where the Jacobian of that map reaches zero. The usual test, sum(k_i * A_i * Q_i) < 1, is a sufficient condition, not the boundary. It is exact only when every wave runs the same direction.

Two waves at +45 and -45 degrees, both at their steepest phase with equal steepness c, give det J = (1 - c)^2, which folds at c = 1, where the sum test reads 2. Cap the sum at one and you never fold, but you have thrown away half the headroom on a spread sea.

The cheap middle test is a 2x2 matrix. Build T = sum(k_i * A_i * Q_i * u_i u_i^T) over the wave directions, one pass over the table you already sum. det(I - T) gives 1 - s for aligned waves and (1 - c)^2 for the diagonal pair, both exact, so it costs nothing you were not already paying. Both it and the scalar test assume every wave can reach its steepest phase at one world point. Usually it cannot, so treat either as conservative, and expect the slack to grow as the directions spread.

When the water does fold, a single world point has more than one height. That is not a slow solver, it is an unanswerable question.

The boring alternative deserves a mention: set Q = 0. A non-choppy ocean has no lateral displacement, so height at a world point is exact by construction. If you are not using the chop for anything, that is a cheaper fix than the inversion.

A second trap: peaks computed from a different table

There is an MIT-licensed Luau JONSWAP ocean module, howhow2315/jonswap-ocean, that I read while writing this. Its generateWaves(config, seed, scale) builds each wave's amplitude twice:

local A = math.sqrt(2 * S * deltaF) * s -- s = config.scale

totalAmplitude += A

waves[i] = { k, omega, A * (scale or 1), ... } -- third argument again

PeakHeight is then set from totalAmplitude, which only ever saw the first scale. Pass a third argument and the stored waves and the published peak diverge by exactly that factor. The module's own comment on that line says "Should be tA but for visuals I recommend tweaking this", so the fudge is deliberate and known.

The reason to care is downstream: any buoyancy system that sizes itself from PeakHeight will submerge or launch a boat that the mesh never asked for. The general rule is cheap: compute any "peak" or "bounds" from the same table you actually sum in the render loop.

A five-minute test you can run tonight

  • Put one anchored part at a fixed world XZ. Every frame, set its Y from your surface query.
  • Put a second anchored part at the same XZ, set its Y from the mesh itself, or just look.
  • Turn choppiness up and down.

If the gap scales with choppiness, the query is not inverted. If the gap stays flat while the sea gets choppier, look somewhere else.

Why this gets worse in multiplayer

If the ocean lives only on the client, each client owns its own wave clock. Two players see two different water heights under the same hull, and the server has no opinion about where the boat should be. That is not a roughness problem or a network problem, and no amount of client polish fixes it. It needs one phase clock that the server owns, with clients sampling it.

I audit exactly this: the wave maths from mesh vertex to float height, plus a fix branch. If your ocean is 500 lines and you have stopped trusting it, that is the job I do.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.