7 Commits

7 changed files with 971 additions and 204 deletions

View File

@@ -95,6 +95,56 @@
font-size: 14px;
backdrop-filter: blur(10px);
}
.slider-group {
margin: 8px 0;
}
.slider-group label {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
font-size: 13px;
}
.slider-group input[type="range"] {
width: 100%;
height: 6px;
border-radius: 3px;
background: rgba(255, 255, 255, 0.2);
outline: none;
-webkit-appearance: none;
appearance: none;
}
.slider-group input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 14px;
height: 14px;
border-radius: 50%;
background: #4a9eff;
cursor: pointer;
}
.slider-group input[type="range"]::-moz-range-thumb {
width: 14px;
height: 14px;
border-radius: 50%;
background: #4a9eff;
cursor: pointer;
border: none;
}
.slider-value {
background: rgba(255, 255, 255, 0.15);
padding: 2px 6px;
border-radius: 3px;
font-size: 11px;
min-width: 35px;
text-align: center;
}
</style>
<script id="noise-fs" type="x-shader/x-fragment">
precision mediump float;
@@ -190,105 +240,355 @@
precision mediump float;
varying vec3 v_fragPos;
varying vec2 v_uv;
varying vec3 v_normal;
varying float v_waveHeight;
varying float v_foamFactor;
varying float v_distanceFade;
uniform vec3 eyePos;
uniform sampler2D displace_map;
uniform float uFoamIntensity;
uniform float uGlitterIntensity;
vec3 lightPos = vec3(0.,0.,10.); //not used in diffuse. diffuse uses a directional light. It is only used for specular glittering.
vec3 lightColor = vec3(1.0,1.0,1.0);
// Simple hash function for noise
float hash(vec2 p) {
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
}
//using forward difference
//Normal vectors are compute as: https://www.scratchapixel.com/lessons/procedural-generation-virtual-worlds/perlin-noise-part-2/perlin-noise-computing-derivatives
// Value noise for foam texture
float noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
f = f * f * (3.0 - 2.0 * f); // smoothstep
float a = hash(i);
float b = hash(i + vec2(1.0, 0.0));
float c = hash(i + vec2(0.0, 1.0));
float d = hash(i + vec2(1.0, 1.0));
return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}
// Fractal noise for more detailed foam
float foamNoise(vec2 p) {
float n = 0.0;
n += 0.5 * noise(p * 8.0);
n += 0.25 * noise(p * 16.0);
n += 0.125 * noise(p * 32.0);
n += 0.0625 * noise(p * 64.0);
return n;
}
void main(void) {
vec4 displace = texture2D(displace_map, v_uv);
//calculate normal
float gridPointDelta = (1. / 256.);
vec3 currPoint = vec3(0.0,0.0,displace.x);
vec3 right = vec3(gridPointDelta,0.0,texture2D(displace_map,vec2(v_uv.x + gridPointDelta,v_uv.y)).x*(1./1.));
vec3 left = vec3(-gridPointDelta,0.0,texture2D(displace_map,vec2(v_uv.x - gridPointDelta,v_uv.y)).x*(1./1.));
vec3 up = vec3(0.,gridPointDelta,texture2D(displace_map,vec2(v_uv.x ,v_uv.y + gridPointDelta)).x*(1./1.));
vec3 down = vec3(0.,-gridPointDelta,texture2D(displace_map,vec2(v_uv.x ,v_uv.y - gridPointDelta)).x*(1./1.));
vec3 lightColor = vec3(1.0, 1.0, 0.95);
vec3 sunDirection = normalize(vec3(0.3, 0.5, 0.8));
//vec3 tangent = normalize(right - currPoint);
//vec3 biTangent = normalize(up - currPoint);
vec3 tangent = normalize(vec3(gridPointDelta,0.,right.z-left.z));
vec3 biTangent = normalize(vec3(0.,gridPointDelta,down.z-up.z));
//vec3 normal = biTangent;
vec3 normal = cross(tangent, biTangent);
vec3 norm = normalize(v_normal);
vec3 norm = normalize(normal);
norm.y *= -1.; //Normal y direction is somehow inverted
//vec3 lightDir = normalize(lightPos - v_fragPos);
vec3 lightDir = normalize(-vec3(0.0,.0,-1.)); //sun shines in drection of -z
// View direction
vec3 viewDir = normalize(eyePos - v_fragPos);
float diff = max(dot(norm,lightDir),0.0);
// Diffuse lighting
float diff = max(dot(norm, sunDirection), 0.0);
vec3 diffuse = diff * lightColor;
vec3 result = (diffuse) * vec3(0.0,0.0,1.0);
//Old lightning
vec3 toCameraVector = normalize(v_fragPos - eyePos);
vec3 reflec = normalize(reflect(toCameraVector, norm));
// Schlick's approximation to Fresnel factor
float R0 = 0.02;
float fresnel = R0 + (1.0 - R0) * pow(1.0 - max(dot(norm, viewDir), 0.0), 5.0);
//Schlicks approximation to Fresnelfactor
float n1 = 1., n2 = 1.33333;
float R0 = pow((n1-n2)/(n1+n2), 2.);
float fresnel = R0 + (1. - R0)*pow((1.-dot(norm,reflec)),5.) ;
// Deep and shallow water colors
vec3 deepColor = vec3(0.0, 0.08, 0.15);
vec3 shallowColor = vec3(0.0, 0.35, 0.45);
vec3 skyColor = vec3(0.55, 0.7, 0.9); // Match skybox horizon color
vec3 foamColor = vec3(0.95, 0.98, 1.0);
//vec3 waterColor = vec3(34./255.,154./255.,211./255.);
vec3 oceanColor = vec3(0,.4,.4); // under-sea colour
vec3 skyColor = vec3(1.,1.,1.);
// Blend between deep and shallow based on wave height
float heightFactor = clamp(v_waveHeight * 2.0 + 0.5, 0.0, 1.0);
vec3 oceanColor = mix(deepColor, shallowColor, heightFactor);
//Subsurface scattering
vec3 sssSun = vec3(0.,-5.,-7.0);
vec3 tosssSunVec = normalize(sssSun - v_fragPos);
vec3 tosssSun = normalize(vec3(0.0,-100.,1.));
float ssDistortion = 0.1;
float sssIntensity = 1.;
vec3 halfWay = normalize(tosssSun+norm*ssDistortion);
float ssScateringCoef = pow(clamp(dot(toCameraVector,-halfWay),0.0,1.0),5.) * sssIntensity;
//Sun glittering
float glitterFactor = max(0.0,dot(tosssSunVec,reflect(-toCameraVector,norm)));
if(!(glitterFactor > 0.98)) {
glitterFactor = 0.0;
}
// Sun glitter - uses wave normals for natural sparkle from fine surface detail
vec3 reflectDir = reflect(-sunDirection, norm);
float specAngle = max(dot(viewDir, reflectDir), 0.0);
//gl_FragColor = vec4(oceanColor + lightColor * glitterFactor,1.0);
//gl_FragColor=vec4(clamp(oceanColor + (oceanColor*ssScateringCoef),0.,1.0),1.0); //Display subsurfacecatterting component
//gl_FragColor = vec4((mix(oceanColor,skyColor,fresnel).xyz), 1.); //Just display reflection component
//gl_FragColor = vec4(diffuse * oceanColor,1.0); //Render only diffuse component
//gl_FragColor = vec4(normal,1.0); //show Normal map
//gl_FragColor = vec4(displace.x,displace.x,displace.x,1.0); //Show Perlin Noise texture deactivate vertex distrotion before
gl_FragColor = vec4((clamp(diffuse,0.97,1.0) * (mix(oceanColor + (oceanColor*ssScateringCoef),skyColor*0.8,fresnel).xyz))+ lightColor * glitterFactor, 1.0); //All combined
// Smooth base specular
float specBase = pow(specAngle, 64.0) * 0.4;
// Medium highlights
float specMid = pow(specAngle, 256.0) * 1.2;
// Sharp glitter peaks
float specSharp = pow(specAngle, 1024.0) * 3.0;
vec3 specular = (specBase + specMid + specSharp) * lightColor * uGlitterIntensity;
// Subsurface scattering
float sssDot = max(dot(viewDir, -sunDirection), 0.0);
float sssWaveContribution = clamp(v_waveHeight + 0.3, 0.0, 1.0);
float sssNormalContribution = pow(1.0 - max(dot(norm, sunDirection), 0.0), 2.0);
float sss = pow(sssDot, 3.0) * sssWaveContribution * sssNormalContribution * 1.5;
vec3 sssColor = vec3(0.1, 0.6, 0.5) * sss;
// Rim SSS effect
float rimSSS = pow(1.0 - max(dot(norm, viewDir), 0.0), 3.0) * 0.3;
vec3 rimColor = vec3(0.0, 0.4, 0.4) * rimSSS * heightFactor;
// Foam with texture - foam persists longer
vec2 foamUV = v_fragPos.xy * 1.5;
float foamPattern = foamNoise(foamUV);
// Create foam patches with softer edges
float foamThreshold = 1.0 - v_foamFactor * 1.2 * uFoamIntensity;
float foam = smoothstep(foamThreshold, foamThreshold + 0.35, foamPattern);
// Add some bubble-like spots with softer transition
float bubbles = smoothstep(0.65, 0.85, noise(foamUV * 15.0)) * v_foamFactor;
foam = clamp(foam + bubbles * 0.3, 0.0, 1.0);
// Softer edge fade based on foam factor
foam *= smoothstep(0.0, 0.25, v_foamFactor);
// Additional soft fade at foam edges and fade out at distance
foam = pow(foam, 0.7) * uFoamIntensity * v_distanceFade;
// Combine all lighting
vec3 reflectedColor = mix(oceanColor, skyColor, fresnel);
vec3 waterColor = reflectedColor * clamp(diffuse, 0.3, 1.0) + specular + sssColor + rimColor;
// Blend foam on top with slight transparency variation
vec3 finalColor = mix(waterColor, foamColor * clamp(diffuse + 0.4, 0.0, 1.0), foam * 0.85);
// Atmospheric fog for distant water - blends to horizon
float dist = length(eyePos - v_fragPos);
// Exponential fog with aggressive horizon fade
float fogFactor = exp(-dist * 0.04);
// Fully fade at stretched horizon vertices
float horizonFade = smoothstep(40.0, 80.0, dist);
fogFactor *= (1.0 - horizonFade);
fogFactor = clamp(fogFactor, 0.0, 1.0);
// Horizon color must exactly match skybox horizon
vec3 horizonColor = vec3(0.55, 0.7, 0.9);
finalColor = mix(horizonColor, finalColor, fogFactor);
gl_FragColor = vec4(finalColor, 1.0);
}
</script>
<script id="default-vs" type="x-shader/x-vertex">
precision mediump float;
attribute vec3 positionAttr;
uniform mat4 view;
uniform mat4 model;
uniform mat4 projection;
uniform sampler2D displace_map;
uniform float uTime;
uniform float uWaveHeight;
uniform float uWaveSpeed;
uniform vec3 eyePos;
varying vec2 v_uv;
varying vec3 v_fragPos;
varying vec3 v_normal;
varying float v_waveHeight;
varying float v_foamFactor;
varying float v_distanceFade;
// Gerstner wave function - higher steepness = spikier waves
vec3 gerstnerWave(vec2 pos, float time, vec2 direction, float steepness, float wavelength, out vec3 tangent, out vec3 binormal) {
float k = 2.0 * 3.14159 / wavelength;
float c = sqrt(9.8 / k);
vec2 d = normalize(direction);
float f = k * (dot(d, pos) - c * time);
float a = steepness / k;
tangent = vec3(
1.0 - steepness * d.x * d.x * sin(f),
steepness * d.x * cos(f),
-steepness * d.x * d.y * sin(f)
);
binormal = vec3(
-steepness * d.x * d.y * sin(f),
steepness * d.y * cos(f),
1.0 - steepness * d.y * d.y * sin(f)
);
return vec3(
d.x * a * cos(f),
a * sin(f),
d.y * a * cos(f)
);
}
void main(void) {
vec4 displace = texture2D(displace_map, vec2(positionAttr.x,positionAttr.y));
vec4 worldPos = model * vec4(positionAttr.x,positionAttr.y,positionAttr.z + displace.x, 1.0);
gl_Position = projection * view * worldPos;
vec4 worldPos = model * vec4(positionAttr.xyz, 1.0);
// Grid is on XY plane, Z is up
vec2 pos = worldPos.xy;
float time = uTime * 0.0004 * uWaveSpeed;
// Calculate distance from camera for wave fading
float distToCamera = length(worldPos.xyz - eyePos);
float waveFade = exp(-distToCamera * 0.015); // Gradual fade over distance
waveFade = clamp(waveFade, 0.0, 1.0);
v_distanceFade = waveFade;
float heightMod = uWaveHeight * waveFade;
vec3 displacement = vec3(0.0);
vec3 tangent = vec3(1.0, 0.0, 0.0);
vec3 binormal = vec3(0.0, 0.0, 1.0);
vec3 t, b;
// === Large primary waves ===
displacement += gerstnerWave(pos, time, vec2(1.0, 0.2), 0.42 * heightMod, 6.0, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time * 1.1, vec2(0.4, 1.0), 0.35 * heightMod, 5.0, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// === Medium waves ===
displacement += gerstnerWave(pos, time * 0.9, vec2(-0.6, 0.8), 0.25 * heightMod, 3.0, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time * 1.2, vec2(0.8, -0.5), 0.2 * heightMod, 2.2, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time, vec2(-0.3, -0.9), 0.18 * heightMod, 1.8, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// === Small detail waves ===
displacement += gerstnerWave(pos, time * 1.2, vec2(0.9, -0.4), 0.12 * heightMod, 1.2, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time * 0.9, vec2(-0.5, -0.7), 0.10 * heightMod, 1.0, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time * 1.3, vec2(0.3, 0.95), 0.08 * heightMod, 0.8, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// === Tiny ripples ===
displacement += gerstnerWave(pos, time * 2.0, vec2(0.9, 0.1), 0.05 * heightMod, 0.35, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time * 2.2, vec2(-0.2, 0.95), 0.04 * heightMod, 0.25, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// === Micro ripples for fine surface detail ===
displacement += gerstnerWave(pos, time * 2.5, vec2(0.7, -0.7), 0.03 * heightMod, 0.18, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time * 3.0, vec2(-0.8, 0.6), 0.025 * heightMod, 0.12, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time * 3.5, vec2(0.5, -0.9), 0.02 * heightMod, 0.08, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// Store wave height for fragment shader
v_waveHeight = displacement.y;
// Calculate foam factor - foam appears on the FRONT/leading edge of waves
// When wave is rising (tangent.y > 0), that's where foam should appear
float waveRising = smoothstep(0.0, 0.3, tangent.y + binormal.y);
float foamFromHeight = smoothstep(0.0, 0.25, displacement.y);
float waveSlope = length(vec2(tangent.y, binormal.y));
float foamFromSlope = smoothstep(0.2, 0.6, waveSlope);
// Foam appears where wave is high AND rising (leading edge / crest)
v_foamFactor = clamp((foamFromHeight * waveRising * 1.2 + foamFromSlope * 0.3), 0.0, 1.0);
// Apply displacement - Z is up, XY is horizontal plane
worldPos.x += displacement.x;
worldPos.y += displacement.z;
worldPos.z += displacement.y; // Height displacement
// Calculate normal from tangent and binormal
// Blend normal towards flat (0, 0, 1) based on distance
vec3 normal = normalize(cross(binormal, tangent));
vec3 flatNormal = vec3(0.0, 0.0, 1.0);
normal = mix(flatNormal, normal, waveFade);
v_normal = vec3(normal.x, normal.z, normal.y);
// Horizon projection: calculate where the world horizon would be in clip space
// The horizon is where z=0 plane meets the sky (at eye height)
// Project a point at the horizon in the same XY direction as this vertex
float horizonStretch = smoothstep(40.0, 100.0, distToCamera);
if (horizonStretch > 0.0) {
// Get direction from camera to vertex (XY only, on ocean plane)
vec2 toVertex = normalize(worldPos.xy - eyePos.xy);
// Create a horizon point far away in that direction at z=0
vec3 horizonPoint = vec3(
eyePos.xy + toVertex * 10000.0,
0.0
);
// Project horizon point to get true horizon clip position
vec4 horizonClip = projection * view * vec4(horizonPoint, 1.0);
// Get actual clip position
vec4 clipPos = projection * view * worldPos;
// Blend vertex toward the horizon point's clip position (normalized)
// Overshoot slightly past horizon to ensure no gap
float horizonY = horizonClip.y / horizonClip.w * clipPos.w;
float overshoot = 1.0 + horizonStretch * 0.1; // Push slightly past horizon
clipPos.y = mix(clipPos.y, horizonY * overshoot, horizonStretch);
gl_Position = clipPos;
} else {
gl_Position = projection * view * worldPos;
}
v_fragPos = worldPos.xyz;
v_uv = positionAttr.xy;
}
</script>
}
</script>
<script id="sky-fs" type="x-shader/x-fragment">
precision mediump float;
varying vec3 fragPos;
varying vec3 v_rayDir;
uniform vec3 uSunDirection;
void main(void) {
gl_FragColor = vec4(fragPos,1.0);
vec3 rayDir = normalize(v_rayDir);
// Use Z as up (matches world space where ocean is on XY plane)
float upAmount = rayDir.z;
// Sky gradient - from horizon to zenith
float horizonBlend = pow(1.0 - max(upAmount, 0.0), 2.0);
vec3 zenithColor = vec3(0.15, 0.35, 0.75); // Deep blue at top
vec3 horizonColor = vec3(0.55, 0.7, 0.9); // Light blue at horizon
vec3 skyColor = mix(zenithColor, horizonColor, horizonBlend);
// Add warm glow near horizon
float horizonGlow = pow(max(1.0 - abs(upAmount), 0.0), 6.0);
skyColor += vec3(0.4, 0.25, 0.1) * horizonGlow * 0.4;
// Sun direction already in correct coordinate system
vec3 sunDir = normalize(uSunDirection);
float sunAngle = max(dot(rayDir, sunDir), 0.0);
// Sun disk
float sunDisk = smoothstep(0.9993, 0.9998, sunAngle);
vec3 sunColor = vec3(1.0, 0.95, 0.85);
// Sun glow
float sunGlow = pow(sunAngle, 48.0) * 0.6;
float sunHalo = pow(sunAngle, 6.0) * 0.25;
// Combine sun effects
skyColor += sunColor * sunDisk * 3.0;
skyColor += vec3(1.0, 0.85, 0.5) * sunGlow;
skyColor += vec3(1.0, 0.9, 0.7) * sunHalo;
// Below horizon - fade to darker color
if (upAmount < 0.0) {
float depth = -upAmount;
vec3 deepColor = vec3(0.02, 0.08, 0.15);
skyColor = mix(horizonColor * 0.7, deepColor, smoothstep(0.0, 0.5, depth));
}
gl_FragColor = vec4(skyColor, 1.0);
}
</script>
<script id="sky-vs" type="x-shader/x-vertex">
@@ -296,14 +596,15 @@
uniform mat4 projection;
uniform mat4 view;
uniform mat4 testModel;
varying vec3 fragPos;
varying vec3 v_rayDir;
void main(void) {
gl_PointSize = 10.;
gl_Position = projection * mat4(mat3(view)) * vec4(positionAttr, 1.0);
fragPos = (view * vec4(positionAttr,1.0)).xyz; //This is wrong probably
v_rayDir = positionAttr;
// Remove translation from view matrix for skybox
mat4 rotView = mat4(mat3(view));
vec4 pos = projection * rotView * vec4(positionAttr, 1.0);
gl_Position = pos;
}
</script>
</head>
@@ -330,6 +631,31 @@
<div class="control-group">
<strong>Toggle Help:</strong> <span class="key">H</span>
</div>
<div class="control-group" style="margin-top: 10px; padding-top: 10px; border-top: 1px solid rgba(255, 255, 255, 0.2);">
<button id="wireframe-toggle" style="background: rgba(255, 255, 255, 0.2); color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer; width: 100%; font-size: 13px;">Wireframe: OFF</button>
</div>
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255, 255, 255, 0.2);">
<strong>Wave Settings</strong>
<div class="slider-group">
<label>Wave Height <span class="slider-value" id="wave-height-val">1.0</span></label>
<input type="range" id="wave-height" min="0" max="2" step="0.1" value="1">
</div>
<div class="slider-group">
<label>Wave Speed <span class="slider-value" id="wave-speed-val">1.0</span></label>
<input type="range" id="wave-speed" min="0.1" max="3" step="0.1" value="1">
</div>
</div>
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255, 255, 255, 0.2);">
<strong>Foam & Glitter</strong>
<div class="slider-group">
<label>Foam Intensity <span class="slider-value" id="foam-intensity-val">1.0</span></label>
<input type="range" id="foam-intensity" min="0" max="2" step="0.1" value="1">
</div>
<div class="slider-group">
<label>Glitter Intensity <span class="slider-value" id="glitter-intensity-val">1.0</span></label>
<input type="range" id="glitter-intensity" min="0" max="3" step="0.1" value="1">
</div>
</div>
</div>
<button id="toggle-controls">Toggle Controls (H)</button>
@@ -351,6 +677,28 @@
controls.classList.toggle('hidden');
}
});
// Wireframe toggle
const wireframeBtn = document.getElementById('wireframe-toggle');
wireframeBtn.addEventListener('click', () => {
window.dispatchEvent(new CustomEvent('toggleWireframe'));
});
// Slider controls
function setupSlider(id, eventName) {
const slider = document.getElementById(id);
const valueDisplay = document.getElementById(id + '-val');
slider.addEventListener('input', (e) => {
const value = parseFloat(e.target.value);
valueDisplay.textContent = value.toFixed(1);
window.dispatchEvent(new CustomEvent(eventName, { detail: value }));
});
}
setupSlider('wave-height', 'waveHeightChange');
setupSlider('wave-speed', 'waveSpeedChange');
setupSlider('foam-intensity', 'foamIntensityChange');
setupSlider('glitter-intensity', 'glitterIntensityChange');
</script>
</body>

