Toward a Better Ocean Simulation for Project Ranger

Written by

on

in

,

Since I was laid off from my job as an engineer at Nav in July, I’ve been on-and-off working on a video game that I’ve wanted to create for a while, one that is as of yet unnamed, but that I’m referring to as Project Ranger.

The core gameplay all centers on seafaring and exploring and traveling across the ocean, so naturally, the ocean is something that I’ve spent quite a lot of time thinking about and planning out.

So-Called “Gerstner Waves”

My initial implementation used what I’d seen described as “Gerstner waves” in gamedev spaces, although this terminology is not strictly accurate, as I’ll cover later. This approach is a system whereby you apply a height map to a tessellated flat plane where each vertex samples that two dimensional coordinate in a function that combines numerous two dimensional sine waves of different directions, amplitudes, and periods. This looks reasonably good visually, and allows some clever optimizations because vertices are only ever displaced vertically, and since the function itself takes in xx and yy coordinates and returns a zz coordinate, you can trivially sample any point you want for your physics calculations without needing to actually deal with the mesh or trying to reverse horizontal displacements:

z(x,y,t)=∑i=1NAisin⁡(kx,ix+ky,iy−ωit+ϕi)z(x, y, t) = \sum_{i=1}^{N} A_i \sin(k_{x,i} x + k_{y,i} y – \omega_i t + \phi_i)

where NN is the number of wave components, AiA_i is the amplitude of wave ii, (kx,i,ky,i)(k_{x,i}, k_{y,i}) is its horizontal wave vector, ωi\omega_i is its angular frequency, tt is time, and ϕi\phi_i is its phase offset.

Interesting Visual Tricks

Before I actually started building the game in Bevy, I built a small WebGL2 topographic contour sandbox called “Sargasso” to experiment with wave shapes and conditions to use in my game, and it used this seemingly common simplified approximation of Gerstner Waves initially.

But while experimenting, I did notice that the waves didn’t quite have the pointy crests or smooth troughs that the real ocean does. As I spent more time researching and tweaking it further, I found that there is a simple mathematical trick to giving a sine wave those characteristics.

By combining the second harmonic of the wave’s frequency (in other words, just generating a second sine wave with exactly double the frequency), and combining this in the correct phase, the peaks of the sine wave receive constructive interference that sharpens them, and the troughs receive destructive interference that flattens them. And you can multiply this second harmonic wave by some scalar to control how strongly it influences the original wave shape, which actually gives you some flexibility to shape the waves beyond the constant shape nature provides.

z(x,y,t)=∑i=1NAi(sin⁡(θi)−s2cos⁡(2θi))z(x, y, t) = \sum_{i=1}^{N} A_i \left( \sin(\theta_i) – \frac{s}{2} \cos(2\theta_i) \right)

where ss is a scalar steepness factor controlling how strongly the second harmonic sharpens the crests, and the phase of wave ii is:

θi=kx,ix+ky,iy−ωit+ϕi\theta_i = k_{x,i} x + k_{y,i} y – \omega_i t + \phi_i

And ultimately, my GLSL fragment shader in this Sargasso project was built around a function that looked something like this:

float heightAt(vec2 p) {
  float y = 0.0;
  for (int i = 0; i < u_waveCount; i++) {
    float k = (2.0 * PI) / u_wavelength[i];
    float omega = u_speed[i] * k;
    vec2 d = vec2(cos(u_dir[i]), sin(u_dir[i]));
    float phase = k * dot(d, p) - omega * u_time;
    float e = sin(phase) - 0.5 * u_steepness * cos(2.0 * phase);
    y += u_amplitude[i] * e;
  }
  return y;
}

Where it Fell Short

But it also has some shortcomings that make it feel just a little off in a real-time simulation. Namely, if you take advantage of the ease of calculating the surface height at given coordinates in order to simulate the buoyancy of a ship, the ship will rise and fall with the surface of the water, but it will also not move laterally with the waves, as a real ship does. If you apply slope-sliding physics to the ship on the sloped water surface, this improves things slightly, as it at least will feel like the ship itself is reacting to the water. That said, the water will feel distinctly “stiff.”

