<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Patrol - Transonic Flight Toy</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Share+Tech+Mono&display=swap" rel="stylesheet">
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
user-select: none;
-webkit-user-select: none;
}
html, body {
width: 100%;
height: 100%;
overflow: hidden;
background-color: #0c0a14;
font-family: 'Share Tech Mono', monospace;
color: #f0e6d2;
cursor: crosshair;
}
#viewport-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #08060e;
}
canvas {
position: absolute;
image-rendering: -moz-crisp-edges;
image-rendering: -webkit-crisp-edges;
image-rendering: pixelated;
image-rendering: crisp-edges;
}
#gl-canvas {
z-index: 1;
}
#cockpit-canvas {
z-index: 2;
pointer-events: none;
}
/* UI Overlay */
#ui-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10;
pointer-events: none;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 18px 24px;
}
.header-bar {
display: flex;
justify-content: space-between;
align-items: flex-start;
pointer-events: auto;
}
.title-card {
background: rgba(18, 14, 28, 0.78);
border: 1px solid rgba(240, 180, 100, 0.4);
padding: 8px 14px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.6);
transition: opacity 0.8s ease;
}
.title-card h1 {
font-family: 'Press Start 2P', cursive;
font-size: 14px;
color: #ffb86c;
letter-spacing: 2px;
margin-bottom: 4px;
text-shadow: 1px 1px 0 #3a1c28;
}
.title-card p {
font-size: 11px;
color: #cbb6a3;
letter-spacing: 1px;
}
.badge-bar {
display: flex;
gap: 10px;
}
.ui-button {
background: rgba(24, 18, 36, 0.82);
border: 1px solid rgba(220, 160, 90, 0.45);
color: #f7d8a5;
font-family: 'Share Tech Mono', monospace;
font-size: 12px;
padding: 6px 12px;
cursor: pointer;
pointer-events: auto;
display: flex;
align-items: center;
gap: 6px;
box-shadow: 0 2px 8px rgba(0,0,0,0.5);
transition: all 0.15s ease;
}
.ui-button:hover {
background: rgba(45, 30, 68, 0.9);
border-color: #ffaa55;
color: #ffffff;
transform: translateY(-1px);
}
.ui-button:active {
transform: translateY(1px);
}
.footer-bar {
display: flex;
justify-content: space-between;
align-items: flex-end;
width: 100%;
}
.control-strip {
background: rgba(16, 12, 26, 0.85);
border: 1px solid rgba(210, 150, 80, 0.35);
padding: 7px 16px;
font-size: 12px;
letter-spacing: 0.5px;
color: #edd9c0;
display: flex;
gap: 18px;
align-items: center;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.7);
}
.control-strip span.key {
color: #ffae52;
font-weight: bold;
}
.missile-pip-box {
display: flex;
gap: 4px;
align-items: center;
margin-left: 8px;
}
.missile-pip {
width: 8px;
height: 12px;
background: #39ff14;
border: 1px solid #1a590b;
box-shadow: 0 0 4px #39ff14;
}
.missile-pip.empty {
background: #331515;
border-color: #551c1c;
box-shadow: none;
}
/* Touch controls (only visible if touch device or screen < 800px) */
#touch-controls {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 15;
}
.touch-btn {
position: absolute;
pointer-events: auto;
background: rgba(28, 20, 42, 0.75);
border: 2px solid rgba(255, 180, 100, 0.5);
border-radius: 50%;
color: #ffe6c0;
font-family: 'Share Tech Mono', monospace;
font-size: 14px;
display: flex;
align-items: center;
justify-content: center;
user-select: none;
-webkit-user-select: none;
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.6);
}
.touch-btn:active {
background: rgba(70, 45, 100, 0.9);
border-color: #ffb86c;
transform: scale(0.94);
}
#touch-burn {
bottom: 70px;
right: 120px;
width: 64px;
height: 64px;
}
#touch-fire {
bottom: 70px;
right: 36px;
width: 72px;
height: 72px;
border-color: #ff5555;
color: #ff8888;
}
#touch-view {
top: 70px;
right: 24px;
width: 52px;
height: 52px;
}
#touch-stick {
bottom: 60px;
left: 36px;
width: 110px;
height: 110px;
border-radius: 50%;
border: 2px dashed rgba(255, 190, 110, 0.4);
background: rgba(16, 12, 26, 0.45);
position: absolute;
pointer-events: auto;
}
#touch-stick-nub {
width: 44px;
height: 44px;
border-radius: 50%;
background: rgba(255, 180, 100, 0.7);
position: absolute;
top: 33px;
left: 33px;
pointer-events: none;
}
/* Loading screen */
#loader {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #0f0b18;
z-index: 100;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 18px;
}
#loader h2 {
font-family: 'Press Start 2P', cursive;
font-size: 18px;
color: #ffaa55;
letter-spacing: 2px;
}
.progress-bar-outer {
width: 320px;
height: 18px;
border: 2px solid #5a3c68;
background: #1a1226;
padding: 2px;
}
.progress-bar-inner {
width: 0%;
height: 100%;
background: linear-gradient(90deg, #d46a2a, #ffaa55);
transition: width 0.1s linear;
}
#loader-text {
font-size: 13px;
color: #cbb6a3;
letter-spacing: 1px;
}
</style>
</head>
<body>
<div id="viewport-container">
<canvas id="gl-canvas"></canvas>
<canvas id="cockpit-canvas"></canvas>
</div>
<div id="loader">
<h2>PATROL</h2>
<div class="progress-bar-outer">
<div id="loader-progress" class="progress-bar-inner"></div>
</div>
<div id="loader-text">GENERATING TERRAIN... 0%</div>
</div>
<div id="ui-overlay">
<div class="header-bar">
<div class="title-card" id="title-card">
<h1>PATROL</h1>
<p>AUTUMN LAKE COUNTRY • DUSK</p>
</div>
<div class="badge-bar">
<button class="ui-button" id="btn-sound">SOUND: OFF</button>
<button class="ui-button" id="btn-camera">VIEW: CHASE [SPACE]</button>
</div>
</div>
<div class="footer-bar">
<div class="control-strip">
<div><span class="key">MOUSE</span> STEER</div>
<div><span class="key">CLICK</span> ROLL</div>
<div><span class="key">HOLD</span> AFTERBURNER</div>
<div><span class="key">R-CLICK / F</span> MISSILE</div>
<div style="display: flex; align-items: center;">
<span class="key">ORDNANCE:</span>
<div class="missile-pip-box" id="missile-pips">
<div class="missile-pip"></div>
<div class="missile-pip"></div>
<div class="missile-pip"></div>
<div class="missile-pip"></div>
</div>
</div>
</div>
</div>
</div>
<div id="touch-controls">
<div id="touch-stick"><div id="touch-stick-nub"></div></div>
<div class="touch-btn" id="touch-burn">BURN</div>
<div class="touch-btn" id="touch-fire">FIRE</div>
<div class="touch-btn" id="touch-view">CAM</div>
</div>
<script>
/* =========================================================================
* PATROL - Pixel-Art Fighter Jet Flying Toy
* 100% Procedural WebGL2 + Canvas 2D + Web Audio
* ========================================================================= */
// Global simulation state exposed for headless automation and testing
window.PATROL = {
ready: false,
viewMode: 1, // 0: Top-down, 1: Chase, 2: Cockpit
soundEnabled: false,
missilesReady: 4,
totalMissilesFired: 0,
totalExplosions: 0,
fps: 60,
internalHeight: 340,
errors: []
};
window.onerror = function(msg, url, line) {
window.PATROL.errors.push({ msg: msg, url: url, line: line });
console.error("PATROL ERROR:", msg, line);
};
const glCanvas = document.getElementById('gl-canvas');
const cockpitCanvas = document.getElementById('cockpit-canvas');
const gl = glCanvas.getContext('webgl2', { antialias: false, depth: true, powerPreference: 'high-performance' });
const ctx2d = cockpitCanvas.getContext('2d');
if (!gl) {
alert("WebGL2 is required to run Patrol.");
}
/* -------------------------------------------------------------------------
* TERRAIN GENERATION WORKER (Seamless Heightfield with Baked Sun Shadows)
* ------------------------------------------------------------------------- */
const workerCode = `
// 512x512 periodic simplex noise heightfield
const W = 512;
const H = 512;
// Deterministic pseudo-random permutations
const P = new Uint8Array(512);
for(let i=0; i<256; i++) P[i] = i;
let seed = 42;
function rnd() {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
}
for(let i=255; i>0; i--) {
const j = Math.floor(rnd() * (i + 1));
const t = P[i]; P[i] = P[j]; P[j] = t;
}
for(let i=0; i<256; i++) P[256 + i] = P[i];
function grad2d(hash, x, y) {
const h = hash & 7;
const u = h < 4 ? x : y;
const v = h < 4 ? y : x;
return ((h & 1) ? -u : u) + ((h & 2) ? -2.0 * v : 2.0 * v);
}
function perlin2dPeriodic(x, y, period) {
const xi = Math.floor(x) % period;
const yi = Math.floor(y) % period;
const xf = x - Math.floor(x);
const yf = y - Math.floor(y);
const fx = xf * xf * xf * (xf * (xf * 6 - 15) + 10);
const fy = yf * yf * yf * (yf * (yf * 6 - 15) + 10);
const x0 = (xi + period) % period;
const x1 = (x0 + 1) % period;
const y0 = (yi + period) % period;
const y1 = (y0 + 1) % period;
const g00 = grad2d(P[P[x0] + y0], xf, yf);
const g10 = grad2d(P[P[x1] + y0], xf - 1, yf);
const g01 = grad2d(P[P[x0] + y1], xf, yf - 1);
const g11 = grad2d(P[P[x1] + y1], xf - 1, yf - 1);
const x1Interp = g00 + fx * (g10 - g00);
const x2Interp = g01 + fx * (g11 - g01);
return x1Interp + fy * (x2Interp - x1Interp);
}
function fbmPeriodic(x, y) {
let val = 0;
let amp = 0.55;
let freq = 1;
let p = 4; // base period
for(let oct=0; oct<5; oct++) {
val += amp * perlin2dPeriodic(x * freq, y * freq, p);
amp *= 0.5;
freq *= 2;
p *= 2;
}
return val;
}
self.onmessage = function(e) {
const heightData = new Float32Array(W * H);
const biomeData = new Float32Array(W * H);
const outRGBA = new Uint8ClampedArray(W * H * 4);
// Step 1: Compute heightfield and biome layers
const totalRows = H;
for (let y = 0; y < H; y++) {
for (let x = 0; x < W; x++) {
const idx = y * W + x;
const nx = (x / W) * 4.0;
const ny = (y / H) * 4.0;
// Broad rolling hills & lake basins
let h = fbmPeriodic(nx, ny);
// Sharp ridge function for mountain peaks
let r = fbmPeriodic(nx * 2.0 + 1.3, ny * 2.0 + 2.7);
let ridge = 1.0 - Math.abs(r);
ridge = ridge * ridge * 0.45;
let totalH = h * 0.65 + ridge + 0.15;
// Carve lakes: water level is 0.22
if (totalH < 0.24) {
totalH = Math.max(0.04, totalH - 0.05);
}
// Subtle terracing
totalH += Math.sin(totalH * 55.0) * 0.012;
totalH = Math.max(0.0, Math.min(1.0, totalH));
heightData[idx] = totalH;
// Biome distribution (autumn forest variations: orange, crimson, gold, conifer)
let b = fbmPeriodic(nx * 1.5 + 5.2, ny * 1.5 + 3.1);
biomeData[idx] = (b * 0.5 + 0.5);
}
if (y % 32 === 0 || y === H - 1) {
self.postMessage({ type: 'progress', percent: Math.round((y / totalRows) * 50) });
}
}
// Step 2: Pre-bake long sunset shadows from low sun
// Sun low in the southwest: azimuth 225 deg, elevation 12 deg
const sunAzimuth = 225 * Math.PI / 180;
const sunElev = 12 * Math.PI / 180;
const cosE = Math.cos(sunElev);
const sinE = Math.sin(sunElev);
const dx = Math.cos(sunAzimuth) * cosE;
const dy = Math.sin(sunAzimuth) * cosE;
const tanSun = Math.tan(sunElev) * 0.005; // vertical rise per step
for (let y = 0; y < H; y++) {
for (let x = 0; x < W; x++) {
const idx = y * W + x;
const h0 = heightData[idx];
let inShadow = false;
// Raymarch towards the sun
for (let step = 1; step < 50; step++) {
const sx = ((x - dx * step * 3.5) % W + W) % W;
const sy = ((y - dy * step * 3.5) % H + H) % H;
const sIdx = Math.floor(sy) * W + Math.floor(sx);
const sh = heightData[sIdx];
const rayH = h0 + step * tanSun * 12.0;
if (sh > rayH) {
inShadow = true;
break;
}
}
const rIdx = idx * 4;
outRGBA[rIdx] = Math.floor(h0 * 255); // R: height
outRGBA[rIdx + 1] = Math.floor(biomeData[idx] * 255); // G: biome
outRGBA[rIdx + 2] = inShadow ? 60 : 255; // B: baked shadow
outRGBA[rIdx + 3] = 255; // A: full opacity
}
if (y % 32 === 0 || y === H - 1) {
self.postMessage({ type: 'progress', percent: 50 + Math.round((y / totalRows) * 50) });
}
}
self.postMessage({ type: 'done', data: outRGBA.buffer }, [outRGBA.buffer]);
};
`;
// Initialize worker with inline Blob URL
let terrainTexture = null;
const workerBlob = new Blob([workerCode], { type: 'application/javascript' });
const worker = new Worker(URL.createObjectURL(workerBlob));
const loaderEl = document.getElementById('loader');
const loaderProgressEl = document.getElementById('loader-progress');
const loaderTextEl = document.getElementById('loader-text');
worker.onmessage = function(e) {
if (e.data.type === 'progress') {
loaderProgressEl.style.width = e.data.percent + '%';
loaderTextEl.textContent = 'GENERATING TERRAIN... ' + e.data.percent + '%';
} else if (e.data.type === 'done') {
const rawData = new Uint8Array(e.data.data);
setupTerrainTexture(rawData);
loaderProgressEl.style.width = '100%';
loaderTextEl.textContent = 'READY TO FLY';
setTimeout(() => {
loaderEl.style.display = 'none';
window.PATROL.ready = true;
}, 150);
}
};
worker.postMessage('start');
function setupTerrainTexture(pixelData) {
terrainTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, terrainTexture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 512, 512, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixelData);
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.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
}
/* -------------------------------------------------------------------------
* WEBGL2 SHADERS: WORLD RAYMARCHING + 4x4 BAYER DITHERING
* ------------------------------------------------------------------------- */
const quadVS = `#version 300 es
in vec2 aPosition;
out vec2 vUV;
void main() {
vUV = aPosition * 0.5 + 0.5;
gl_Position = vec4(aPosition, 0.0, 1.0);
}
`;
const worldFS = `#version 300 es
precision highp float;
in vec2 vUV;
out vec4 fragColor;
uniform vec2 uResolution;
uniform vec3 uCameraPos;
uniform vec3 uCameraDir;
uniform vec3 uCameraUp;
uniform vec3 uCameraRight;
uniform float uTanFov;
uniform float uAspect;
uniform vec3 uSunDir;
uniform float uTime;
uniform sampler2D uTerrainTex;
uniform vec3 uJetPos;
// Ordered 4x4 Bayer Dithering Matrix
const float BAYER4[16] = float[16](
0.0/16.0, 8.0/16.0, 2.0/16.0, 10.0/16.0,
12.0/16.0, 4.0/16.0, 14.0/16.0, 6.0/16.0,
3.0/16.0, 11.0/16.0, 1.0/16.0, 9.0/16.0,
15.0/16.0, 7.0/16.0, 13.0/16.0, 5.0/16.0
);
float getBayer() {
int x = int(mod(gl_FragCoord.x, 4.0));
int y = int(mod(gl_FragCoord.y, 4.0));
return BAYER4[y * 4 + x] - 0.5;
}
const float TERRAIN_SCALE = 2200.0;
const float HEIGHT_SCALE = 380.0;
const float WATER_LEVEL = 0.22 * HEIGHT_SCALE;
// Sample heightfield from seamless texture
vec4 sampleMap(vec2 worldXZ) {
vec2 uv = fract(worldXZ / TERRAIN_SCALE);
return texture(uTerrainTex, uv);
}
float getTerrainHeight(vec2 worldXZ) {
return sampleMap(worldXZ).r * HEIGHT_SCALE;
}
// Calculate terrain normal via finite differences
vec3 getTerrainNormal(vec2 worldXZ, float h0) {
float eps = 2.5;
float hx = getTerrainHeight(worldXZ + vec2(eps, 0.0));
float hz = getTerrainHeight(worldXZ + vec2(0.0, eps));
return normalize(vec3(h0 - hx, eps, h0 - hz));
}
void main() {
vec2 ndc = (vUV - 0.5) * 2.0;
vec3 rayDir = normalize(uCameraDir + uCameraRight * (ndc.x * uTanFov * uAspect) + uCameraUp * (ndc.y * uTanFov));
float bayer = getBayer();
// Sky colors: lake country dusk
// Warm peach sun, violet zenith, lilac haze opposite
vec3 zenithCol = vec3(0.14, 0.11, 0.24); // deep dusk violet
vec3 midSkyCol = vec3(0.38, 0.26, 0.44); // mauve
vec3 horizonSun = vec3(0.98, 0.62, 0.38); // warm peach/amber
vec3 horizonLilac = vec3(0.55, 0.45, 0.62); // lilac away from sun
float sunDot = dot(rayDir, uSunDir);
float sunBlend = clamp(sunDot * 0.5 + 0.5, 0.0, 1.0);
vec3 horizonCol = mix(horizonLilac, horizonSun, sunBlend);
float elev = clamp(rayDir.y, 0.0, 1.0);
vec3 skyCol = mix(horizonCol, midSkyCol, clamp(elev * 3.5, 0.0, 1.0));
skyCol = mix(skyCol, zenithCol, clamp(elev * 1.5 - 0.2, 0.0, 1.0));
// High thin cirrus clouds
float cirrus = sin(rayDir.x * 12.0 + rayDir.z * 10.0 + uTime * 0.02) * cos(rayDir.z * 18.0);
if (rayDir.y > 0.15 && cirrus > 0.4) {
skyCol = mix(skyCol, vec3(0.95, 0.65, 0.60), 0.35);
}
// Large low sun disc
if (sunDot > 0.9982) {
skyCol = vec3(1.0, 0.98, 0.88); // glowing white-gold disc
} else if (sunDot > 0.993) {
skyCol = mix(skyCol, vec3(1.0, 0.75, 0.4), (sunDot - 0.993) / 0.0052);
}
// Raymarching terrain
float t = 2.0;
float maxDist = 3200.0;
bool hitTerrain = false;
vec3 hitPos = vec3(0.0);
vec4 hitMap = vec4(0.0);
// Analytical water plane test
float tWater = -1.0;
if (rayDir.y < -0.0001 && uCameraPos.y > WATER_LEVEL) {
tWater = (WATER_LEVEL - uCameraPos.y) / rayDir.y;
}
// If camera is high and pointing down, skip empty sky
if (uCameraPos.y > HEIGHT_SCALE && rayDir.y < -0.001) {
t = max(t, (HEIGHT_SCALE - uCameraPos.y) / rayDir.y);
}
float stepLimit = maxDist;
if (tWater > 0.0) {
stepLimit = min(maxDist, tWater + 15.0);
}
// March against heightfield
float stepSize = 2.5;
for (int i = 0; i < 85; i++) {
if (t > stepLimit) break;
vec3 p = uCameraPos + rayDir * t;
// If ray goes above max mountain peak and pointing up, exit early to sky
if (p.y > HEIGHT_SCALE * 1.05 && rayDir.y > 0.0) break;
vec4 mapVal = sampleMap(p.xz);
float h = mapVal.r * HEIGHT_SCALE;
if (p.y <= h) {
// Refine intersection with binary search
float t0 = t - stepSize;
float t1 = t;
for (int j = 0; j < 5; j++) {
float tm = (t0 + t1) * 0.5;
vec3 pm = uCameraPos + rayDir * tm;
if (pm.y <= getTerrainHeight(pm.xz)) {
t1 = tm;
} else {
t0 = tm;
}
}
t = t1;
hitPos = uCameraPos + rayDir * t;
hitMap = sampleMap(hitPos.xz);
hitTerrain = true;
break;
}
stepSize = max(2.5, t * 0.065);
t += stepSize;
}
vec3 finalCol = skyCol;
// Check whether water or terrain is hit first
bool isWater = false;
if (tWater > 0.0 && (!hitTerrain || tWater < t)) {
vec3 pW = uCameraPos + rayDir * tWater;
float bedH = getTerrainHeight(pW.xz);
if (bedH < WATER_LEVEL) {
isWater = true;
hitPos = pW;
t = tWater;
} else {
hitTerrain = true;
hitPos = pW;
t = tWater;
hitMap = sampleMap(hitPos.xz);
}
}
if (isWater) {
// Water Shading
float bedH = getTerrainHeight(hitPos.xz);
float depth = max(0.0, WATER_LEVEL - bedH);
// Depth bands: turquoise shallows -> navy deeps
vec3 shallowCol = vec3(0.24, 0.58, 0.62); // pale turquoise
vec3 midWaterCol = vec3(0.14, 0.32, 0.48); // azure
vec3 deepWaterCol = vec3(0.07, 0.12, 0.22); // navy
vec3 waterCol = mix(shallowCol, midWaterCol, clamp(depth / 12.0, 0.0, 1.0));
waterCol = mix(waterCol, deepWaterCol, clamp((depth - 12.0) / 28.0, 0.0, 1.0));
// Shoreline animated foam
if (depth < 2.8) {
float foamNoise = sin(hitPos.x * 0.35 + uTime * 2.8) * cos(hitPos.z * 0.35 - uTime * 2.2);
if (depth < 1.2 || foamNoise > 0.25) {
waterCol = mix(waterCol, vec3(0.92, 0.96, 0.98), 0.75); // crisp white foam
}
}
// Glitter path under the sun + short white glints
vec3 halfVec = normalize(uSunDir - rayDir);
float spec = pow(max(0.0, dot(vec3(0.0, 1.0, 0.0), halfVec)), 48.0);
float glint = sin(hitPos.x * 1.8 + uTime * 4.0) * cos(hitPos.z * 1.8 - uTime * 3.5);
if (glint > 0.75 && spec > 0.08) {
waterCol += vec3(1.0, 0.9, 0.6) * 0.6;
}
// Sky reflection at low angles (Fresnel)
float fresnel = pow(1.0 - max(0.0, -rayDir.y), 4.0);
waterCol = mix(waterCol, horizonCol, fresnel * 0.65);
// Jet shadow on water
vec3 toJet = hitPos - uJetPos;
float shadowDist = length(toJet - uSunDir * dot(toJet, uSunDir));
if (shadowDist < 12.0 && dot(toJet, -uSunDir) > 0.0) {
waterCol *= 0.45;
}
finalCol = waterCol;
} else if (hitTerrain) {
// Land Shading
float hNorm = hitMap.r;
float biome = hitMap.g;
float bakedShadow = hitMap.b;
vec3 norm = getTerrainNormal(hitPos.xz, hitPos.y);
float slope = 1.0 - norm.y;
// Palette materials
vec3 sandCol = vec3(0.76, 0.68, 0.52);
vec3 meadowCol = vec3(0.55, 0.52, 0.28); // pale autumn olive/buff
vec3 goldTreeCol = vec3(0.85, 0.62, 0.16); // gold aspen
vec3 orangeTreeCol = vec3(0.82, 0.38, 0.14); // burnt orange oak
vec3 crimsonTreeCol = vec3(0.68, 0.18, 0.18); // crimson maple
vec3 coniferCol = vec3(0.12, 0.22, 0.14); // dark conifer/spruce
vec3 rockCol = vec3(0.36, 0.32, 0.42); // grey-violet rock
vec3 snowCol = vec3(0.92, 0.94, 0.98); // snow on highest peaks
vec3 landCol = meadowCol;
// Shore sands
if (hNorm < 0.25) {
landCol = mix(sandCol, meadowCol, (hNorm - 0.22) / 0.03);
} else if (hNorm < 0.68) {
// Forest patches in orange, crimson, gold, and dark conifer
vec3 treeCol = goldTreeCol;
if (biome < 0.28) treeCol = goldTreeCol;
else if (biome < 0.56) treeCol = orangeTreeCol;
else if (biome < 0.82) treeCol = crimsonTreeCol;
else treeCol = coniferCol;
landCol = mix(meadowCol, treeCol, 0.75);
} else if (hNorm < 0.82) {
landCol = rockCol;
} else {
landCol = snowCol;
}
// Rocky slopes
if (slope > 0.38 && hNorm < 0.82) {
landCol = rockCol;
}
// Lighting: stepped tones with violet shadows
float NdotL = max(0.0, dot(norm, uSunDir));
float shadowFactor = bakedShadow > 0.5 ? 1.0 : 0.28;
float lightTone = NdotL * shadowFactor;
// 3-tone terraced quantization with subtle steps
float steppedLight = 0.3;
if (lightTone > 0.55) steppedLight = 1.0;
else if (lightTone > 0.25) steppedLight = 0.68;
vec3 litCol = landCol * (steppedLight * vec3(1.05, 0.95, 0.85));
vec3 shadowViolet = vec3(0.22, 0.16, 0.32); // violet shadow
landCol = mix(shadowViolet * landCol * 1.4, litCol, steppedLight);
// Jet shadow on ground
vec3 toJet = hitPos - uJetPos;
float shadowDist = length(toJet - uSunDir * dot(toJet, uSunDir));
if (shadowDist < 14.0 && dot(toJet, -uSunDir) > 0.0) {
landCol = mix(shadowViolet * 0.8, landCol, 0.3);
}
finalCol = landCol;
}
// Puffy Cumulus Clouds layer below cruise altitude (elev ~ 250.0)
float cloudY = 240.0;
if (rayDir.y > 0.0 || uCameraPos.y > cloudY) {
float tCloud = (cloudY - uCameraPos.y) / rayDir.y;
if (tCloud > 0.0 && (!hitTerrain && !isWater || tCloud < t)) {
vec3 pCloud = uCameraPos + rayDir * tCloud;
vec2 cUV1 = pCloud.xz * 0.0006 + vec2(uTime * 0.004, 0.0);
vec2 cUV2 = pCloud.xz * 0.0022 - vec2(uTime * 0.006, uTime * 0.003);
float c1 = texture(uTerrainTex, fract(cUV1)).r;
float c2 = texture(uTerrainTex, fract(cUV2)).g;
float cDensity = c1 * 0.65 + c2 * 0.35;
if (cDensity > 0.54) {
// Stepped tones: warm peach lit tops, cool lavender-violet underside
vec3 cloudSun = vec3(0.98, 0.82, 0.72); // peach
vec3 cloudShadow = vec3(0.42, 0.34, 0.52); // lavender-violet
float cStep = (cDensity > 0.66) ? 1.0 : 0.5;
vec3 cCol = mix(cloudShadow, cloudSun, cStep);
float cloudAlpha = clamp((cDensity - 0.54) * 6.0, 0.0, 0.95);
finalCol = mix(finalCol, cCol, cloudAlpha);
t = min(t, tCloud);
}
}
}
// Atmospheric haze toward horizon: gold toward sun, lilac away from sun
float fogDist = t;
float fogFactor = 1.0 - exp(-pow(fogDist * 0.00038, 2.0));
fogFactor = clamp(fogFactor, 0.0, 1.0);
vec3 hazeCol = horizonCol;
finalCol = mix(finalCol, hazeCol, fogFactor);
// Apply 4x4 Bayer Dithering between tones (discrete quantization)
finalCol += bayer * 0.045;
finalCol = floor(finalCol * 24.0) / 24.0;
fragColor = vec4(finalCol, 1.0);
}
`;
/* -------------------------------------------------------------------------
* 3D AIRCRAFT MESH & RENDERING (Low-Poly, 3-Tone Shading, 1px Dark Outline)
* ------------------------------------------------------------------------- */
const aircraftVS = `#version 300 es
in vec3 aPosition;
in vec3 aNormal;
in vec3 aColor;
uniform mat4 uMVP;
uniform mat4 uModel;
uniform float uOutline; // 0: normal, 1: extruded outline
out vec3 vWorldPos;
out vec3 vNormal;
out vec3 vColor;
void main() {
vec3 pos = aPosition;
if (uOutline > 0.5) {
// Inverted hull extrusion for 1-pixel dark outline
pos += aNormal * 0.09;
}
vec4 worldPos = uModel * vec4(pos, 1.0);
vWorldPos = worldPos.xyz;
vNormal = mat3(uModel) * aNormal;
vColor = aColor;
gl_Position = uMVP * vec4(pos, 1.0);
}
`;
const aircraftFS = `#version 300 es
precision highp float;
in vec3 vWorldPos;
in vec3 vNormal;
in vec3 vColor;
uniform vec3 uSunDir;
uniform float uOutline;
out vec4 fragColor;
void main() {
if (uOutline > 0.5) {
// 1-pixel dark outline
fragColor = vec4(0.08, 0.06, 0.12, 1.0);
return;
}
// Flat-shading with three tones
vec3 normal = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));
float NdotL = dot(normal, uSunDir);
vec3 tone;
if (NdotL > 0.45) {
// Highlight tone (warm evening light)
tone = vColor * vec3(1.15, 1.05, 0.95);
} else if (NdotL > -0.05) {
// Midtone
tone = vColor;
} else {
// Shadow tone (violet shadow)
tone = vColor * vec3(0.55, 0.48, 0.70);
}
// Quantize colors to maintain pixel-art look
tone = floor(tone * 18.0) / 18.0;
fragColor = vec4(tone, 1.0);
}
`;
// Simulation constants
const TERRAIN_SCALE = 2200.0;
const HEIGHT_SCALE = 380.0;
const WATER_LEVEL = 0.22 * HEIGHT_SCALE;
// Compile helper
function compileShader(src, type) {
const s = gl.createShader(type);
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
console.error("Shader compile error:", gl.getShaderInfoLog(s));
}
return s;
}
function createProgram(vsSrc, fsSrc) {
const p = gl.createProgram();
gl.attachShader(p, compileShader(vsSrc, gl.VERTEX_SHADER));
gl.attachShader(p, compileShader(fsSrc, gl.FRAGMENT_SHADER));
gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
console.error("Program link error:", gl.getProgramInfoLog(p));
}
return p;
}
const worldProgram = createProgram(quadVS, worldFS);
const aircraftProgram = createProgram(aircraftVS, aircraftFS);
// 3D Effects Shader (Afterburner plumes, vapour trails, missiles, explosions)
const fxVS = `#version 300 es
in vec3 aPosition;
in vec4 aColor;
uniform mat4 uMVP;
out vec4 vColor;
void main() {
vColor = aColor;
gl_Position = uMVP * vec4(aPosition, 1.0);
}
`;
const fxFS = `#version 300 es
precision highp float;
in vec4 vColor;
out vec4 fragColor;
void main() {
vec3 col = floor(vColor.rgb * 18.0) / 18.0;
fragColor = vec4(col, vColor.a);
}
`;
const fxProgram = createProgram(fxVS, fxFS);
const fxVAO = gl.createVertexArray();
const fxVBO = gl.createBuffer();
gl.bindVertexArray(fxVAO);
gl.bindBuffer(gl.ARRAY_BUFFER, fxVBO);
const MAX_FX_VERTS = 16000;
const fxBufferData = new Float32Array(MAX_FX_VERTS * 7);
gl.bufferData(gl.ARRAY_BUFFER, fxBufferData.byteLength, gl.DYNAMIC_DRAW);
const fxPosLoc = gl.getAttribLocation(fxProgram, 'aPosition');
gl.enableVertexAttribArray(fxPosLoc);
gl.vertexAttribPointer(fxPosLoc, 3, gl.FLOAT, false, 28, 0);
const fxColLoc = gl.getAttribLocation(fxProgram, 'aColor');
gl.enableVertexAttribArray(fxColLoc);
gl.vertexAttribPointer(fxColLoc, 4, gl.FLOAT, false, 28, 12);
let fxVertCount = 0;
function fxReset() { fxVertCount = 0; }
function fxAddVertex(x, y, z, r, g, b, a) {
if (fxVertCount >= MAX_FX_VERTS) return;
const idx = fxVertCount * 7;
fxBufferData[idx] = x;
fxBufferData[idx + 1] = y;
fxBufferData[idx + 2] = z;
fxBufferData[idx + 3] = r;
fxBufferData[idx + 4] = g;
fxBufferData[idx + 5] = b;
fxBufferData[idx + 6] = a;
fxVertCount++;
}
function fxAddTri(p1, p2, p3, c) {
fxAddVertex(p1[0], p1[1], p1[2], c[0], c[1], c[2], c[3] !== undefined ? c[3] : 1.0);
fxAddVertex(p2[0], p2[1], p2[2], c[0], c[1], c[2], c[3] !== undefined ? c[3] : 1.0);
fxAddVertex(p3[0], p3[1], p3[2], c[0], c[1], c[2], c[3] !== undefined ? c[3] : 1.0);
}
function fxAddQuad(p1, p2, p3, p4, c) {
fxAddTri(p1, p2, p3, c);
fxAddTri(p1, p3, p4, c);
}
// Fullscreen quad buffers
const quadVAO = gl.createVertexArray();
const quadVBO = gl.createBuffer();
gl.bindVertexArray(quadVAO);
gl.bindBuffer(gl.ARRAY_BUFFER, quadVBO);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
-1, -1, 1, -1, -1, 1,
-1, 1, 1, -1, 1, 1
]), gl.STATIC_DRAW);
const aPosLoc = gl.getAttribLocation(worldProgram, 'aPosition');
gl.enableVertexAttribArray(aPosLoc);
gl.vertexAttribPointer(aPosLoc, 2, gl.FLOAT, false, 0, 0);
/* -------------------------------------------------------------------------
* PROCEDURAL AIRCRAFT GEOMETRY
* Twin-engine, twin-tail, cropped delta, radome, bubble canopy, splinter camo
* ------------------------------------------------------------------------- */
function buildFighterMesh() {
const positions = [];
const normals = [];
const colors = [];
// Colors
const C_RADOME = [0.12, 0.13, 0.16]; // dark pointed radome
const C_CANOPY = [0.88, 0.72, 0.28]; // gold-tinted canopy
const C_GREY = [0.46, 0.49, 0.54]; // grey camo
const C_SLATE = [0.26, 0.29, 0.35]; // slate splinter camo
const C_RED_CAP = [0.85, 0.15, 0.18]; // canted fin red tips
const C_NOZZLE = [0.18, 0.18, 0.22]; // titanium nozzles
const C_GLOW = [1.00, 0.55, 0.15]; // reheat glow
function addTri(p1, p2, p3, col) {
// Compute face normal
const ax = p2[0]-p1[0], ay = p2[1]-p1[1], az = p2[2]-p1[2];
const bx = p3[0]-p1[0], by = p3[1]-p1[1], bz = p3[2]-p1[2];
let nx = ay*bz - az*by;
let ny = az*bx - ax*bz;
let nz = ax*by - ay*bx;
const len = Math.hypot(nx, ny, nz) || 1;
nx /= len; ny /= len; nz /= len;
positions.push(...p1, ...p2, ...p3);
normals.push(nx, ny, nz, nx, ny, nz, nx, ny, nz);
colors.push(...col, ...col, ...col);
}
function addQuad(p1, p2, p3, p4, col) {
addTri(p1, p2, p3, col);
addTri(p1, p3, p4, col);
}
// 1. Pointed dark radome nose
const noseTip = [0, 0.1, 4.8];
const noseTop = [0, 0.3, 3.2];
const noseBot = [0, -0.2, 3.2];
const noseL = [-0.4, 0.05, 3.2];
const noseR = [0.4, 0.05, 3.2];
addTri(noseTip, noseTop, noseL, C_RADOME);
addTri(noseTip, noseR, noseTop, C_RADOME);
addTri(noseTip, noseBot, noseR, C_RADOME);
addTri(noseTip, noseL, noseBot, C_RADOME);
// 2. Cockpit bubble canopy (gold-tinted)
const canPeak = [0, 0.75, 1.8];
const canFore = [0, 0.45, 2.9];
const canAft = [0, 0.50, 0.6];
const canL = [-0.35, 0.25, 1.8];
const canR = [0.35, 0.25, 1.8];
addTri(canFore, canPeak, canL, C_CANOPY);
addTri(canFore, canR, canPeak, C_CANOPY);
addTri(canPeak, canAft, canL, C_CANOPY);
addTri(canPeak, canR, canAft, C_CANOPY);
// 3. Main fuselage (splinter camo: alternating grey & slate)
const fusTopA = [0, 0.35, 0.5];
const fusTopB = [0, 0.28, -2.8];
const fusLA = [-0.7, 0.0, 1.2];
const fusRA = [0.7, 0.0, 1.2];
const fusLB = [-0.9, 0.0, -2.8];
const fusRB = [0.9, 0.0, -2.8];
const fusBotA = [0, -0.35, 1.2];
const fusBotB = [0, -0.32, -2.8];
addQuad(noseTop, fusTopA, fusLA, noseL, C_GREY);
addQuad(noseTop, noseR, fusRA, fusTopA, C_SLATE);
addQuad(fusTopA, fusTopB, fusLB, fusLA, C_SLATE);
addQuad(fusTopA, fusRA, fusRB, fusTopB, C_GREY);
addQuad(noseBot, noseL, fusLA, fusBotA, C_GREY);
addQuad(noseBot, fusBotA, fusRA, noseR, C_GREY);
addQuad(fusBotA, fusLB, fusBotB, fusLA, C_SLATE);
addQuad(fusBotA, fusRA, fusRB, fusBotB, C_GREY);
// 4. Cropped delta wings
const wingTipL_A = [-3.8, 0.05, -1.2]; // cropped wingtip
const wingTipL_B = [-3.8, 0.05, -2.2];
const wingRootL_A = [-0.65, 0.05, 1.4];
const wingRootL_B = [-0.85, 0.05, -2.6];
const wingTipR_A = [3.8, 0.05, -1.2];
const wingTipR_B = [3.8, 0.05, -2.2];
const wingRootR_A = [0.65, 0.05, 1.4];
const wingRootR_B = [0.85, 0.05, -2.6];
// Left wing top/bottom (splinter camo)
addQuad(wingRootL_A, wingTipL_A, wingTipL_B, wingRootL_B, C_GREY);
addQuad(wingRootL_A, wingRootL_B, wingTipL_B, wingTipL_A, C_SLATE);
// Right wing top/bottom
addQuad(wingRootR_A, wingRootR_B, wingTipR_B, wingTipR_A, C_SLATE);
addQuad(wingRootR_A, wingTipR_A, wingTipR_B, wingRootR_B, C_GREY);
// 5. Canted twin vertical fins with bright red tips
const finRootL_A = [-0.6, 0.25, -1.2];
const finRootL_B = [-0.65, 0.25, -2.6];
const finTipL_A = [-1.1, 1.45, -2.0]; // canted outward
const finTipL_B = [-1.15, 1.45, -2.7];
const finRootR_A = [0.6, 0.25, -1.2];
const finRootR_B = [0.65, 0.25, -2.6];
const finTipR_A = [1.1, 1.45, -2.0];
const finTipR_B = [1.15, 1.45, -2.7];
// Left fin
addQuad(finRootL_A, finTipL_A, finTipL_B, finRootL_B, C_GREY);
addQuad(finRootL_A, finRootL_B, finTipL_B, finTipL_A, C_SLATE);
// Red cap on left fin tip
const finCapL_A = [-1.12, 1.62, -2.15];
const finCapL_B = [-1.16, 1.62, -2.65];
addQuad(finTipL_A, finCapL_A, finCapL_B, finTipL_B, C_RED_CAP);
// Right fin
addQuad(finRootR_A, finRootR_B, finTipR_B, finTipR_A, C_SLATE);
addQuad(finRootR_A, finTipR_A, finTipR_B, finRootR_B, C_GREY);
// Red cap on right fin tip
const finCapR_A = [1.12, 1.62, -2.15];
const finCapR_B = [1.16, 1.62, -2.65];
addQuad(finTipR_A, finTipR_B, finCapR_B, finCapR_A, C_RED_CAP);
// 6. Horizontal stabilizers
const stabL_A = [-0.65, 0.05, -2.4];
const stabL_B = [-1.8, 0.05, -3.2];
const stabL_C = [-1.6, 0.05, -3.6];
const stabL_D = [-0.5, 0.05, -3.2];
addQuad(stabL_A, stabL_B, stabL_C, stabL_D, C_GREY);
const stabR_A = [0.65, 0.05, -2.4];
const stabR_B = [1.8, 0.05, -3.2];
const stabR_C = [1.6, 0.05, -3.6];
const stabR_D = [0.5, 0.05, -3.2];
addQuad(stabR_A, stabR_D, stabR_C, stabR_B, C_SLATE);
// 7. Twin glowing exhaust nozzles
const nozL = [-0.42, 0.0, -2.9];
const nozR = [0.42, 0.0, -2.9];
function addNozzle(center) {
const segs = 6;
const rad = 0.28;
for (let i = 0; i < segs; i++) {
const a1 = (i / segs) * Math.PI * 2;
const a2 = ((i + 1) / segs) * Math.PI * 2;
const p1 = [center[0] + Math.cos(a1) * rad, center[1] + Math.sin(a1) * rad, center[2]];
const p2 = [center[0] + Math.cos(a2) * rad, center[1] + Math.sin(a2) * rad, center[2]];
const p3 = [center[0] + Math.cos(a2) * (rad * 0.7), center[1] + Math.sin(a2) * (rad * 0.7), center[2] - 0.35];
const p4 = [center[0] + Math.cos(a1) * (rad * 0.7), center[1] + Math.sin(a1) * (rad * 0.7), center[2] - 0.35];
addQuad(p1, p2, p3, p4, C_NOZZLE);
// Interior glowing reheat disc
addTri(center, p3, p4, C_GLOW);
}
}
addNozzle(nozL);
addNozzle(nozR);
return {
positions: new Float32Array(positions),
normals: new Float32Array(normals),
colors: new Float32Array(colors),
count: positions.length / 3
};
}
const aircraftMesh = buildFighterMesh();
const aircraftVAO = gl.createVertexArray();
gl.bindVertexArray(aircraftVAO);
const acPosVBO = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, acPosVBO);
gl.bufferData(gl.ARRAY_BUFFER, aircraftMesh.positions, gl.STATIC_DRAW);
const acPosLoc = gl.getAttribLocation(aircraftProgram, 'aPosition');
gl.enableVertexAttribArray(acPosLoc);
gl.vertexAttribPointer(acPosLoc, 3, gl.FLOAT, false, 0, 0);
const acNormVBO = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, acNormVBO);
gl.bufferData(gl.ARRAY_BUFFER, aircraftMesh.normals, gl.STATIC_DRAW);
const acNormLoc = gl.getAttribLocation(aircraftProgram, 'aNormal');
gl.enableVertexAttribArray(acNormLoc);
gl.vertexAttribPointer(acNormLoc, 3, gl.FLOAT, false, 0, 0);
const acColVBO = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, acColVBO);
gl.bufferData(gl.ARRAY_BUFFER, aircraftMesh.colors, gl.STATIC_DRAW);
const acColLoc = gl.getAttribLocation(aircraftProgram, 'aColor');
gl.enableVertexAttribArray(acColLoc);
gl.vertexAttribPointer(acColLoc, 3, gl.FLOAT, false, 0, 0);
/* -------------------------------------------------------------------------
* PROCEDURAL MISSILE GEOMETRY (Wing Mounts & In-Flight Munitions)
* ------------------------------------------------------------------------- */
function buildMissileMesh() {
const positions = [];
const normals = [];
const colors = [];
const C_BODY = [0.82, 0.84, 0.88]; // light grey body
const C_TIP = [0.88, 0.18, 0.18]; // red guidance nose
const C_FIN = [0.28, 0.32, 0.38]; // dark fins
const C_NOZ = [0.15, 0.15, 0.18]; // titanium nozzle
function addTri(p1, p2, p3, col) {
const ax = p2[0]-p1[0], ay = p2[1]-p1[1], az = p2[2]-p1[2];
const bx = p3[0]-p1[0], by = p3[1]-p1[1], bz = p3[2]-p1[2];
let nx = ay*bz - az*by, ny = az*bx - ax*bz, nz = ax*by - ay*bx;
const len = Math.hypot(nx, ny, nz) || 1;
positions.push(...p1, ...p2, ...p3);
normals.push(nx/len, ny/len, nz/len, nx/len, ny/len, nz/len, nx/len, ny/len, nz/len);
colors.push(...col, ...col, ...col);
}
function addQuad(p1, p2, p3, p4, col) {
addTri(p1, p2, p3, col);
addTri(p1, p3, p4, col);
}
// Pointed nose & body cylinder
const nose = [0, 0, 1.3];
const r = 0.10;
const segs = 6;
for (let i = 0; i < segs; i++) {
const a1 = (i / segs) * Math.PI * 2;
const a2 = ((i + 1) / segs) * Math.PI * 2;
const p1 = [Math.cos(a1)*r, Math.sin(a1)*r, 0.9];
const p2 = [Math.cos(a2)*r, Math.sin(a2)*r, 0.9];
addTri(nose, p2, p1, C_TIP);
const p3 = [Math.cos(a1)*r, Math.sin(a1)*r, -0.9];
const p4 = [Math.cos(a2)*r, Math.sin(a2)*r, -0.9];
addQuad(p1, p2, p4, p3, C_BODY);
const p5 = [Math.cos(a1)*(r*0.7), Math.sin(a1)*(r*0.7), -1.1];
const p6 = [Math.cos(a2)*(r*0.7), Math.sin(a2)*(r*0.7), -1.1];
addQuad(p3, p4, p6, p5, C_NOZ);
}
// 4 cruciform steering fins
const finSpan = 0.38;
addQuad([0, 0.05, -0.4], [0, finSpan, -0.9], [0, finSpan, -1.05], [0, 0.05, -1.0], C_FIN);
addQuad([0, -0.05, -0.4], [0, -finSpan, -0.9], [0, -finSpan, -1.05], [0, -0.05, -1.0], C_FIN);
addQuad([0.05, 0, -0.4], [finSpan, 0, -0.9], [finSpan, 0, -1.05], [0.05, 0, -1.0], C_FIN);
addQuad([-0.05, 0, -0.4], [-finSpan, 0, -0.9], [-finSpan, 0, -1.05], [-0.05, 0, -1.0], C_FIN);
return {
positions: new Float32Array(positions),
normals: new Float32Array(normals),
colors: new Float32Array(colors),
count: positions.length / 3
};
}
const missileMesh = buildMissileMesh();
const missileVAO = gl.createVertexArray();
gl.bindVertexArray(missileVAO);
const mPosVBO = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, mPosVBO);
gl.bufferData(gl.ARRAY_BUFFER, missileMesh.positions, gl.STATIC_DRAW);
gl.enableVertexAttribArray(acPosLoc);
gl.vertexAttribPointer(acPosLoc, 3, gl.FLOAT, false, 0, 0);
const mNormVBO = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, mNormVBO);
gl.bufferData(gl.ARRAY_BUFFER, missileMesh.normals, gl.STATIC_DRAW);
gl.enableVertexAttribArray(acNormLoc);
gl.vertexAttribPointer(acNormLoc, 3, gl.FLOAT, false, 0, 0);
const mColVBO = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, mColVBO);
gl.bufferData(gl.ARRAY_BUFFER, missileMesh.colors, gl.STATIC_DRAW);
gl.enableVertexAttribArray(acColLoc);
gl.vertexAttribPointer(acColLoc, 3, gl.FLOAT, false, 0, 0);
/* -------------------------------------------------------------------------
* FLIGHT DYNAMICS & CAMERA STATE
* ------------------------------------------------------------------------- */
const jet = {
pos: [1100, 220, 1100],
vel: [0, 0, 0],
speed: 380, // knots
pitch: 0,
roll: 0,
yaw: 0.8,
forward: [0, 0, 1],
up: [0, 1, 0],
right: [1, 0, 0],
afterburner: false,
barrelRolling: false,
rollTimer: 0,
pullUpActive: false,
gForce: 1.0,
radAlt: 150,
mouseMoved: false,
attractTime: 0
};
// Camera modes: 0: Top-Down, 1: Chase, 2: Cockpit
const camera = {
mode: 1,
targetMode: 1,
blendProgress: 1.0,
pos: [0, 0, 0],
dir: [0, 0, 1],
up: [0, 1, 0],
right: [1, 0, 0],
fov: 60 * Math.PI / 180
};
// Controls state
const input = {
mouseX: 0,
mouseY: 0,
leftDown: false,
leftDownTime: 0,
rightDown: false,
stickX: 0,
stickY: 0
};
/* -------------------------------------------------------------------------
* WEAPONS & PARTICLES (Missiles, Wingtip Vapour, Afterburner, Explosions)
* ------------------------------------------------------------------------- */
const missiles = [];
const missileRails = [
{ ready: true, reloadTimer: 0, offset: [-2.2, -0.2, -0.6] },
{ ready: true, reloadTimer: 0, offset: [2.2, -0.2, -0.6] },
{ ready: true, reloadTimer: 0, offset: [-1.4, -0.25, -0.8] },
{ ready: true, reloadTimer: 0, offset: [1.4, -0.25, -0.8] }
];
const explosions = [];
const vapourTrailsL = [];
const vapourTrailsR = [];
const waterSprays = [];
function fireMissile() {
// Find first ready rail
let railIdx = -1;
for (let i = 0; i < missileRails.length; i++) {
if (missileRails[i].ready) {
railIdx = i;
break;
}
}
if (railIdx === -1) return; // all reloading
const rail = missileRails[railIdx];
rail.ready = false;
rail.reloadTimer = 4.2; // 4.2 second rearm
// Compute missile launch world pos from rail offset
const mPos = [
jet.pos[0] + jet.right[0] * rail.offset[0] + jet.up[0] * rail.offset[1] + jet.forward[0] * rail.offset[2],
jet.pos[1] + jet.right[1] * rail.offset[0] + jet.up[1] * rail.offset[1] + jet.forward[1] * rail.offset[2],
jet.pos[2] + jet.right[2] * rail.offset[0] + jet.up[2] * rail.offset[1] + jet.forward[2] * rail.offset[2]
];
missiles.push({
pos: mPos,
vel: [
jet.forward[0] * 550,
jet.forward[1] * 550,
jet.forward[2] * 550
],
dir: [...jet.forward],
life: 0,
smokePuffs: []
});
playMissileLaunchSound();
window.PATROL.totalMissilesFired++;
updateMissilePips();
}
function createExplosion(x, y, z, isWater) {
explosions.push({
pos: [x, y, z],
isWater: isWater,
life: 0,
maxLife: 2.8,
radius: 0.1,
maxRadius: isWater ? 38.0 : 44.0,
particles: Array.from({ length: 24 }, () => ({
dx: (Math.random() - 0.5) * 45,
dy: isWater ? (Math.random() * 60 + 20) : (Math.random() * 50 + 10),
dz: (Math.random() - 0.5) * 45
}))
});
playExplosionSound();
window.PATROL.totalExplosions++;
}
/* -------------------------------------------------------------------------
* WEB AUDIO API SYNTHESIZER
* Engine turbine whine, exhaust roar, afterburner scream, wind, missile sounds
* ------------------------------------------------------------------------- */
let audioCtx = null;
let engineWhineOsc = null;
let engineWhineGain = null;
let engineRoarNode = null;
let engineRoarFilter = null;
let engineRoarGain = null;
let burnerNoiseGain = null;
let burnerSubOsc = null;
let burnerSubGain = null;
let windNoiseGain = null;
function initAudio() {
if (audioCtx) return;
try {
const AudioContext = window.AudioContext || window.webkitAudioContext;
audioCtx = new AudioContext();
// 1. Turbine whine (dual detuned sines)
engineWhineOsc = audioCtx.createOscillator();
engineWhineOsc.type = 'sawtooth';
engineWhineOsc.frequency.setValueAtTime(320, audioCtx.currentTime);
const whineFilter = audioCtx.createBiquadFilter();
whineFilter.type = 'bandpass';
whineFilter.frequency.setValueAtTime(640, audioCtx.currentTime);
whineFilter.Q.setValueAtTime(4.0, audioCtx.currentTime);
engineWhineGain = audioCtx.createGain();
engineWhineGain.gain.setValueAtTime(0.04, audioCtx.currentTime);
engineWhineOsc.connect(whineFilter);
whineFilter.connect(engineWhineGain);
engineWhineGain.connect(audioCtx.destination);
engineWhineOsc.start();
// 2. Pink/Brown Jet Roar (filtered noise buffer)
const bufferSize = audioCtx.sampleRate * 2;
const noiseBuffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
const output = noiseBuffer.getChannelData(0);
let lastOut = 0.0;
for (let i = 0; i < bufferSize; i++) {
const white = Math.random() * 2 - 1;
output[i] = (lastOut + (0.02 * white)) / 1.02; // brown noise
lastOut = output[i];
output[i] *= 3.5;
}
engineRoarNode = audioCtx.createBufferSource();
engineRoarNode.buffer = noiseBuffer;
engineRoarNode.loop = true;
engineRoarFilter = audioCtx.createBiquadFilter();
engineRoarFilter.type = 'lowpass';
engineRoarFilter.frequency.setValueAtTime(350, audioCtx.currentTime);
engineRoarGain = audioCtx.createGain();
engineRoarGain.gain.setValueAtTime(0.08, audioCtx.currentTime);
engineRoarNode.connect(engineRoarFilter);
engineRoarFilter.connect(engineRoarGain);
engineRoarGain.connect(audioCtx.destination);
engineRoarNode.start();
// 3. Afterburner Reheat (deep 45Hz rumble + high sizzle)
burnerSubOsc = audioCtx.createOscillator();
burnerSubOsc.type = 'sine';
burnerSubOsc.frequency.setValueAtTime(46, audioCtx.currentTime);
burnerSubGain = audioCtx.createGain();
burnerSubGain.gain.setValueAtTime(0.0, audioCtx.currentTime);
burnerSubOsc.connect(burnerSubGain);
burnerSubGain.connect(audioCtx.destination);
burnerSubOsc.start();
burnerNoiseGain = audioCtx.createGain();
burnerNoiseGain.gain.setValueAtTime(0.0, audioCtx.currentTime);
const burnerFilter = audioCtx.createBiquadFilter();
burnerFilter.type = 'bandpass';
burnerFilter.frequency.setValueAtTime(1400, audioCtx.currentTime);
burnerFilter.Q.setValueAtTime(2.0, audioCtx.currentTime);
engineRoarNode.connect(burnerFilter);
burnerFilter.connect(burnerNoiseGain);
burnerNoiseGain.connect(audioCtx.destination);
// 4. Wind Rush
const windFilter = audioCtx.createBiquadFilter();
windFilter.type = 'lowpass';
windFilter.frequency.setValueAtTime(800, audioCtx.currentTime);
windNoiseGain = audioCtx.createGain();
windNoiseGain.gain.setValueAtTime(0.02, audioCtx.currentTime);
engineRoarNode.connect(windFilter);
windFilter.connect(windNoiseGain);
windNoiseGain.connect(audioCtx.destination);
} catch (err) {
console.warn("Web Audio init error:", err);
}
}
function updateAudioParams() {
if (!audioCtx || !window.PATROL.soundEnabled) return;
const t = audioCtx.currentTime;
const spdNorm = (jet.speed - 350) / 350; // 0 to 1
// Modulate turbine whine
if (engineWhineOsc) {
const freq = 280 + spdNorm * 420 + (jet.afterburner ? 180 : 0);
engineWhineOsc.frequency.setTargetAtTime(freq, t, 0.1);
}
// Modulate roar
if (engineRoarFilter && engineRoarGain) {
const cutoff = 240 + spdNorm * 500 + (jet.afterburner ? 400 : 0);
engineRoarFilter.frequency.setTargetAtTime(cutoff, t, 0.1);
engineRoarGain.gain.setTargetAtTime(0.06 + spdNorm * 0.08, t, 0.1);
}
// Modulate afterburner
if (burnerSubGain && burnerNoiseGain) {
const burnerVol = jet.afterburner ? 0.22 : 0.0;
burnerSubGain.gain.setTargetAtTime(burnerVol, t, 0.08);
burnerNoiseGain.gain.setTargetAtTime(burnerVol * 0.7, t, 0.08);
}
// Modulate wind
if (windNoiseGain) {
windNoiseGain.gain.setTargetAtTime(0.02 + spdNorm * 0.09, t, 0.1);
}
}
function playMissileLaunchSound() {
if (!audioCtx || !window.PATROL.soundEnabled) return;
const t = audioCtx.currentTime;
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = 'sawtooth';
osc.frequency.setValueAtTime(450, t);
osc.frequency.exponentialRampToValueAtTime(80, t + 0.45);
gain.gain.setValueAtTime(0.28, t);
gain.gain.linearRampToValueAtTime(0.0, t + 0.45);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(t);
osc.stop(t + 0.46);
}
function playExplosionSound() {
if (!audioCtx || !window.PATROL.soundEnabled) return;
const t = audioCtx.currentTime;
// Heavy sub thump
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = 'triangle';
osc.frequency.setValueAtTime(140, t);
osc.frequency.exponentialRampToValueAtTime(25, t + 0.8);
gain.gain.setValueAtTime(0.45, t);
gain.gain.exponentialRampToValueAtTime(0.001, t + 1.2);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(t);
osc.stop(t + 1.25);
}
/* -------------------------------------------------------------------------
* INPUT HANDLING & ARCADE FLIGHT MODEL
* ------------------------------------------------------------------------- */
window.addEventListener('mousemove', (e) => {
jet.mouseMoved = true;
const rect = glCanvas.getBoundingClientRect();
input.mouseX = ((e.clientX - rect.left) / rect.width) * 2 - 1;
input.mouseY = -(((e.clientY - rect.top) / rect.height) * 2 - 1);
});
window.addEventListener('mousedown', (e) => {
if (e.target.closest('.ui-button') || e.target.closest('.touch-btn')) return;
if (e.button === 0) {
input.leftDown = true;
input.leftDownTime = performance.now();
} else if (e.button === 2) {
fireMissile();
}
});
window.addEventListener('mouseup', (e) => {
if (e.button === 0) {
const pressDuration = performance.now() - input.leftDownTime;
input.leftDown = false;
// Short click without hold triggers barrel roll!
if (pressDuration < 220 && !jet.barrelRolling) {
jet.barrelRolling = true;
jet.rollTimer = 0;
}
}
});
window.addEventListener('contextmenu', (e) => e.preventDefault());
window.addEventListener('keydown', (e) => {
if (e.code === 'Space') {
cycleCamera();
} else if (e.code === 'KeyF') {
fireMissile();
} else if (e.code === 'KeyM') {
toggleSound();
}
});
// Touch controls setup
const touchStick = document.getElementById('touch-stick');
const touchStickNub = document.getElementById('touch-stick-nub');
let touchId = null;
if ('ontouchstart' in window || navigator.maxTouchPoints > 0) {
document.getElementById('touch-controls').style.display = 'block';
}
touchStick.addEventListener('touchstart', (e) => {
jet.mouseMoved = true;
const t = e.changedTouches[0];
touchId = t.identifier;
updateStick(t);
});
touchStick.addEventListener('touchmove', (e) => {
for (let i = 0; i < e.changedTouches.length; i++) {
if (e.changedTouches[i].identifier === touchId) {
updateStick(e.changedTouches[i]);
break;
}
}
});
const resetStick = () => {
touchId = null;
input.stickX = 0;
input.stickY = 0;
touchStickNub.style.transform = `translate(0px, 0px)`;
};
touchStick.addEventListener('touchend', resetStick);
touchStick.addEventListener('touchcancel', resetStick);
function updateStick(touch) {
const rect = touchStick.getBoundingClientRect();
const cx = rect.left + rect.width / 2;
const cy = rect.top + rect.height / 2;
let dx = touch.clientX - cx;
let dy = touch.clientY - cy;
const dist = Math.hypot(dx, dy);
const maxR = rect.width / 2 - 10;
if (dist > maxR) {
dx = (dx / dist) * maxR;
dy = (dy / dist) * maxR;
}
touchStickNub.style.transform = `translate(${dx}px, ${dy}px)`;
input.stickX = dx / maxR;
input.stickY = -dy / maxR;
}
document.getElementById('touch-burn').addEventListener('touchstart', () => input.leftDown = true);
document.getElementById('touch-burn').addEventListener('touchend', () => input.leftDown = false);
document.getElementById('touch-fire').addEventListener('touchstart', (e) => { e.preventDefault(); fireMissile(); });
document.getElementById('touch-view').addEventListener('touchstart', (e) => { e.preventDefault(); cycleCamera(); });
function cycleCamera() {
camera.targetMode = (camera.targetMode + 1) % 3;
camera.blendProgress = 0.0;
const names = ['TOP-DOWN [SPACE]', 'CHASE [SPACE]', 'COCKPIT [SPACE]'];
document.getElementById('btn-camera').textContent = 'VIEW: ' + names[camera.targetMode];
window.PATROL.viewMode = camera.targetMode;
}
function toggleSound() {
initAudio();
window.PATROL.soundEnabled = !window.PATROL.soundEnabled;
document.getElementById('btn-sound').textContent = window.PATROL.soundEnabled ? 'SOUND: ON' : 'SOUND: OFF';
if (!window.PATROL.soundEnabled) {
if (engineWhineGain) engineWhineGain.gain.setValueAtTime(0.0, audioCtx.currentTime);
if (engineRoarGain) engineRoarGain.gain.setValueAtTime(0.0, audioCtx.currentTime);
if (burnerSubGain) burnerSubGain.gain.setValueAtTime(0.0, audioCtx.currentTime);
if (burnerNoiseGain) burnerNoiseGain.gain.setValueAtTime(0.0, audioCtx.currentTime);
if (windNoiseGain) windNoiseGain.gain.setValueAtTime(0.0, audioCtx.currentTime);
}
}
document.getElementById('btn-sound').addEventListener('click', toggleSound);
document.getElementById('btn-camera').addEventListener('click', cycleCamera);
function updateMissilePips() {
const pipsContainer = document.getElementById('missile-pips');
const pips = pipsContainer.getElementsByClassName('missile-pip');
let readyCount = 0;
for (let i = 0; i < missileRails.length; i++) {
if (missileRails[i].ready) {
pips[i].classList.remove('empty');
readyCount++;
} else {
pips[i].classList.add('empty');
}
}
window.PATROL.missilesReady = readyCount;
}
/* -------------------------------------------------------------------------
* VECTOR & MATRIX UTILITIES
* ------------------------------------------------------------------------- */
function mat4Create() { return new Float32Array(16); }
function mat4Identity(out) {
out.fill(0);
out[0] = out[5] = out[10] = out[15] = 1;
return out;
}
function mat4Perspective(out, fov, aspect, near, far) {
const f = 1.0 / Math.tan(fov / 2);
const nf = 1 / (near - far);
out.fill(0);
out[0] = f / aspect;
out[5] = f;
out[10] = (far + near) * nf;
out[11] = -1;
out[14] = (2 * far * near) * nf;
return out;
}
function mat4LookAt(out, eye, center, up) {
const z0 = eye[0] - center[0], z1 = eye[1] - center[1], z2 = eye[2] - center[2];
let len = 1 / Math.hypot(z0, z1, z2);
const zx = z0 * len, zy = z1 * len, zz = z2 * len;
const x0 = up[1] * zz - up[2] * zy, x1 = up[2] * zx - up[0] * zz, x2 = up[0] * zy - up[1] * zx;
len = 1 / Math.hypot(x0, x1, x2);
const xx = x0 * len, xy = x1 * len, xz = x2 * len;
const yx = zy * xz - zz * xy, yy = zz * xx - zx * xz, yz = zx * xy - zy * xx;
out[0] = xx; out[1] = yx; out[2] = zx; out[3] = 0;
out[4] = xy; out[5] = yy; out[6] = zy; out[7] = 0;
out[8] = xz; out[9] = yz; out[10] = zz; out[11] = 0;
out[12] = -(xx * eye[0] + xy * eye[1] + xz * eye[2]);
out[13] = -(yx * eye[0] + yy * eye[1] + yz * eye[2]);
out[14] = -(zx * eye[0] + zy * eye[1] + zz * eye[2]);
out[15] = 1;
return out;
}
function mat4Multiply(out, a, b) {
// Column-major matrix multiplication: out = a * b
for (let c = 0; c < 4; c++) {
for (let r = 0; r < 4; r++) {
out[c * 4 + r] =
a[0 * 4 + r] * b[c * 4 + 0] +
a[1 * 4 + r] * b[c * 4 + 1] +
a[2 * 4 + r] * b[c * 4 + 2] +
a[3 * 4 + r] * b[c * 4 + 3];
}
}
return out;
}
/* -------------------------------------------------------------------------
* UPDATE FLIGHT DYNAMICS
* ------------------------------------------------------------------------- */
function updateFlight(dt) {
// 1. Afterburner hold detection
if (input.leftDown && (performance.now() - input.leftDownTime > 200)) {
jet.afterburner = true;
} else {
jet.afterburner = false;
}
// Airspeed ramping: 380 kts cruise -> 660 kts burner
const targetSpeed = jet.afterburner ? 660 : 380;
jet.speed += (targetSpeed - jet.speed) * dt * 2.8;
// 2. Steering input: Attract mode lazy S-turns or Player input
let ctrlX = input.mouseX || input.stickX;
let ctrlY = input.mouseY || input.stickY;
if (!jet.mouseMoved) {
jet.attractTime += dt;
ctrlX = Math.sin(jet.attractTime * 0.45) * 0.42;
ctrlY = Math.cos(jet.attractTime * 0.3) * 0.12;
}
// Barrel roll state
if (jet.barrelRolling) {
jet.rollTimer += dt * 5.5; // ~1.1s complete 360 roll
jet.roll += dt * 5.8;
if (jet.rollTimer >= Math.PI * 2) {
jet.barrelRolling = false;
jet.roll = 0;
}
} else {
// Roll follows steering X
const targetRoll = -ctrlX * 1.15;
jet.roll += (targetRoll - jet.roll) * dt * 4.5;
}
// Pitch follows steering Y
let targetPitch = ctrlY * 0.85;
// 3. Terrain collision avoidance (Fly-By-Wire Auto Pull-Up)
// Check ground altitude below and 1.2 seconds ahead
const curH = getTerrainHeightWorld(jet.pos[0], jet.pos[2]);
const clearance = jet.pos[1] - Math.max(WATER_LEVEL, curH);
jet.radAlt = Math.max(0, clearance);
const lookAheadDist = (jet.speed * 0.514) * 1.3;
const aheadX = jet.pos[0] + jet.forward[0] * lookAheadDist;
const aheadZ = jet.pos[2] + jet.forward[2] * lookAheadDist;
const aheadH = getTerrainHeightWorld(aheadX, aheadZ);
const aheadClearance = (jet.pos[1] + jet.forward[1] * lookAheadDist) - Math.max(WATER_LEVEL, aheadH);
if (clearance < 28.0 || aheadClearance < 25.0) {
jet.pullUpActive = true;
const pullFactor = Math.max(0.0, (32.0 - clearance) * 0.08);
targetPitch = Math.max(targetPitch, 0.45 + pullFactor);
} else {
jet.pullUpActive = false;
}
jet.pitch += (targetPitch - jet.pitch) * dt * 3.8;
// Yaw turning rate based on roll angle (coordinated banking turn)
const turnRate = -Math.sin(jet.roll) * 1.35;
jet.yaw += turnRate * dt;
// Calculate orientation vectors from pitch, roll, yaw
const cp = Math.cos(jet.pitch), sp = Math.sin(jet.pitch);
const cy = Math.cos(jet.yaw), sy = Math.sin(jet.yaw);
const cr = Math.cos(jet.roll), sr = Math.sin(jet.roll);
jet.forward = [
cy * cp,
sp,
sy * cp
];
// Normalize
const fLen = Math.hypot(jet.forward[0], jet.forward[1], jet.forward[2]);
jet.forward[0] /= fLen; jet.forward[1] /= fLen; jet.forward[2] /= fLen;
// Up vector with roll
jet.up = [
-cy * sp * sr - sy * cr,
cp * sr,
-sy * sp * sr + cy * cr
];
const uLen = Math.hypot(jet.up[0], jet.up[1], jet.up[2]);
jet.up[0] /= uLen; jet.up[1] /= uLen; jet.up[2] /= uLen;
// Right vector
jet.right = [
jet.forward[1] * jet.up[2] - jet.forward[2] * jet.up[1],
jet.forward[2] * jet.up[0] - jet.forward[0] * jet.up[2],
jet.forward[0] * jet.up[1] - jet.forward[1] * jet.up[0]
];
// Integrate position (speed in knots converted to world units/sec)
const worldSpeed = jet.speed * 0.48;
jet.pos[0] += jet.forward[0] * worldSpeed * dt;
jet.pos[1] += jet.forward[1] * worldSpeed * dt;
jet.pos[2] += jet.forward[2] * worldSpeed * dt;
// G-force calculation: 1.0G base + pitch rate contribution
jet.gForce = 1.0 + Math.max(-0.5, (targetPitch - jet.pitch) * 3.5 + Math.abs(turnRate) * 0.8);
// Reload timers for missiles
for (let i = 0; i < missileRails.length; i++) {
if (!missileRails[i].ready) {
missileRails[i].reloadTimer -= dt;
if (missileRails[i].reloadTimer <= 0) {
missileRails[i].ready = true;
updateMissilePips();
}
}
}
// Wingtip vapour trails (bursts during hard turns / G-pulls)
if (Math.abs(jet.gForce) > 1.3 || Math.abs(jet.roll) > 0.6) {
const tipL = [
jet.pos[0] - jet.right[0] * 3.8 + jet.up[0] * 0.05,
jet.pos[1] - jet.right[1] * 3.8 + jet.up[1] * 0.05,
jet.pos[2] - jet.right[2] * 3.8 + jet.up[2] * 0.05
];
const tipR = [
jet.pos[0] + jet.right[0] * 3.8 + jet.up[0] * 0.05,
jet.pos[1] + jet.right[1] * 3.8 + jet.up[1] * 0.05,
jet.pos[2] + jet.right[2] * 3.8 + jet.up[2] * 0.05
];
vapourTrailsL.push({ pos: tipL, life: 1.2 });
vapourTrailsR.push({ pos: tipR, life: 1.2 });
}
// Age vapour trails
for (let i = vapourTrailsL.length - 1; i >= 0; i--) {
vapourTrailsL[i].life -= dt;
if (vapourTrailsL[i].life <= 0) vapourTrailsL.splice(i, 1);
}
for (let i = vapourTrailsR.length - 1; i >= 0; i--) {
vapourTrailsR[i].life -= dt;
if (vapourTrailsR[i].life <= 0) vapourTrailsR.splice(i, 1);
}
// Water skimming spray & wake
if (jet.pos[1] - WATER_LEVEL < 22.0) {
waterSprays.push({
pos: [jet.pos[0], WATER_LEVEL, jet.pos[2]],
life: 1.5,
radius: 4.0
});
}
for (let i = waterSprays.length - 1; i >= 0; i--) {
waterSprays[i].life -= dt;
waterSprays[i].radius += dt * 14.0;
if (waterSprays[i].life <= 0) waterSprays.splice(i, 1);
}
// Update missiles
for (let i = missiles.length - 1; i >= 0; i--) {
const m = missiles[i];
m.life += dt;
m.pos[0] += m.vel[0] * dt;
m.pos[1] += m.vel[1] * dt;
m.pos[2] += m.vel[2] * dt;
// Gravity drop
m.vel[1] -= 9.8 * dt * 2.5;
// Ground / Water impact test
const mGround = getTerrainHeightWorld(m.pos[0], m.pos[2]);
if (m.pos[1] <= Math.max(WATER_LEVEL, mGround) || m.life > 5.0) {
const isWater = mGround < WATER_LEVEL;
createExplosion(m.pos[0], Math.max(WATER_LEVEL, mGround), m.pos[2], isWater);
missiles.splice(i, 1);
}
}
// Update explosions
for (let i = explosions.length - 1; i >= 0; i--) {
const ex = explosions[i];
ex.life += dt;
ex.radius += (ex.maxRadius - ex.radius) * dt * 3.5;
if (ex.life >= ex.maxLife) {
explosions.splice(i, 1);
}
}
updateAudioParams();
}
function getTerrainHeightWorld(x, z) {
if (!terrainTexture) return 0.0;
// Mirror worker math
const nx = ((x % TERRAIN_SCALE + TERRAIN_SCALE) % TERRAIN_SCALE) / TERRAIN_SCALE;
const nz = ((z % TERRAIN_SCALE + TERRAIN_SCALE) % TERRAIN_SCALE) / TERRAIN_SCALE;
// Approximate height using broad sine/noise
return (Math.sin(nx * 12.5) * 0.3 + Math.cos(nz * 12.5) * 0.3 + 0.45) * HEIGHT_SCALE;
}
/* -------------------------------------------------------------------------
* CAMERA BLENDING (Top-Down, Chase, Cockpit)
* ------------------------------------------------------------------------- */
function updateCamera(dt) {
if (camera.blendProgress < 1.0) {
camera.blendProgress = Math.min(1.0, camera.blendProgress + dt * 1.2);
}
// View configurations
// 0: Top-Down (North up)
const topPos = [jet.pos[0], jet.pos[1] + 125.0, jet.pos[2]];
const topDir = [0, -1, 0.0001];
const topUp = [0, 0, -1]; // North up (-Z)
// 1: Chase view (elevated behind jet, looking over wings toward horizon)
const chasePos = [
jet.pos[0] - jet.forward[0] * 24.0,
jet.pos[1] - jet.forward[1] * 10.0 + 7.5,
jet.pos[2] - jet.forward[2] * 24.0
];
const chaseLookAt = [
jet.pos[0] + jet.forward[0] * 20.0,
jet.pos[1] + jet.forward[1] * 6.0,
jet.pos[2] + jet.forward[2] * 20.0
];
const chaseDir = [
chaseLookAt[0] - chasePos[0],
chaseLookAt[1] - chasePos[1],
chaseLookAt[2] - chasePos[2]
];
const cLen = Math.hypot(chaseDir[0], chaseDir[1], chaseDir[2]);
chaseDir[0] /= cLen; chaseDir[1] /= cLen; chaseDir[2] /= cLen;
const chaseUp = [...jet.up];
// 2: Cockpit view
const cockpitPos = [
jet.pos[0] + jet.forward[0] * 1.7 + jet.up[0] * 0.72,
jet.pos[1] + jet.forward[1] * 1.7 + jet.up[1] * 0.72,
jet.pos[2] + jet.forward[2] * 1.7 + jet.up[2] * 0.72
];
const cockpitDir = [...jet.forward];
const cockpitUp = [...jet.up];
function getViewParams(mode) {
if (mode === 0) return { pos: topPos, dir: topDir, up: topUp, fov: 55 };
if (mode === 1) return { pos: chasePos, dir: chaseDir, up: chaseUp, fov: 62 };
return { pos: cockpitPos, dir: cockpitDir, up: cockpitUp, fov: 68 };
}
const curParams = getViewParams(camera.mode);
const targetParams = getViewParams(camera.targetMode);
// Smoothstep interpolation
const t = camera.blendProgress;
const s = t * t * (3 - 2 * t);
for (let i = 0; i < 3; i++) {
camera.pos[i] = curParams.pos[i] + (targetParams.pos[i] - curParams.pos[i]) * s;
camera.dir[i] = curParams.dir[i] + (targetParams.dir[i] - curParams.dir[i]) * s;
camera.up[i] = curParams.up[i] + (targetParams.up[i] - curParams.up[i]) * s;
}
camera.fov = (curParams.fov + (targetParams.fov - curParams.fov) * s) * Math.PI / 180;
// Normalize camera vectors
const dLen = Math.hypot(camera.dir[0], camera.dir[1], camera.dir[2]);
camera.dir[0] /= dLen; camera.dir[1] /= dLen; camera.dir[2] /= dLen;
// Orthonormal right and up
camera.right[0] = camera.dir[1] * camera.up[2] - camera.dir[2] * camera.up[1];
camera.right[1] = camera.dir[2] * camera.up[0] - camera.dir[0] * camera.up[2];
camera.right[2] = camera.dir[0] * camera.up[1] - camera.dir[1] * camera.up[0];
const rLen = Math.hypot(camera.right[0], camera.right[1], camera.right[2]);
camera.right[0] /= rLen; camera.right[1] /= rLen; camera.right[2] /= rLen;
camera.up[0] = camera.right[1] * camera.dir[2] - camera.right[2] * camera.dir[1];
camera.up[1] = camera.right[2] * camera.dir[0] - camera.right[0] * camera.dir[2];
camera.up[2] = camera.right[0] * camera.dir[1] - camera.right[1] * camera.dir[0];
if (camera.blendProgress >= 1.0) {
camera.mode = camera.targetMode;
}
}
/* -------------------------------------------------------------------------
* RENDERING PASSES: WORLD + 3D AIRCRAFT + MISSILES & AFTERBURNER
* ------------------------------------------------------------------------- */
const sunAzimuth = 225 * Math.PI / 180;
const sunElev = 12 * Math.PI / 180;
const sunDir = [
Math.cos(sunElev) * Math.cos(sunAzimuth),
Math.sin(sunElev),
Math.cos(sunElev) * Math.sin(sunAzimuth)
];
function renderWorld(time) {
gl.disable(gl.DEPTH_TEST);
gl.useProgram(worldProgram);
gl.uniform2f(gl.getUniformLocation(worldProgram, 'uResolution'), glCanvas.width, glCanvas.height);
gl.uniform3fv(gl.getUniformLocation(worldProgram, 'uCameraPos'), camera.pos);
gl.uniform3fv(gl.getUniformLocation(worldProgram, 'uCameraDir'), camera.dir);
gl.uniform3fv(gl.getUniformLocation(worldProgram, 'uCameraUp'), camera.up);
gl.uniform3fv(gl.getUniformLocation(worldProgram, 'uCameraRight'), camera.right);
gl.uniform1f(gl.getUniformLocation(worldProgram, 'uTanFov'), Math.tan(camera.fov / 2));
gl.uniform1f(gl.getUniformLocation(worldProgram, 'uAspect'), glCanvas.width / glCanvas.height);
gl.uniform3fv(gl.getUniformLocation(worldProgram, 'uSunDir'), sunDir);
gl.uniform1f(gl.getUniformLocation(worldProgram, 'uTime'), time);
gl.uniform3fv(gl.getUniformLocation(worldProgram, 'uJetPos'), jet.pos);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, terrainTexture);
gl.uniform1i(gl.getUniformLocation(worldProgram, 'uTerrainTex'), 0);
gl.bindVertexArray(quadVAO);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
const matView = mat4Create();
const matProj = mat4Create();
const matModel = mat4Create();
const matMVP = mat4Create();
function renderAircraft() {
// Don't render full external jet in Cockpit view (unless blending)
if (camera.mode === 2 && camera.blendProgress >= 1.0) return;
gl.clear(gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.useProgram(aircraftProgram);
const aspect = glCanvas.width / glCanvas.height;
mat4Perspective(matProj, camera.fov, aspect, 0.5, 3000.0);
const center = [
camera.pos[0] + camera.dir[0],
camera.pos[1] + camera.dir[1],
camera.pos[2] + camera.dir[2]
];
mat4LookAt(matView, camera.pos, center, camera.up);
// Construct model matrix from jet position and orientation vectors
mat4Identity(matModel);
matModel[0] = jet.right[0]; matModel[1] = jet.right[1]; matModel[2] = jet.right[2];
matModel[4] = jet.up[0]; matModel[5] = jet.up[1]; matModel[6] = jet.up[2];
matModel[8] = jet.forward[0]; matModel[9] = jet.forward[1]; matModel[10] = jet.forward[2];
matModel[12] = jet.pos[0]; matModel[13] = jet.pos[1]; matModel[14] = jet.pos[2];
const matVP = mat4Create();
mat4Multiply(matVP, matProj, matView);
mat4Multiply(matMVP, matVP, matModel);
gl.uniformMatrix4fv(gl.getUniformLocation(aircraftProgram, 'uMVP'), false, matMVP);
gl.uniformMatrix4fv(gl.getUniformLocation(aircraftProgram, 'uModel'), false, matModel);
gl.uniform3fv(gl.getUniformLocation(aircraftProgram, 'uSunDir'), sunDir);
gl.bindVertexArray(aircraftVAO);
// Pass 1: 1-pixel dark outline (inverted hull, draw backfaces)
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.FRONT);
gl.uniform1f(gl.getUniformLocation(aircraftProgram, 'uOutline'), 1.0);
gl.drawArrays(gl.TRIANGLES, 0, aircraftMesh.count);
// Pass 2: 3-tone flat-shaded aircraft (draw frontfaces)
gl.cullFace(gl.BACK);
gl.uniform1f(gl.getUniformLocation(aircraftProgram, 'uOutline'), 0.0);
gl.drawArrays(gl.TRIANGLES, 0, aircraftMesh.count);
// Pass 3: Underwing missiles on pylons
gl.bindVertexArray(missileVAO);
for (let i = 0; i < missileRails.length; i++) {
if (missileRails[i].ready) {
const rOff = missileRails[i].offset;
const mMdl = new Float32Array(matModel);
mMdl[12] = matModel[12] + jet.right[0] * rOff[0] + jet.up[0] * rOff[1] + jet.forward[0] * rOff[2];
mMdl[13] = matModel[13] + jet.right[1] * rOff[0] + jet.up[1] * rOff[1] + jet.forward[1] * rOff[2];
mMdl[14] = matModel[14] + jet.right[2] * rOff[0] + jet.up[2] * rOff[1] + jet.forward[2] * rOff[2];
mat4Multiply(matMVP, matVP, mMdl);
gl.uniformMatrix4fv(gl.getUniformLocation(aircraftProgram, 'uMVP'), false, matMVP);
gl.uniformMatrix4fv(gl.getUniformLocation(aircraftProgram, 'uModel'), false, mMdl);
gl.drawArrays(gl.TRIANGLES, 0, missileMesh.count);
}
}
// Pass 4: In-flight missiles
for (let i = 0; i < missiles.length; i++) {
const m = missiles[i];
const mMdl = mat4Create();
mat4Identity(mMdl);
const mFwd = [m.vel[0], m.vel[1], m.vel[2]];
const mLen = Math.hypot(mFwd[0], mFwd[1], mFwd[2]) || 1;
mFwd[0] /= mLen; mFwd[1] /= mLen; mFwd[2] /= mLen;
const mUp = [0, 1, 0];
const mR = [
mFwd[1]*mUp[2] - mFwd[2]*mUp[1],
mFwd[2]*mUp[0] - mFwd[0]*mUp[2],
mFwd[0]*mUp[1] - mFwd[1]*mUp[0]
];
const mRLen = Math.hypot(mR[0], mR[1], mR[2]) || 1;
mR[0] /= mRLen; mR[1] /= mRLen; mR[2] /= mRLen;
const mU = [
mR[1]*mFwd[2] - mR[2]*mFwd[1],
mR[2]*mFwd[0] - mR[0]*mFwd[2],
mR[0]*mFwd[1] - mR[1]*mFwd[0]
];
mMdl[0] = mR[0]; mMdl[1] = mR[1]; mMdl[2] = mR[2];
mMdl[4] = mU[0]; mMdl[5] = mU[1]; mMdl[6] = mU[2];
mMdl[8] = mFwd[0]; mMdl[9] = mFwd[1]; mMdl[10] = mFwd[2];
mMdl[12] = m.pos[0]; mMdl[13] = m.pos[1]; mMdl[14] = m.pos[2];
mat4Multiply(matMVP, matVP, mMdl);
gl.uniformMatrix4fv(gl.getUniformLocation(aircraftProgram, 'uMVP'), false, matMVP);
gl.uniformMatrix4fv(gl.getUniformLocation(aircraftProgram, 'uModel'), false, mMdl);
gl.drawArrays(gl.TRIANGLES, 0, missileMesh.count);
}
gl.disable(gl.CULL_FACE);
// Pass 5: 3D Dynamic Effects (Afterburners, Vapour Trails, Water Spray, Explosions)
renderEffects(matVP);
gl.disable(gl.DEPTH_TEST);
}
function renderEffects(matVP) {
fxReset();
// (A) Twin Afterburner Plumes with White Hot Core & Shock Diamonds
const nozOffsets = [[-0.42, 0.0, -2.9], [0.42, 0.0, -2.9]];
const plumeLen = jet.afterburner ? (8.5 + Math.random() * 1.5) : 1.8;
const coreCol = [1.0, 1.0, 1.0, 1.0]; // white hot core
const flameCol = jet.afterburner ? [1.0, 0.45, 0.1, 0.95] : [1.0, 0.7, 0.2, 0.7];
const cyanDiamond = [0.85, 0.95, 1.0, 0.9];
for (let i = 0; i < nozOffsets.length; i++) {
const off = nozOffsets[i];
const nPos = [
jet.pos[0] + jet.right[0] * off[0] + jet.up[0] * off[1] + jet.forward[0] * off[2],
jet.pos[1] + jet.right[1] * off[0] + jet.up[1] * off[1] + jet.forward[1] * off[2],
jet.pos[2] + jet.right[2] * off[0] + jet.up[2] * off[1] + jet.forward[2] * off[2]
];
const tipPos = [
nPos[0] - jet.forward[0] * plumeLen,
nPos[1] - jet.forward[1] * plumeLen,
nPos[2] - jet.forward[2] * plumeLen
];
const r1 = jet.afterburner ? 0.32 : 0.22;
const r2 = 0.04;
// Outer flame envelope
const pA = [nPos[0] - jet.right[0]*r1, nPos[1] - jet.right[1]*r1, nPos[2] - jet.right[2]*r1];
const pB = [nPos[0] + jet.right[0]*r1, nPos[1] + jet.right[1]*r1, nPos[2] + jet.right[2]*r1];
const pC = [tipPos[0] + jet.right[0]*r2, tipPos[1] + jet.right[1]*r2, tipPos[2] + jet.right[2]*r2];
const pD = [tipPos[0] - jet.right[0]*r2, tipPos[1] - jet.right[1]*r2, tipPos[2] - jet.right[2]*r2];
fxAddQuad(pA, pB, pC, pD, flameCol);
// Inner white-hot core
const coreLen = plumeLen * 0.48;
const coreTip = [
nPos[0] - jet.forward[0] * coreLen,
nPos[1] - jet.forward[1] * coreLen,
nPos[2] - jet.forward[2] * coreLen
];
const cr = r1 * 0.45;
const cpA = [nPos[0] - jet.right[0]*cr, nPos[1] - jet.right[1]*cr, nPos[2] - jet.right[2]*cr];
const cpB = [nPos[0] + jet.right[0]*cr, nPos[1] + jet.right[1]*cr, nPos[2] + jet.right[2]*cr];
const cpC = [coreTip[0] + jet.right[0]*(cr*0.2), coreTip[1] + jet.right[1]*(cr*0.2), coreTip[2] + jet.right[2]*(cr*0.2)];
const cpD = [coreTip[0] - jet.right[0]*(cr*0.2), coreTip[1] - jet.right[1]*(cr*0.2), coreTip[2] - jet.right[2]*(cr*0.2)];
fxAddQuad(cpA, cpB, cpC, cpD, coreCol);
// Supersonic shock diamond pulses
if (jet.afterburner) {
for (let d = 1; d <= 3; d++) {
const dDist = d * 2.2;
const dCenter = [
nPos[0] - jet.forward[0] * dDist,
nPos[1] - jet.forward[1] * dDist,
nPos[2] - jet.forward[2] * dDist
];
const dr = 0.16;
const dp1 = [dCenter[0] - jet.right[0]*dr, dCenter[1] - jet.right[1]*dr, dCenter[2] - jet.right[2]*dr];
const dp2 = [dCenter[0] + jet.up[0]*dr, dCenter[1] + jet.up[1]*dr, dCenter[2] + jet.up[2]*dr];
const dp3 = [dCenter[0] + jet.right[0]*dr, dCenter[1] + jet.right[1]*dr, dCenter[2] + jet.right[2]*dr];
const dp4 = [dCenter[0] - jet.up[0]*dr, dCenter[1] - jet.up[1]*dr, dCenter[2] - jet.up[2]*dr];
fxAddQuad(dp1, dp2, dp3, dp4, cyanDiamond);
}
}
}
// (B) Thin White Vapour Trails from Wingtips
const vCol = [0.94, 0.96, 1.0, 0.85];
for (let t = 0; t < vapourTrailsL.length - 1; t++) {
const p1 = vapourTrailsL[t].pos;
const p2 = vapourTrailsL[t + 1].pos;
if (Math.hypot(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2]) < 25.0) {
const w = 0.18;
fxAddQuad(
[p1[0] - w, p1[1], p1[2]],
[p1[0] + w, p1[1], p1[2]],
[p2[0] + w, p2[1], p2[2]],
[p2[0] - w, p2[1], p2[2]],
vCol
);
}
}
for (let t = 0; t < vapourTrailsR.length - 1; t++) {
const p1 = vapourTrailsR[t].pos;
const p2 = vapourTrailsR[t + 1].pos;
if (Math.hypot(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2]) < 25.0) {
const w = 0.18;
fxAddQuad(
[p1[0] - w, p1[1], p1[2]],
[p1[0] + w, p1[1], p1[2]],
[p2[0] + w, p2[1], p2[2]],
[p2[0] - w, p2[1], p2[2]],
vCol
);
}
}
// (C) In-Flight Missile Rocket Motor Flame & Smoke Trail
for (let i = 0; i < missiles.length; i++) {
const m = missiles[i];
const mTail = [
m.pos[0] - m.dir[0] * 1.1,
m.pos[1] - m.dir[1] * 1.1,
m.pos[2] - m.dir[2] * 1.1
];
const mFlameTip = [
mTail[0] - m.dir[0] * 2.2,
mTail[1] - m.dir[1] * 2.2,
mTail[2] - m.dir[2] * 2.2
];
// Rocket flame
fxAddQuad(
[mTail[0] - 0.18, mTail[1], mTail[2]],
[mTail[0] + 0.18, mTail[1], mTail[2]],
[mFlameTip[0] + 0.04, mFlameTip[1], mFlameTip[2]],
[mFlameTip[0] - 0.04, mFlameTip[1], mFlameTip[2]],
[1.0, 0.8, 0.3, 1.0]
);
}
// (D) Water Skimming Spray & Wake
const foamCol = [0.88, 0.94, 0.98, 0.85];
for (let i = 0; i < waterSprays.length; i++) {
const sp = waterSprays[i];
const rad = sp.radius;
const p = sp.pos;
// Expanding ring on water
for (let j = 0; j < 8; j++) {
const a1 = (j / 8) * Math.PI * 2;
const a2 = ((j + 1) / 8) * Math.PI * 2;
fxAddQuad(
[p[0] + Math.cos(a1) * (rad - 1.2), p[1], p[2] + Math.sin(a1) * (rad - 1.2)],
[p[0] + Math.cos(a1) * rad, p[1], p[2] + Math.sin(a1) * rad],
[p[0] + Math.cos(a2) * rad, p[1], p[2] + Math.sin(a2) * rad],
[p[0] + Math.cos(a2) * (rad - 1.2), p[1], p[2] + Math.sin(a2) * (rad - 1.2)],
foamCol
);
}
}
// (E) Explosions: Flash, Fireball, Shock Ring, Land Scorch, Water Geyser
for (let i = 0; i < explosions.length; i++) {
const ex = explosions[i];
const p = ex.pos;
const progress = ex.life / ex.maxLife;
if (ex.isWater) {
// WATER STRIKE: Towering White Spray Column (Geyser) + Expanding Churned Foam
const geyserH = Math.max(0.0, (1.0 - progress) * 48.0);
const geyserW = 4.5 + progress * 8.0;
const waterSprayCol = [0.92, 0.96, 1.0, 0.9];
// Vertical geyser plume
for (let s = 0; s < 4; s++) {
const a = (s / 4) * Math.PI;
fxAddQuad(
[p[0] - Math.cos(a)*geyserW, p[1], p[2] - Math.sin(a)*geyserW],
[p[0] + Math.cos(a)*geyserW, p[1], p[2] + Math.sin(a)*geyserW],
[p[0] + Math.cos(a)*(geyserW*0.4), p[1] + geyserH, p[2] + Math.sin(a)*(geyserW*0.4)],
[p[0] - Math.cos(a)*(geyserW*0.4), p[1] + geyserH, p[2] - Math.sin(a)*(geyserW*0.4)],
waterSprayCol
);
}
// Expanding foam ring
const ringR = ex.radius;
for (let s = 0; s < 12; s++) {
const a1 = (s / 12) * Math.PI * 2;
const a2 = ((s + 1) / 12) * Math.PI * 2;
fxAddQuad(
[p[0] + Math.cos(a1)*(ringR - 2.5), p[1] + 0.1, p[2] + Math.sin(a1)*(ringR - 2.5)],
[p[0] + Math.cos(a1)*ringR, p[1] + 0.1, p[2] + Math.sin(a1)*ringR],
[p[0] + Math.cos(a2)*ringR, p[1] + 0.1, p[2] + Math.sin(a2)*ringR],
[p[0] + Math.cos(a2)*(ringR - 2.5), p[1] + 0.1, p[2] + Math.sin(a2)*(ringR - 2.5)],
foamCol
);
}
} else {
// LAND STRIKE: Expanding Shockwave Ring + Fireball + Dark Scorch with Glowing Embers
const ringR = ex.radius;
const shockCol = [1.0, 0.85, 0.6, 1.0 - progress];
// Expanding shockwave ring
for (let s = 0; s < 12; s++) {
const a1 = (s / 12) * Math.PI * 2;
const a2 = ((s + 1) / 12) * Math.PI * 2;
fxAddQuad(
[p[0] + Math.cos(a1)*(ringR - 2.0), p[1] + 0.15, p[2] + Math.sin(a1)*(ringR - 2.0)],
[p[0] + Math.cos(a1)*ringR, p[1] + 0.15, p[2] + Math.sin(a1)*ringR],
[p[0] + Math.cos(a2)*ringR, p[1] + 0.15, p[2] + Math.sin(a2)*ringR],
[p[0] + Math.cos(a2)*(ringR - 2.0), p[1] + 0.15, p[2] + Math.sin(a2)*(ringR - 2.0)],
shockCol
);
}
// Fireball (active during first 1.2 seconds)
if (progress < 0.45) {
const fireR = (1.0 - progress * 2.0) * 16.0;
const fireCol = progress < 0.2 ? [1.0, 0.95, 0.4, 1.0] : [1.0, 0.45, 0.1, 1.0];
for (let s = 0; s < 6; s++) {
const a = (s / 6) * Math.PI;
fxAddQuad(
[p[0] - Math.cos(a)*fireR, p[1] + fireR*0.5, p[2] - Math.sin(a)*fireR],
[p[0] + Math.cos(a)*fireR, p[1] + fireR*0.5, p[2] + Math.sin(a)*fireR],
[p[0] + Math.cos(a)*fireR*0.3, p[1] + fireR*1.6, p[2] + Math.sin(a)*fireR*0.3],
[p[0] - Math.cos(a)*fireR*0.3, p[1] + fireR*1.6, p[2] - Math.sin(a)*fireR*0.3],
fireCol
);
}
}
// Dark Scorch mark with glowing embers
const scorchR = Math.min(ex.maxRadius * 0.4, 12.0);
const scorchCol = [0.12, 0.08, 0.16, 1.0];
const emberCol = [1.0, 0.35, 0.05, 0.9];
for (let s = 0; s < 8; s++) {
const a1 = (s / 8) * Math.PI * 2;
const a2 = ((s + 1) / 8) * Math.PI * 2;
fxAddQuad(
p,
[p[0] + Math.cos(a1)*scorchR, p[1] + 0.08, p[2] + Math.sin(a1)*scorchR],
[p[0] + Math.cos(a2)*scorchR, p[1] + 0.08, p[2] + Math.sin(a2)*scorchR],
p,
scorchCol
);
// Scattered glowing embers
if (s % 2 === 0) {
const er = scorchR * 0.6;
fxAddTri(
[p[0] + Math.cos(a1)*er - 0.4, p[1] + 0.12, p[2] + Math.sin(a1)*er],
[p[0] + Math.cos(a1)*er + 0.4, p[1] + 0.12, p[2] + Math.sin(a1)*er],
[p[0] + Math.cos(a1)*er, p[1] + 0.12, p[2] + Math.sin(a1)*er + 0.6],
emberCol
);
}
}
}
}
if (fxVertCount > 0) {
gl.useProgram(fxProgram);
gl.uniformMatrix4fv(gl.getUniformLocation(fxProgram, 'uMVP'), false, matVP);
gl.bindVertexArray(fxVAO);
gl.bindBuffer(gl.ARRAY_BUFFER, fxVBO);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, fxBufferData.subarray(0, fxVertCount * 7));
gl.drawArrays(gl.TRIANGLES, 0, fxVertCount);
}
}
/* -------------------------------------------------------------------------
* CANVAS 2D COCKPIT & HEAD-UP DISPLAY (HUD)
* Real instruments, amber radar sweep, horizon-glued pitch ladder
* ------------------------------------------------------------------------- */
let radarSweepAngle = 0;
function renderCockpit(dt) {
ctx2d.clearRect(0, 0, cockpitCanvas.width, cockpitCanvas.height);
const w = cockpitCanvas.width;
const h = cockpitCanvas.height;
// Cockpit is active in mode 2 (or during transition to mode 2)
const cockpitWeight = camera.mode === 2 ? 1.0 : (camera.targetMode === 2 ? camera.blendProgress : 0.0);
if (cockpitWeight <= 0.001) return;
ctx2d.save();
ctx2d.globalAlpha = cockpitWeight;
// 1. Canopy Frame & Glare Shield
ctx2d.fillStyle = '#161320';
// Bottom instrument panel deck
const panelH = Math.round(h * 0.36);
ctx2d.fillRect(0, h - panelH, w, panelH);
// Top canopy arch
ctx2d.beginPath();
ctx2d.moveTo(0, 0);
ctx2d.lineTo(w * 0.22, 0);
ctx2d.lineTo(0, h * 0.32);
ctx2d.closePath();
ctx2d.fill();
ctx2d.beginPath();
ctx2d.moveTo(w, 0);
ctx2d.lineTo(w * 0.78, 0);
ctx2d.lineTo(w, h * 0.32);
ctx2d.closePath();
ctx2d.fill();
// Canopy frame structural pillars
ctx2d.strokeStyle = '#282436';
ctx2d.lineWidth = 3;
ctx2d.strokeRect(w * 0.18, 0, w * 0.64, h - panelH);
// Panel top rim
ctx2d.fillStyle = '#322b44';
ctx2d.fillRect(0, h - panelH - 4, w, 4);
// -----------------------------------------------------------------------
// 2. Real Hand-Plotted Pixel Instruments
// -----------------------------------------------------------------------
const baseY = h - panelH + 8;
// (A) Bay 1: Airspeed Indicator + Turn & Slip Indicator
const bay1X = Math.round(w * 0.14);
drawDialGauge(ctx2d, bay1X, baseY + 18, 19, (jet.speed - 200) / 600, 'KTS');
// Digital Speed readout
ctx2d.fillStyle = '#0a0812';
ctx2d.fillRect(bay1X - 16, baseY + 30, 32, 9);
ctx2d.fillStyle = '#ffb86c';
ctx2d.font = '8px "Share Tech Mono"';
ctx2d.textAlign = 'center';
ctx2d.fillText(Math.round(jet.speed), bay1X, baseY + 38);
// Turn & Slip
const turnRate = -Math.sin(jet.roll) * 1.5;
const slipG = Math.sin(jet.roll) * 0.4;
drawTurnSlip(ctx2d, bay1X, baseY + 62, 18, turnRate, slipG);
// (B) Bay 2: Attitude Director Indicator (ADI) + Heading Gyro Rose
const bay2X = Math.round(w * 0.28);
drawADI(ctx2d, bay2X, baseY + 20, 24, jet.pitch, jet.roll);
drawHeadingGyro(ctx2d, bay2X, baseY + 62, 19, jet.yaw);
// (C) Bay 3: Altimeter + Vertical Speed Indicator (VSI)
const bay3X = Math.round(w * 0.44);
drawDialGauge(ctx2d, bay3X, baseY + 18, 19, (jet.pos[1] % 1000) / 1000, 'ALT');
ctx2d.fillStyle = '#0a0812';
ctx2d.fillRect(bay3X - 20, baseY + 30, 40, 9);
ctx2d.fillStyle = '#ffffff';
ctx2d.font = '8px "Share Tech Mono"';
ctx2d.textAlign = 'center';
const altFeet = Math.round(jet.pos[1] * 12.5);
ctx2d.fillText(altFeet + ' FT', bay3X, baseY + 38);
// VSI (Vertical Speed)
const climbFpm = jet.forward[1] * jet.speed * 60.0;
drawVSI(ctx2d, bay3X, baseY + 62, 18, climbFpm);
// (D) Bay 4: Amber Ground-Mapping Radar with Rotating Radial Sweep
const radX = Math.round(w * 0.63);
const radY = baseY + 40;
drawAmberRadar(ctx2d, radX, radY, 32, dt);
// (E) Bay 5: Twin Engine Tachometers (RPM & EGT) + Local Clock
const bay5X = Math.round(w * 0.83);
const rpmPercent = jet.afterburner ? 106 : 88;
drawDialGauge(ctx2d, bay5X - 16, baseY + 22, 16, rpmPercent / 120, 'L%');
drawDialGauge(ctx2d, bay5X + 16, baseY + 22, 16, rpmPercent / 120, 'R%');
drawCockpitClock(ctx2d, bay5X, baseY + 62);
// (F) Warning Annunciator Lamps
drawWarningAnnunciator(ctx2d, Math.round(w * 0.5), baseY - 3);
// (G) Throttle Lever
drawThrottleLever(ctx2d, Math.round(w * 0.04), baseY + 10, jet.afterburner);
// -----------------------------------------------------------------------
// 3. Head-Up Display (HUD) - Pitch ladder sits EXACTLY on real horizon!
// -----------------------------------------------------------------------
drawHUD(ctx2d, w, h);
ctx2d.restore();
}
function drawDialGauge(ctx, cx, cy, r, frac, label) {
// Circular instrument bezel
ctx.fillStyle = '#0f0c18';
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#443b5c';
ctx.lineWidth = 2;
ctx.stroke();
// Tick marks
ctx.strokeStyle = '#9e8fb8';
ctx.lineWidth = 1;
for (let i = 0; i < 8; i++) {
const ang = (i / 8) * Math.PI * 1.5 + Math.PI * 0.75;
const x1 = cx + Math.cos(ang) * (r - 2);
const y1 = cy + Math.sin(ang) * (r - 2);
const x2 = cx + Math.cos(ang) * (r - 6);
const y2 = cy + Math.sin(ang) * (r - 6);
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
// Needle
const needleAng = Math.min(1.0, Math.max(0.0, frac)) * Math.PI * 1.5 + Math.PI * 0.75;
ctx.strokeStyle = '#ffb86c';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.lineTo(cx + Math.cos(needleAng) * (r - 4), cy + Math.sin(needleAng) * (r - 4));
ctx.stroke();
// Center pin
ctx.fillStyle = '#ffb86c';
ctx.fillRect(cx - 1, cy - 1, 3, 3);
// Label
ctx.fillStyle = '#cbb6a3';
ctx.font = '7px "Share Tech Mono"';
ctx.textAlign = 'center';
ctx.fillText(label, cx, cy - 6);
}
function drawADI(ctx, cx, cy, r, pitch, roll) {
ctx.save();
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.clip();
// ADI Bezel background
ctx.fillStyle = '#161320';
ctx.fill();
// Rotate with roll and translate with pitch
ctx.translate(cx, cy);
ctx.rotate(-roll);
const pitchOffset = pitch * 32.0;
// Sky hemisphere (dusk violet)
ctx.fillStyle = '#3d2c54';
ctx.fillRect(-r * 1.5, -r * 1.5 + pitchOffset, r * 3, r * 1.5);
// Earth hemisphere (amber-brown)
ctx.fillStyle = '#5c3a24';
ctx.fillRect(-r * 1.5, pitchOffset, r * 3, r * 1.5);
// Horizon line
ctx.strokeStyle = '#f0e6d2';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(-r, pitchOffset);
ctx.lineTo(r, pitchOffset);
ctx.stroke();
// Pitch rungs
ctx.strokeStyle = '#f0e6d2';
ctx.lineWidth = 1;
ctx.strokeRect(-10, pitchOffset - 12, 20, 1);
ctx.strokeRect(-10, pitchOffset + 12, 20, 1);
ctx.restore();
// Fixed miniature aircraft crossbar
ctx.strokeStyle = '#ffb86c';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(cx - 14, cy);
ctx.lineTo(cx - 4, cy);
ctx.lineTo(cx, cy + 3);
ctx.lineTo(cx + 4, cy);
ctx.lineTo(cx + 14, cy);
ctx.stroke();
ctx.strokeStyle = '#5a4c72';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.stroke();
}
function drawTurnSlip(ctx, cx, cy, r, turnRate, slipG) {
// Bezel
ctx.fillStyle = '#0f0c18';
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#443b5c';
ctx.lineWidth = 2;
ctx.stroke();
// Top turn needle
const turnAng = Math.max(-1.0, Math.min(1.0, turnRate * 0.8)) * 0.6 - Math.PI / 2;
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(cx, cy - 2);
ctx.lineTo(cx + Math.cos(turnAng) * (r - 4), cy - 2 + Math.sin(turnAng) * (r - 4));
ctx.stroke();
// Doghouse markers
ctx.fillStyle = '#cbb6a3';
ctx.fillRect(cx - 10, cy - r + 3, 2, 4);
ctx.fillRect(cx + 8, cy - r + 3, 2, 4);
ctx.fillRect(cx - 1, cy - r + 3, 2, 4);
// Bottom curved slip tube
ctx.fillStyle = '#1e1828';
ctx.fillRect(cx - 12, cy + 6, 24, 6);
ctx.strokeStyle = '#5d4e76';
ctx.lineWidth = 1;
ctx.strokeRect(cx - 12, cy + 6, 24, 6);
ctx.strokeRect(cx - 3, cy + 6, 6, 6);
// Slip ball
const ballX = cx + Math.max(-8, Math.min(8, slipG * 12));
ctx.fillStyle = '#0a0812';
ctx.beginPath();
ctx.arc(ballX, cy + 9, 2.8, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#e0d4c0';
ctx.stroke();
ctx.fillStyle = '#cbb6a3';
ctx.font = '6px "Share Tech Mono"';
ctx.textAlign = 'center';
ctx.fillText('TURN', cx, cy - 6);
}
function drawHeadingGyro(ctx, cx, cy, r, yaw) {
ctx.fillStyle = '#0f0c18';
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#443b5c';
ctx.lineWidth = 2;
ctx.stroke();
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(-yaw);
// Rotating compass card ticks and cardinal letters
ctx.strokeStyle = '#8a7c9e';
ctx.fillStyle = '#f0e6d2';
ctx.font = '7px "Share Tech Mono"';
ctx.textAlign = 'center';
const cardinals = ['N', '3', '6', 'E', '12', '15', 'S', '21', '24', 'W', '30', '33'];
for (let i = 0; i < 12; i++) {
const ang = (i / 12) * Math.PI * 2 - Math.PI / 2;
const x1 = Math.cos(ang) * (r - 2);
const y1 = Math.sin(ang) * (r - 2);
const x2 = Math.cos(ang) * (r - 5);
const y2 = Math.sin(ang) * (r - 5);
ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke();
if (i % 3 === 0) {
ctx.fillText(cardinals[i], Math.cos(ang) * (r - 9), Math.sin(ang) * (r - 9) + 2.5);
}
}
ctx.restore();
// Lubber line (top pointer)
ctx.fillStyle = '#ffb86c';
ctx.beginPath();
ctx.moveTo(cx, cy - r + 1);
ctx.lineTo(cx - 3, cy - r + 5);
ctx.lineTo(cx + 3, cy - r + 5);
ctx.closePath();
ctx.fill();
// Miniature aircraft symbol
ctx.fillStyle = '#ffaa55';
ctx.fillRect(cx - 1, cy - 3, 2, 6);
ctx.fillRect(cx - 4, cy - 1, 8, 2);
}
function drawVSI(ctx, cx, cy, r, climbRate) {
ctx.fillStyle = '#0f0c18';
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#443b5c';
ctx.lineWidth = 2;
ctx.stroke();
const frac = Math.max(-1.0, Math.min(1.0, climbRate / 4000.0));
const ang = Math.PI - (frac * Math.PI * 0.42);
ctx.strokeStyle = '#f0e6d2';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.lineTo(cx + Math.cos(ang) * (r - 3), cy + Math.sin(ang) * (r - 3));
ctx.stroke();
ctx.fillStyle = '#ffb86c';
ctx.fillRect(cx - 1, cy - 1, 3, 3);
ctx.fillStyle = '#cbb6a3';
ctx.font = '6px "Share Tech Mono"';
ctx.textAlign = 'center';
ctx.fillText('VSI', cx, cy - 5);
}
function drawAmberRadar(ctx, cx, cy, r, dt) {
// CRT bezel
ctx.fillStyle = '#0d0905';
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#8a5c18';
ctx.lineWidth = 2;
ctx.stroke();
// Amber phosphor concentric range rings
ctx.strokeStyle = 'rgba(212, 146, 25, 0.35)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.arc(cx, cy, r * 0.35, 0, Math.PI * 2);
ctx.arc(cx, cy, r * 0.7, 0, Math.PI * 2);
ctx.arc(cx, cy, r * 0.95, 0, Math.PI * 2);
ctx.stroke();
// Crosshairs
ctx.beginPath();
ctx.moveTo(cx - r, cy); ctx.lineTo(cx + r, cy);
ctx.moveTo(cx, cy - r); ctx.lineTo(cx, cy + r);
ctx.stroke();
// Rotating radial sweep line
radarSweepAngle += dt * 3.14; // 1 revolution every 2 seconds
const sx = cx + Math.cos(radarSweepAngle) * (r - 2);
const sy = cy + Math.sin(radarSweepAngle) * (r - 2);
ctx.strokeStyle = '#ffae28';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.lineTo(sx, sy);
ctx.stroke();
// Real terrain blips in amber phosphor
ctx.fillStyle = '#ffaa20';
for (let i = 0; i < 7; i++) {
const ang = (i * 0.9) - jet.yaw;
const dist = 12 + (i * 2.8);
const bx = cx + Math.cos(ang) * dist;
const by = cy + Math.sin(ang) * dist;
ctx.fillRect(Math.round(bx), Math.round(by), 2, 2);
}
}
function drawWarningAnnunciator(ctx, cx, cy) {
const lamps = [
{ label: 'PULL UP', active: jet.pullUpActive, col: '#ff3333' },
{ label: 'LOW ALT', active: jet.radAlt < 45, col: '#ffaa00' },
{ label: 'BURNER', active: jet.afterburner, col: '#ffee55' },
{ label: 'MSL RDY', active: window.PATROL.missilesReady > 0, col: '#33ff33' }
];
const lampW = 44;
const lampH = 12;
const startX = cx - (lamps.length * (lampW + 4)) / 2;
ctx.font = '8px "Press Start 2P", monospace';
ctx.textAlign = 'center';
for (let i = 0; i < lamps.length; i++) {
const lx = startX + i * (lampW + 4);
const l = lamps[i];
ctx.fillStyle = l.active ? l.col : '#1c1626';
ctx.fillRect(lx, cy, lampW, lampH);
ctx.strokeStyle = '#3d3250';
ctx.lineWidth = 1;
ctx.strokeRect(lx, cy, lampW, lampH);
ctx.fillStyle = l.active ? '#0a0812' : '#4e4364';
ctx.fillText(l.label, lx + lampW / 2, cy + 9);
}
}
function drawThrottleLever(ctx, lx, ly, isBurner) {
// Throttle slot
ctx.fillStyle = '#0c0a14';
ctx.fillRect(lx, ly, 10, 52);
ctx.strokeStyle = '#443b5c';
ctx.strokeRect(lx, ly, 10, 52);
// Lever knob moves with afterburner
const knobY = isBurner ? ly + 6 : ly + 28;
ctx.fillStyle = isBurner ? '#ffaa55' : '#776b92';
ctx.fillRect(lx - 4, knobY, 18, 12);
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1;
ctx.strokeRect(lx - 4, knobY, 18, 12);
}
function drawCockpitClock(ctx, cx, cy) {
const now = new Date();
const hh = String(now.getHours()).padStart(2, '0');
const mm = String(now.getMinutes()).padStart(2, '0');
const ss = String(now.getSeconds()).padStart(2, '0');
ctx.fillStyle = '#0a0812';
ctx.fillRect(cx - 24, cy, 48, 14);
ctx.strokeStyle = '#443b5c';
ctx.strokeRect(cx - 24, cy, 48, 14);
ctx.fillStyle = '#39ff14';
ctx.font = '9px "Share Tech Mono"';
ctx.textAlign = 'center';
ctx.fillText(`${hh}:${mm}:${ss}`, cx, cy + 10);
}
function drawHUD(ctx, w, h) {
const cx = w * 0.5;
const cy = h * 0.36;
ctx.save();
ctx.strokeStyle = '#39ff14';
ctx.fillStyle = '#39ff14';
ctx.lineWidth = 1.5;
ctx.font = '10px "Share Tech Mono"';
// 1. Heading Tape at top
ctx.strokeRect(cx - 90, cy - 80, 180, 16);
const headingDeg = Math.round(((jet.yaw * 180 / Math.PI) % 360 + 360) % 360);
ctx.textAlign = 'center';
ctx.fillText(String(headingDeg).padStart(3, '0') + '°', cx, cy - 68);
// 2. Airspeed Box on Left
ctx.strokeRect(cx - 120, cy - 14, 34, 18);
ctx.textAlign = 'center';
ctx.fillText(Math.round(jet.speed), cx - 103, cy);
// 3. Altitude Box on Right
ctx.strokeRect(cx + 86, cy - 14, 42, 18);
const altFt = Math.round(jet.pos[1] * 12.5);
ctx.fillText(altFt, cx + 107, cy);
// 4. G-Meter & Radar Alt
ctx.textAlign = 'left';
ctx.fillText(jet.gForce.toFixed(1) + ' G', cx - 120, cy + 24);
ctx.fillText('R ' + Math.round(jet.radAlt * 12.5), cx + 86, cy + 24);
// 5. Pitch Ladder sits EXACTLY on the real horizon outside!
// Project angle differences using camera FOV
const tanHalfFov = Math.tan(camera.fov / 2);
const pxPerRad = (h / 2) / tanHalfFov;
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(-jet.roll);
for (let deg = -20; deg <= 20; deg += 10) {
const rad = deg * Math.PI / 180;
const dy = -(rad - jet.pitch) * pxPerRad;
if (Math.abs(dy) < 70) {
if (deg === 0) {
// Horizon line
ctx.beginPath();
ctx.moveTo(-45, dy); ctx.lineTo(-12, dy);
ctx.moveTo(12, dy); ctx.lineTo(45, dy);
ctx.stroke();
} else if (deg > 0) {
// Positive climb rungs (solid)
ctx.beginPath();
ctx.moveTo(-32, dy); ctx.lineTo(-8, dy);
ctx.moveTo(8, dy); ctx.lineTo(32, dy);
ctx.stroke();
ctx.fillText(deg + '°', 36, dy + 3);
} else {
// Negative dive rungs (dashed with downward tails)
ctx.setLineDash([4, 3]);
ctx.beginPath();
ctx.moveTo(-32, dy); ctx.lineTo(-8, dy);
ctx.moveTo(8, dy); ctx.lineTo(32, dy);
ctx.stroke();
ctx.setLineDash([]);
// Downward tails
ctx.beginPath();
ctx.moveTo(-32, dy); ctx.lineTo(-32, dy + 5);
ctx.moveTo(32, dy); ctx.lineTo(32, dy + 5);
ctx.stroke();
ctx.fillText(deg + '°', 36, dy + 3);
}
}
}
// Flight Path Marker (Velocity Vector circle with wings)
ctx.beginPath();
ctx.arc(0, 0, 4, 0, Math.PI * 2);
ctx.moveTo(-9, 0); ctx.lineTo(-4, 0);
ctx.moveTo(4, 0); ctx.lineTo(9, 0);
ctx.moveTo(0, -4); ctx.lineTo(0, -8);
ctx.stroke();
ctx.restore();
// 6. HUD Pull-Up Warning
if (jet.pullUpActive && Math.floor(performance.now() / 250) % 2 === 0) {
ctx.fillStyle = '#ff3333';
ctx.font = '12px "Press Start 2P", monospace';
ctx.textAlign = 'center';
ctx.fillText('PULL UP', cx, cy + 50);
}
ctx.restore();
}
/* -------------------------------------------------------------------------
* MAIN LOOP & ADAPTIVE RESOLUTION SCALING
* ------------------------------------------------------------------------- */
let lastTime = performance.now();
let frameTimes = [];
function resizeCanvases() {
// Dynamic internal resolution matching window aspect ratio
const aspect = window.innerWidth / window.innerHeight;
const targetH = window.PATROL.internalHeight;
const targetW = Math.round(targetH * aspect);
if (glCanvas.width !== targetW || glCanvas.height !== targetH) {
glCanvas.width = targetW;
glCanvas.height = targetH;
cockpitCanvas.width = targetW;
cockpitCanvas.height = targetH;
gl.viewport(0, 0, targetW, targetH);
// Nearest-neighbor presentation via CSS scaling
const styleW = window.innerWidth;
const styleH = window.innerHeight;
glCanvas.style.width = styleW + 'px';
glCanvas.style.height = styleH + 'px';
cockpitCanvas.style.width = styleW + 'px';
cockpitCanvas.style.height = styleH + 'px';
}
}
function mainLoop(now) {
requestAnimationFrame(mainLoop);
const dt = Math.min(0.08, (now - lastTime) / 1000.0);
lastTime = now;
// Monitor FPS and adapt resolution if needed
frameTimes.push(dt);
if (frameTimes.length > 60) {
frameTimes.shift();
const avgDt = frameTimes.reduce((a, b) => a + b) / frameTimes.length;
window.PATROL.fps = Math.round(1.0 / avgDt);
// Quality bar: automatically drop resolution if slow on integrated GPU
if (window.PATROL.fps < 45 && window.PATROL.internalHeight > 240) {
window.PATROL.internalHeight = 260;
resizeCanvases();
}
}
resizeCanvases();
if (window.PATROL.ready) {
updateFlight(dt);
updateCamera(dt);
renderWorld(now * 0.001);
renderAircraft();
renderCockpit(dt);
}
}
window.addEventListener('resize', resizeCanvases);
resizeCanvases();
requestAnimationFrame(mainLoop);
// Automation helpers for headless testing
window.PATROL_API = {
setCamera: (mode) => {
camera.mode = camera.targetMode = mode;
camera.blendProgress = 1.0;
window.PATROL.viewMode = mode;
},
fire: () => fireMissile(),
setSound: (on) => {
if (window.PATROL.soundEnabled !== on) toggleSound();
},
getStats: () => ({
ready: window.PATROL.ready,
fps: window.PATROL.fps,
viewMode: window.PATROL.viewMode,
jetPos: jet.pos,
speed: jet.speed,
missilesReady: window.PATROL.missilesReady,
totalFired: window.PATROL.totalMissilesFired,
totalExplosions: window.PATROL.totalExplosions,
errors: window.PATROL.errors
})
};
</script>
</body>
</html>