When building flagship dark-fantasy projects like Ghost Galleon 3D or the Abyssal Ocean Simulator, standard three.js materials like MeshStandardMaterial or MeshPhongMaterial only take you so far. To simulate tempestuous ocean water, rolling deep-sea fog, and glowing luminescent ember waves directly on the GPU, you need the raw power of GLSL (OpenGL Shading Language).

1. The WebGL Graphics Pipeline Unveiled

WebGL leverages your graphics card's massively parallel architecture. Instead of computing physics on one or two CPU cores, the GPU can run millions of simultaneous threads:

  1. Input Assembly: Vertex attributes (positions, normals, UV coordinates) are transferred to GPU VRAM as BufferGeometry.
  2. Vertex Shader: Executes once per vertex. Computes the screen-space projection and allows dynamic mathematical deformation (e.g., lifting waves).
  3. Rasterization: Converts geometric triangles into 2D fragments (candidate pixels on the screen).
  4. Fragment Shader: Executes once per fragment. Determines color, Fresnel reflection, lighting calculation, and alpha blending.

2. Vertex Shaders vs Fragment Shaders

Memory Communication in GLSL
Uniforms: Values sent from CPU JavaScript that stay constant across all vertices/pixels (e.g., uTime, uResolution, light positions).
Attributes: Unique data per vertex (e.g., position, UV).
Varyings: Variables passed from the Vertex Shader to the Fragment Shader, smoothly interpolated across the surface of the triangle.

3. Gerstner Waves: Math for Realistic Ocean Swells

Simple sine waves produce unnatural rounded swells. Real ocean waves have steep crests and wide troughs. In 1802, Franz Josef von Gerstner formulated trochoidal waves, displacing vertices both vertically and horizontally:

OceanVertexShader.glsl
uniform float uTime;
uniform float uWaveSpeed;
uniform float uWaveHeight;

varying vec2 vUv;
varying vec3 vNormal;
varying vec3 vWorldPosition;

// Gerstner Wave Displacement Function
vec3 calculateGerstnerWave(vec4 wave, vec3 p, inout vec3 tangent, inout vec3 binormal) {
    float steepness = wave.z;
    float wavelength = wave.w;
    float k = 2.0 * 3.14159265 / wavelength;
    float c = sqrt(9.8 / k);
    vec2 d = normalize(wave.xy);
    float f = k * (dot(d, p.xz) - c * uTime * uWaveSpeed);
    float a = steepness / k;

    tangent += vec3(
        -d.x * d.x * (steepness * sin(f)),
        d.x * (steepness * cos(f)),
        -d.x * d.y * (steepness * sin(f))
    );
    binormal += vec3(
        -d.x * d.y * (steepness * sin(f)),
        d.y * (steepness * cos(f)),
        -d.y * d.y * (steepness * sin(f))
    );

    return vec3(
        d.x * (a * cos(f)),
        a * sin(f) * uWaveHeight,
        d.y * (a * cos(f))
    );
}

void main() {
    vUv = uv;
    vec3 gridPoint = position;
    vec3 tangent = vec3(1.0, 0.0, 0.0);
    vec3 binormal = vec3(0.0, 0.0, 1.0);
    vec3 p = gridPoint;

    // Layer 3 harmonic wave fronts for organic chaotic sea swells
    p += calculateGerstnerWave(vec4(1.0, 0.2, 0.25, 60.0), gridPoint, tangent, binormal);
    p += calculateGerstnerWave(vec4(0.4, 0.9, 0.15, 30.0), gridPoint, tangent, binormal);
    p += calculateGerstnerWave(vec4(-0.2, 0.8, 0.1, 15.0), gridPoint, tangent, binormal);

    vec3 normal = normalize(cross(binormal, tangent));
    vNormal = normalMatrix * normal;
    
    vec4 worldPos = modelMatrix * vec4(p, 1.0);
    vWorldPosition = worldPos.xyz;

    gl_Position = projectionMatrix * viewMatrix * worldPos;
}

4. Constructing the Three.js ShaderMaterial

Now we bind our GLSL code inside Three.js using THREE.ShaderMaterial. We pass elapsed time continuously in our render loop:

ocean-scene.js
import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);

// High-subdivision plane for fluid displacement
const geometry = new THREE.PlaneGeometry(300, 300, 128, 128);
geometry.rotateX(-Math.PI / 2);

const oceanMaterial = new THREE.ShaderMaterial({
  vertexShader: oceanVertexShaderCode,
  fragmentShader: `
    uniform vec3 uDeepColor;
    uniform vec3 uSurfaceColor;
    varying vec3 vNormal;
    varying vec3 vWorldPosition;

    void main() {
      vec3 lightDir = normalize(vec3(0.5, 1.0, 0.3));
      float diffuse = max(dot(vNormal, lightDir), 0.0);
      
      // Dynamic Fresnel calculation for deep sea glow
      vec3 viewDir = normalize(cameraPosition - vWorldPosition);
      float fresnel = pow(1.0 - max(dot(viewDir, vNormal), 0.0), 3.0);
      
      vec3 finalColor = mix(uDeepColor, uSurfaceColor, diffuse);
      finalColor += vec3(0.89, 0.72, 0.36) * fresnel * 0.6; // Gold moonlight glint

      gl_FragColor = vec4(finalColor, 0.95);
    }
  `,
  uniforms: {
    uTime: { value: 0 },
    uWaveSpeed: { value: 1.2 },
    uWaveHeight: { value: 1.8 },
    uDeepColor: { value: new THREE.Color('#030b17') },
    uSurfaceColor: { value: new THREE.Color('#0d274c') }
  },
  transparent: true,
  wireframe: false
});

const oceanMesh = new THREE.Mesh(geometry, oceanMaterial);
scene.add(oceanMesh);

const clock = new THREE.Clock();
function animate() {
  requestAnimationFrame(animate);
  oceanMaterial.uniforms.uTime.value = clock.getElapsedTime();
  renderer.render(scene, camera);
}
animate();

5. 60 FPS Optimization: Minimizing Draw Calls

WebGL performance bottlenecks almost always stem from too many draw calls rather than vertex counts:

  • Cap Pixel Ratio: Always use Math.min(window.devicePixelRatio, 2). Retinas at 3x or 4x render 16x more fragments with no perceptible visual benefit.
  • Use InstancedMesh: If you are rendering 2,000 floating sea lanterns or cannonballs, never create 2,000 separate Mesh objects. Use a single THREE.InstancedMesh to draw everything in 1 single draw call!
  • Frustum Culling: Ensure bounding spheres on large animated meshes are configured accurately so Three.js discards off-screen geometry before sending it to the GPU.