In real ocean waves a fixed point on the surface of water actually moves in elliptical patterns in 3-dimensional space, it doesn’t just bob up and down. This is what our esteemed legend himself, Franz Josef Gerstner, for whom these waves are named, actually observed and described. You can see this in practice by placing something small and buoyant on water with waves. If you watch its motion, it is actually moving both vertically and laterally, in a circle or ellipse. If you care about the academic terminology, observing a single fixed point in a flowing fluid is referred to as the Lagrangian perspective.

The approach I originally took was an Eulerian perspective instead, and really more of a visually acceptable approximation of Gerstner waves that relies on that phase-locked second harmonic trick to even replicate the trochoidal shape, without actually being mathematically accurate. It was a simple but effective approximation of rolling ocean waves, especially if I only wanted static geometry, but it lacks the deeper realism I’m after.

Actually Understanding Gerstner

What Gerstner actually described was the free surface of water forming an inverted “trochoid”, with sharper crests and flat troughs. If you’re unfamiliar with what an “inverted trochoid” actually looks like (as I’ll happily admit I was before digging into this specific project), imagine taking a sine wave and pinching the higher vertices together, and spreading apart the lower vertices. And this is exactly what happens when you allow the vertices to move in that same elliptical pattern.

a graph showing a trochoidal wave, and showing how the vertices of its surface track points along a rotating elliptical path
This image shows the inverted trochoid shape (dark blue) of a trochoidal wave, the elliptical path of several Lagrangian vertices on its surface (light blue), the current position of several Lagrangian vertices on its surface (black), and the velocity vectors of said Lagrangian vertices.
© Kraaiennest, CC BY-SA 4.0, via Wikimedia Commons, modified by adding a white background.

In mathematical terms, we get this exact behavior by coupling horizontal and vertical sinusoidal motion to the same wave phase. Instead of holding a vertex’s horizontal position fixed and only varying its height, we offset its undisplaced rest coordinates (x0,y0)(x_0, y_0) along the wave’s direction of travel using a cosine term while driving its vertical elevation with a sine term. Summing across all wave components gives the full Lagrangian surface position:

x=x0+∑i=1Nkx,ikiAicos⁡(θi)y=y0+∑i=1Nky,ikiAicos⁡(θi)z=∑i=1NAisin⁡(θi)\begin{aligned} x &= x_0 + \sum_{i=1}^{N} \frac{k_{x,i}}{k_i} A_i \cos(\theta_i) \\ y &= y_0 + \sum_{i=1}^{N} \frac{k_{y,i}}{k_i} A_i \cos(\theta_i) \\ z &= \sum_{i=1}^{N} A_i \sin(\theta_i) \end{aligned}

where (x0,y0)(x_0, y_0) is the undisplaced rest position on the surface mesh, and the wavenumber kik_i and phase θi\theta_i of wave ii are:

ki=kx,i2+ky,i2θi=kx,ix0+ky,iy0−ωit+ϕi\begin{aligned} k_i &= \sqrt{k_{x,i}^2 + k_{y,i}^2} \\ \theta_i &= k_{x,i} x_0 + k_{y,i} y_0 – \omega_i t + \phi_i \end{aligned}

So, to describe the intended change as succinctly and accurately as possible: changing the simulation from an Eulerian perspective of a plane of combined sine waves, to a Lagrangian perspective of combined trochoidal waves, will both improve the realism of the shape of the ocean’s waves, and properly simulate the realistic movement of its surface and anything floating on its surface.

Getting Started: API Changes

That’s a lot of theoretical mathematics, but we’re writing code, so let’s talk about the code itself. Let’s start with the API.

The Eulerian Summed-Sines Approach

The initial approach uses a function that takes three things: a configuration of the wave composition (I’m going to kind of hand-wave this here, but really it’s just a list of structs containing the parameters for individual wave components), an xx coordinate, and a yy coordinate. It returns one thing: a Δz\Delta z displacement (meaning the vertical displacement of the ocean at those xx and yy coordinates):