View File

@@ -1,62 +1,87 @@
import { vec3, mat4, vec4 } from 'gl-matrix';
/** A camera that always looks at the world origin. Can have an offset and be rotated. */
/** FPS-style flight camera with free movement */
export class Camera {
pos: vec3;
target: vec3;
up: vec3;
xRot: number;
yRot: number;
offset: number;
// FPS camera angles (in radians)
pitch: number; // Up/down rotation
yaw: number; // Left/right rotation
// Direction vectors
forward: vec3;
right: vec3;
constructor() {
this.pos = vec3.create();
vec3.set(this.pos, 0.0, 0.0, 0.0);
vec3.set(this.pos, 0.0, -3.0, 2.0); // Start above and behind origin
this.target = vec3.create();
vec3.set(this.target, 0.0, 0.0, 0.0);
this.up = vec3.create();
vec3.set(this.up, 0.0, 1.0, 0.0);
this.xRot = 0.0;
this.yRot = 0.0;
this.offset = 0.0;
vec3.set(this.up, 0.0, 0.0, 1.0); // Z is up
this.forward = vec3.create();
this.right = vec3.create();
this.pitch = -0.3; // Looking slightly down
this.yaw = Math.PI / 2; // Looking toward +Y
this.updateVectors();
}
setRotationX(rotX: number): void {
this.xRot = rotX;
this.updatePos();
/** Rotate camera by mouse delta */
rotate(deltaX: number, deltaY: number, sensitivity: number = 0.003): void {
this.yaw -= deltaX * sensitivity;
this.pitch -= deltaY * sensitivity;
// Clamp pitch to avoid flipping
const maxPitch = Math.PI / 2 - 0.01;
this.pitch = Math.max(-maxPitch, Math.min(maxPitch, this.pitch));
this.updateVectors();
}
setRotationY(rotY: number): void {
this.yRot = rotY;
this.updatePos();
/** Move camera in the direction it's looking */
moveForward(amount: number): void {
vec3.scaleAndAdd(this.pos, this.pos, this.forward, amount);
this.updateVectors();
}
/** Sets the offset to world origin. */
setOffset(off: number): void {
this.offset = off;
this.updatePos();
moveRight(amount: number): void {
vec3.scaleAndAdd(this.pos, this.pos, this.right, amount);
this.updateVectors();
}
/** Recalculates the position according to xy-rotation and offset. */
private updatePos(): void {
const transformation: mat4 = mat4.create();
mat4.identity(transformation);
moveUp(amount: number): void {
// Move along world Z axis
this.pos[2] += amount;
this.updateVectors();
}
//2. xy-Rotation
mat4.rotateX(transformation, transformation, this.xRot);
mat4.rotateY(transformation, transformation, this.yRot);
/** Move in the actual look direction (including vertical) */
moveInLookDirection(amount: number): void {
vec3.scaleAndAdd(this.pos, this.pos, this.forward, amount);
this.updateVectors();
}
//1. Translation
const translation = vec3.create();
vec3.set(translation, 0.0, 0.0, this.offset);
mat4.translate(transformation, transformation, translation);
/** Update direction vectors from pitch/yaw */
private updateVectors(): void {
// Calculate forward vector from pitch and yaw
// Z is up, so we use different axis mapping
this.forward[0] = Math.cos(this.pitch) * Math.cos(this.yaw);
this.forward[1] = Math.cos(this.pitch) * Math.sin(this.yaw);
this.forward[2] = Math.sin(this.pitch);
vec3.normalize(this.forward, this.forward);
const temp: vec4 = vec4.create();
vec4.set(temp, 0.0, 0.0, 0.0, 1.0);
vec4.transformMat4(temp, temp, transformation);
// Right vector is perpendicular to forward and world up
const worldUp = vec3.fromValues(0, 0, 1);
vec3.cross(this.right, this.forward, worldUp);
vec3.normalize(this.right, this.right);
vec3.set(this.pos, temp[0], temp[1], temp[2]);
// Camera up is perpendicular to forward and right
vec3.cross(this.up, this.right, this.forward);
vec3.normalize(this.up, this.up);
// Update target
vec3.add(this.target, this.pos, this.forward);
}
getViewMatrix(): mat4 {
@@ -64,4 +89,9 @@ export class Camera {
mat4.lookAt(ret, this.pos, this.target, this.up);
return ret;
}
/** Get view direction for LOD calculations */
getViewDirection(): vec3 {
return vec3.clone(this.forward);
}
}

View File

@@ -1,23 +1,35 @@
/** Grid for the water surface */
export class Grid {
private indices: number[] = [];
private lineIndices: number[] = [];
private vertices: number[] = [];
private vao: WebGLVertexArrayObject | null = null;
private lineVao: WebGLVertexArrayObject | null = null;
private size: number;
private offsetX: number;
private offsetY: number;
private scale: number;
constructor(size: number = 128) {
constructor(size: number = 128, offsetX: number = 0, offsetY: number = 0, scale: number = 1) {
this.size = size;
this.offsetX = offsetX;
this.offsetY = offsetY;
this.scale = scale;
}
generate(): void {
this.indices = [];
this.lineIndices = [];
this.vertices = [];
for (let j = 0; j <= this.size; ++j) {
for (let i = 0; i <= this.size; ++i) {
// Generate Vertices
const x = i / this.size;
const y = j / this.size;
// Generate Vertices normalized to 0-1, then scale and offset
// Grid is on XY plane (horizontal), Z is up
const u = i / this.size;
const v = j / this.size;
const x = (u - 0.5) * this.scale + this.offsetX;
const y = (v - 0.5) * this.scale + this.offsetY;
const z = 0;
this.vertices.push(x, y, z);
@@ -35,6 +47,16 @@ export class Grid {
this.indices.push(row2 + i + 1);
this.indices.push(row2 + i);
}
// Generate line indices for wireframe
if (i < this.size) {
const currentVertex = j * (this.size + 1) + i;
this.lineIndices.push(currentVertex, currentVertex + 1);
}
if (j < this.size) {
const currentVertex = j * (this.size + 1) + i;
this.lineIndices.push(currentVertex, currentVertex + (this.size + 1));
}
}
}
}
@@ -42,6 +64,7 @@ export class Grid {
initVAO(gl: WebGL2RenderingContext): void {
this.generate();
// Create VAO for filled triangles
this.vao = gl.createVertexArray();
gl.bindVertexArray(this.vao);
@@ -56,10 +79,28 @@ export class Grid {
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 3 * Float32Array.BYTES_PER_ELEMENT, 0);
gl.enableVertexAttribArray(0);
gl.bindVertexArray(null);
// Create VAO for wireframe lines
this.lineVao = gl.createVertexArray();
gl.bindVertexArray(this.lineVao);
gl.bindBuffer(gl.ARRAY_BUFFER, vboGrid);
const iboLine: WebGLBuffer | null = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, iboLine);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(this.lineIndices), gl.STATIC_DRAW);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 3 * Float32Array.BYTES_PER_ELEMENT, 0);
gl.enableVertexAttribArray(0);
gl.bindVertexArray(null);
}
draw(gl: WebGL2RenderingContext): void {
if (this.vao) {
draw(gl: WebGL2RenderingContext, wireframe: boolean = false): void {
if (wireframe && this.lineVao) {
gl.bindVertexArray(this.lineVao);
gl.drawElements(gl.LINES, this.lineIndices.length, gl.UNSIGNED_INT, 0);
gl.bindVertexArray(null);
} else if (this.vao) {
gl.bindVertexArray(this.vao);
gl.drawElements(gl.TRIANGLES, this.indices.length, gl.UNSIGNED_INT, 0);
gl.bindVertexArray(null);

200
src/OceanLOD.ts Normal file
View File

@@ -0,0 +1,200 @@
import { Grid } from './Grid';
import { vec3 } from 'gl-matrix';
/** Manages multiple ocean grid patches with LOD based on camera distance and view cone */
export class OceanLOD {
private grids: Array<{
grid: Grid;
centerX: number;
centerY: number;
size: number;
lodLevel: number;
visible: boolean;
}> = [];
private readonly LOD_LEVELS = [
{ distance: 3.0, gridSize: 256 }, // Very close - ultra detail
{ distance: 8.0, gridSize: 128 }, // Close - high detail
{ distance: 20.0, gridSize: 64 }, // Medium distance
{ distance: 40.0, gridSize: 16 }, // Far - low detail
{ distance: 80.0, gridSize: 8 }, // Very far - minimal
{ distance: Infinity, gridSize: 4 },// Horizon - lowest (will be stretched anyway)
];
private readonly PATCH_SIZE = 10.0; // Larger patches = fewer needed
private readonly PATCHES_PER_SIDE = 21; // 21x21 = 441 patches (covers ~200 units)
private readonly VIEW_CONE_COS = Math.cos(Math.PI * 0.45); // ~81 degree half-angle (wider than typical FOV)
// Track the grid origin to re-center when camera moves
private gridOriginX: number = 0;
private gridOriginY: number = 0;
constructor() {
this.createGridPatches();
}
private createGridPatches(): void {
const halfPatches = Math.floor(this.PATCHES_PER_SIDE / 2);
for (let y = -halfPatches; y <= halfPatches; y++) {
for (let x = -halfPatches; x <= halfPatches; x++) {
const centerX = x * this.PATCH_SIZE + this.gridOriginX;
const centerY = y * this.PATCH_SIZE + this.gridOriginY;
// Start with lowest detail - will be updated based on camera
const grid = new Grid(
this.LOD_LEVELS[5].gridSize,
centerX,
centerY,
this.PATCH_SIZE
);
this.grids.push({
grid,
centerX,
centerY,
size: this.PATCH_SIZE,
lodLevel: 5,
visible: true
});
}
}
}
/** Re-center the grid around a new origin */
private recenterGrid(gl: WebGL2RenderingContext, newOriginX: number, newOriginY: number): void {
this.gridOriginX = newOriginX;
this.gridOriginY = newOriginY;
const halfPatches = Math.floor(this.PATCHES_PER_SIDE / 2);
let i = 0;
for (let y = -halfPatches; y <= halfPatches; y++) {
for (let x = -halfPatches; x <= halfPatches; x++) {
const patch = this.grids[i];
const newCenterX = x * this.PATCH_SIZE + this.gridOriginX;
const newCenterY = y * this.PATCH_SIZE + this.gridOriginY;
// Only update if patch position changed
if (patch.centerX !== newCenterX || patch.centerY !== newCenterY) {
patch.centerX = newCenterX;
patch.centerY = newCenterY;
// Force LOD recalculation
patch.lodLevel = -1;
}
i++;
}
}
}
/** Update LOD based on camera position and view direction */
updateLOD(gl: WebGL2RenderingContext, cameraPos: vec3, cameraTarget: vec3): void {
// Calculate view direction (normalized)
const viewDir = vec3.create();
vec3.subtract(viewDir, cameraTarget, cameraPos);
vec3.normalize(viewDir, viewDir);
// Check if we need to recenter the grid (camera moved more than one patch size from origin)
const cameraGridX = Math.floor(cameraPos[0] / this.PATCH_SIZE) * this.PATCH_SIZE;
const cameraGridY = Math.floor(cameraPos[1] / this.PATCH_SIZE) * this.PATCH_SIZE;
if (cameraGridX !== this.gridOriginX || cameraGridY !== this.gridOriginY) {
this.recenterGrid(gl, cameraGridX, cameraGridY);
}
for (const patch of this.grids) {
// Calculate vector from camera to patch center (on XY plane, Z=0 for ocean surface)
const toPatch = vec3.fromValues(
patch.centerX - cameraPos[0],
patch.centerY - cameraPos[1],
0 - cameraPos[2] // Ocean is at Z=0
);
const distance = vec3.length(toPatch);
// Normalize direction to patch
const toPatchDir = vec3.create();
vec3.normalize(toPatchDir, toPatch);
// Calculate dot product with view direction (how aligned is patch with where we're looking)
const dotProduct = vec3.dot(viewDir, toPatchDir);
// Determine if patch is in front of camera and within view cone
const isInFront = dotProduct > -0.3; // Slightly behind is ok for edge cases
const isInViewCone = dotProduct > this.VIEW_CONE_COS;
// Frustum culling - don't draw patches behind camera
patch.visible = isInFront;
// Calculate LOD level
let newLodLevel = 5; // Default to lowest detail
if (!isInFront) {
// Behind camera - skip (will not be drawn)
newLodLevel = 5;
} else if (isInViewCone) {
// In view cone - use distance-based LOD
for (let i = 0; i < this.LOD_LEVELS.length; i++) {
if (distance < this.LOD_LEVELS[i].distance) {
newLodLevel = i;
break;
}
}
} else {
// In front but outside view cone - reduce detail by 1-2 levels
for (let i = 0; i < this.LOD_LEVELS.length; i++) {
if (distance < this.LOD_LEVELS[i].distance) {
newLodLevel = Math.min(i + 2, 5); // Reduce detail
break;
}
}
}
// Only recreate grid if LOD level changed
if (newLodLevel !== patch.lodLevel) {
patch.lodLevel = newLodLevel;
patch.grid = new Grid(
this.LOD_LEVELS[newLodLevel].gridSize,
patch.centerX,
patch.centerY,
patch.size
);
patch.grid.initVAO(gl);
}
}
}
initVAO(gl: WebGL2RenderingContext): void {
for (const { grid } of this.grids) {
grid.initVAO(gl);
}
}
draw(gl: WebGL2RenderingContext, wireframe: boolean = false): void {
for (const patch of this.grids) {
if (patch.visible) {
patch.grid.draw(gl, wireframe);
}
}
}
getGridCount(): number {
return this.grids.length;
}
getTotalVertexCount(): number {
let total = 0;
for (const { grid } of this.grids) {
total += grid.getIndexCount() / 3;
}
return total;
}
/** Get statistics about current LOD distribution */
getLODStats(): { [key: number]: number } {
const stats: { [key: number]: number } = { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };
for (const patch of this.grids) {
stats[patch.lodLevel]++;
}
return stats;
}
}

85
src/Skybox.ts Normal file
View File

@@ -0,0 +1,85 @@
/** Skybox cube for rendering the sky */
export class Skybox {
private vao: WebGLVertexArrayObject | null = null;
private vbo: WebGLBuffer | null = null;
private indexCount: number = 0;
constructor() {}
initVAO(gl: WebGL2RenderingContext): void {
// Cube vertices - positions only
const vertices = new Float32Array([
// Front face
-1, -1, 1,
1, -1, 1,
1, 1, 1,
-1, 1, 1,
// Back face
-1, -1, -1,
-1, 1, -1,
1, 1, -1,
1, -1, -1,
// Top face
-1, 1, -1,
-1, 1, 1,
1, 1, 1,
1, 1, -1,
// Bottom face
-1, -1, -1,
1, -1, -1,
1, -1, 1,
-1, -1, 1,
// Right face
1, -1, -1,
1, 1, -1,
1, 1, 1,
1, -1, 1,
// Left face
-1, -1, -1,
-1, -1, 1,
-1, 1, 1,
-1, 1, -1,
]);
const indices = new Uint16Array([
0, 2, 1, 0, 3, 2, // front
4, 6, 5, 4, 7, 6, // back
8, 10, 9, 8, 11, 10, // top
12, 14, 13, 12, 15, 14, // bottom
16, 18, 17, 16, 19, 18, // right
20, 22, 21, 20, 23, 22, // left
]);
this.indexCount = indices.length;
this.vao = gl.createVertexArray();
gl.bindVertexArray(this.vao);
this.vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
const ibo = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
// Position attribute
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
gl.bindVertexArray(null);
}
draw(gl: WebGL2RenderingContext): void {
if (!this.vao) return;
// Disable face culling for skybox (we're inside the cube)
gl.disable(gl.CULL_FACE);
gl.bindVertexArray(this.vao);
gl.drawElements(gl.TRIANGLES, this.indexCount, gl.UNSIGNED_SHORT, 0);
gl.bindVertexArray(null);
gl.enable(gl.CULL_FACE);
}
}

View File

@@ -1,7 +1,7 @@
// Configuration Constants
export const GRID_SIZE = 128;
export const NOISE_TEXTURE_WIDTH = 256;
export const NOISE_TEXTURE_HEIGHT = 256;
export const NOISE_TEXTURE_WIDTH = 1024;
export const NOISE_TEXTURE_HEIGHT = 1024;
export const CANVAS_WIDTH = 800;
export const CANVAS_HEIGHT = 600;
export const FOV = 1.0;

View File

@@ -1,6 +1,7 @@
import { vec3, mat4 } from 'gl-matrix';
import { Camera } from './Camera';
import { Grid } from './Grid';
import { OceanLOD } from './OceanLOD';
import { Skybox } from './Skybox';
import { createProgram } from './Shader';
import * as Config from './constants';
@@ -89,10 +90,12 @@ function initGeometry() {
var perlinNoiseProgram: WebGLProgram | null;
var defaultProgram: WebGLProgram | null;
var textureProgram: WebGLProgram | null;
var skyProgram: WebGLProgram | null;
function initShaders() {
perlinNoiseProgram = createProgram(gl, "ndc-vs", "noise-fs", "Perlin Noise");
defaultProgram = createProgram(gl, "default-vs", "default-fs", "Default");
textureProgram = createProgram(gl, "texture-vs", "texture-fs", "Texture");
skyProgram = createProgram(gl, "sky-vs", "sky-fs", "Sky");
}
/** Init an FBO used for the first render pass / perlin noise */
@@ -112,8 +115,8 @@ function initFBO() {
// set the filtering so we don't need mips
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureFBO, 0);
@@ -131,23 +134,31 @@ var lastTime = new Date().getTime();
var counter = 0.0;
var fps = 0;
var fpsDisplay: HTMLElement | null = null;
var lodStatsTimer = 0;
/** Input states*/
var mouseXVel = 0;
var mouseYVel = 0;
var keyboardRotationX = 0;
var keyboardRotationY = 0;
var keyboardZoom = 0;
var keysPressed: Set<string> = new Set();
/** Objects and states*/
var camera: Camera;
var oceanGrid: Grid;
var curRotX = Config.CAMERA_DEFAULT_ROT_X;
var curRotY = Config.CAMERA_DEFAULT_ROT_Y;
var oceanLOD: OceanLOD;
var skybox: Skybox;
var wireframeMode = false;
/** Camera movement speed */
var moveSpeed = 0.15;
var fastMoveSpeed = 0.4;
/** Ocean shader settings */
var waveHeight = 1.0;
var waveSpeed = 1.0;
var foamIntensity = 1.0;
var glitterIntensity = 1.0;
function drawScene() {
fps++;
let now = new Date();
let delta = now.getTime() - lastTime;
timeSpent += delta;
lodStatsTimer += delta;
if ((counter += delta) >= Config.FPS_UPDATE_INTERVAL) {
counter = 0;
if (fpsDisplay) {
@@ -155,62 +166,62 @@ function drawScene() {
}
fps = 0;
}
lastTime = now.getTime();
// Two Rendering passes. The first one generates a perlin noise
// texture. Second one uses the textur for vertex displacement
// of a grid representing the water surface.
//--- First render pass -> Perlin Noise (it updates the perlin noise texture)
{
gl.bindFramebuffer(gl.FRAMEBUFFER, perlinNoiseFBO);
gl.viewport(0, 0, perlinNoiseFBOWidth, perlinNoiseFBOHeight);
//Clear buffer content
gl.clearColor(1.0, 1.0, 1.0, 1);
gl.clear(gl.COLOR_BUFFER_BIT); //No depth buffer
//draw a fullscreen quad
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
// There are 7 floating-point values per vertex
let stride = 5 * Float32Array.BYTES_PER_ELEMENT;
// Set up position stream
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, stride, 0);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(1, 2, gl.FLOAT, false, stride, 3 * Float32Array.BYTES_PER_ELEMENT);
gl.enableVertexAttribArray(1);
gl.useProgram(perlinNoiseProgram);
let uTime = gl.getUniformLocation(<WebGLProgram>perlinNoiseProgram, "uTime");
gl.uniform1f(uTime, timeSpent);
gl.drawArrays(gl.TRIANGLES, 0, 6); // Draw fullscreen quad
// Log LOD stats every 5 seconds
if (lodStatsTimer >= 5000) {
lodStatsTimer = 0;
const stats = oceanLOD.getLODStats();
console.log(`LOD Stats - High:${stats[0]} Med:${stats[1]} Low:${stats[2]} VeryLow:${stats[3]}`);
}
lastTime = now.getTime();
//--- Second render pass -> Geomtry with displacement by perlin noise texture ---
// Sun direction (matches the one in ocean shader)
const sunDirection = vec3.fromValues(0.3, 0.5, 0.8);
vec3.normalize(sunDirection, sunDirection);
//--- Render pass -> Skybox first (no depth write) ---
{
gl.bindFramebuffer(gl.FRAMEBUFFER, null); //Bind default framebuffer
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, viewportWidth, viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.activeTexture(gl.TEXTURE0); //Binds the texture to 0
gl.bindTexture(gl.TEXTURE_2D, textureFBO);
var projection = mat4.create();
mat4.identity(projection);
mat4.perspective(projection, Config.FOV, viewportWidth / viewportHeight, Config.NEAR_PLANE, Config.FAR_PLANE); //projection mode should actually be camera specific
mat4.perspective(projection, Config.FOV, viewportWidth / viewportHeight, Config.NEAR_PLANE, Config.FAR_PLANE);
// Handle FPS camera movement
handleCameraMovement();
// Apply mouse rotation
if (mouseXVel !== 0 || mouseYVel !== 0) {
camera.rotate(mouseXVel, mouseYVel);
mouseXVel = 0;
mouseYVel = 0;
}
camera.setOffset(Config.CAMERA_DEFAULT_OFFSET + keyboardZoom);
camera.setRotationX((curRotX += mouseYVel * Config.MOUSE_SENSITIVITY + keyboardRotationX));
camera.setRotationY((curRotY += mouseXVel * Config.MOUSE_SENSITIVITY + keyboardRotationY));
var view = camera.getViewMatrix();
// Draw skybox first with depth test disabled (always behind everything)
gl.depthMask(false);
gl.disable(gl.DEPTH_TEST);
gl.useProgram(skyProgram);
let sky_view_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "view");
gl.uniformMatrix4fv(sky_view_loc, false, view);
let sky_projection_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "projection");
gl.uniformMatrix4fv(sky_projection_loc, false, projection);
let sky_sun_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "uSunDirection");
gl.uniform3fv(sky_sun_loc, sunDirection);
skybox.draw(gl);
gl.enable(gl.DEPTH_TEST);
gl.depthMask(true);
// Update LOD based on camera position and view direction
oceanLOD.updateLOD(gl, camera.pos, camera.target);
var model = mat4.create();
mat4.identity(model);
let translationCentering = vec3.create();
vec3.set(translationCentering, -0.5, -0.5, 0.0);
mat4.translate(model, model, translationCentering); //1. First Center the Surface in the origin.
// No centering needed - grids are already positioned correctly in world space
gl.useProgram(defaultProgram);
let view_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "view");
@@ -221,37 +232,56 @@ function drawScene() {
gl.uniformMatrix4fv(projection_loc, false, projection);
let eye_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "eyePos");
gl.uniform3fv(eye_loc, camera.pos);
//let uTime_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uTime");
//gl.uniform1f(uTime_loc, timeSpent);
let displacementMap_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "displace_map");
gl.uniform1i(displacementMap_loc, 0); //Get texture from slot 0
oceanGrid.draw(gl);
let uTime_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uTime");
gl.uniform1f(uTime_loc, timeSpent);
// Ocean shader settings
let uWaveHeight_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uWaveHeight");
gl.uniform1f(uWaveHeight_loc, waveHeight);
let uWaveSpeed_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uWaveSpeed");
gl.uniform1f(uWaveSpeed_loc, waveSpeed);
let uFoamIntensity_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uFoamIntensity");
gl.uniform1f(uFoamIntensity_loc, foamIntensity);
let uGlitterIntensity_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uGlitterIntensity");
gl.uniform1f(uGlitterIntensity_loc, glitterIntensity);
oceanLOD.draw(gl, wireframeMode);
}
requestAnimationFrame(drawScene);
}
/** Handle keyboard input for camera controls */
function handleKeyboardInput() {
keyboardRotationX = 0;
keyboardRotationY = 0;
/** Handle FPS camera movement */
function handleCameraMovement() {
const speed = keysPressed.has('Shift') ? fastMoveSpeed : moveSpeed;
if (keysPressed.has('w') || keysPressed.has('W') || keysPressed.has('ArrowUp')) {
keyboardRotationX = Config.KEYBOARD_ROTATION_SPEED;
// WASD for horizontal movement
if (keysPressed.has('w') || keysPressed.has('W')) {
camera.moveForward(speed);
}
if (keysPressed.has('s') || keysPressed.has('S') || keysPressed.has('ArrowDown')) {
keyboardRotationX = -Config.KEYBOARD_ROTATION_SPEED;
if (keysPressed.has('s') || keysPressed.has('S')) {
camera.moveForward(-speed);
}
if (keysPressed.has('a') || keysPressed.has('A') || keysPressed.has('ArrowLeft')) {
keyboardRotationY = Config.KEYBOARD_ROTATION_SPEED;
if (keysPressed.has('a') || keysPressed.has('A')) {
camera.moveRight(-speed);
}
if (keysPressed.has('d') || keysPressed.has('D') || keysPressed.has('ArrowRight')) {
keyboardRotationY = -Config.KEYBOARD_ROTATION_SPEED;
if (keysPressed.has('d') || keysPressed.has('D')) {
camera.moveRight(speed);
}
if (keysPressed.has('q') || keysPressed.has('Q') || keysPressed.has('+')) {
keyboardZoom -= Config.KEYBOARD_ZOOM_SPEED;
// Q/E for vertical movement
if (keysPressed.has('q') || keysPressed.has('Q')) {
camera.moveUp(-speed);
}
if (keysPressed.has('e') || keysPressed.has('E') || keysPressed.has('-')) {
keyboardZoom += Config.KEYBOARD_ZOOM_SPEED;
if (keysPressed.has('e') || keysPressed.has('E')) {
camera.moveUp(speed);
}
// Space to go up, Ctrl to go down
if (keysPressed.has(' ')) {
camera.moveUp(speed);
}
if (keysPressed.has('Control')) {
camera.moveUp(-speed);
}
}
@@ -298,19 +328,20 @@ function main() {
// Keyboard controls
window.addEventListener('keydown', (evt) => {
keysPressed.add(evt.key);
handleKeyboardInput();
// Reset camera on 'R' key
if (evt.key === 'r' || evt.key === 'R') {
curRotX = Config.CAMERA_DEFAULT_ROT_X;
curRotY = Config.CAMERA_DEFAULT_ROT_Y;
keyboardZoom = 0;
camera = new Camera(); // Reset to initial position
}
// Prevent default for space to avoid page scroll
if (evt.key === ' ') {
evt.preventDefault();
}
});
window.addEventListener('keyup', (evt) => {
keysPressed.delete(evt.key);
handleKeyboardInput();
});
// Window resize handler
@@ -318,12 +349,44 @@ function main() {
updateCanvasSize(canvas);
});
// Wireframe toggle handler
window.addEventListener('toggleWireframe', () => {
wireframeMode = !wireframeMode;
const wireframeBtn = document.getElementById('wireframe-toggle');
if (wireframeBtn) {
wireframeBtn.textContent = `Wireframe: ${wireframeMode ? 'ON' : 'OFF'}`;
}
console.log(`Wireframe mode: ${wireframeMode ? 'ON' : 'OFF'}`);
});
// Ocean settings sliders
window.addEventListener('waveHeightChange', ((evt: CustomEvent) => {
waveHeight = evt.detail;
}) as EventListener);
window.addEventListener('waveSpeedChange', ((evt: CustomEvent) => {
waveSpeed = evt.detail;
}) as EventListener);
window.addEventListener('foamIntensityChange', ((evt: CustomEvent) => {
foamIntensity = evt.detail;
}) as EventListener);
window.addEventListener('glitterIntensityChange', ((evt: CustomEvent) => {
glitterIntensity = evt.detail;
}) as EventListener);
initShaders();
initGeometry();
initFBO();
oceanGrid = new Grid(Config.GRID_SIZE);
oceanGrid.initVAO(gl);
oceanLOD = new OceanLOD();
oceanLOD.initVAO(gl);
console.log(`Ocean LOD initialized with ${oceanLOD.getGridCount()} patches`);
skybox = new Skybox();
skybox.initVAO(gl);
console.log('Skybox initialized');
camera = new Camera();
//Check if any errors apeared during init.