# Ocean Design and Implementation The ocean system uses an inverse Fast Fourier Transform (iFFT) to simulate realistic wave motion across many waves (128² = 16,384 waves at default resolution). This method provides detailed, dynamic ocean visuals while maintaining performance. ![](./Images/OceanSystem/Fig0.png) ## Choosing iFFT Over Gerstner Waves Early tests with Gerstner waves in the vertex shader were inefficient for realistic ocean simulation. While suitable for stylized games, Gerstner waves require individual control over direction, amplitude, and wavelength, making them hard to manage and computationally expensive at high wave counts. In contrast, iFFT generates a frequency spectrum of waves, offering greater realism and easier control. Although iFFT can be computationally expensive, optimizations ensured it remained viable. A key decision was whether to run the simulation on the CPU or GPU. The GPU is well-suited for parallel processing, but the project required high frame rates and high-resolution rendering, making additional GPU load undesirable. Moreover, ocean height queries for floating objects and ship physics would require costly GPU-to-CPU data transfers. To address these concerns, the simulation runs on the CPU, leveraging Unity's job system and Burst compiler for parallelized, optimized calculations. Certain iFFT components update only when parameters change, further reducing CPU load. ## Environment Profile & Ocean Settings ![](./Images/OceanSystem/Fig1.png) 1. **Wind Yaw/Pitch** Controls the wind direction and, consequently, the ocean waves. Instead of a full XYZ rotation, pitch and yaw suffice to control wind direction, converted to a vector via spherical coordinate transform. The ocean does not react to up/down wind, but other effects, like sails, do. The total projected length of the wind vector along the ocean plane is used as the final wind speed/direction for the ocean simulation. Wind speed is set specifically for the ocean, independent of other systems, for more control. 2. **Wind Speed** Controls the strength, speed, and height of the waves. Higher speeds cause larger, choppier waves, while lower speeds produce gentle waves. 3. **Directionality** Controls wave alignment with the wind direction. A value of 0 gives a random, choppy look, while 1 aligns most waves with the wind. Very low or high values are most useful for random or windy scenarios; in-between values give a non-specific look. 4. **Choppiness** Controls horizontal wave displacement. Simple up/down movement is insufficient for a convincing ocean, so extra horizontal displacement is calculated/applied to the vertices. This value generally looks best at 1 but is included for flexibility. 5. **Patch Size** Defines the world-space size the ocean simulation covers. Simulating an infinite ocean is not feasible, so a small patch is simulated and repeated over the ocean surface. Smaller values concentrate detail in a smaller area, but tiling may be more noticeable. Larger values reduce repetition and allow for larger, varied waves, especially with higher wind speeds, but lose fine detail. A detail normal map can restore some fine detail. A scrolling noise texture modulates displacement to break up tiling. 6. **MinWaveSize** A fine control filter to fade out very small waves generated by the simulation. At lower resolutions and patch sizes, small wavelengths can alias, causing a faceted or flickering look. It can also be used for a stylized look, removing finer waves and leaving larger rolling waves. 7. **(Advanced) Gravity** Earth's gravity in meters per second controls the relation between wave size and speed. Generally, this should not be adjusted as it can make waves look oddly fast or slow, but it is included for special cases. 8. **(Advanced) SequenceLength** The sequence repeats after a certain time to avoid accumulating floating-point errors. It can be shortened to produce a looping sequence, e.g., a 10-second loop baked into displacement/normal maps to avoid runtime computation. Larger waves will not progress correctly at short sequences. For most cases, set this to a high value, like 200 seconds, to reduce errors without noticeable repetition. 9. **(Advanced) TimeScale** Scales the simulation speed. Usually left at 1, it can slow down or speed up the simulation or achieve certain ocean states/looks not possible with regular controls. However, other controls should be used instead, as this parameter often produces unrealistic results. ## Ocean Simulation & Material The material used for rendering the ocean can vary per environment profile. The system smoothly transitions between different materials/parameters when profiles change. Care is needed as texture properties can't be interpolated, and certain parameters, like changing time scales or texture scaling/offsets, can cause large changes during transitions. More details are in the Ocean Shader section. ## Ocean Simulation This component updates the ocean simulation, setting up data for burst jobs, dispatching them, and updating the final texture contents. It dispatches a job to fill the ocean spectrum data when ocean properties change, like wind speed or direction. This fills an n*n resolution array with float4's containing two complex numbers, representing initial wave properties like amplitude and frequency. It also fills a dispersion table buffer with initial time-related properties. Each frame starts with a dispersion job update, initializing a complex number array for the height component and two additional arrays for X and Z displacement components. These are inputs into the iFFT jobs, processed in groups targeting an entire row and then an entire column of the texture. The final result is written to the displacement texture using GetRawTextureData to write directly to the pixel data without requiring copies/conversions. This is an RGBA 16-bit float texture; the alpha channel is unused since there is no signed float texture format with only RGB channels. An unsigned texture could be used with a bias, but precision close to zero is essential. A second pass generates a normal/foam/smoothness map based on the displacement data. Normals are computed via the central difference of four neighboring displacement samples. Foam at wave peaks is calculated using the Jacobian of the displacement. The final value is processed in the shader according to foam threshold and strength parameters. The alpha channel stores a filtered smoothness value, helping with consistent highlights and environment reflections in the distance. It's calculated by averaging normal length and mapping it to a roughness value via analytical importance sampling of a GGX distribution. **Normal Map Baker** A function, accessible via a context menu option (right-clicking on the OceanSimulation component), bakes the current ocean's normal map into a texture. This can be used as a detail normal map in the ocean material or for other purposes. Increasing simulation resolution and adjusting properties can capture smaller-scale details in the normal map while leaving the ocean simulation to calculate larger-scale details and displacement. ![](./Images/OceanSystem/Fig2.png) ## Quadtree Renderer The ocean uses a Quadtree system for rendering instead of a single mesh like a plane. This approach balances vertex density and draw distance. The system moves with the camera, ensuring the ocean is always visible. ![](./Images/OceanSystem/Fig3.png) Each frame, the quadtree aligns with the camera position based on a grid size, set to the vertex spacing of the largest subdivision level. This prevents mesh sliding, which can cause artifacts as the camera moves. The highest quadtree level is checked against the camera view frustum. If visible, it is evaluated for subdivision based on its distance to the camera, multiplied by the current quadtree level's radius. If below a threshold, it subdivides, and each child patch is checked against the view frustum and tested for further subdivision if visible. Visible patches that are not close enough for further subdivision, or have reached the max subdivision level, are added to a rendering list. Patches are grouped into draw calls based on subdivision levels. If all neighbors share the same level, a simple tessellated quad is used. Otherwise, an index buffer with edge-stitching prevents seams between meshes. All patches use the same vertex buffer for performance but different index buffers. The final draw calls are rendered using Graphics.DrawMeshInstanced. Efforts to use displacement map LODs for smoother transitions between LODs were explored, but time constraints prevented full implementation. Issues with cracks between patches and performance concerns due to extra data processing remain. The system is controlled by several parameters: - **Size:** Total patch size, ideally large enough to reach the far plane in all directions. Balances processing needs and detail up close. Avoid excessive size. Techniques like fog can hide the ocean disappearing at a distance. - **Vertex Count:** Number of vertices along one side of a patch. For example, a value of 8 creates a patch with 8*8=64 vertices. (Actual count is N+1 to form a quad with N*N patches.) - **LOD levels:** Maximum grid subdivisions. Subdivision level depends on camera distance, with higher levels offering more detail up close but requiring more processing. - **Max Height:** Corresponds to wave height in world space, used for culling patches below the camera. - **Culling Bounds Scale:** Patches are culled based on a bounding box. High wind speeds can cause patches to disappear while still visible due to horizontal and vertical displacement. - **LOD threshold:** A patch subdivides into smaller patches when closer to the camera than its radius multiplied by this threshold. Increasing this value reduces flickering/popping as the camera moves but increases GPU vertex processing. - **Skirting Size:** Beyond the ocean distance, a simple "skirting mesh" renders more of the mesh with simplified geometry. No LOD-stitching means minor cracks may appear. Best used if rendering the ocean to the far plane is too demanding. ## Conclusion By using iFFT, CPU-side processing, and a dynamic quadtree renderer, the ocean system achieves high visual fidelity while maintaining performance. Future improvements could include smoother LOD transitions and optimizations for GPU-based displacement rendering. ### Relevant Files - [OceanSimulation.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanSimulation.cs) - [OceanSpectrumJob.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanSpectrumJob.cs) - [OceanDispersionJob.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanDispersionJob.cs) - [OceanFFTRowJob.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanFFTRowJob.cs) - [OceanFFTColumnJob.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanFFTColumnJob.cs) - [OceanFFTFinalJob.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanFFTFinalJob.cs) - [QuadtreeRenderer.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/QuadtreeRenderer.cs)