f(W,x,y)→Δzf(W, x, y) \to \Delta z

where WW is the wave configuration, (x,y)(x, y) is the horizontal surface position, and Δz\Delta z is the vertical surface displacement at that coordinate.

The advantage of this approach is that this is the only API we need. You can call this function to displace the vertices in your mesh, and you can also call it to measure the surface height at a given coordinate.

The True Lagrangian Gerstner Wave Approach

To simulate actual Gerstner waves using the Lagrangian perspective, the displacement function takes a wave configuration (technically slightly different parameters, but conceptually the same thing), an x0x_0 coordinate, and a y0y_0 coordinate.

You’re still passing in coordinates for a specific point on the surface, but the important distinction here that didn’t matter before is that (x0,y0)(x_0, y_0) refers to a position on the ocean’s surface mesh before displacement. In the previous function, this distinction didn’t matter because we were only displacing the zz coordinate.

Our new function now must displace the vertex in all three dimensions. So instead of returning a single zz coordinate, it will now return (Δx,Δy,Δz)(\Delta x, \Delta y, \Delta z), describing a displacement vector to apply to that vertex in your ocean surface mesh:

f(W,x0,y0)→(Δx,Δy,Δz)f(W, x_0, y_0) \to (\Delta x, \Delta y, \Delta z)

where (x0,y0)(x_0, y_0) is the undisplaced rest position on the surface mesh and (Δx,Δy,Δz)(\Delta x, \Delta y, \Delta z) is the three-dimensional displacement vector.

Whereas in the Eulerian approach, we could use that same function for both vertex displacement and probing heights, this can only be used for the vertex displacement because of the horizontal displacement.

Additionally, we’ll also want a very similar function that returns that displacement vector along with a second three-dimensional vector. Let’s call its components (u,v,w)(u, v, w). This second vector refers to the velocity of that surface point, and will be useful in physics calculations:

g(W,x0,y0)→((Δx,Δy,Δz),(u,v,w))g(W, x_0, y_0) \to \big((\Delta x, \Delta y, \Delta z),\; (u, v, w)\big)

where (u,v,w)(u, v, w) is the instantaneous three-dimensional velocity vector of the surface point, obtained by taking the time derivative of the trochoidal displacement:

𝐯(x0,y0,t)=(uvw)=∑i=1NωiAi(kx,ikisin⁡(θi)ky,ikisin⁡(θi)−cos⁡(θi))\mathbf{v}(x_0, y_0, t) = \begin{pmatrix} u \\ v \\ w \end{pmatrix} = \sum_{i=1}^{N} \omega_i A_i \begin{pmatrix} \frac{k_{x,i}}{k_i} \sin(\theta_i) \\ \frac{k_{y,i}}{k_i} \sin(\theta_i) \\ -\cos(\theta_i) \end{pmatrix}

And finally, if we’re to create a drop-in replacement for the surface probing calculations that we can do so trivially with the Eulerian approach, then we need an API that takes a coordinate on the displaced ocean surface and calculates the height at that coordinate, where we will also want to return the velocity of that surface point:

h(W,x1,y1)→(Δz,(u,v,w))h(W, x_1, y_1) \to \big(\Delta z,\; (u, v, w)\big)

But again, because of the horizontal displacement, the actual implementation of this isn’t quite so obvious. I’ll discuss that more later on in this post.

The Physics Calculations

In this true Gerstner approach, we care about the displacement and velocity for different purposes, and in different amounts, at different vertices. But, we do know that whenever we require the velocity at a vertex, we also require its displacement vector, and those two can be computed more efficiently together than as two separate function calls.

In order to calculate the physics of the ship or other objects interacting with the ocean, we actually only need to measure a small number of points on a limited area of the ocean. More specifically, we only need to check pre-defined points around objects that we know could be touching or interacting with the ocean, meaning buoyant objects that are in spatial ranges that could plausibly be touching the ocean. We can skip every other object, any empty ocean, and even buoyant objects that are simply too high up on an island or in the air to be touching the ocean. This calculation will need to happen on the CPU, and will always care about both the displacement vector and the velocity vector, so both must be calculated.

