Compare commits
4 Commits
109eafa90a
...
screenspac
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ffee04185 | |||
| 503435bdf7 | |||
| 5677f03dc2 | |||
| b576d6a8cf |
199
index.html
199
index.html
@@ -243,6 +243,7 @@
|
|||||||
varying vec3 v_normal;
|
varying vec3 v_normal;
|
||||||
varying float v_waveHeight;
|
varying float v_waveHeight;
|
||||||
varying float v_foamFactor;
|
varying float v_foamFactor;
|
||||||
|
varying float v_distanceFade;
|
||||||
|
|
||||||
uniform vec3 eyePos;
|
uniform vec3 eyePos;
|
||||||
uniform float uFoamIntensity;
|
uniform float uFoamIntensity;
|
||||||
@@ -297,7 +298,7 @@
|
|||||||
// Deep and shallow water colors
|
// Deep and shallow water colors
|
||||||
vec3 deepColor = vec3(0.0, 0.08, 0.15);
|
vec3 deepColor = vec3(0.0, 0.08, 0.15);
|
||||||
vec3 shallowColor = vec3(0.0, 0.35, 0.45);
|
vec3 shallowColor = vec3(0.0, 0.35, 0.45);
|
||||||
vec3 skyColor = vec3(0.5, 0.7, 0.9);
|
vec3 skyColor = vec3(0.55, 0.7, 0.9); // Match skybox horizon color
|
||||||
vec3 foamColor = vec3(0.95, 0.98, 1.0);
|
vec3 foamColor = vec3(0.95, 0.98, 1.0);
|
||||||
|
|
||||||
// Blend between deep and shallow based on wave height
|
// Blend between deep and shallow based on wave height
|
||||||
@@ -343,8 +344,8 @@
|
|||||||
// Softer edge fade based on foam factor
|
// Softer edge fade based on foam factor
|
||||||
foam *= smoothstep(0.0, 0.25, v_foamFactor);
|
foam *= smoothstep(0.0, 0.25, v_foamFactor);
|
||||||
|
|
||||||
// Additional soft fade at foam edges
|
// Additional soft fade at foam edges and fade out at distance
|
||||||
foam = pow(foam, 0.7) * uFoamIntensity;
|
foam = pow(foam, 0.7) * uFoamIntensity * v_distanceFade;
|
||||||
|
|
||||||
// Combine all lighting
|
// Combine all lighting
|
||||||
vec3 reflectedColor = mix(oceanColor, skyColor, fresnel);
|
vec3 reflectedColor = mix(oceanColor, skyColor, fresnel);
|
||||||
@@ -353,28 +354,43 @@
|
|||||||
// Blend foam on top with slight transparency variation
|
// Blend foam on top with slight transparency variation
|
||||||
vec3 finalColor = mix(waterColor, foamColor * clamp(diffuse + 0.4, 0.0, 1.0), foam * 0.85);
|
vec3 finalColor = mix(waterColor, foamColor * clamp(diffuse + 0.4, 0.0, 1.0), foam * 0.85);
|
||||||
|
|
||||||
// Slight fog for distant water
|
// Atmospheric fog for distant water - blends to horizon
|
||||||
float dist = length(eyePos - v_fragPos);
|
float dist = length(eyePos - v_fragPos);
|
||||||
float fog = 1.0 - clamp(dist * 0.015, 0.0, 0.6);
|
|
||||||
finalColor = mix(skyColor * 0.85, finalColor, fog);
|
// 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);
|
gl_FragColor = vec4(finalColor, 1.0);
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
<script id="default-vs" type="x-shader/x-vertex">
|
<script id="default-vs" type="x-shader/x-vertex">
|
||||||
attribute vec3 positionAttr;
|
precision mediump float;
|
||||||
|
|
||||||
|
attribute vec2 positionAttr; // Grid position in [0,1] range
|
||||||
|
|
||||||
uniform mat4 view;
|
uniform mat4 view;
|
||||||
uniform mat4 model;
|
|
||||||
uniform mat4 projection;
|
uniform mat4 projection;
|
||||||
|
uniform mat4 uProjectorMatrix; // Inverse projector view-proj
|
||||||
|
uniform mat4 uRangeMatrix; // Range conversion matrix
|
||||||
uniform float uTime;
|
uniform float uTime;
|
||||||
uniform float uWaveHeight;
|
uniform float uWaveHeight;
|
||||||
uniform float uWaveSpeed;
|
uniform float uWaveSpeed;
|
||||||
|
uniform vec3 eyePos;
|
||||||
|
uniform float uHorizonClipY; // Y position of horizon in clip space [-1,1]
|
||||||
|
|
||||||
varying vec3 v_fragPos;
|
varying vec3 v_fragPos;
|
||||||
varying vec3 v_normal;
|
varying vec3 v_normal;
|
||||||
varying float v_waveHeight;
|
varying float v_waveHeight;
|
||||||
varying float v_foamFactor;
|
varying float v_foamFactor;
|
||||||
|
varying float v_distanceFade;
|
||||||
|
|
||||||
// Gerstner wave function - higher steepness = spikier waves
|
// 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) {
|
vec3 gerstnerWave(vec2 pos, float time, vec2 direction, float steepness, float wavelength, out vec3 tangent, out vec3 binormal) {
|
||||||
@@ -403,11 +419,96 @@
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Project grid point onto ocean plane using projector
|
||||||
|
vec3 projectToOcean(vec2 gridPos, out float horizonBlend, out vec3 rayDirection) {
|
||||||
|
// Transform grid position [0,1] through range matrix to projector space [-1,1]
|
||||||
|
vec4 clipPos = uRangeMatrix * vec4(gridPos, 0.0, 1.0);
|
||||||
|
|
||||||
|
// Get two points along the projection ray (near and far planes)
|
||||||
|
vec4 nearPoint = uProjectorMatrix * vec4(clipPos.xy, -1.0, 1.0);
|
||||||
|
vec4 farPoint = uProjectorMatrix * vec4(clipPos.xy, 1.0, 1.0);
|
||||||
|
|
||||||
|
// Perspective divide to get world positions
|
||||||
|
nearPoint /= nearPoint.w;
|
||||||
|
farPoint /= farPoint.w;
|
||||||
|
|
||||||
|
vec3 rayOrigin = nearPoint.xyz;
|
||||||
|
vec3 rayDir = normalize(farPoint.xyz - nearPoint.xyz);
|
||||||
|
rayDirection = rayDir;
|
||||||
|
|
||||||
|
// The skybox horizon is where rayDir.z = 0 (looking horizontally)
|
||||||
|
float angleToHorizon = -rayDir.z; // 0 at horizon, negative = looking up, positive = looking down
|
||||||
|
|
||||||
|
// If ray is pointing up or nearly horizontal, this vertex approaches horizon
|
||||||
|
if (angleToHorizon <= 0.001) {
|
||||||
|
horizonBlend = 1.0;
|
||||||
|
// Project in horizontal direction at ocean level
|
||||||
|
vec2 hDir = length(rayDir.xy) > 0.001 ? normalize(rayDir.xy) : vec2(1.0, 0.0);
|
||||||
|
return vec3(rayOrigin.xy + hDir * 5000.0, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ray is pointing down - intersect with ocean plane (Z = 0)
|
||||||
|
float t = -rayOrigin.z / rayDir.z;
|
||||||
|
|
||||||
|
if (t < 0.0) {
|
||||||
|
horizonBlend = 1.0;
|
||||||
|
vec2 hDir = length(rayDir.xy) > 0.001 ? normalize(rayDir.xy) : vec2(1.0, 0.0);
|
||||||
|
return vec3(rayOrigin.xy + hDir * 5000.0, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Camera height affects max render distance
|
||||||
|
// Higher camera = need to limit distance more to avoid precision issues
|
||||||
|
float cameraHeight = max(eyePos.z, 0.5);
|
||||||
|
|
||||||
|
// Base max distance scales with camera height, but with diminishing returns
|
||||||
|
// At height 2: maxBase = ~200
|
||||||
|
// At height 10: maxBase = ~450
|
||||||
|
// At height 100: maxBase = ~1400
|
||||||
|
// At height 500: maxBase = ~3100
|
||||||
|
float maxBase = 100.0 * sqrt(cameraHeight);
|
||||||
|
|
||||||
|
// Also limit based on angle - shallow angles get much shorter max distance
|
||||||
|
float angleScale = smoothstep(0.001, 0.3, angleToHorizon); // 0 at horizon, 1 at ~17 degrees down
|
||||||
|
float maxT = maxBase * (0.1 + 0.9 * angleScale);
|
||||||
|
maxT = max(maxT, 50.0); // Minimum distance
|
||||||
|
|
||||||
|
// Smooth horizon blend based on angle AND distance
|
||||||
|
horizonBlend = 1.0 - smoothstep(0.001, 0.05, angleToHorizon);
|
||||||
|
|
||||||
|
// If t exceeds limit, increase horizon blend
|
||||||
|
if (t > maxT * 0.8) {
|
||||||
|
float distBlend = smoothstep(maxT * 0.8, maxT, t);
|
||||||
|
horizonBlend = max(horizonBlend, distBlend);
|
||||||
|
}
|
||||||
|
|
||||||
|
t = min(t, maxT);
|
||||||
|
|
||||||
|
// Compute world position
|
||||||
|
vec3 worldPos = rayOrigin + rayDir * t;
|
||||||
|
|
||||||
|
return worldPos;
|
||||||
|
}
|
||||||
|
|
||||||
void main(void) {
|
void main(void) {
|
||||||
vec4 worldPos = model * vec4(positionAttr.xyz, 1.0);
|
// Project grid point onto ocean plane
|
||||||
|
float horizonBlend;
|
||||||
|
vec3 rayDir;
|
||||||
|
vec3 worldPos3 = projectToOcean(positionAttr, horizonBlend, rayDir);
|
||||||
|
vec4 worldPos = vec4(worldPos3, 1.0);
|
||||||
|
|
||||||
|
// Grid is on XY plane, Z is up
|
||||||
vec2 pos = worldPos.xy;
|
vec2 pos = worldPos.xy;
|
||||||
float time = uTime * 0.0004 * uWaveSpeed;
|
float time = uTime * 0.0004 * uWaveSpeed;
|
||||||
float heightMod = uWaveHeight;
|
|
||||||
|
// 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);
|
||||||
|
// Fade out waves at horizon to prevent edge breakup
|
||||||
|
waveFade *= (1.0 - horizonBlend);
|
||||||
|
v_distanceFade = waveFade;
|
||||||
|
|
||||||
|
float heightMod = uWaveHeight * waveFade;
|
||||||
|
|
||||||
vec3 displacement = vec3(0.0);
|
vec3 displacement = vec3(0.0);
|
||||||
vec3 tangent = vec3(1.0, 0.0, 0.0);
|
vec3 tangent = vec3(1.0, 0.0, 0.0);
|
||||||
@@ -470,28 +571,83 @@
|
|||||||
// Foam appears where wave is high AND rising (leading edge / crest)
|
// 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);
|
v_foamFactor = clamp((foamFromHeight * waveRising * 1.2 + foamFromSlope * 0.3), 0.0, 1.0);
|
||||||
|
|
||||||
// Apply displacement
|
// Apply displacement - Z is up, XY is horizontal plane
|
||||||
worldPos.x += displacement.x;
|
worldPos.x += displacement.x;
|
||||||
worldPos.y += displacement.z;
|
worldPos.y += displacement.z;
|
||||||
worldPos.z += displacement.y;
|
worldPos.z += displacement.y; // Height displacement
|
||||||
|
|
||||||
// Calculate normal from tangent and binormal
|
// Calculate normal from tangent and binormal
|
||||||
|
// Blend normal towards flat (0, 0, 1) based on distance
|
||||||
vec3 normal = normalize(cross(binormal, tangent));
|
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);
|
v_normal = vec3(normal.x, normal.z, normal.y);
|
||||||
|
|
||||||
|
// Project back to clip space
|
||||||
gl_Position = projection * view * worldPos;
|
gl_Position = projection * view * worldPos;
|
||||||
v_fragPos = worldPos.xyz;
|
|
||||||
|
// For vertices near the horizon, smoothly blend Y towards the horizon line
|
||||||
|
// This ensures ocean meets skybox without gaps or discontinuities
|
||||||
|
if (horizonBlend > 0.0) {
|
||||||
|
float targetY = uHorizonClipY * gl_Position.w;
|
||||||
|
// Use squared blend for smoother transition
|
||||||
|
float smoothBlend = horizonBlend * horizonBlend;
|
||||||
|
gl_Position.y = mix(gl_Position.y, targetY, smoothBlend);
|
||||||
|
// Push depth towards far plane for horizon vertices
|
||||||
|
gl_Position.z = mix(gl_Position.z, gl_Position.w * 0.9999, smoothBlend);
|
||||||
}
|
}
|
||||||
</script>
|
|
||||||
|
v_fragPos = worldPos.xyz;
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
<script id="sky-fs" type="x-shader/x-fragment">
|
<script id="sky-fs" type="x-shader/x-fragment">
|
||||||
precision mediump float;
|
precision mediump float;
|
||||||
|
|
||||||
varying vec3 fragPos;
|
varying vec3 v_rayDir;
|
||||||
|
|
||||||
|
uniform vec3 uSunDirection;
|
||||||
|
|
||||||
void main(void) {
|
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>
|
||||||
<script id="sky-vs" type="x-shader/x-vertex">
|
<script id="sky-vs" type="x-shader/x-vertex">
|
||||||
@@ -499,14 +655,15 @@
|
|||||||
|
|
||||||
uniform mat4 projection;
|
uniform mat4 projection;
|
||||||
uniform mat4 view;
|
uniform mat4 view;
|
||||||
uniform mat4 testModel;
|
|
||||||
|
|
||||||
varying vec3 fragPos;
|
varying vec3 v_rayDir;
|
||||||
|
|
||||||
void main(void) {
|
void main(void) {
|
||||||
gl_PointSize = 10.;
|
v_rayDir = positionAttr;
|
||||||
gl_Position = projection * mat4(mat3(view)) * vec4(positionAttr, 1.0);
|
// Remove translation from view matrix for skybox
|
||||||
fragPos = (view * vec4(positionAttr,1.0)).xyz; //This is wrong probably
|
mat4 rotView = mat4(mat3(view));
|
||||||
|
vec4 pos = projection * rotView * vec4(positionAttr, 1.0);
|
||||||
|
gl_Position = pos;
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
100
src/Camera.ts
100
src/Camera.ts
@@ -1,62 +1,87 @@
|
|||||||
import { vec3, mat4, vec4 } from 'gl-matrix';
|
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 {
|
export class Camera {
|
||||||
pos: vec3;
|
pos: vec3;
|
||||||
target: vec3;
|
target: vec3;
|
||||||
up: vec3;
|
up: vec3;
|
||||||
|
|
||||||
xRot: number;
|
// FPS camera angles (in radians)
|
||||||
yRot: number;
|
pitch: number; // Up/down rotation
|
||||||
offset: number;
|
yaw: number; // Left/right rotation
|
||||||
|
|
||||||
|
// Direction vectors
|
||||||
|
forward: vec3;
|
||||||
|
right: vec3;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.pos = vec3.create();
|
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();
|
this.target = vec3.create();
|
||||||
vec3.set(this.target, 0.0, 0.0, 0.0);
|
|
||||||
this.up = vec3.create();
|
this.up = vec3.create();
|
||||||
vec3.set(this.up, 0.0, 1.0, 0.0);
|
vec3.set(this.up, 0.0, 0.0, 1.0); // Z is up
|
||||||
this.xRot = 0.0;
|
this.forward = vec3.create();
|
||||||
this.yRot = 0.0;
|
this.right = vec3.create();
|
||||||
this.offset = 0.0;
|
this.pitch = -0.3; // Looking slightly down
|
||||||
|
this.yaw = Math.PI / 2; // Looking toward +Y
|
||||||
|
this.updateVectors();
|
||||||
}
|
}
|
||||||
|
|
||||||
setRotationX(rotX: number): void {
|
/** Rotate camera by mouse delta */
|
||||||
this.xRot = rotX;
|
rotate(deltaX: number, deltaY: number, sensitivity: number = 0.003): void {
|
||||||
this.updatePos();
|
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 {
|
/** Move camera in the direction it's looking */
|
||||||
this.yRot = rotY;
|
moveForward(amount: number): void {
|
||||||
this.updatePos();
|
vec3.scaleAndAdd(this.pos, this.pos, this.forward, amount);
|
||||||
|
this.updateVectors();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Sets the offset to world origin. */
|
moveRight(amount: number): void {
|
||||||
setOffset(off: number): void {
|
vec3.scaleAndAdd(this.pos, this.pos, this.right, amount);
|
||||||
this.offset = off;
|
this.updateVectors();
|
||||||
this.updatePos();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Recalculates the position according to xy-rotation and offset. */
|
moveUp(amount: number): void {
|
||||||
private updatePos(): void {
|
// Move along world Z axis
|
||||||
const transformation: mat4 = mat4.create();
|
this.pos[2] += amount;
|
||||||
mat4.identity(transformation);
|
this.updateVectors();
|
||||||
|
}
|
||||||
|
|
||||||
//2. xy-Rotation
|
/** Move in the actual look direction (including vertical) */
|
||||||
mat4.rotateX(transformation, transformation, this.xRot);
|
moveInLookDirection(amount: number): void {
|
||||||
mat4.rotateY(transformation, transformation, this.yRot);
|
vec3.scaleAndAdd(this.pos, this.pos, this.forward, amount);
|
||||||
|
this.updateVectors();
|
||||||
|
}
|
||||||
|
|
||||||
//1. Translation
|
/** Update direction vectors from pitch/yaw */
|
||||||
const translation = vec3.create();
|
private updateVectors(): void {
|
||||||
vec3.set(translation, 0.0, 0.0, this.offset);
|
// Calculate forward vector from pitch and yaw
|
||||||
mat4.translate(transformation, transformation, translation);
|
// 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();
|
// Right vector is perpendicular to forward and world up
|
||||||
vec4.set(temp, 0.0, 0.0, 0.0, 1.0);
|
const worldUp = vec3.fromValues(0, 0, 1);
|
||||||
vec4.transformMat4(temp, temp, transformation);
|
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 {
|
getViewMatrix(): mat4 {
|
||||||
@@ -64,4 +89,9 @@ export class Camera {
|
|||||||
mat4.lookAt(ret, this.pos, this.target, this.up);
|
mat4.lookAt(ret, this.pos, this.target, this.up);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Get view direction for LOD calculations */
|
||||||
|
getViewDirection(): vec3 {
|
||||||
|
return vec3.clone(this.forward);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ export class Grid {
|
|||||||
for (let j = 0; j <= this.size; ++j) {
|
for (let j = 0; j <= this.size; ++j) {
|
||||||
for (let i = 0; i <= this.size; ++i) {
|
for (let i = 0; i <= this.size; ++i) {
|
||||||
// Generate Vertices normalized to 0-1, then scale and offset
|
// 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 u = i / this.size;
|
||||||
const v = j / this.size;
|
const v = j / this.size;
|
||||||
const x = (u - 0.5) * this.scale + this.offsetX;
|
const x = (u - 0.5) * this.scale + this.offsetX;
|
||||||
|
|||||||
293
src/OceanLOD.ts
293
src/OceanLOD.ts
@@ -1,160 +1,167 @@
|
|||||||
import { Grid } from './Grid';
|
import { vec3, vec4, mat4 } from 'gl-matrix';
|
||||||
import { vec3 } from 'gl-matrix';
|
|
||||||
|
|
||||||
/** Manages multiple ocean grid patches with LOD based on camera distance and view cone */
|
/**
|
||||||
export class OceanLOD {
|
* Projected Grid Ocean - Based on the projected grid algorithm.
|
||||||
private grids: Array<{
|
* Uses a separate projector that can be adjusted to avoid backfiring.
|
||||||
grid: Grid;
|
* The grid is created in projector space and projected onto the ocean plane.
|
||||||
centerX: number;
|
*/
|
||||||
centerY: number;
|
export class ProjectedOcean {
|
||||||
size: number;
|
private vao: WebGLVertexArrayObject | null = null;
|
||||||
lodLevel: number;
|
private lineVao: WebGLVertexArrayObject | null = null;
|
||||||
visible: boolean;
|
private indexBuffer: WebGLBuffer | null = null;
|
||||||
}> = [];
|
private vertexBuffer: WebGLBuffer | null = null;
|
||||||
|
private indexCount: number = 0;
|
||||||
|
private lineIndexCount: number = 0;
|
||||||
|
|
||||||
private readonly LOD_LEVELS = [
|
// Grid resolution
|
||||||
{ distance: 2.0, gridSize: 128 }, // Closest - highest detail
|
private readonly GRID_SIZE_X = 400;
|
||||||
{ distance: 5.0, gridSize: 64 }, // Medium distance
|
private readonly GRID_SIZE_Y = 400;
|
||||||
{ distance: 10.0, gridSize: 32 }, // Far distance
|
|
||||||
{ distance: 20.0, gridSize: 16 }, // Very far - lowest detail
|
|
||||||
];
|
|
||||||
|
|
||||||
private readonly PATCH_SIZE = 2.0; // World size of each patch
|
// Ocean plane parameters (Z = 0 plane, normal pointing up)
|
||||||
private readonly PATCHES_PER_SIDE = 7; // 7x7 = 49 patches total
|
private readonly OCEAN_LEVEL = 0.0;
|
||||||
private readonly VIEW_CONE_COS = Math.cos(Math.PI * 0.45); // ~81 degree half-angle (wider than typical FOV)
|
private readonly MAX_WAVE_HEIGHT = 1.5; // Maximum displacement above ocean level
|
||||||
|
private readonly MIN_WAVE_HEIGHT = -0.5; // Maximum displacement below ocean level
|
||||||
|
|
||||||
constructor() {
|
// Projector parameters
|
||||||
this.createGridPatches();
|
private readonly MIN_PROJECTOR_HEIGHT = 5.0; // Minimum height above upper bound
|
||||||
}
|
|
||||||
|
|
||||||
private createGridPatches(): void {
|
// Matrices for the shader
|
||||||
const halfPatches = Math.floor(this.PATCHES_PER_SIDE / 2);
|
public projectorMatrix: mat4 = mat4.create();
|
||||||
|
public rangeMatrix: mat4 = mat4.create();
|
||||||
|
|
||||||
for (let y = -halfPatches; y <= halfPatches; y++) {
|
constructor() {}
|
||||||
for (let x = -halfPatches; x <= halfPatches; x++) {
|
|
||||||
const centerX = x * this.PATCH_SIZE;
|
|
||||||
const centerY = y * this.PATCH_SIZE;
|
|
||||||
|
|
||||||
// Start with lowest detail - will be updated based on camera
|
|
||||||
const grid = new Grid(
|
|
||||||
this.LOD_LEVELS[3].gridSize,
|
|
||||||
centerX,
|
|
||||||
centerY,
|
|
||||||
this.PATCH_SIZE
|
|
||||||
);
|
|
||||||
|
|
||||||
this.grids.push({
|
|
||||||
grid,
|
|
||||||
centerX,
|
|
||||||
centerY,
|
|
||||||
size: this.PATCH_SIZE,
|
|
||||||
lodLevel: 3,
|
|
||||||
visible: true
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 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);
|
|
||||||
|
|
||||||
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 = 3; // Default to lowest detail
|
|
||||||
|
|
||||||
if (!isInFront) {
|
|
||||||
// Behind camera - skip (will not be drawn)
|
|
||||||
newLodLevel = 3;
|
|
||||||
} 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, 3); // 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/** Generate the grid vertices (in [0,1] range) */
|
||||||
initVAO(gl: WebGL2RenderingContext): void {
|
initVAO(gl: WebGL2RenderingContext): void {
|
||||||
for (const { grid } of this.grids) {
|
const vertices: number[] = [];
|
||||||
grid.initVAO(gl);
|
const indices: number[] = [];
|
||||||
|
|
||||||
|
// Create grid in [0,1] range - will be transformed by projector matrix
|
||||||
|
for (let y = 0; y <= this.GRID_SIZE_Y; y++) {
|
||||||
|
for (let x = 0; x <= this.GRID_SIZE_X; x++) {
|
||||||
|
const u = x / this.GRID_SIZE_X;
|
||||||
|
const v = y / this.GRID_SIZE_Y;
|
||||||
|
vertices.push(u, v);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create indices (counter-clockwise winding when viewed from above, Z up)
|
||||||
|
for (let y = 0; y < this.GRID_SIZE_Y; y++) {
|
||||||
|
for (let x = 0; x < this.GRID_SIZE_X; x++) {
|
||||||
|
const topLeft = y * (this.GRID_SIZE_X + 1) + x;
|
||||||
|
const topRight = topLeft + 1;
|
||||||
|
const bottomLeft = (y + 1) * (this.GRID_SIZE_X + 1) + x;
|
||||||
|
const bottomRight = bottomLeft + 1;
|
||||||
|
|
||||||
|
// CCW winding for front face visible from +Z (above)
|
||||||
|
indices.push(topLeft, topRight, bottomLeft);
|
||||||
|
indices.push(topRight, bottomRight, bottomLeft);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.indexCount = indices.length;
|
||||||
|
|
||||||
|
// Create line indices for wireframe
|
||||||
|
const lineIndices: number[] = [];
|
||||||
|
for (let y = 0; y <= this.GRID_SIZE_Y; y++) {
|
||||||
|
for (let x = 0; x <= this.GRID_SIZE_X; x++) {
|
||||||
|
const currentVertex = y * (this.GRID_SIZE_X + 1) + x;
|
||||||
|
// Horizontal line
|
||||||
|
if (x < this.GRID_SIZE_X) {
|
||||||
|
lineIndices.push(currentVertex, currentVertex + 1);
|
||||||
|
}
|
||||||
|
// Vertical line
|
||||||
|
if (y < this.GRID_SIZE_Y) {
|
||||||
|
lineIndices.push(currentVertex, currentVertex + (this.GRID_SIZE_X + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.lineIndexCount = lineIndices.length;
|
||||||
|
|
||||||
|
// Create vertex buffer (shared between both VAOs)
|
||||||
|
this.vertexBuffer = gl.createBuffer();
|
||||||
|
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
|
||||||
|
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
|
||||||
|
|
||||||
|
// Create VAO for filled triangles
|
||||||
|
this.vao = gl.createVertexArray();
|
||||||
|
gl.bindVertexArray(this.vao);
|
||||||
|
|
||||||
|
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
|
||||||
|
gl.enableVertexAttribArray(0);
|
||||||
|
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
|
||||||
|
|
||||||
|
this.indexBuffer = gl.createBuffer();
|
||||||
|
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
|
||||||
|
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(indices), gl.STATIC_DRAW);
|
||||||
|
|
||||||
|
gl.bindVertexArray(null);
|
||||||
|
|
||||||
|
// Create VAO for wireframe lines
|
||||||
|
this.lineVao = gl.createVertexArray();
|
||||||
|
gl.bindVertexArray(this.lineVao);
|
||||||
|
|
||||||
|
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
|
||||||
|
gl.enableVertexAttribArray(0);
|
||||||
|
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
|
||||||
|
|
||||||
|
const lineIndexBuffer = gl.createBuffer();
|
||||||
|
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, lineIndexBuffer);
|
||||||
|
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(lineIndices), gl.STATIC_DRAW);
|
||||||
|
|
||||||
|
gl.bindVertexArray(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the projector matrices based on camera position.
|
||||||
|
* We use the camera's own view-projection to ensure screen coverage.
|
||||||
|
*/
|
||||||
|
updateProjector(cameraPos: vec3, cameraForward: vec3, viewMatrix: mat4, projMatrix: mat4): void {
|
||||||
|
// Use camera's view-projection directly
|
||||||
|
const viewProj = mat4.create();
|
||||||
|
mat4.multiply(viewProj, projMatrix, viewMatrix);
|
||||||
|
|
||||||
|
// Invert to get unprojection matrix
|
||||||
|
mat4.invert(this.projectorMatrix, viewProj);
|
||||||
|
|
||||||
|
// Range matrix maps [0,1] grid to [-1,1] clip space
|
||||||
|
this.calculateRangeMatrix(cameraPos, viewMatrix, projMatrix, viewProj);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculate the range conversion matrix to focus geometry on visible area
|
||||||
|
* For simplicity and to ensure horizon coverage, we use the full clip space range
|
||||||
|
*/
|
||||||
|
private calculateRangeMatrix(
|
||||||
|
cameraPos: vec3,
|
||||||
|
viewMatrix: mat4,
|
||||||
|
projMatrix: mat4,
|
||||||
|
projectorViewProj: mat4
|
||||||
|
): void {
|
||||||
|
// Use full clip space [-1, 1] to ensure complete coverage including horizon
|
||||||
|
// The grid [0,1] maps to [-1,1] in projector clip space
|
||||||
|
mat4.identity(this.rangeMatrix);
|
||||||
|
this.rangeMatrix[0] = 2.0; // Scale X: [0,1] -> [0,2]
|
||||||
|
this.rangeMatrix[5] = 2.0; // Scale Y: [0,1] -> [0,2]
|
||||||
|
this.rangeMatrix[10] = 2.0; // Scale Z
|
||||||
|
this.rangeMatrix[12] = -1.0; // Translate X: [0,2] -> [-1,1]
|
||||||
|
this.rangeMatrix[13] = -1.0; // Translate Y: [0,2] -> [-1,1]
|
||||||
|
this.rangeMatrix[14] = -1.0; // Translate Z
|
||||||
|
}
|
||||||
|
|
||||||
draw(gl: WebGL2RenderingContext, wireframe: boolean = false): void {
|
draw(gl: WebGL2RenderingContext, wireframe: boolean = false): void {
|
||||||
for (const patch of this.grids) {
|
if (wireframe && this.lineVao) {
|
||||||
if (patch.visible) {
|
gl.bindVertexArray(this.lineVao);
|
||||||
patch.grid.draw(gl, wireframe);
|
gl.drawElements(gl.LINES, this.lineIndexCount, gl.UNSIGNED_INT, 0);
|
||||||
}
|
gl.bindVertexArray(null);
|
||||||
|
} else if (this.vao) {
|
||||||
|
gl.bindVertexArray(this.vao);
|
||||||
|
gl.drawElements(gl.TRIANGLES, this.indexCount, gl.UNSIGNED_INT, 0);
|
||||||
|
gl.bindVertexArray(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
getGridCount(): number {
|
getIndexCount(): number {
|
||||||
return this.grids.length;
|
return this.indexCount;
|
||||||
}
|
|
||||||
|
|
||||||
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 };
|
|
||||||
for (const patch of this.grids) {
|
|
||||||
stats[patch.lodLevel]++;
|
|
||||||
}
|
|
||||||
return stats;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
85
src/Skybox.ts
Normal file
85
src/Skybox.ts
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
197
src/main.ts
197
src/main.ts
@@ -1,6 +1,7 @@
|
|||||||
import { vec3, mat4 } from 'gl-matrix';
|
import { vec3, vec4, mat4 } from 'gl-matrix';
|
||||||
import { Camera } from './Camera';
|
import { Camera } from './Camera';
|
||||||
import { OceanLOD } from './OceanLOD';
|
import { ProjectedOcean } from './OceanLOD';
|
||||||
|
import { Skybox } from './Skybox';
|
||||||
import { createProgram } from './Shader';
|
import { createProgram } from './Shader';
|
||||||
import * as Config from './constants';
|
import * as Config from './constants';
|
||||||
|
|
||||||
@@ -89,10 +90,12 @@ function initGeometry() {
|
|||||||
var perlinNoiseProgram: WebGLProgram | null;
|
var perlinNoiseProgram: WebGLProgram | null;
|
||||||
var defaultProgram: WebGLProgram | null;
|
var defaultProgram: WebGLProgram | null;
|
||||||
var textureProgram: WebGLProgram | null;
|
var textureProgram: WebGLProgram | null;
|
||||||
|
var skyProgram: WebGLProgram | null;
|
||||||
function initShaders() {
|
function initShaders() {
|
||||||
perlinNoiseProgram = createProgram(gl, "ndc-vs", "noise-fs", "Perlin Noise");
|
perlinNoiseProgram = createProgram(gl, "ndc-vs", "noise-fs", "Perlin Noise");
|
||||||
defaultProgram = createProgram(gl, "default-vs", "default-fs", "Default");
|
defaultProgram = createProgram(gl, "default-vs", "default-fs", "Default");
|
||||||
textureProgram = createProgram(gl, "texture-vs", "texture-fs", "Texture");
|
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 */
|
/** Init an FBO used for the first render pass / perlin noise */
|
||||||
@@ -131,20 +134,18 @@ var lastTime = new Date().getTime();
|
|||||||
var counter = 0.0;
|
var counter = 0.0;
|
||||||
var fps = 0;
|
var fps = 0;
|
||||||
var fpsDisplay: HTMLElement | null = null;
|
var fpsDisplay: HTMLElement | null = null;
|
||||||
var lodStatsTimer = 0;
|
|
||||||
/** Input states*/
|
/** Input states*/
|
||||||
var mouseXVel = 0;
|
var mouseXVel = 0;
|
||||||
var mouseYVel = 0;
|
var mouseYVel = 0;
|
||||||
var keyboardRotationX = 0;
|
|
||||||
var keyboardRotationY = 0;
|
|
||||||
var keyboardZoom = 0;
|
|
||||||
var keysPressed: Set<string> = new Set();
|
var keysPressed: Set<string> = new Set();
|
||||||
/** Objects and states*/
|
/** Objects and states*/
|
||||||
var camera: Camera;
|
var camera: Camera;
|
||||||
var oceanLOD: OceanLOD;
|
var projectedOcean: ProjectedOcean;
|
||||||
var curRotX = Config.CAMERA_DEFAULT_ROT_X;
|
var skybox: Skybox;
|
||||||
var curRotY = Config.CAMERA_DEFAULT_ROT_Y;
|
|
||||||
var wireframeMode = false;
|
var wireframeMode = false;
|
||||||
|
/** Camera movement speed */
|
||||||
|
var moveSpeed = 0.15;
|
||||||
|
var fastMoveSpeed = 0.4;
|
||||||
/** Ocean shader settings */
|
/** Ocean shader settings */
|
||||||
var waveHeight = 1.0;
|
var waveHeight = 1.0;
|
||||||
var waveSpeed = 1.0;
|
var waveSpeed = 1.0;
|
||||||
@@ -155,7 +156,6 @@ function drawScene() {
|
|||||||
let now = new Date();
|
let now = new Date();
|
||||||
let delta = now.getTime() - lastTime;
|
let delta = now.getTime() - lastTime;
|
||||||
timeSpent += delta;
|
timeSpent += delta;
|
||||||
lodStatsTimer += delta;
|
|
||||||
|
|
||||||
if ((counter += delta) >= Config.FPS_UPDATE_INTERVAL) {
|
if ((counter += delta) >= Config.FPS_UPDATE_INTERVAL) {
|
||||||
counter = 0;
|
counter = 0;
|
||||||
@@ -164,46 +164,61 @@ function drawScene() {
|
|||||||
}
|
}
|
||||||
fps = 0;
|
fps = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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();
|
lastTime = now.getTime();
|
||||||
// Single render pass with Gerstner waves computed in vertex shader
|
|
||||||
|
|
||||||
//--- Render pass -> Ocean with Gerstner wave displacement ---
|
// 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.viewport(0, 0, viewportWidth, viewportHeight);
|
||||||
|
|
||||||
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
|
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
|
||||||
|
|
||||||
var projection = mat4.create();
|
var projection = mat4.create();
|
||||||
mat4.identity(projection);
|
|
||||||
mat4.perspective(projection, Config.FOV, viewportWidth / viewportHeight, Config.NEAR_PLANE, Config.FAR_PLANE);
|
mat4.perspective(projection, Config.FOV, viewportWidth / viewportHeight, Config.NEAR_PLANE, Config.FAR_PLANE);
|
||||||
|
|
||||||
camera.setOffset(Config.CAMERA_DEFAULT_OFFSET + keyboardZoom);
|
// Handle FPS camera movement
|
||||||
camera.setRotationX((curRotX += mouseYVel * Config.MOUSE_SENSITIVITY + keyboardRotationX));
|
handleCameraMovement();
|
||||||
camera.setRotationY((curRotY += mouseXVel * Config.MOUSE_SENSITIVITY + keyboardRotationY));
|
|
||||||
|
// Apply mouse rotation
|
||||||
|
if (mouseXVel !== 0 || mouseYVel !== 0) {
|
||||||
|
camera.rotate(mouseXVel, mouseYVel);
|
||||||
|
mouseXVel = 0;
|
||||||
|
mouseYVel = 0;
|
||||||
|
}
|
||||||
|
|
||||||
var view = camera.getViewMatrix();
|
var view = camera.getViewMatrix();
|
||||||
|
|
||||||
// Update LOD based on camera position and view direction
|
// Draw skybox first with depth test disabled (always behind everything)
|
||||||
oceanLOD.updateLOD(gl, camera.pos, camera.target);
|
gl.depthMask(false);
|
||||||
|
gl.disable(gl.DEPTH_TEST);
|
||||||
|
gl.useProgram(skyProgram);
|
||||||
|
|
||||||
var model = mat4.create();
|
let sky_view_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "view");
|
||||||
mat4.identity(model);
|
gl.uniformMatrix4fv(sky_view_loc, false, view);
|
||||||
// No centering needed - grids are already positioned correctly in world space
|
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 projected ocean's projector matrices
|
||||||
|
projectedOcean.updateProjector(camera.pos, camera.forward, view, projection);
|
||||||
|
|
||||||
gl.useProgram(defaultProgram);
|
gl.useProgram(defaultProgram);
|
||||||
let view_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "view");
|
let view_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "view");
|
||||||
gl.uniformMatrix4fv(view_loc, false, view);
|
gl.uniformMatrix4fv(view_loc, false, view);
|
||||||
let model_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "model");
|
|
||||||
gl.uniformMatrix4fv(model_loc, false, model);
|
|
||||||
let projection_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "projection");
|
let projection_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "projection");
|
||||||
gl.uniformMatrix4fv(projection_loc, false, projection);
|
gl.uniformMatrix4fv(projection_loc, false, projection);
|
||||||
|
let projectorMatrix_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uProjectorMatrix");
|
||||||
|
gl.uniformMatrix4fv(projectorMatrix_loc, false, projectedOcean.projectorMatrix);
|
||||||
|
let rangeMatrix_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uRangeMatrix");
|
||||||
|
gl.uniformMatrix4fv(rangeMatrix_loc, false, projectedOcean.rangeMatrix);
|
||||||
let eye_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "eyePos");
|
let eye_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "eyePos");
|
||||||
gl.uniform3fv(eye_loc, camera.pos);
|
gl.uniform3fv(eye_loc, camera.pos);
|
||||||
let uTime_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uTime");
|
let uTime_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uTime");
|
||||||
@@ -219,33 +234,96 @@ function drawScene() {
|
|||||||
let uGlitterIntensity_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uGlitterIntensity");
|
let uGlitterIntensity_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uGlitterIntensity");
|
||||||
gl.uniform1f(uGlitterIntensity_loc, glitterIntensity);
|
gl.uniform1f(uGlitterIntensity_loc, glitterIntensity);
|
||||||
|
|
||||||
oceanLOD.draw(gl, wireframeMode);
|
// Calculate horizon Y in clip space
|
||||||
|
// The skybox horizon is where rayDir.z = 0 (horizontal ray from camera)
|
||||||
|
// This is a point at infinity in a horizontal direction from the camera
|
||||||
|
// We need to find where this projects to in clip space
|
||||||
|
|
||||||
|
// Get a horizontal direction (camera forward projected onto XY plane)
|
||||||
|
const horizonDir = vec3.fromValues(camera.forward[0], camera.forward[1], 0);
|
||||||
|
if (vec3.length(horizonDir) > 0.001) {
|
||||||
|
vec3.normalize(horizonDir, horizonDir);
|
||||||
|
} else {
|
||||||
|
vec3.set(horizonDir, 1, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transform a direction vector (not a point) to clip space
|
||||||
|
// For a point at infinity in direction D, its clip space position is:
|
||||||
|
// lim(t->inf) ViewProj * (eye + t*D) / w
|
||||||
|
// Which equals ViewProj * D (as a vec4 with w=0), then we look at x/w, y/w
|
||||||
|
// But since w would be 0 for a direction, we use the view matrix only
|
||||||
|
|
||||||
|
// The horizon is where view-space Y = 0 for an infinite point
|
||||||
|
// In our Z-up system, the horizon is where the ray is horizontal (z=0 in world)
|
||||||
|
// Transform a horizontal direction through view matrix
|
||||||
|
const horizonDirView = vec4.fromValues(horizonDir[0], horizonDir[1], 0, 0);
|
||||||
|
vec4.transformMat4(horizonDirView, horizonDirView, view);
|
||||||
|
|
||||||
|
// The Y in clip space where this direction points is based on the view-space direction
|
||||||
|
// projected through the projection matrix
|
||||||
|
// For perspective: clipY/clipW = viewY/(-viewZ) * projectionScaleY
|
||||||
|
// For a horizontal ray at infinity, we can compute where it ends up
|
||||||
|
|
||||||
|
// Simpler approach: transform a point very far away in horizon direction
|
||||||
|
const farDist = 1000000.0;
|
||||||
|
const horizonPoint = vec4.fromValues(
|
||||||
|
camera.pos[0] + horizonDir[0] * farDist,
|
||||||
|
camera.pos[1] + horizonDir[1] * farDist,
|
||||||
|
camera.pos[2], // Same height as camera - this is the horizon!
|
||||||
|
1
|
||||||
|
);
|
||||||
|
const viewProj = mat4.create();
|
||||||
|
mat4.multiply(viewProj, projection, view);
|
||||||
|
vec4.transformMat4(horizonPoint, horizonPoint, viewProj);
|
||||||
|
const horizonClipY = horizonPoint[3] !== 0 ? horizonPoint[1] / horizonPoint[3] : 0;
|
||||||
|
|
||||||
|
let uHorizonClipY_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uHorizonClipY");
|
||||||
|
gl.uniform1f(uHorizonClipY_loc, horizonClipY);
|
||||||
|
|
||||||
|
// Enable backface culling so ocean isn't visible from below
|
||||||
|
gl.enable(gl.CULL_FACE);
|
||||||
|
gl.cullFace(gl.BACK);
|
||||||
|
gl.frontFace(gl.CCW);
|
||||||
|
|
||||||
|
projectedOcean.draw(gl, wireframeMode);
|
||||||
|
|
||||||
|
gl.disable(gl.CULL_FACE);
|
||||||
}
|
}
|
||||||
requestAnimationFrame(drawScene);
|
requestAnimationFrame(drawScene);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Handle keyboard input for camera controls */
|
/** Handle FPS camera movement */
|
||||||
function handleKeyboardInput() {
|
function handleCameraMovement() {
|
||||||
keyboardRotationX = 0;
|
const speed = keysPressed.has('Shift') ? fastMoveSpeed : moveSpeed;
|
||||||
keyboardRotationY = 0;
|
|
||||||
|
|
||||||
if (keysPressed.has('w') || keysPressed.has('W') || keysPressed.has('ArrowUp')) {
|
// WASD for horizontal movement
|
||||||
keyboardRotationX = Config.KEYBOARD_ROTATION_SPEED;
|
if (keysPressed.has('w') || keysPressed.has('W')) {
|
||||||
|
camera.moveForward(speed);
|
||||||
}
|
}
|
||||||
if (keysPressed.has('s') || keysPressed.has('S') || keysPressed.has('ArrowDown')) {
|
if (keysPressed.has('s') || keysPressed.has('S')) {
|
||||||
keyboardRotationX = -Config.KEYBOARD_ROTATION_SPEED;
|
camera.moveForward(-speed);
|
||||||
}
|
}
|
||||||
if (keysPressed.has('a') || keysPressed.has('A') || keysPressed.has('ArrowLeft')) {
|
if (keysPressed.has('a') || keysPressed.has('A')) {
|
||||||
keyboardRotationY = Config.KEYBOARD_ROTATION_SPEED;
|
camera.moveRight(-speed);
|
||||||
}
|
}
|
||||||
if (keysPressed.has('d') || keysPressed.has('D') || keysPressed.has('ArrowRight')) {
|
if (keysPressed.has('d') || keysPressed.has('D')) {
|
||||||
keyboardRotationY = -Config.KEYBOARD_ROTATION_SPEED;
|
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('-')) {
|
if (keysPressed.has('e') || keysPressed.has('E')) {
|
||||||
keyboardZoom += Config.KEYBOARD_ZOOM_SPEED;
|
camera.moveUp(speed);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Space to go up, Ctrl to go down
|
||||||
|
if (keysPressed.has(' ')) {
|
||||||
|
camera.moveUp(speed);
|
||||||
|
}
|
||||||
|
if (keysPressed.has('Control')) {
|
||||||
|
camera.moveUp(-speed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -292,19 +370,20 @@ function main() {
|
|||||||
// Keyboard controls
|
// Keyboard controls
|
||||||
window.addEventListener('keydown', (evt) => {
|
window.addEventListener('keydown', (evt) => {
|
||||||
keysPressed.add(evt.key);
|
keysPressed.add(evt.key);
|
||||||
handleKeyboardInput();
|
|
||||||
|
|
||||||
// Reset camera on 'R' key
|
// Reset camera on 'R' key
|
||||||
if (evt.key === 'r' || evt.key === 'R') {
|
if (evt.key === 'r' || evt.key === 'R') {
|
||||||
curRotX = Config.CAMERA_DEFAULT_ROT_X;
|
camera = new Camera(); // Reset to initial position
|
||||||
curRotY = Config.CAMERA_DEFAULT_ROT_Y;
|
}
|
||||||
keyboardZoom = 0;
|
|
||||||
|
// Prevent default for space to avoid page scroll
|
||||||
|
if (evt.key === ' ') {
|
||||||
|
evt.preventDefault();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
window.addEventListener('keyup', (evt) => {
|
window.addEventListener('keyup', (evt) => {
|
||||||
keysPressed.delete(evt.key);
|
keysPressed.delete(evt.key);
|
||||||
handleKeyboardInput();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Window resize handler
|
// Window resize handler
|
||||||
@@ -343,9 +422,13 @@ function main() {
|
|||||||
initGeometry();
|
initGeometry();
|
||||||
initFBO();
|
initFBO();
|
||||||
|
|
||||||
oceanLOD = new OceanLOD();
|
projectedOcean = new ProjectedOcean();
|
||||||
oceanLOD.initVAO(gl);
|
projectedOcean.initVAO(gl);
|
||||||
console.log(`Ocean LOD initialized with ${oceanLOD.getGridCount()} patches`);
|
console.log(`Projected ocean initialized with ${projectedOcean.getIndexCount()} indices`);
|
||||||
|
|
||||||
|
skybox = new Skybox();
|
||||||
|
skybox.initVAO(gl);
|
||||||
|
console.log('Skybox initialized');
|
||||||
|
|
||||||
camera = new Camera();
|
camera = new Camera();
|
||||||
//Check if any errors apeared during init.
|
//Check if any errors apeared during init.
|
||||||
|
|||||||
Reference in New Issue
Block a user