So we’re able to optimize the physics calculation by narrowing down the number of places that we need to measure. But we can actually go a step further. Looking at the equations above, we know that calculating the displacement is linear O(N)O(N) time relative to the number of wave components that we have to iterate over, and the number of wave components is fixed. But not all of these components have the same impact on the final waves. The most important ones from a physics perspective are the large magnitude, generally longer wavelength waves, which can heave ships on the order of meters. But the wave composition also includes many much smaller magnitude waves that might influence movement by only a few centimeters or millimeters at a time. Visually, these are important for making the waves look realistic, but in the physics simulation? The movement of a real ship is already dampened by its own mass and momentum, so at these scales it’s genuinely not possible to tell whether they’re present or missing. Omitting them linearly decreases the computational cost of performing physics math. In my opinion, this is a no-brainer.

The Graphics Calculations

Now for actually rendering the ocean, these lower-magnitude and narrower wavelength waves do have a profound visual effect, so they do need to be retained. And you also need to calculate a lot of these values, like tens of thousands to millions of them. But the good news is for this, you will be using the GPU instead, and since the displacements are totally independent pure functions with linear time complexity and no branching, you can efficiently run them in parallel for as many different vertices as your GPU has the ability to parallelize.

That doesn’t mean there’s nothing you can do to optimize performance, still. Looking at the physics calculations, we are able to substantially reduce the amount of work we have to do by avoiding irrelevant calculations. Can’t we do that with graphics as well?

We definitely can. Depending on where you are in the game, large amounts of the ocean might be totally occluded from the camera. If the ocean is actually a grid of chunks, rather than just a completely uniform, single plane, we can actually treat each chunk of ocean as a cuboid of area where the ocean could possibly be visible. Then, with that cuboid, we can perform frustum culling, checking to see if any part of the cuboid lies inside the camera’s frustum. This is extremely quick to calculate, and for every tile that we know isn’t in the frustum, we can just avoid drawing it at all.

Then, with that same cuboid, we can also perform occlusion culling. So if you’re inside the lower deck of your ship, and you have no line of sight to the ocean, or perhaps you’re inside a building that is blocking large swaths of the ocean, some of those patches of ocean will be totally covered up by objects nearer to the camera. Using similarly inexpensive checks, if we can determine that no part of the cuboid could be visible on the screen, we can simply discard it before we draw it.

Then, it’s worth considering how clearly you can see detail depending on the range of a patch of water. For the water you’re swimming in, or the water right next to your ship, it would be preferable to render this water using a very large number of vertices, because you can actually see the small ripples and imperfections. But water 100 meters away? You can’t see it as clearly, so it really wouldn’t hurt to render that at a much lower resolution. And the water a kilometer out? At that range it’s debatable whether you even need to bother rendering realistic water vs a textured plane. This technique is referred to as LOD (Level of Detail).

And even at those close ranges, you don’t necessarily even need to use so many vertices that every ripple is clearly defined in the mesh itself. In fact, you shouldn’t do that. For the very smallest details, you can leverage the fragment shader to vary the smallest-scale ripples via the surface normals it uses to shade each pixel.

Of course, if you’ve done any amount of gamedev in the past, frustum culling, occlusion culling, LOD, normal mapping, these are all very standard optimization techniques that you’ll learn in any introductory game graphics book or youtube series, so I may not be saying anything groundbreaking here. But it kind of illustrates a broader point that I know I sometimes forget when I’m swimming in all of the complexity of systems like this: when you render the ocean, it’s still just a mesh at the end of the day.


Today’s Project Ranger Oceans

By the time I got far enough along in building Project Ranger to actually start adding the ocean, I had actually learned about a lot of the limitations of that early approach, so I set up the wave math in Rust and WGSL to use true Gerstner waves, displaced in three dimensions. I also added f64 floating-origin phase accumulation (phase_origin) so waves stay crisp and synchronized even millions of units away from the world origin. This is meant to be an “infinite” world game, after all, and I’ve played enough Bedrock Minecraft to have experienced the weird precision jitter you get beyond 15km or so from the origin, and I definitely want to avoid that same issue in a game where precision at the helm might be pretty important.

One important note to mention, regarding the Bevy code that follows, vs the code and math above, is that in Bevy, the “up” dimension is actually the yy coordinate, not the zz coordinate. This might be confusing if your intuition comes from using a graphing calculator, but should be pretty familiar to my fellow Minecraft players.

On the CPU side, a displace method on a struct that encapsulates the wave configuration takes in the xx and zz components of a vertex on the undisplaced ocean surface mesh, and returns the displacement vector for that vertex:

pub fn displace(&self, rest: DVec2, t: f32) -> DVec3 {
    let mut offset = DVec3::ZERO;

    for wave in &self.waves {
        let k = wave.wavenumber();
        let amplitude = wave.amplitude as f64;
        let q = wave.steepness as f64 / (k * amplitude * WAVE_COUNT as f64);
        let phase = k * wave.direction.as_dvec2().dot(rest) - wave.speed as f64 * k * t as f64;
        let (sin, cos) = phase.sin_cos();

        offset.x += q * amplitude * wave.direction.x as f64 * cos;
        offset.z += q * amplitude * wave.direction.y as f64 * cos;
        offset.y += amplitude * sin;
    }

    DVec3::new(rest.x + offset.x, SEA_LEVEL as f64 + offset.y, rest.y + offset.z)
}

On the GPU, a WGSL function called gerstner_surface in the ocean surface’s shaders (used by both the vertex and fragment shaders) performs the same calculation, this time using f32s in camera space, shifted by the earlier mentioned phase origin. It also accumulates the analytical partial derivatives (dpdx and dpdz). These are used by the fragment shader to generate smooth normals instead of purely relying on high vertex density for fine details, and calculating a horizontal Jacobian determinant for rendering the foam on the breaking crests of waves:

fn gerstner_surface(rest: vec2<f32>, t: f32) -> Surface {
    var offset = vec3<f32>(0.0);
    var dpdx = vec3<f32>(1.0, 0.0, 0.0);
    var dpdz = vec3<f32>(0.0, 0.0, 1.0);

    for (var i = 0u; i < WAVE_COUNT; i = i + 1u) {
        let wave = settings.waves[i];
        let dir = wave.direction_amplitude_k.xy;
        let amplitude = wave.direction_amplitude_k.z;
        let k = wave.direction_amplitude_k.w;
        let omega = wave.omega_steepness.x;
        let q = wave.omega_steepness.y;
        let phase_origin = wave.omega_steepness.z;

        let phase = k * dot(dir, rest) + phase_origin - omega * t;
        let s = sin(phase);
        let c = cos(phase);

        let qa = q * amplitude;
        offset += vec3<f32>(qa * dir.x * c, amplitude * s, qa * dir.y * c);

        let kdx = k * dir.x;
        let kdz = k * dir.y;
        dpdx += vec3<f32>(-qa * dir.x * s * kdx, amplitude * c * kdx, -qa * dir.y * s * kdx);
        dpdz += vec3<f32>(-qa * dir.x * s * kdz, amplitude * c * kdz, -qa * dir.y * s * kdz);
    }

    let normal = normalize(cross(dpdz, dpdx));
    let jacobian = dpdx.x * dpdz.z - dpdx.z * dpdz.x;
    return Surface(offset, normal, jacobian);
}

Probing a Laterally Displaced Surface

In my original approach from Sargasso, determining the height of the ocean at an exact coordinate was completely trivial. Since the function only ever displaced vertically, and never horizontally, if you calculated the displacement for a given coordinate, you know the height at that coordinate.

With Gerstner waves, vertices on the ocean surface are displaced horizontally too, and so most of the time, the vertex produced by displacing your desired coordinates is actually above a different surface coordinate, so you cannot rely on this same technique:

displace(x0,z0)=(x0+Δx(x0,z0),y(x0,z0),z0+Δz(x0,z0))\text{displace}(x_0, z_0) = \big(x_0 + \Delta x(x_0, z_0),\;\; y(x_0, z_0),\;\; z_0 + \Delta z(x_0, z_0)\big)

Now, that same operation instead tells you where the coordinate 𝐩\mathbf{p} on a perfectly smooth surface would have drifted to in the current wave state, which is somewhere else now.

Initially, I thought this problem might require generating a kinematic triangle mesh for every ocean tile, and then letting the physics engine actually calculate collisions and intersections with it, because I wasn’t sure whether there would be an inexpensive way to probe the surface at a given coordinate. But this approach has several things that make it problematic at the outset:

  • The ocean surface is a volumeless flat mesh, not a volume that can be intersected. If I wanted to intersect it, I would either need to make every ocean tile into a volume, which adds more vertices for the physics engine to deal with, or deal with some complex custom physics math to decide what parts of a given volume are considered to be below one (or more, at edges/corners) flat, finite mesh. Neither is impossible, but both have the undeniable stench of “doing it wrong.”
  • The game is an infinite world and meant to be multiplayer, with potentially many players online at any given time. If players are spread out, the server will need to be performing collision checks between potentially thousands of individual objects in the water, and potentially millions of vertices of kinematic meshes. This just isn’t scalable.
  • If you reduce the resolution of the kinematic meshes enough to kind of make this scalable, then the angles between different edges of the meshes get more jagged, and when small objects with few buoyancy probes cross those edges, it will cause very unnatural behavior.

But eventually what I realized is that you don’t actually need to calculate the exact value. As is so often the case with game development, what you actually need is a good enough approximation, and approximating reversing the displacement to get the height at a given coordinate is actually not all that hard at all.

Thus, we can keep the limited probe vertices and grids that are only on objects that might interact with the water, and we can do the same analytical calculations using fixed-point iteration. What we need is the unknown rest coordinate 𝐫=(x0,z0)\mathbf{r} = (x_0, z_0) whose displaced lateral position lands directly on our probe coordinates, 𝐩=(x,z)\mathbf{p} = (x, z):

𝐫+𝚫(𝐫)=𝐩⟺𝐫=𝐩−𝚫(𝐫)\mathbf{r} + \boldsymbol{\Delta}(\mathbf{r}) = \mathbf{p} \quad \Longleftrightarrow \quad \mathbf{r} = \mathbf{p} – \boldsymbol{\Delta}(\mathbf{r})

Because 𝐫\mathbf{r} appears on both sides, we can’t isolate it algebraically in one step. But instead we can iteratively converge on the value.

Start by guessing horizontal displacement is zero, since the mean displacement over time is zero:

𝐫0=𝐩=(xz)\mathbf{r}_0 = \mathbf{p} = \begin{pmatrix} x \\ z \end{pmatrix}

Then refine the estimate across n = 1, …, M iterations by subtracting the horizontal wave displacement evaluated at the previous guess:

𝐫n=𝐩−∑i=1NQiAicos⁡(θi(𝐫n−1,t))𝐝^i\mathbf{r}_{n} = \mathbf{p} – \sum_{i=1}^{N} Q_i A_i \cos\big(\theta_i(\mathbf{r}_{n-1}, t)\big)\,\hat{\mathbf{d}}_i

where the wave phase at the previous estimate is given by:

θi(𝐫n−1,t)=ki(𝐝^i⋅𝐫n−1)+ϕ0,i−ωit\theta_i(\mathbf{r}_{n-1}, t) = k_i (\hat{\mathbf{d}}_i \cdot \mathbf{r}_{n-1}) + \phi_{0,i} – \omega_i t

Here, d is the unit direction vector of wave ii, kk is its wavenumber, AA is its amplitude, QQ is its normalized steepness, ωω is its angular frequency, and ϕϕ is its phase offset at the origin. Once MM iterations complete (four in my actual implementation), we evaluate the vertical surface elevation at the converged rest coordinate:

y(𝐩,t)≈ysea+∑i=1NAisin⁡(θi(𝐫M,t))y(\mathbf{p}, t) \approx y_{\text{sea}} + \sum_{i=1}^{N} A_i \sin\big(\theta_i(\mathbf{r}_M, t)\big)

And all of this ended up as a Rust method called height_at on the struct that wraps the wave configuration, and looks something like this:

pub fn height_at(&self, at: DVec2, t: f32) -> f32 {
    let mut rest = at;
    let mut surface = self.displace(rest, t);

    for _ in 0..INVERSE_ITERATIONS {
        rest -= DVec2::new(surface.x - at.x, surface.z - at.y);
        surface = self.displace(rest, t);
    }

    surface.y as f32
}

In any expected realistic ocean conditions, this function will converge to within millimeters of the correct answer, which is more than enough precision for the sorts of physics calculations we’ll need. And it does this in linear O(M)O(M) time based on the number of iterations for a fixed wave count, which is a constant value in my game, but it could easily be made a const generic too. Maybe you’re okay with slightly lower precision when you’re calculating the buoyancy of a plank floating in the ocean, but you want higher precision for calculating the buoyancy of player ships. For each of the buoyancy probes on the player ship, you might run 4 rounds, and maybe you only do 2 or 3 for the floating planks. This is of course a miniscule difference, but if you reach the point where you expect to have thousands of planks in the ocean at any given time, it might offer meaningful optimization then.

This calculation also has another useful byproduct: because we’ve obtained the resting vertex of the displaced surface vertex at our probe’s coordinates, we’re also able to compute the orbital velocity at that vertex as well.

The Missing Piece

While I did build the rendering code to utilize real Gerstner waves, the physics side has been left somewhat lacking in the same level of realism.

Initially, I wasn’t sure if any of the features I was planning to build would actually care about accurately simulating ship physics in three dimensions in a server-authoritative way. I figured, absent things like naval combat, or boarding, or PvP, this wouldn’t be necessary. We could instead let the server treat the physical location of ships as a simple two-dimensional position on a totally flat plane, and leave the ships bobbing in the waves as a purely client-side visual effect.

While this technically is fine if the scope stayed that limited, my ambitions for what I wanted to do with the game expanded, and I realized that I do actually want the realism offered by authentic, server-authoritative ocean physics.

So I’ve since updated the buoyancy calculations into the server code. Each ship uses an N×NN \times N grid of Archimedes probes across the hull’s waterplane. This gives genuine pitch and roll on the server, but each probe is still only querying a scalar water elevation and applying it as a strictly vertical upward force in the physics engine, which means the ship still doesn’t displace laterally as the waves roll by:

for iz in 0..n {
    for ix in 0..n {
        let sx = (ix as f32 / (n - 1) as f32) * 2.0 - 1.0;
        let sz = (iz as f32 / (n - 1) as f32) * 2.0 - 1.0;

        let local_offset = right * (sx * half_beam) + forward * (sz * half_length);
        let probe_world = world_pos + local_offset.as_dvec3();
        let water_y = field.height_at(DVec2::new(probe_world.x, probe_world.z), t);

        let probe_local = Vec3::new(sx * half_beam, -keel, sz * half_length);
        let probe_y = world_pos.y as f32 + (tf.rotation * probe_local).y;

        let depth = (water_y - probe_y).clamp(0.0, SHIP_HULL_HEIGHT);
        let force = Vec3::new(0.0, WATER_DENSITY * gravity * depth * sample_area, 0.0);

        net_force += force;
        let arm_from_com = tf.rotation * Vec3::new(sx * half_beam, 0.0, sz * half_length);
        net_torque += arm_from_com.cross(force);
    }
}

What is Our Course, Captain?

Closing that last gap in terms of realism is the next thing I plan to cross off my list.

Taking everything discussed in this post, the work that remains is:

First, I’ll be refactoring height_at so that it returns the surface velocity vector in addition to the height. Obviously it’ll need to be renamed, since it’ll no longer just be returning height.

Then I’ll utilize the newly-returned ocean surface velocity in combination with the known velocity of the probe to calculate relative hydrodynamic drag, thus making the ocean actually realistically exert force on a ship:

𝐯rel=𝐯water−𝐯probe\mathbf{v}_{\text{rel}} = \mathbf{v}_{\text{water}} – \mathbf{v}_{\text{probe}}

I think that will go a long way in giving the ocean a more realistic feel, and make the game overall feel more exciting and alive. With this change, ocean swells will physically surge the ship forward as it hits the crest, it’ll slide back in troughs, induce yaw forces when waves strike the quarter, and naturally damp vertical heave without relying on hacky arbitrary vertical damping constants, as it does now:

let v_water = sample.velocity;
let v_probe = lin_vel + ang_vel.cross(arm_from_com);
let v_rel = v_water - v_probe;

let drag_force = v_rel * drag_coeff * submerged_ratio;
net_force += buoyant_force + drag_force;
net_torque += arm_from_com.cross(buoyant_force + drag_force);

While it might sound silly to care about the realism to this degree, these small characteristics actually create some emergent gameplay in themselves, and will interact in interesting ways with a lot of the other elements of the game I have planned. If your ship just moves in a straight line and stays perfectly put when you stop it, there’s a lot less excitement to navigating and piloting a ship, but with these dynamics, everything is a little less certain and the skill ceiling gets pushed just a little bit higher.

And After That?

My roadmap actually includes a LOT more ocean dynamics than I covered here, but I’d be shocked if anybody even made it this far without their eyes glazing over. As of now I’ve spent too many hours writing and fine-tuning my wording and equations and code snippets, and I can leave the deep dives on those further exciting features for later posts I intend to write, and will hopefully have more insightful things to say about as I actually start implementing them.

But I’m happy to tease some of them:

  • Directional Fast Fourier Transform cascades to replace the analytical Gerstner waves. I know, I know, I just spent so much time talking about Gerstner waves in this post, just to tease replacing them. But in truth, this approach shares a lot and is more of a refinement than a total replacement. I promise I’ll explain.
  • A stateless infinite macro-atmosphere as part of the world generation. This will affect things like wind belts, curl-noise ocean gyres, and roaming cyclonic pressure systems via deterministic spatial hashing, so there are infinite weather systems endlessly evolving and moving across the world. No two days on the sea should be the same.
  • Player-local groundswells, wave shadows, and wave diffraction around islands. I think it’d be cool if a skilled sailor can learn to use the terrain to react to weather.
  • Continuous bathymetry shoaling and refraction, amplifying wave height where the depth decreases and naturally refracting waves around islands so terrain has a realistic effect on the ocean dynamics.
  • Emergent breaking waves and rogue waves. Using actual physics to calculate where and how waves are breaking, and applying relevant physics interactions, particles, etc.
  • Short-range Kelvin wakes and convoy wake shadows. When you’re close to other ships, your ships should have an effect on each other’s ocean.
  • Hull drag and green water on deck. When you’re fighting heavy seas, your ship should react appropriately violently, and water washing over your deck should matter.
  • Hull ocean-water exclusion and bilge flooding dynamics. You should be able to go below deck without seeing the ocean intersecting the inside of your ship, and when you’re sinking or water is washing onto your deck, your ship should realistically fill with water.

And there will of course be plenty more than that as I go. This game isn’t meant to be a pure sailing simulator, though it might sound like it based on this roadmap. Really, I just feel that the ocean is central enough to my idea of what this game should be that I want to make sure if I get anything right, I get that right. And also, to be completely honest, I just find these features really fun to work on, and being unemployed for four months is terrifying and stressful, so if I can make something useful that gives me some joy for a few hours at a time, I’ll take it.

But for now, I think that’s it. Look forward to some more updates on this game as I continue working on it. I’m hoping the next post can be a little more heavy on showing than just telling. While the game does have a working prototype, right now there’s just not much to do or see, and the ocean is pretty much the same everywhere. But I suspect as these features get checked off, it’ll become more and more easy to lean heavily on video content, which is eventually where I’d like to pivot most of my devlogs.