Open full screen ↗
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Stormwall</title>
<link rel="stylesheet" href="/src/style.css" />
</head>
<body>
<canvas id="gl"></canvas>
<canvas id="hud"></canvas>
<div id="title" class="overlay">
<div class="panel">
<div class="kicker">OPERATION</div>
<h1>STORMWALL</h1>
<div class="brief">
Enemy fighters are hiding inside a storm front over the Halden range.
Fly into the cloud deck, find them, and destroy every hostile.
Expect a bomber strike on Halden Air Base. Stop it.
</div>
<table class="controls">
<tr><td>Pitch / Roll</td><td>Arrow keys</td><td>Left stick</td></tr>
<tr><td>Yaw</td><td>A / D</td><td>LB / RB</td></tr>
<tr><td>Throttle / Brake</td><td>W / S</td><td>RT / LT</td></tr>
<tr><td>Missile</td><td>Space</td><td>A</td></tr>
<tr><td>Gun</td><td>Shift (hold)</td><td>X</td></tr>
<tr><td>Switch target</td><td>Q</td><td>Y</td></tr>
<tr><td>Look at target</td><td>E (hold)</td><td>B (hold)</td></tr>
<tr><td>Invert pitch / Mute / Pause</td><td>I / M / P</td><td>Start</td></tr>
</table>
<div id="loading" class="loading">GENERATING WEATHER…</div>
<div id="startPrompt" class="start hidden">PRESS ENTER TO SORTIE</div>
</div>
</div>
<div id="pause" class="overlay hidden">
<div class="panel small"><h2>PAUSED</h2><div class="start">P TO RESUME</div></div>
</div>
<div id="result" class="overlay hidden">
<div class="panel small">
<h2 id="resultTitle">MISSION ACCOMPLISHED</h2>
<div id="resultStats" class="stats"></div>
<div class="start">PRESS R TO RETRY</div>
</div>
</div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
import * as THREE from 'three';
import { instantiate } from './models.js';
const FLAME_VERT = /* glsl */ `
varying vec2 vUv;
void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }
`;
const FLAME_FRAG = /* glsl */ `
uniform float uTime;
uniform float uPower;
varying vec2 vUv;
void main() {
float t = vUv.y;
float flick = 0.75 + 0.25 * sin(uTime * 70.0 + t * 24.0) * sin(uTime * 43.0);
float a = pow(1.0 - t, 1.5) * flick * uPower;
vec3 c = mix(vec3(1.0, 0.45, 0.15), vec3(0.55, 0.7, 1.0), pow(1.0 - t, 3.0)) * 5.0;
gl_FragColor = vec4(c * a, a);
}
`;
function makeFlame(uniforms, radius, length) {
const g = new THREE.ConeGeometry(radius, length, 14, 1, true);
g.rotateX(Math.PI / 2);
g.translate(0, 0, length / 2);
const m = new THREE.Mesh(g, new THREE.ShaderMaterial({
uniforms,
vertexShader: FLAME_VERT,
fragmentShader: FLAME_FRAG,
transparent: true,
depthWrite: false,
blending: THREE.AdditiveBlending,
side: THREE.DoubleSide,
}));
m.frustumCulled = false;
return m;
}
// Linear paint baked into each model's base-colour texture; variant colours are applied relative to it.
const FIGHTER_PAINT = [0.105, 0.112, 0.122];
const BOMBER_PAINT = [0.135, 0.142, 0.15];
const MISSILE_PAINT = [0.62, 0.63, 0.64];
const tintFor = (hex, paint) => new THREE.Color(hex).multiply(new THREE.Color(1 / paint[0], 1 / paint[1], 1 / paint[2]));
function uniqueNozzles(markers) {
const out = [];
for (const [name, p] of Object.entries(markers)) {
if (name.startsWith('nozzle') && !out.some((q) => q.distanceToSquared(p) < 0.01)) out.push(p.clone());
}
return out;
}
function addFlames(g, nozzles, power, radius, length) {
const flameUniforms = { uTime: { value: 0 }, uPower: { value: power } };
const flames = nozzles.map((p) => {
const f = makeFlame(flameUniforms, radius, length);
f.position.copy(p);
g.add(f);
return f;
});
return { flameUniforms, flames };
}
export function buildMissile(color = null) {
const tints = color === null ? {} : { MissileBody: tintFor(color, MISSILE_PAINT) };
return instantiate('missile', tints).root;
}
export function buildFighter({ body = null, tail = null, withMissiles = false } = {}) {
const tints = {};
if (body !== null) tints.Body = tintFor(body, FIGHTER_PAINT);
if (tail !== null) tints.Tail = tintFor(tail, FIGHTER_PAINT);
else if (body !== null) tints.Tail = tints.Body;
const { root: g, markers } = instantiate('fighter', tints);
const nozzles = uniqueNozzles(markers);
const { flameUniforms, flames } = addFlames(g, nozzles, 0.5, 0.55, 7);
const pylons = [markers.pylon_L.clone(), markers.pylon_R.clone()];
const pylonMissiles = [];
if (withMissiles) {
for (const p of pylons) {
const m = buildMissile();
m.position.copy(p);
g.add(m);
pylonMissiles.push(m);
}
}
g.userData = {
flameUniforms,
flames,
wingtips: [markers.wingtip_L.clone(), markers.wingtip_R.clone()],
nozzles,
pylons,
pylonMissiles,
nose: markers.nose.clone(),
};
return g;
}
export function buildBomber({ body = null } = {}) {
const tints = {};
if (body !== null) tints.BomberBody = tints.BomberPod = tintFor(body, BOMBER_PAINT);
const { root: g, markers } = instantiate('bomber', tints);
const nozzles = uniqueNozzles(markers);
const { flameUniforms, flames } = addFlames(g, nozzles, 0.25, 0.55, 4);
g.userData = {
flameUniforms,
flames,
wingtips: [markers.wingtip_L.clone(), markers.wingtip_R.clone()],
nozzles,
pylons: [],
pylonMissiles: [],
nose: markers.nose.clone(),
};
return g;
}
// Procedural SFX. Everything is synthesised; no audio files.
export class AudioFX {
constructor() {
this.ctx = null;
this.muted = false;
this.beepT = 0;
this.alertT = 0;
}
init() {
if (this.ctx) {
this.ctx.resume();
return;
}
const AC = window.AudioContext || window.webkitAudioContext;
if (!AC) return;
const ctx = new AC();
this.ctx = ctx;
this.master = ctx.createGain();
this.master.gain.value = 0.55;
this.master.connect(ctx.destination);
const len = ctx.sampleRate * 2;
this.noise = ctx.createBuffer(1, len, ctx.sampleRate);
const d = this.noise.getChannelData(0);
for (let i = 0; i < len; i++) d[i] = Math.random() * 2 - 1;
this.engineGain = this.loopNoise('bandpass', 380, 0.6);
this.rumbleGain = this.loopNoise('lowpass', 140, 1);
this.windGain = this.loopNoise('highpass', 1400, 0.4);
this.gunGain = this.loopNoise('bandpass', 900, 1.5);
this.gunLfo = ctx.createOscillator();
this.gunLfo.type = 'square';
this.gunLfo.frequency.value = 18;
const lfoAmt = ctx.createGain();
lfoAmt.gain.value = 0.5;
this.gunLfo.connect(lfoAmt).connect(this.gunGain.gain);
this.gunLfo.start();
this.toneOsc = ctx.createOscillator();
this.toneOsc.type = 'sine';
this.toneGain = ctx.createGain();
this.toneGain.gain.value = 0;
this.toneOsc.connect(this.toneGain).connect(this.master);
this.toneOsc.start();
this.alertOsc = ctx.createOscillator();
this.alertOsc.type = 'square';
this.alertOsc.frequency.value = 2100;
this.alertGain = ctx.createGain();
this.alertGain.gain.value = 0;
this.alertOsc.connect(this.alertGain).connect(this.master);
this.alertOsc.start();
}
loopNoise(type, freq, q) {
const src = this.ctx.createBufferSource();
src.buffer = this.noise;
src.loop = true;
const f = this.ctx.createBiquadFilter();
f.type = type;
f.frequency.value = freq;
f.Q.value = q;
const g = this.ctx.createGain();
g.gain.value = 0;
src.connect(f).connect(g).connect(this.master);
src.start();
g.filter = f;
return g;
}
toggleMute() {
this.muted = !this.muted;
if (this.master) this.master.gain.value = this.muted ? 0 : 0.55;
}
set(param, v, tc = 0.05) {
param.setTargetAtTime(v, this.ctx.currentTime, tc);
}
update(dt, s) {
if (!this.ctx) return;
const thr = Math.max(0, s.throttle);
const on = s.alive ? 1 : 0;
this.set(this.engineGain.gain, on * (0.08 + thr * 0.12));
this.set(this.engineGain.filter.frequency, 300 + thr * 500 + s.speed);
this.set(this.rumbleGain.gain, on * (0.25 + thr * 0.35));
this.set(this.windGain.gain, on * (0.02 + s.inCloud * 0.18 + (s.speed / 400) * 0.03));
this.beepT += dt;
if (s.lockState === 'lock') {
this.toneOsc.frequency.value = 1500;
this.set(this.toneGain.gain, 0.06, 0.01);
} else if (s.lockState === 'seek') {
this.toneOsc.frequency.value = 1000;
this.set(this.toneGain.gain, this.beepT % 0.22 < 0.07 ? 0.05 : 0, 0.005);
} else {
this.set(this.toneGain.gain, 0, 0.01);
}
this.alertT += dt;
if (s.alertDist !== null && s.alive) {
const period = Math.max(0.08, Math.min(0.5, s.alertDist / 6000));
this.set(this.alertGain.gain, this.alertT % period < period * 0.5 ? 0.035 : 0, 0.004);
} else {
this.set(this.alertGain.gain, 0, 0.01);
}
}
gun(on) {
if (!this.ctx) return;
this.set(this.gunGain.gain, on ? 0.5 : 0, 0.02);
}
burst(type, f0, f1, dur, vol) {
if (!this.ctx || vol < 0.01) return;
const ctx = this.ctx, t = ctx.currentTime;
const src = ctx.createBufferSource();
src.buffer = this.noise;
const f = ctx.createBiquadFilter();
f.type = type;
f.frequency.setValueAtTime(f0, t);
f.frequency.exponentialRampToValueAtTime(f1, t + dur);
const g = ctx.createGain();
g.gain.setValueAtTime(vol, t);
g.gain.exponentialRampToValueAtTime(0.001, t + dur);
src.connect(f).connect(g).connect(this.master);
src.start(t, Math.random());
src.stop(t + dur + 0.05);
}
missileLaunch() {
this.burst('bandpass', 1400, 200, 1.4, 0.7);
}
explosion(dist) {
const vol = 1.2 / (1 + dist / 700);
this.burst('lowpass', 1500, 60, 2.2, vol);
}
hit() {
this.burst('lowpass', 600, 80, 0.6, 1.0);
}
}
import * as THREE from 'three';
import { clamp, damp } from './config.js';
const OFFSET = new THREE.Vector3(0, 5.5, 27);
const vA = new THREE.Vector3();
const vB = new THREE.Vector3();
const vUp = new THREE.Vector3();
const m4 = new THREE.Matrix4();
export class ChaseCamera {
constructor(camera) {
this.camera = camera;
this.smoothQuat = new THREE.Quaternion();
this.lookBlend = 0;
this.shake = 0;
this.orbit = 0;
this.fov = camera.fov;
}
snap(player) {
this.smoothQuat.copy(player.quat);
}
addShake(a) {
this.shake = Math.min(1.5, this.shake + a);
}
update(dt, player, target, mode, inCloud) {
const cam = this.camera;
if (mode === 'title') {
this.orbit += dt * 0.12;
vA.set(Math.sin(this.orbit) * 30, 6, Math.cos(this.orbit) * 30).applyQuaternion(player.quat).add(player.pos);
cam.position.copy(vA);
cam.up.set(0, 1, 0);
cam.lookAt(player.pos);
this.snap(player);
} else if (!player.alive) {
this.orbit += dt * 0.2;
vA.set(Math.sin(this.orbit) * 120, 50, Math.cos(this.orbit) * 120).add(player.pos);
cam.position.lerp(vA, damp(2, dt));
cam.up.set(0, 1, 0);
cam.lookAt(player.pos);
} else {
this.followPlayer(dt, player, target);
}
this.shake = Math.max(0, this.shake - dt * 1.8);
const s = this.shake * this.shake + (inCloud > 0.05 ? 0.04 * inCloud : 0) + Math.max(0, player.throttle) * 0.02;
if (s > 0) {
cam.position.x += (Math.random() - 0.5) * s;
cam.position.y += (Math.random() - 0.5) * s;
cam.position.z += (Math.random() - 0.5) * s;
}
const targetFov = clamp(66 + (player.speed - 230) * 0.045, 60, 80);
this.fov += (targetFov - this.fov) * damp(3, dt);
if (Math.abs(cam.fov - this.fov) > 0.01) {
cam.fov = this.fov;
cam.updateProjectionMatrix();
}
}
followPlayer(dt, player, target) {
const cam = this.camera;
this.smoothQuat.slerp(player.quat, damp(5, dt));
const wantLook = target && player.lookTarget ? 1 : 0;
this.lookBlend += (wantLook - this.lookBlend) * damp(6, dt);
const off = vA.copy(OFFSET);
off.z += clamp((player.speed - 230) * 0.02, -2, 4);
off.applyQuaternion(this.smoothQuat);
const chasePos = vB.copy(player.pos).add(off);
const chaseLook = new THREE.Vector3(0, 1.5, -40).applyQuaternion(this.smoothQuat).add(player.pos);
vUp.set(0, 1, 0).applyQuaternion(this.smoothQuat);
if (this.lookBlend > 0.01 && target) {
const dir = target.pos.clone().sub(player.pos).normalize();
const lookPos = player.pos.clone().addScaledVector(dir, -24).add(new THREE.Vector3(0, 6, 0));
chasePos.lerp(lookPos, this.lookBlend);
chaseLook.lerp(target.pos, this.lookBlend);
vUp.lerp(new THREE.Vector3(0, 1, 0), this.lookBlend).normalize();
}
cam.position.copy(chasePos);
m4.lookAt(chasePos, chaseLook, vUp);
cam.quaternion.setFromRotationMatrix(m4);
}
}
import * as THREE from 'three';
import { Perlin, makeWorley, worley3, mulberry32 } from './noise.js';
import { WORLD, QUALITY, clamp } from './config.js';
import { ATMOSPHERE } from './shaders/common.js';
export function makeCloudNoise() {
return { shape: makeShapeTexture(64), detail: makeDetailTexture(32) };
}
function make3D(data, n, format) {
const t = new THREE.Data3DTexture(data, n, n, n);
t.format = format;
t.type = THREE.UnsignedByteType;
t.minFilter = THREE.LinearFilter;
t.magFilter = THREE.LinearFilter;
t.wrapS = t.wrapT = t.wrapR = THREE.RepeatWrapping;
t.unpackAlignment = 1;
t.needsUpdate = true;
return t;
}
// R = Perlin-Worley, GBA = Worley FBM at rising frequencies (Nubis-style shape noise).
function makeShapeTexture(N) {
const rnd = mulberry32(1337);
const perlin = new Perlin(7);
const W4 = makeWorley(4, rnd), W8 = makeWorley(8, rnd), W16 = makeWorley(16, rnd), W32 = makeWorley(32, rnd);
const inv = (W, u, v, w) => 1 - Math.min(worley3(W, u, v, w), 1);
const data = new Uint8Array(N * N * N * 4);
let k = 0;
for (let z = 0; z < N; z++) {
for (let y = 0; y < N; y++) {
for (let x = 0; x < N; x++) {
const u = (x + 0.5) / N, v = (y + 0.5) / N, w = (z + 0.5) / N;
let pf = perlin.noise3(u * 4, v * 4, w * 4, 4)
+ 0.5 * perlin.noise3(u * 8, v * 8, w * 8, 8)
+ 0.25 * perlin.noise3(u * 16, v * 16, w * 16, 16);
pf = clamp(pf / 1.75 * 0.9 + 0.5, 0, 1);
const w4 = inv(W4, u, v, w), w8 = inv(W8, u, v, w), w16 = inv(W16, u, v, w), w32 = inv(W32, u, v, w);
const wf1 = w4 * 0.625 + w8 * 0.25 + w16 * 0.125;
const wf2 = w8 * 0.625 + w16 * 0.25 + w32 * 0.125;
const wf3 = w16 * 0.75 + w32 * 0.25;
const pw = clamp(wf1 + pf * (1 - wf1) - 0.15, 0, 1);
data[k++] = pw * 255;
data[k++] = wf1 * 255;
data[k++] = wf2 * 255;
data[k++] = wf3 * 255;
}
}
}
return make3D(data, N, THREE.RGBAFormat);
}
function makeDetailTexture(N) {
const rnd = mulberry32(4242);
const W4 = makeWorley(4, rnd), W8 = makeWorley(8, rnd), W16 = makeWorley(16, rnd);
const inv = (W, u, v, w) => 1 - Math.min(worley3(W, u, v, w), 1);
const data = new Uint8Array(N * N * N);
let k = 0;
for (let z = 0; z < N; z++) {
for (let y = 0; y < N; y++) {
for (let x = 0; x < N; x++) {
const u = (x + 0.5) / N, v = (y + 0.5) / N, w = (z + 0.5) / N;
data[k++] = (inv(W4, u, v, w) * 0.625 + inv(W8, u, v, w) * 0.25 + inv(W16, u, v, w) * 0.125) * 255;
}
}
}
return make3D(data, N, THREE.RedFormat);
}
const FS_VERT = /* glsl */ `
varying vec2 vUv;
void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }
`;
const CLOUD_FRAG = /* glsl */ `
precision highp float;
precision highp sampler3D;
uniform sampler2D tDepth;
uniform sampler3D tShape;
uniform sampler3D tDetail;
uniform sampler2D tWeather;
uniform mat4 uInvProj;
uniform mat4 uCamWorld;
uniform vec3 uCamPos;
uniform float uTime;
uniform float uBottom;
uniform float uTop;
uniform float uWeatherSize;
uniform float uSigma;
uniform float uSunIntensity;
uniform float uAmbient;
uniform float uMaxDist;
varying vec2 vUv;
${ATMOSPHERE}
float remap(float v, float l0, float h0, float l1, float h1) {
return l1 + (v - l0) * (h1 - l1) / (h0 - l0);
}
float hgPhase(float c, float g) {
float g2 = g * g;
return (1.0 - g2) / (12.566371 * pow(1.0 + g2 - 2.0 * g * c, 1.5));
}
float cloudBase(vec3 p, out float hf) {
vec4 w = texture(tWeather, p.xz / uWeatherSize);
float cov = w.r;
float top = uBottom + (uTop - uBottom) * mix(0.45, 1.0, w.g);
hf = (p.y - uBottom) / (top - uBottom);
if (cov < 0.03 || hf < 0.0 || hf > 1.0) return 0.0;
float hgrad = smoothstep(0.0, 0.12, hf) * (1.0 - smoothstep(0.45, 1.0, hf));
vec4 s = texture(tShape, (p + vec3(uTime * 6.0, 0.0, uTime * 2.5)) / 7000.0);
float fbm = s.g * 0.625 + s.b * 0.25 + s.a * 0.125;
float base = remap(s.r, fbm - 1.0, 1.0, 0.0, 1.0);
base = remap(base * hgrad, 1.0 - cov, 1.0, 0.0, 1.0) * cov;
return clamp(base, 0.0, 1.0);
}
float cloudDetail(vec3 p, float base, float hf) {
float d = texture(tDetail, (p + vec3(uTime * 12.0, -uTime * 3.0, uTime * 5.0)) / 1100.0).r;
float m = mix(d, 1.0 - d, clamp(hf * 4.0, 0.0, 1.0));
return clamp(remap(base, m * 0.4, 1.0, 0.0, 1.0), 0.0, 1.0);
}
float lightMarch(vec3 p) {
float od = 0.0;
float st = 55.0;
float hf;
vec3 q = p;
for (int i = 0; i < LIGHT_STEPS; i++) {
q += uSunDir * st;
float b = cloudBase(q, hf);
if (b > 0.0) od += (i < 2 ? cloudDetail(q, b, hf) : b) * st;
st *= 1.75;
}
return od;
}
// Multiple-scattering approximation (octaves with reduced extinction and anisotropy).
vec3 sunScatter(float od, float cosT) {
float a = 1.0, b = 1.0, c = 1.0;
float s = 0.0;
for (int o = 0; o < 3; o++) {
float ph = mix(hgPhase(cosT, 0.75 * c), hgPhase(cosT, -0.25 * c), 0.3);
s += b * ph * exp(-uSigma * od * a);
a *= 0.25; b *= 0.55; c *= 0.5;
}
return uSunColor * uSunIntensity * s;
}
void main() {
float depth = texture(tDepth, vUv).r;
vec4 vp = uInvProj * vec4(vUv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);
vp.xyz /= vp.w;
vec3 wp = (uCamWorld * vec4(vp.xyz, 1.0)).xyz;
vec3 ro = uCamPos;
vec3 rd = normalize(wp - ro);
float sceneDist = depth >= 0.999999 ? 1e9 : length(vp.xyz);
float tMin, tMax;
if (abs(rd.y) < 1e-5) {
tMin = 0.0;
tMax = (ro.y > uBottom && ro.y < uTop) ? uMaxDist : -1.0;
} else {
float t0 = (uBottom - ro.y) / rd.y;
float t1 = (uTop - ro.y) / rd.y;
tMin = max(min(t0, t1), 0.0);
tMax = max(t0, t1);
}
tMax = min(tMax, min(sceneDist, uMaxDist));
if (tMax <= tMin) { gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); return; }
float jitter = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
float cosT = dot(rd, uSunDir);
vec3 L = vec3(0.0);
float T = 1.0;
float wd = 0.0, ws = 0.0;
float t = tMin + clamp(tMin * 0.03, 30.0, 900.0) * jitter;
for (int i = 0; i < CLOUD_STEPS; i++) {
if (t >= tMax || T < 0.01) break;
float dt = clamp(t * 0.03, 30.0, 900.0);
vec3 p = ro + rd * t;
float hf;
float b = cloudBase(p, hf);
if (b > 0.0) {
float d = cloudDetail(p, b, hf);
if (d > 0.003) {
float sigE = d * uSigma;
float od = lightMarch(p);
float powder = 1.0 - 0.6 * exp(-sigE * 120.0);
vec3 sun = sunScatter(od, cosT) * powder;
vec3 amb = mix(vec3(0.20, 0.24, 0.31), vec3(0.62, 0.72, 0.88), hf) * uAmbient;
float Ts = exp(-sigE * dt);
float a = T * (1.0 - Ts);
L += (sun + amb) * a;
wd += a * t;
ws += a;
T *= Ts;
}
t += dt;
} else {
t += dt * 1.8;
}
}
float ad = ws > 0.0 ? wd / ws : tMax;
L = mix(L, fogColor(rd) * (1.0 - T), heightFog(ro, rd, ad));
gl_FragColor = vec4(L, T);
}
`;
export function makeCloudMaterial(noise, weather, uniforms) {
return new THREE.ShaderMaterial({
defines: { CLOUD_STEPS: QUALITY.cloudSteps, LIGHT_STEPS: QUALITY.lightSteps },
uniforms: {
uSunDir: uniforms.uSunDir,
uSunColor: uniforms.uSunColor,
uTime: uniforms.uTime,
tDepth: { value: null },
tShape: { value: noise.shape },
tDetail: { value: noise.detail },
tWeather: { value: weather.texture },
uInvProj: { value: new THREE.Matrix4() },
uCamWorld: { value: new THREE.Matrix4() },
uCamPos: { value: new THREE.Vector3() },
uBottom: { value: WORLD.cloudBottom },
uTop: { value: WORLD.cloudTop },
uWeatherSize: { value: WORLD.weatherSize },
uSigma: { value: 0.03 },
uSunIntensity: { value: 22 },
uAmbient: { value: 1.0 },
uMaxDist: { value: 32000 },
},
vertexShader: FS_VERT,
fragmentShader: CLOUD_FRAG,
depthTest: false,
depthWrite: false,
});
}
export { FS_VERT };
import * as THREE from 'three';
export const WORLD = {
terrainSize: 48000,
terrainSegments: 768,
seaLevel: 25,
areaRadius: 16000,
cloudBottom: 1300,
cloudTop: 3900,
weatherSize: 36000,
weatherRes: 256,
};
export const BASE_POS = new THREE.Vector3(-9000, 70, 7000);
export const SUN_DIR = new THREE.Vector3(-0.55, 0.38, -0.74).normalize();
export const SUN_COLOR = new THREE.Color(1.0, 0.88, 0.74);
const q = new URLSearchParams(location.search).get('q') || 'high';
const PRESETS = {
low: { cloudScale: 0.4, cloudSteps: 72, lightSteps: 4, pixelRatio: 1 },
high: { cloudScale: 0.5, cloudSteps: 110, lightSteps: 6, pixelRatio: Math.min(window.devicePixelRatio, 1.5) },
ultra: { cloudScale: 0.75, cloudSteps: 140, lightSteps: 6, pixelRatio: Math.min(window.devicePixelRatio, 2) },
};
export const QUALITY = PRESETS[q] || PRESETS.high;
export const clamp = (v, a, b) => Math.min(Math.max(v, a), b);
export const lerp = (a, b, t) => a + (b - a) * t;
export const smoothstep = (a, b, x) => {
const t = clamp((x - a) / (b - a), 0, 1);
return t * t * (3 - 2 * t);
};
export const damp = (k, dt) => 1 - Math.exp(-k * dt);
import * as THREE from 'three';
import { buildFighter, buildBomber } from './aircraft.js';
import { WORLD, BASE_POS, clamp, damp, smoothstep } from './config.js';
export const TYPES = {
fighter: { hp: 100, speed: 215, maxSpeed: 300, pitchRate: 0.95, rollRate: 2.4, hitRadius: 14, score: 100, label: 'FTR', fireCd: [10, 16], range: 2600 },
ace: { hp: 190, speed: 240, maxSpeed: 340, pitchRate: 1.3, rollRate: 3.0, hitRadius: 14, score: 500, label: 'ACE', fireCd: [5, 8], range: 3000 },
bomber: { hp: 280, speed: 165, maxSpeed: 180, pitchRate: 0.3, rollRate: 0.7, hitRadius: 32, score: 300, label: 'BMR', fireCd: null, range: 0 },
};
const AX = new THREE.Vector3(1, 0, 0);
const AY = new THREE.Vector3(0, 1, 0);
const AZ = new THREE.Vector3(0, 0, 1);
const UP = new THREE.Vector3(0, 1, 0);
const qTmp = new THREE.Quaternion();
const qInv = new THREE.Quaternion();
const vL = new THREE.Vector3();
const vU = new THREE.Vector3();
const vD = new THREE.Vector3();
const vT = new THREE.Vector3();
const rnd = (a, b) => a + Math.random() * (b - a);
// Bank-to-turn: roll so the goal sits above the canopy, then pull.
export function steer(ac, dir, dt, pitchRate, rollRate) {
qInv.copy(ac.quat).invert();
vL.copy(dir).applyQuaternion(qInv);
const off = Math.acos(clamp(-vL.z, -1, 1));
vU.copy(UP).applyQuaternion(qInv);
const levelErr = Math.atan2(vU.x, vU.y);
const goalErr = Math.atan2(vL.x, vL.y);
const w = smoothstep(0.04, 0.25, off);
const rollErr = levelErr * (1 - w) + goalErr * w;
const rollCmd = clamp(rollErr * 2.5, -1, 1);
const pitchCmd = clamp(Math.atan2(vL.y, -vL.z) * 3, -0.35, 1);
const yawCmd = clamp(vL.x * 2, -1, 1) * 0.3;
ac.rates.p += (pitchCmd * pitchRate - ac.rates.p) * damp(4, dt);
ac.rates.r += (rollCmd * rollRate - ac.rates.r) * damp(5, dt);
ac.quat.multiply(qTmp.setFromAxisAngle(AX, ac.rates.p * dt));
ac.quat.multiply(qTmp.setFromAxisAngle(AZ, -ac.rates.r * dt));
ac.quat.multiply(qTmp.setFromAxisAngle(AY, -yawCmd * 0.3 * dt));
ac.quat.normalize();
}
class Enemy {
constructor(type, name, mesh) {
this.type = type;
this.def = TYPES[type];
this.name = name;
this.mesh = mesh;
this.pos = new THREE.Vector3();
this.quat = new THREE.Quaternion();
this.vel = new THREE.Vector3();
this.forward = new THREE.Vector3(0, 0, -1);
this.rates = { p: 0, r: 0 };
this.hp = this.def.hp;
this.speed = this.def.speed;
this.alive = true;
this.falling = false;
this.fallTime = 0;
this.state = 'engage';
this.stateTime = 0;
this.fireCd = this.def.fireCd ? rnd(...this.def.fireCd) : Infinity;
this.jinkPhase = Math.random() * 10;
this.hitRadius = this.def.hitRadius;
this.escortOf = null;
this.escortOffset = new THREE.Vector3();
this.goal = new THREE.Vector3();
}
}
export class EnemyManager {
constructor(game) {
this.game = game;
this.list = [];
}
clear() {
for (const e of this.list) this.game.scene.remove(e.mesh);
this.list.length = 0;
}
get alive() {
return this.list.filter((e) => e.alive);
}
spawn(type, name, pos, heading) {
let mesh;
if (type === 'bomber') mesh = buildBomber();
else if (type === 'ace') mesh = buildFighter({ body: 0x2a2d33, tail: 0xc9a227 });
else mesh = buildFighter({ body: 0x6b7064, tail: 0x8a2a22 });
const e = new Enemy(type, name, mesh);
e.pos.copy(pos);
e.quat.setFromAxisAngle(AY, heading);
this.game.scene.add(mesh);
this.list.push(e);
return e;
}
update(dt, time) {
for (let i = this.list.length - 1; i >= 0; i--) {
const e = this.list[i];
if (e.alive) this.think(e, dt);
else if (e.falling) this.fall(e, dt);
if (!e.alive && !e.falling) {
this.game.scene.remove(e.mesh);
this.list.splice(i, 1);
continue;
}
e.forward.set(0, 0, -1).applyQuaternion(e.quat);
e.vel.copy(e.forward).multiplyScalar(e.speed);
if (e.falling) e.vel.y -= e.fallTime * 25;
e.pos.addScaledVector(e.vel, dt);
e.mesh.position.copy(e.pos);
e.mesh.quaternion.copy(e.quat);
const u = e.mesh.userData;
u.flameUniforms.uTime.value = time;
u.flameUniforms.uPower.value = e.falling ? 0 : 0.3 + (e.speed / e.def.maxSpeed) * 0.5;
if (e.alive && e.hp < e.def.hp * 0.5) {
this.game.fx.damageSmoke(vT.copy(u.nozzles[0]).applyQuaternion(e.quat).add(e.pos), e.vel);
}
}
}
think(e, dt) {
const g = this.game;
const p = g.player;
e.stateTime += dt;
const toP = vD.copy(p.pos).sub(e.pos);
const dist = toP.length();
const desired = new THREE.Vector3();
let targetSpeed = e.def.speed;
if (e.type === 'bomber') {
desired.copy(e.goal).sub(e.pos);
desired.y = (2600 - e.pos.y) * 2;
desired.normalize();
desired.x += Math.sin(g.time * 0.2 + e.jinkPhase) * 0.05;
} else {
const threat = g.weapons.incomingFor(e);
if (e.state === 'escort' && (dist < 4500 || !e.escortOf?.alive || threat)) e.state = 'engage';
if (threat && e.state !== 'evade' && threat.pos.distanceTo(e.pos) < 2200 && Math.random() < dt * 3) {
e.state = 'evade';
e.stateTime = 0;
const side = Math.random() < 0.5 ? -1 : 1;
e.evadeDir = new THREE.Vector3().crossVectors(threat.dir, UP).multiplyScalar(side).normalize();
e.evadeDir.y = rnd(-0.3, 0.4);
}
if (e.state === 'evade') {
desired.copy(e.evadeDir).normalize();
targetSpeed = e.def.maxSpeed;
if (e.stateTime > 3.5) e.state = 'engage';
} else if (e.state === 'extend') {
desired.copy(e.extendDir);
targetSpeed = e.def.maxSpeed;
if (e.stateTime > 4) e.state = 'engage';
} else if (e.state === 'escort') {
desired.copy(e.escortOffset).applyQuaternion(e.escortOf.quat).add(e.escortOf.pos).sub(e.pos);
const d = desired.length();
desired.normalize();
targetSpeed = e.escortOf.speed + clamp(d * 0.2, -40, 80);
} else {
this.engage(e, dist, desired);
targetSpeed = dist > 3000 ? e.def.maxSpeed : e.def.speed;
}
this.tryFire(e, dist, toP, dt);
}
this.avoid(e, desired);
steer(e, desired, dt, e.def.pitchRate, e.def.rollRate);
e.speed += (targetSpeed - e.speed) * damp(0.6, dt);
}
engage(e, dist, desired) {
const p = this.game.player;
const lead = clamp(dist / 700, 0, 2.5);
desired.copy(p.pos).addScaledVector(p.vel, lead).sub(e.pos).normalize();
// Weave when the player sits on their tail.
const behind = vT.copy(e.pos).sub(p.pos).normalize().dot(p.forward);
if (behind > 0.85 && dist < 2500) {
e.jinkPhase += 0.016;
const lateral = new THREE.Vector3().crossVectors(e.forward, UP).normalize();
desired.copy(e.forward).addScaledVector(lateral, Math.sin(e.jinkPhase * 1.7) * 0.9);
desired.y += Math.cos(e.jinkPhase * 1.1) * 0.4;
desired.normalize();
}
if (dist < 350 && p.alive) {
e.state = 'extend';
e.stateTime = 0;
e.extendDir = e.forward.clone().add(new THREE.Vector3(rnd(-0.5, 0.5), rnd(-0.1, 0.3), rnd(-0.5, 0.5))).normalize();
}
}
tryFire(e, dist, toP, dt) {
const p = this.game.player;
e.fireCd -= dt;
if (!p.alive || e.fireCd > 0 || dist > e.def.range || dist < 500) return;
const ang = e.forward.angleTo(toP);
if (ang < 0.35) {
this.game.weapons.launchEnemyMissile(e, p);
e.fireCd = rnd(...e.def.fireCd);
}
}
avoid(e, desired) {
const g = this.game;
vT.copy(e.pos).addScaledVector(e.forward, 1800);
const ground = Math.max(g.terrain.floorAt(vT.x, vT.z), g.terrain.floorAt(e.pos.x, e.pos.z));
const agl = e.pos.y - ground;
if (agl < 600) desired.y += (600 - agl) / 150;
if (e.pos.y > 7000) desired.y -= 0.5;
const r = Math.hypot(e.pos.x, e.pos.z);
if (r > WORLD.areaRadius * 1.05) {
desired.x -= (e.pos.x / r) * 1.5;
desired.z -= (e.pos.z / r) * 1.5;
}
desired.normalize();
}
fall(e, dt) {
e.fallTime += dt;
e.rates.r += dt * 2;
e.quat.multiply(qTmp.setFromAxisAngle(AZ, e.rates.r * dt));
e.quat.multiply(qTmp.setFromAxisAngle(AX, -0.3 * dt));
this.game.fx.burning(e.pos, e.vel);
const floor = this.game.terrain.floorAt(e.pos.x, e.pos.z);
if (e.pos.y < floor + 5 || e.fallTime > 4) {
this.game.fx.explosion(e.pos, vT.set(0, 0, 0), e.type === 'bomber' ? 1.8 : 1);
this.game.audio.explosion(e.pos.distanceTo(this.game.camera.position));
e.falling = false;
}
}
damage(e, amount, byPlayer) {
if (!e.alive) return false;
e.hp -= amount;
if (e.hp > 0) return false;
e.alive = false;
e.falling = true;
e.fallTime = 0;
e.rates.r = Math.random() < 0.5 ? -1 : 1;
this.game.fx.explosion(e.pos, e.vel, e.type === 'bomber' ? 1.4 : 0.8);
this.game.audio.explosion(e.pos.distanceTo(this.game.camera.position));
if (byPlayer) this.game.mission.onKill(e);
return true;
}
distanceToBase(e) {
return Math.hypot(e.pos.x - BASE_POS.x, e.pos.z - BASE_POS.z);
}
}
import * as THREE from 'three';
import { WORLD, BASE_POS, clamp } from './config.js';
import { SEEKER_ANGLE } from './weapons.js';
const COLORS = {
green: 'rgba(140,255,170,0.95)',
dim: 'rgba(140,255,170,0.5)',
red: 'rgba(255,72,60,0.98)',
amber: 'rgba(255,200,80,0.98)',
blue: 'rgba(120,200,255,0.95)',
};
const FONT = 'Menlo, Consolas, monospace';
const RADAR_RANGE = 9000;
const vP = new THREE.Vector3();
const vD = new THREE.Vector3();
const qInv = new THREE.Quaternion();
export class HUD {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.msg = null;
this.blink = 0;
}
resize() {
const dpr = Math.min(window.devicePixelRatio, 2);
this.w = window.innerWidth;
this.h = window.innerHeight;
this.canvas.width = this.w * dpr;
this.canvas.height = this.h * dpr;
this.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
message(text, color = 'green', dur = 1.6) {
this.msg = { text, color: COLORS[color], t: 0, dur };
}
project(v, camera) {
vP.copy(v).project(camera);
return {
x: (vP.x * 0.5 + 0.5) * this.w,
y: (-vP.y * 0.5 + 0.5) * this.h,
behind: vP.z > 1,
};
}
font(px, weight = '') {
this.ctx.font = `${weight} ${px}px ${FONT}`;
}
text(s, x, y, color = COLORS.green, align = 'left', px = 13) {
const c = this.ctx;
this.font(px);
c.textAlign = align;
c.fillStyle = color;
c.fillText(s, x, y);
}
line(x0, y0, x1, y1) {
const c = this.ctx;
c.beginPath();
c.moveTo(x0, y0);
c.lineTo(x1, y1);
c.stroke();
}
clear() {
this.ctx.clearRect(0, 0, this.w, this.h);
}
draw(game, dt) {
const c = this.ctx;
this.clear();
this.blink += dt;
if (game.state !== 'playing' && game.state !== 'ended') return;
const p = game.player;
const cam = game.camera;
c.save();
c.lineWidth = 1.5;
c.strokeStyle = COLORS.green;
c.shadowColor = 'rgba(0,0,0,0.75)';
c.shadowBlur = 3;
if (p.alive) {
this.drawLadder(p, cam);
this.drawCenter(p, cam);
this.drawTapes(p, game);
this.drawHeading(p);
this.drawTargets(game);
}
this.drawRadar(game);
this.drawWeapons(game);
this.drawStatus(game);
this.drawWarnings(game);
this.drawRadio(game);
this.drawMessage(dt);
c.restore();
if (game.alert && p.alive) this.drawAlertEdge();
}
hdir(p) {
const h = new THREE.Vector3(p.forward.x, 0, p.forward.z);
if (h.lengthSq() < 1e-4) h.set(-p.up.x, 0, -p.up.z);
return h.normalize();
}
drawLadder(p, cam) {
const c = this.ctx;
const cx = this.w / 2, cy = this.h / 2;
const hd = this.hdir(p);
const right = new THREE.Vector3().crossVectors(hd, new THREE.Vector3(0, 1, 0)).normalize();
const pitchDeg = (Math.asin(clamp(p.forward.y, -1, 1)) * 180) / Math.PI;
c.save();
c.beginPath();
c.rect(cx - 260, cy - 210, 520, 420);
c.clip();
c.lineWidth = 1.2;
const start = Math.ceil((pitchDeg - 30) / 5) * 5;
for (let a = start; a <= pitchDeg + 30; a += 5) {
if (Math.abs(a) > 85) continue;
const r = (a * Math.PI) / 180;
const dir = hd.clone().multiplyScalar(Math.cos(r)).add(new THREE.Vector3(0, Math.sin(r), 0));
const center = cam.position.clone().addScaledVector(dir, 1000);
const half = a === 0 ? 260 : 110;
const gap = a === 0 ? 50 : 40;
const L0 = this.project(center.clone().addScaledVector(right, -half), cam);
const L1 = this.project(center.clone().addScaledVector(right, -gap), cam);
const R0 = this.project(center.clone().addScaledVector(right, gap), cam);
const R1 = this.project(center.clone().addScaledVector(right, half), cam);
if (L0.behind || R1.behind) continue;
c.strokeStyle = a === 0 ? COLORS.green : COLORS.dim;
c.setLineDash(a < 0 ? [8, 6] : []);
this.line(L0.x, L0.y, L1.x, L1.y);
this.line(R0.x, R0.y, R1.x, R1.y);
c.setLineDash([]);
if (a !== 0) {
const tick = a > 0 ? 8 : -8;
const ang = Math.atan2(R1.y - L0.y, R1.x - L0.x);
const tx = -Math.sin(ang) * tick, ty = Math.cos(ang) * tick;
this.line(L0.x, L0.y, L0.x + tx, L0.y + ty);
this.line(R1.x, R1.y, R1.x + tx, R1.y + ty);
this.text(String(Math.abs(a)), R1.x + 6, R1.y + 4, COLORS.dim, 'left', 11);
}
}
c.restore();
}
drawCenter(p, cam) {
const c = this.ctx;
const bore = this.project(p.pos.clone().addScaledVector(p.forward, 1500), cam);
if (!bore.behind) {
const { x, y } = bore;
c.beginPath();
c.moveTo(x - 18, y - 4); c.lineTo(x - 9, y + 6); c.lineTo(x, y - 2);
c.lineTo(x + 9, y + 6); c.lineTo(x + 18, y - 4);
c.stroke();
}
const fpm = this.project(p.pos.clone().addScaledVector(p.vel, 6), cam);
if (!fpm.behind) {
const { x, y } = fpm;
c.beginPath();
c.arc(x, y, 6, 0, Math.PI * 2);
c.stroke();
this.line(x - 16, y, x - 6, y);
this.line(x + 6, y, x + 16, y);
this.line(x, y - 6, x, y - 12);
}
}
drawTapes(p, game) {
const c = this.ctx;
const cx = this.w / 2, cy = this.h / 2;
const spd = p.speed * 3.6;
const alt = p.pos.y * 3.281;
const sx = cx - 250, ax = cx + 250;
c.save();
c.beginPath();
c.rect(sx - 90, cy - 120, 100, 240);
c.rect(ax - 10, cy - 120, 100, 240);
c.clip();
c.strokeStyle = COLORS.dim;
for (let v = Math.floor((spd - 200) / 20) * 20; v < spd + 200; v += 20) {
const y = cy - (v - spd) * 0.55;
this.line(sx, y, sx - (v % 100 === 0 ? 14 : 7), y);
if (v % 100 === 0) this.text(String(v), sx - 18, y + 4, COLORS.dim, 'right', 10);
}
for (let v = Math.floor((alt - 2000) / 100) * 100; v < alt + 2000; v += 100) {
const y = cy - (v - alt) * 0.055;
this.line(ax, y, ax + (v % 500 === 0 ? 14 : 7), y);
if (v % 500 === 0) this.text(String(v), ax + 18, y + 4, COLORS.dim, 'left', 10);
}
c.restore();
c.fillStyle = 'rgba(0,20,8,0.55)';
c.fillRect(sx - 78, cy - 13, 74, 26);
c.fillRect(ax + 4, cy - 13, 84, 26);
c.strokeRect(sx - 78, cy - 13, 74, 26);
c.strokeRect(ax + 4, cy - 13, 84, 26);
this.font(17);
this.text(String(Math.round(spd)), sx - 10, cy + 6, COLORS.green, 'right', 17);
this.text(String(Math.round(alt)), ax + 82, cy + 6, COLORS.green, 'right', 17);
this.text('SPEED', sx - 78, cy - 20, COLORS.dim, 'left', 11);
this.text('ALT', ax + 4, cy - 20, COLORS.dim, 'left', 11);
const g = p.gLoad;
this.text(`G ${g.toFixed(1)}`, sx - 78, cy + 34, Math.abs(g) > 7 ? COLORS.amber : COLORS.dim, 'left', 12);
const thr = p.throttle;
let thrLabel = 'MIL';
if (thr > 0.4) thrLabel = 'AB';
else if (thr < -0.4) thrLabel = 'BRK';
this.text(thrLabel, sx - 78, cy + 50, thr > 0.4 ? COLORS.amber : COLORS.dim, 'left', 12);
const agl = p.pos.y - game.terrain.floorAt(p.pos.x, p.pos.z);
this.text(`R ${Math.round(agl * 3.281)}`, ax + 4, cy + 34, agl < 300 ? COLORS.amber : COLORS.dim, 'left', 12);
}
drawHeading(p) {
const c = this.ctx;
const cx = this.w / 2, y = 46;
const hd = this.hdir(p);
const hdg = ((Math.atan2(hd.x, -hd.z) * 180) / Math.PI + 360) % 360;
c.save();
c.beginPath();
c.rect(cx - 180, y - 24, 360, 40);
c.clip();
c.strokeStyle = COLORS.dim;
for (let a = Math.floor((hdg - 40) / 5) * 5; a <= hdg + 40; a += 5) {
const x = cx + (a - hdg) * 4.5;
const major = a % 10 === 0;
this.line(x, y, x, y + (major ? 10 : 5));
if (a % 30 === 0) {
const n = ((a % 360) + 360) % 360;
const lbl = { 0: 'N', 90: 'E', 180: 'S', 270: 'W' }[n] ?? String(n / 10).padStart(2, '0');
this.text(lbl, x, y - 4, COLORS.dim, 'center', 11);
}
}
c.restore();
this.text(String(Math.round(hdg) % 360).padStart(3, '0'), cx, y + 28, COLORS.green, 'center', 14);
c.beginPath();
c.moveTo(cx - 5, y + 14); c.lineTo(cx, y + 8); c.lineTo(cx + 5, y + 14);
c.stroke();
}
drawTargets(game) {
const c = this.ctx;
const cam = game.camera;
const p = game.player;
const w = game.weapons;
const cx = this.w / 2, cy = this.h / 2;
const fovR = THREE.MathUtils.degToRad(cam.fov) / 2;
const seekR = (Math.tan(SEEKER_ANGLE) / Math.tan(fovR)) * (this.h / 2);
const tgt = w.target;
if (tgt) {
c.strokeStyle = w.lockState === 'none' ? COLORS.dim : COLORS.green;
c.setLineDash([3, 7]);
c.beginPath();
c.arc(cx, cy, seekR, 0, Math.PI * 2);
c.stroke();
c.setLineDash([]);
}
for (const e of game.enemies.list) {
if (!e.alive) continue;
const s = this.project(e.pos, cam);
const d = e.pos.distanceTo(p.pos);
const isT = e === tgt;
const onScreen = !s.behind && s.x > 0 && s.x < this.w && s.y > 0 && s.y < this.h;
if (!onScreen) continue;
const locked = isT && w.locked;
let col = COLORS.green;
if (locked) col = COLORS.red;
else if (e.type === 'ace') col = COLORS.amber;
c.strokeStyle = col;
const r = isT ? 14 : 9;
c.strokeRect(s.x - r, s.y - r, r * 2, r * 2);
if (isT) {
const k = r + 6;
c.beginPath();
c.moveTo(s.x - k, s.y - k + 6); c.lineTo(s.x - k, s.y - k); c.lineTo(s.x - k + 6, s.y - k);
c.moveTo(s.x + k - 6, s.y - k); c.lineTo(s.x + k, s.y - k); c.lineTo(s.x + k, s.y - k + 6);
c.moveTo(s.x - k, s.y + k - 6); c.lineTo(s.x - k, s.y + k); c.lineTo(s.x - k + 6, s.y + k);
c.moveTo(s.x + k - 6, s.y + k); c.lineTo(s.x + k, s.y + k); c.lineTo(s.x + k, s.y + k - 6);
c.stroke();
}
this.text(`${e.def.label}`, s.x + r + 4, s.y - 2, col, 'left', 11);
this.text(`${Math.round(d)}`, s.x + r + 4, s.y + 11, col, 'left', 11);
if (isT || e.type === 'ace') this.text(e.name, s.x, s.y - r - 8, col, 'center', 11);
if (locked) this.text('LOCK', s.x, s.y + r + 16, COLORS.red, 'center', 12);
}
if (!tgt) return;
const ts = this.project(tgt.pos, cam);
const onScreen = !ts.behind && ts.x > 0 && ts.x < this.w && ts.y > 0 && ts.y < this.h;
if (onScreen && w.lockProgress > 0) {
const k = w.lockProgress;
const x = cx + (ts.x - cx) * k, y = cy + (ts.y - cy) * k;
c.strokeStyle = w.locked ? COLORS.red : COLORS.green;
c.beginPath();
c.moveTo(x, y - 20); c.lineTo(x + 20, y); c.lineTo(x, y + 20); c.lineTo(x - 20, y); c.closePath();
c.stroke();
}
if (!onScreen) this.drawOffscreenArrow(tgt, cam, cx, cy, tgt.pos.distanceTo(p.pos));
}
drawOffscreenArrow(tgt, cam, cx, cy, dist) {
const c = this.ctx;
qInv.copy(cam.quaternion).invert();
vD.copy(tgt.pos).sub(cam.position).applyQuaternion(qInv);
const ang = Math.atan2(-vD.y, vD.x);
const R = Math.min(this.w, this.h) * 0.32;
const x = cx + Math.cos(ang) * R, y = cy + Math.sin(ang) * R;
c.save();
c.translate(x, y);
c.rotate(ang);
c.fillStyle = tgt.type === 'ace' ? COLORS.amber : COLORS.green;
c.beginPath();
c.moveTo(14, 0); c.lineTo(-6, -9); c.lineTo(-2, 0); c.lineTo(-6, 9); c.closePath();
c.fill();
c.restore();
this.text(`${Math.round(dist)}`, x, y + 22, COLORS.green, 'center', 11);
}
drawRadar(game) {
const c = this.ctx;
const p = game.player;
const R = 88, rx = 28 + R, ry = this.h - 28 - R;
const hd = this.hdir(p);
const fx = hd.x, fz = hd.z;
const toR = (x, z) => {
const dx = x - p.pos.x, dz = z - p.pos.z;
return [((dx * -fz + dz * fx) / RADAR_RANGE) * R, (-(dx * fx + dz * fz) / RADAR_RANGE) * R];
};
c.save();
c.fillStyle = 'rgba(0,25,10,0.45)';
c.beginPath();
c.arc(rx, ry, R, 0, Math.PI * 2);
c.fill();
c.strokeStyle = COLORS.dim;
c.stroke();
c.beginPath();
c.arc(rx, ry, R / 2, 0, Math.PI * 2);
c.stroke();
c.clip();
const [bx, by] = toR(0, 0);
c.strokeStyle = 'rgba(255,200,80,0.6)';
c.beginPath();
c.arc(rx + bx, ry + by, (WORLD.areaRadius / RADAR_RANGE) * R, 0, Math.PI * 2);
c.stroke();
const [hx, hy] = toR(BASE_POS.x, BASE_POS.z);
c.fillStyle = COLORS.blue;
c.fillRect(rx + hx - 4, ry + hy - 4, 8, 8);
for (const e of game.enemies.list) {
if (!e.alive) continue;
let [ex, ey] = toR(e.pos.x, e.pos.z);
const l = Math.hypot(ex, ey);
if (l > R - 4) { ex *= (R - 4) / l; ey *= (R - 4) / l; }
c.fillStyle = e.type === 'ace' ? COLORS.amber : COLORS.red;
if (e === game.weapons.target) {
c.strokeStyle = c.fillStyle;
c.strokeRect(rx + ex - 5, ry + ey - 5, 10, 10);
}
c.fillRect(rx + ex - 2.5, ry + ey - 2.5, 5, 5);
}
for (const m of game.weapons.missiles) {
const [mx, my] = toR(m.pos.x, m.pos.z);
c.fillStyle = m.owner === 'player' ? COLORS.green : COLORS.red;
c.fillRect(rx + mx - 1, ry + my - 1, 2, 2);
}
c.restore();
c.fillStyle = COLORS.green;
c.beginPath();
c.moveTo(rx, ry - 7); c.lineTo(rx + 5, ry + 5); c.lineTo(rx - 5, ry + 5); c.closePath();
c.fill();
this.text(`${RADAR_RANGE / 1000}km`, rx + R - 4, ry + R + 2, COLORS.dim, 'right', 10);
}
drawWeapons(game) {
const w = game.weapons;
const p = game.player;
const x = this.w - 200, y = this.h - 120;
const c = this.ctx;
c.fillStyle = 'rgba(0,20,8,0.45)';
c.fillRect(x - 10, y - 22, 190, 112);
c.strokeStyle = COLORS.dim;
c.strokeRect(x - 10, y - 22, 190, 112);
this.text('GUN', x, y, COLORS.dim, 'left', 13);
this.text(String(w.gunAmmo), x + 160, y, COLORS.green, 'right', 16);
this.text('MSL', x, y + 26, COLORS.dim, 'left', 13);
this.text(String(w.missileAmmo), x + 160, y + 26, COLORS.green, 'right', 16);
for (let i = 0; i < 2; i++) {
c.fillStyle = w.pylonReady[i] <= 0 ? COLORS.green : 'rgba(140,255,170,0.15)';
c.fillRect(x + 44 + i * 16, y + 16, 10, 12);
}
const dmg = Math.round(p.damage);
let dmgCol = COLORS.green;
if (dmg >= 60) dmgCol = COLORS.red;
else if (dmg >= 30) dmgCol = COLORS.amber;
this.text('DMG', x, y + 52, COLORS.dim, 'left', 13);
this.text(`${dmg}%`, x + 160, y + 52, dmgCol, 'right', 16);
c.fillStyle = 'rgba(140,255,170,0.15)';
c.fillRect(x, y + 62, 160, 5);
c.fillStyle = dmgCol;
c.fillRect(x, y + 62, 160 * (dmg / 100), 5);
}
drawStatus(game) {
const m = game.mission;
const t = m.timeLeft;
const mm = String(Math.floor(t / 60)).padStart(2, '0');
const ss = String(Math.floor(t % 60)).padStart(2, '0');
const ms = String(Math.floor((t % 1) * 100)).padStart(2, '0');
this.text('TIME', 24, 30, COLORS.dim, 'left', 11);
this.text(`${mm}:${ss}:${ms}`, 24, 50, t < 60 ? COLORS.amber : COLORS.green, 'left', 18);
this.text('SCORE', 24, 74, COLORS.dim, 'left', 11);
this.text(String(m.score), 24, 92, COLORS.green, 'left', 16);
this.text('TGT', this.w - 24, 30, COLORS.dim, 'right', 11);
this.text(String(m.remaining), this.w - 24, 52, COLORS.green, 'right', 20);
}
drawWarnings(game) {
const p = game.player;
if (!p.alive) return;
const cx = this.w / 2;
const on = this.blink % 0.5 < 0.3;
let y = this.h / 2 - 150;
if (game.alert && on) {
this.text('MISSILE ALERT', cx, y, COLORS.red, 'center', 22);
y += 26;
}
const agl = p.pos.y - game.terrain.floorAt(p.pos.x, p.pos.z);
if (agl < 250 && p.forward.y < 0 && on) {
this.text('PULL UP', cx, y, COLORS.red, 'center', 22);
y += 26;
}
if (p.speed < 100 && on) {
this.text('STALL', cx, y, COLORS.amber, 'center', 18);
y += 24;
}
const m = game.mission;
if (m.outTime > 0) {
this.text(`RETURN TO MISSION AREA ${Math.ceil(15 - m.outTime)}`, cx, this.h / 2 + 140, COLORS.amber, 'center', 16);
}
}
drawRadio(game) {
const r = game.mission.radio;
if (!r) return;
const c = this.ctx;
const cx = this.w / 2, y = this.h - 70;
this.font(14);
const w = Math.max(c.measureText(r.text).width, 200) + 40;
c.fillStyle = 'rgba(0,15,6,0.55)';
c.fillRect(cx - w / 2, y - 30, w, 48);
let col = COLORS.red;
if (r.who.startsWith('KESTREL')) col = COLORS.green;
else if (r.who === 'OVERWATCH') col = COLORS.blue;
this.text(r.who, cx - w / 2 + 12, y - 12, col, 'left', 11);
this.text(r.text, cx, y + 8, 'rgba(230,255,235,0.95)', 'center', 14);
}
drawMessage(dt) {
if (!this.msg) return;
this.msg.t += dt;
if (this.msg.t > this.msg.dur) {
this.msg = null;
return;
}
const a = this.msg.t < 0.1 ? this.msg.t / 0.1 : 1;
const c = this.ctx;
c.globalAlpha = a;
this.font(26, 'bold');
c.textAlign = 'center';
c.fillStyle = this.msg.color;
c.fillText(this.msg.text, this.w / 2, this.h / 2 + 95);
c.globalAlpha = 1;
}
drawAlertEdge() {
const c = this.ctx;
const a = 0.18 + 0.12 * Math.sin(this.blink * 18);
const g = c.createRadialGradient(this.w / 2, this.h / 2, Math.min(this.w, this.h) * 0.35, this.w / 2, this.h / 2, Math.max(this.w, this.h) * 0.75);
g.addColorStop(0, 'rgba(255,0,0,0)');
g.addColorStop(1, `rgba(255,20,10,${a})`);
c.fillStyle = g;
c.fillRect(0, 0, this.w, this.h);
}
}
const BLOCK = new Set(['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space', 'Tab']);
const DEADZONE = 0.12;
const axis = (v) => (Math.abs(v) < DEADZONE ? 0 : v);
export class Input {
constructor() {
this.keys = new Set();
this.pressed = new Set();
this.invert = false;
this.pad = null;
this.padPrev = [];
window.addEventListener('keydown', (e) => {
if (BLOCK.has(e.code)) e.preventDefault();
if (!this.keys.has(e.code)) this.pressed.add(e.code);
this.keys.add(e.code);
});
window.addEventListener('keyup', (e) => this.keys.delete(e.code));
window.addEventListener('blur', () => this.keys.clear());
}
down(code) { return this.keys.has(code); }
hit(code) { return this.pressed.has(code); }
padButton(i) { return !!this.pad?.buttons[i]?.pressed; }
padHit(i) { return this.padButton(i) && !this.padPrev[i]; }
poll() {
const pads = navigator.getGamepads ? navigator.getGamepads() : [];
this.pad = [...pads].find((p) => p?.connected) || null;
if (this.hit('KeyI')) this.invert = !this.invert;
const k = (a, b) => (this.down(a) ? 1 : 0) - (this.down(b) ? 1 : 0);
// Stick-forward convention: Up arrow pushes the nose down.
let pitch = k('ArrowDown', 'ArrowUp');
let roll = k('ArrowRight', 'ArrowLeft');
let yaw = k('KeyD', 'KeyA');
let throttle = k('KeyW', 'KeyS');
if (this.pad) {
const ax = this.pad.axes;
pitch += -axis(ax[1] || 0);
roll += axis(ax[0] || 0);
yaw += (this.padButton(5) ? 1 : 0) - (this.padButton(4) ? 1 : 0);
const rt = this.pad.buttons[7]?.value || 0, lt = this.pad.buttons[6]?.value || 0;
throttle += rt - lt;
}
const c = (v) => Math.max(-1, Math.min(1, v));
this.pitch = c(this.invert ? -pitch : pitch);
this.roll = c(roll);
this.yaw = c(yaw);
this.throttle = c(throttle);
this.gun = this.down('ShiftLeft') || this.down('ShiftRight') || this.padButton(2);
this.missile = this.hit('Space') || this.padHit(0);
this.switchTarget = this.hit('KeyQ') || this.padHit(3);
this.lookTarget = this.down('KeyE') || this.padButton(1);
this.pause = this.hit('KeyP') || this.hit('Escape') || this.padHit(9);
this.restart = this.hit('KeyR');
this.start = this.hit('Enter') || this.padHit(0) || this.padHit(9);
this.mute = this.hit('KeyM');
}
endFrame() {
this.pressed.clear();
this.padPrev = this.pad ? this.pad.buttons.map((b) => b.pressed) : [];
}
}
import * as THREE from 'three';
import { QUALITY, WORLD, SUN_DIR, SUN_COLOR } from './config.js';
import { Weather } from './weather.js';
import { Terrain, makeWater, makeSky, makeAirBase, makeSharedUniforms } from './world.js';
import { makeCloudNoise } from './clouds.js';
import { Pipeline } from './pipeline.js';
import { ScreenRain } from './rain.js';
import { FX } from './particles.js';
import { Player } from './player.js';
import { ChaseCamera } from './camera.js';
import { EnemyManager } from './enemies.js';
import { Weapons } from './weapons.js';
import { Mission } from './mission.js';
import { HUD } from './hud.js';
import { AudioFX } from './audio.js';
import { Input } from './input.js';
import { loadModels } from './models.js';
const $ = (id) => document.getElementById(id);
const nextFrame = () => new Promise((r) => setTimeout(r, 30));
const PLAYER_START = new THREE.Vector3(0, 2900, 12000);
async function boot() {
const renderer = new THREE.WebGLRenderer({ canvas: $('gl'), antialias: false, powerPreference: 'high-performance' });
renderer.setPixelRatio(QUALITY.pixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.autoClear = false;
const game = {
renderer,
scene: new THREE.Scene(),
camera: new THREE.PerspectiveCamera(66, window.innerWidth / window.innerHeight, 1.5, 260000),
state: 'loading',
time: 0,
inCloud: 0,
alert: null,
};
window.game = game;
const loading = $('loading');
loading.textContent = 'GENERATING WEATHER…';
await nextFrame();
game.weather = new Weather();
const uniforms = makeSharedUniforms(game.weather);
game.uniforms = uniforms;
loading.textContent = 'GENERATING TERRAIN…';
await nextFrame();
game.terrain = new Terrain(uniforms);
loading.textContent = 'LOADING AIRCRAFT…';
await loadModels();
loading.textContent = 'GENERATING CLOUD NOISE…';
await nextFrame();
const noise = makeCloudNoise();
const scene = game.scene;
scene.add(makeSky(uniforms), game.terrain.mesh, makeWater(uniforms), makeAirBase());
scene.fog = new THREE.FogExp2(0x8fa6c4, 0.000035);
const sun = new THREE.DirectionalLight(SUN_COLOR, 3.2);
sun.position.copy(SUN_DIR).multiplyScalar(1000);
scene.add(sun, new THREE.HemisphereLight(0x9fb8dd, 0x3a3f36, 0.9));
game.sun = sun;
const pmrem = new THREE.PMREMGenerator(renderer);
const envScene = new THREE.Scene();
envScene.add(makeSky(uniforms, 100));
scene.environment = pmrem.fromScene(envScene, 0.02).texture;
game.rain = new ScreenRain();
game.pipeline = new Pipeline(renderer, noise, game.weather, uniforms, game.rain);
game.fx = new FX(scene);
game.audio = new AudioFX();
game.hud = new HUD($('hud'));
game.input = new Input();
game.chase = new ChaseCamera(game.camera);
game.enemies = new EnemyManager(game);
game.mission = new Mission(game);
game.player = new Player(scene, game);
game.weapons = new Weapons(game);
game.player.reset(safeStart(game), 0);
game.onMissionEnd = (result) => {
setTimeout(() => {
if (game.state !== 'playing') return;
game.state = 'ended';
$('resultTitle').textContent = result.success ? 'MISSION ACCOMPLISHED' : 'MISSION FAILED';
const t = game.mission.time;
$('resultStats').textContent = [
result.reason,
'',
`SCORE ${game.mission.score}`,
`KILLS ${game.mission.kills}`,
`TIME ${Math.floor(t / 60)}:${String(Math.floor(t % 60)).padStart(2, '0')}`,
`DAMAGE ${Math.round(game.player.damage)}%`,
].join('\n');
$('result').classList.remove('hidden');
}, result.success ? 4000 : 3000);
};
const resize = () => {
const w = window.innerWidth, h = window.innerHeight;
renderer.setSize(w, h, false);
game.camera.aspect = w / h;
game.camera.updateProjectionMatrix();
game.pipeline.setSize(w, h);
game.hud.resize();
game.fx.setScale(h * renderer.getPixelRatio(), game.camera.fov);
};
window.addEventListener('resize', resize);
resize();
loading.classList.add('hidden');
$('startPrompt').classList.remove('hidden');
game.state = 'title';
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => frame(game, Math.min(clock.getDelta(), 1 / 20)));
}
function safeStart(game) {
const t = game.terrain;
let ground = 0;
for (let z = PLAYER_START.z; z > PLAYER_START.z - 6000; z -= 250) ground = Math.max(ground, t.floorAt(PLAYER_START.x, z));
return PLAYER_START.clone().setY(Math.max(PLAYER_START.y, ground + 700));
}
function startMission(game) {
game.audio.init();
game.enemies.clear();
game.weapons.reset();
game.fx.clear();
game.rain.clear();
game.mission.reset();
game.player.reset(safeStart(game), 0);
game.chase.snap(game.player);
game.mission.start();
game.state = 'playing';
$('title').classList.add('hidden');
$('result').classList.add('hidden');
$('pause').classList.add('hidden');
}
function handleMeta(game, input) {
if (input.mute) game.audio.toggleMute();
if (game.state === 'title' && input.start) startMission(game);
else if (game.state === 'ended' && input.restart) startMission(game);
else if (game.state === 'playing' && input.restart && !game.player.alive) startMission(game);
else if (input.pause && (game.state === 'playing' || game.state === 'paused')) {
game.state = game.state === 'playing' ? 'paused' : 'playing';
$('pause').classList.toggle('hidden', game.state !== 'paused');
if (game.audio.ctx) {
if (game.state === 'paused') game.audio.ctx.suspend();
else game.audio.ctx.resume();
}
}
}
const flowV = new THREE.Vector3();
function frame(game, dt) {
const { input, player, camera } = game;
input.poll();
handleMeta(game, input);
const running = game.state === 'playing' || game.state === 'ended';
if (game.state !== 'paused') {
game.time += dt;
game.uniforms.uTime.value = game.time;
if (game.state === 'title') {
player.updateAuto(dt);
} else if (running) {
player.lookTarget = input.lookTarget;
player.update(dt, game.state === 'playing' ? input : { pitch: 0, roll: 0, yaw: 0, throttle: 0 });
game.weapons.update(dt, game.state === 'playing' ? input : {});
game.enemies.update(dt, game.time);
game.mission.update(dt);
checkCollisions(game);
}
player.updateVisuals(dt, game.time, game.fx);
game.fx.update(dt);
game.chase.update(dt, player, game.weapons.target, game.state === 'title' ? 'title' : 'chase', game.inCloud);
game.fx.setScale(window.innerHeight * game.renderer.getPixelRatio(), camera.fov);
camera.updateMatrixWorld();
game.uniforms.uCamPos.value.copy(camera.position);
game.inCloud = game.weather.cloudAmount(camera.position);
const am = running ? game.weapons.alertMissile : null;
game.alert = am && am.dist < 4000 ? am : null;
flowV.copy(player.pos).addScaledVector(player.forward, 2000).project(camera);
const flow = flowV.z < 1 ? { x: flowV.x * 0.5 + 0.5, y: flowV.y * 0.5 + 0.5 } : { x: 0.5, y: 0.5 };
game.rain.update(dt, game.inCloud, player.alive ? player.speed : 0, flow);
const fu = game.pipeline.finalMat.uniforms;
fu.uFlow.value.set(flow.x, flow.y);
fu.uDamage.value = player.damageFlash;
game.audio.update(dt, {
throttle: player.throttle,
speed: player.speed,
inCloud: game.inCloud,
alive: player.alive && running,
lockState: game.state === 'playing' ? game.weapons.lockState : 'none',
alertDist: game.alert ? game.alert.dist : null,
});
}
game.pipeline.render(game.scene, camera);
game.hud.draw(game, game.state === 'paused' ? 0 : dt);
input.endFrame();
}
function checkCollisions(game) {
const p = game.player;
if (!p.alive) return;
for (const e of game.enemies.list) {
if (!e.alive) continue;
if (e.pos.distanceTo(p.pos) < e.hitRadius + 6) {
game.enemies.damage(e, 9999, true);
p.applyDamage(999);
}
}
const r = Math.hypot(p.pos.x, p.pos.z);
if (r > WORLD.areaRadius * 1.6) p.applyDamage(999);
}
boot().catch((err) => {
console.error(err);
$('loading').textContent = `ERROR: ${err.message}`;
});
import * as THREE from 'three';
import { WORLD, BASE_POS } from './config.js';
const TIME_LIMIT = 12 * 60;
const BASE_FAIL_DIST = 2000;
const OUT_OF_AREA_LIMIT = 15;
const OW = 'OVERWATCH';
const ACE1 = 'MISTRAL 1';
const ACE2 = 'MISTRAL 2';
const KILL_LINES = [
[OW, 'Splash one. Good work, Kestrel.'],
[OW, 'Target down.'],
[OW, 'Confirmed kill. Keep pressing.'],
[OW, 'That one is not coming back out of the clouds.'],
];
const ENEMY_LAUNCH_LINES = [
['HOSTILE', 'Fox two! Fox two!'],
['HOSTILE', 'Missile away, break, Kestrel!'],
[ACE1, 'Let us see how you dance.'],
];
const bearing = (from, to) => {
const deg = (Math.atan2(to.x - from.x, -(to.z - from.z)) * 180) / Math.PI;
return String(Math.round((deg + 360) % 360)).padStart(3, '0');
};
export class Mission {
constructor(game) {
this.game = game;
this.reset();
}
reset() {
this.time = 0;
this.score = 0;
this.kills = 0;
this.phase = 0;
this.radioQueue = [];
this.radio = null;
this.result = null;
this.outTime = 0;
this.warned5k = false;
this.lowHpWarned = false;
this.events = [];
}
get timeLeft() {
return Math.max(0, TIME_LIMIT - this.time);
}
get remaining() {
return this.game.enemies.list.filter((e) => e.alive).length;
}
say(who, text, dur = 4.5) {
this.radioQueue.push({ who, text, dur });
}
at(t, fn) {
this.events.push({ t: this.time + t, fn });
}
start() {
const g = this.game;
const spawn = (name, x, y, z, h) => g.enemies.spawn('fighter', name, new THREE.Vector3(x, y, z), h);
spawn('BANDIT 1', -1500, 2400, -2000, Math.PI);
spawn('BANDIT 2', -1200, 2550, -2300, Math.PI);
spawn('BANDIT 3', -1800, 2300, -2400, Math.PI);
spawn('BANDIT 4', 3500, 3000, -5500, Math.PI * 0.8);
spawn('BANDIT 5', 3800, 3200, -5800, Math.PI * 0.8);
spawn('BANDIT 6', 3300, 2900, -6000, Math.PI * 0.8);
this.phase = 1;
this.say(OW, 'Kestrel One, Overwatch. Enemy fighters are hiding inside the storm front.');
this.say(OW, 'Radar is patchy in this weather. Trust your HUD and clear the sky.');
this.say('KESTREL 1', 'Copy, Overwatch. Going into the clouds.', 3);
}
startWave2() {
const g = this.game;
this.phase = 2;
const origin = new THREE.Vector3(14500, 2600, -9500);
const toBase = new THREE.Vector3(BASE_POS.x - origin.x, 0, BASE_POS.z - origin.z);
const heading = Math.atan2(-toBase.x, -toBase.z);
const bombers = [];
const offsets = [[0, 0], [-260, 200], [260, 200]];
offsets.forEach(([dx, dz], i) => {
const off = new THREE.Vector3(dx, i * 40, dz).applyAxisAngle(new THREE.Vector3(0, 1, 0), heading);
const b = g.enemies.spawn('bomber', `BOMBER ${i + 1}`, origin.clone().add(off), heading);
b.goal.copy(BASE_POS);
bombers.push(b);
});
[[ACE1, -300, 150], [ACE2, 300, 150]].forEach(([name, dx, dy]) => {
const off = new THREE.Vector3(dx, dy, 350).applyAxisAngle(new THREE.Vector3(0, 1, 0), heading);
const a = g.enemies.spawn('ace', name, origin.clone().add(off), heading);
a.state = 'escort';
a.escortOf = bombers[0];
a.escortOffset.set(dx, dy, 350);
});
const brg = bearing(g.player.pos, origin);
this.say(OW, `New contacts, bearing ${brg}. Heavy bombers, heading for Halden Air Base.`);
this.say(OW, 'Intercept them before they reach the base. Do not let them through.');
this.say(OW, 'Two escorts with them. Mistral squadron. They are good, Kestrel.');
this.say(ACE1, 'Stay on the bombers, Two. We deal with the one in the clouds after.', 4);
}
update(dt) {
if (this.result) return;
const g = this.game;
this.time += dt;
this.updateRadio(dt);
for (let i = this.events.length - 1; i >= 0; i--) {
if (this.time >= this.events[i].t) {
this.events[i].fn();
this.events.splice(i, 1);
}
}
if (this.phase === 1 && this.remaining <= 1) this.startWave2();
if (this.phase === 2 && this.remaining === 0) this.finish(true, 'All targets destroyed.');
for (const e of g.enemies.list) {
if (!e.alive || e.type !== 'bomber') continue;
const d = g.enemies.distanceToBase(e);
if (d < 6000 && !this.warned5k) {
this.warned5k = true;
this.say(OW, 'Bombers are six kilometers from the base! Stop them now!');
}
if (d < BASE_FAIL_DIST) this.finish(false, 'The bombers reached Halden Air Base.');
}
if (this.time >= TIME_LIMIT) this.finish(false, 'Out of time.');
const r = Math.hypot(g.player.pos.x, g.player.pos.z);
if (g.player.alive && r > WORLD.areaRadius) {
this.outTime += dt;
if (this.outTime > OUT_OF_AREA_LIMIT) this.finish(false, 'Left the mission area.');
} else {
this.outTime = 0;
}
}
updateRadio(dt) {
if (this.radio) {
this.radio.t += dt;
if (this.radio.t > this.radio.dur) this.radio = null;
}
if (!this.radio && this.radioQueue.length) this.radio = { ...this.radioQueue.shift(), t: 0 };
}
onKill(e) {
this.kills++;
this.score += e.def.score;
if (e.type === 'ace') {
this.say(e.name === ACE1 ? ACE2 : ACE1, e.name === ACE1 ? 'Lead is down! Lead is down!' : 'Two! Answer me, Two!', 3.5);
} else if (Math.random() < 0.6 && this.radioQueue.length < 2) {
const [who, text] = KILL_LINES[Math.floor(Math.random() * KILL_LINES.length)];
this.say(who, text, 3);
}
}
radioEnemyLaunch(e) {
if (this.radioQueue.length > 1) return;
const pool = e.type === 'ace' ? ENEMY_LAUNCH_LINES : ENEMY_LAUNCH_LINES.slice(0, 2);
const [who, text] = pool[Math.floor(Math.random() * pool.length)];
this.say(who === 'HOSTILE' ? e.name : who, text, 2.5);
}
onPlayerHit() {
const p = this.game.player;
if (p.alive && p.hp < 45 && !this.lowHpWarned) {
this.lowHpWarned = true;
this.say(OW, 'Kestrel, you are trailing smoke. Watch your six!', 3.5);
}
}
onPlayerDown() {
this.finish(false, 'Kestrel One is down.');
}
finish(success, reason) {
if (this.result) return;
this.result = { success, reason };
if (success) this.say(OW, 'All hostiles down. Mission complete. Outstanding flying, Kestrel.', 6);
else this.say(OW, reason, 6);
this.game.onMissionEnd(this.result);
}
}
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const FILES = {
fighter: new URL('../models/fighter.glb', import.meta.url).href,
bomber: new URL('../models/bomber.glb', import.meta.url).href,
missile: new URL('../models/missile.glb', import.meta.url).href,
};
const templates = {};
export async function loadModels() {
const loader = new GLTFLoader();
await Promise.all(Object.entries(FILES).map(async ([key, url]) => {
const gltf = await loader.loadAsync(url);
const scene = gltf.scene;
scene.updateMatrixWorld(true);
const markers = {};
scene.traverse((o) => {
if (o.userData.marker) markers[o.userData.marker] = o.getWorldPosition(new THREE.Vector3());
if (o.isMesh) o.frustumCulled = true;
});
templates[key] = { scene, markers };
}));
}
// Clone shares geometry; materials named in `tints` are cloned and multiplied by the given colour.
export function instantiate(key, tints = {}) {
const t = templates[key];
if (!t) throw new Error(`model not loaded: ${key}`);
const root = t.scene.clone(true);
const cache = new Map();
root.traverse((o) => {
if (!o.isMesh) return;
const tint = tints[o.material.name];
if (!tint) return;
if (!cache.has(o.material)) {
const m = o.material.clone();
m.color.multiply(tint);
cache.set(o.material, m);
}
o.material = cache.get(o.material);
});
return { root, markers: t.markers };
}
export function mulberry32(seed) {
let a = seed >>> 0;
return function () {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const fade = (t) => t * t * t * (t * (t * 6 - 15) + 10);
const lerp = (a, b, t) => a + (b - a) * t;
const wrap = (i, p) => ((i % p) + p) % p;
const G3 = [
[1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0],
[1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1],
[0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1],
];
export class Perlin {
constructor(seed = 1) {
const rnd = mulberry32(seed);
const p = new Uint8Array(256);
for (let i = 0; i < 256; i++) p[i] = i;
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;
}
this.perm = new Uint16Array(512);
for (let i = 0; i < 512; i++) this.perm[i] = p[i & 255];
this.gx = new Float32Array(256);
this.gy = new Float32Array(256);
for (let i = 0; i < 256; i++) {
const a = rnd() * Math.PI * 2;
this.gx[i] = Math.cos(a);
this.gy[i] = Math.sin(a);
}
}
// period (lattice units, <= 256) makes the noise tile
noise2(x, y, period = 256) {
const xi = Math.floor(x), yi = Math.floor(y);
const xf = x - xi, yf = y - yi;
const x0 = wrap(xi, period), x1 = wrap(xi + 1, period);
const y0 = wrap(yi, period), y1 = wrap(yi + 1, period);
const P = this.perm, gx = this.gx, gy = this.gy;
const h00 = P[P[x0] + y0], h10 = P[P[x1] + y0], h01 = P[P[x0] + y1], h11 = P[P[x1] + y1];
const d00 = gx[h00] * xf + gy[h00] * yf;
const d10 = gx[h10] * (xf - 1) + gy[h10] * yf;
const d01 = gx[h01] * xf + gy[h01] * (yf - 1);
const d11 = gx[h11] * (xf - 1) + gy[h11] * (yf - 1);
const u = fade(xf), v = fade(yf);
return lerp(lerp(d00, d10, u), lerp(d01, d11, u), v) * 1.4142;
}
noise3(x, y, z, period = 256) {
const xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z);
const xf = x - xi, yf = y - yi, zf = z - zi;
const x0 = wrap(xi, period), x1 = wrap(xi + 1, period);
const y0 = wrap(yi, period), y1 = wrap(yi + 1, period);
const z0 = wrap(zi, period), z1 = wrap(zi + 1, period);
const P = this.perm;
const g = (xx, yy, zz, dx, dy, dz) => {
const v = G3[P[P[P[xx] + yy] + zz] % 12];
return v[0] * dx + v[1] * dy + v[2] * dz;
};
const u = fade(xf), v = fade(yf), w = fade(zf);
const a = lerp(g(x0, y0, z0, xf, yf, zf), g(x1, y0, z0, xf - 1, yf, zf), u);
const b = lerp(g(x0, y1, z0, xf, yf - 1, zf), g(x1, y1, z0, xf - 1, yf - 1, zf), u);
const c = lerp(g(x0, y0, z1, xf, yf, zf - 1), g(x1, y0, z1, xf - 1, yf, zf - 1), u);
const d = lerp(g(x0, y1, z1, xf, yf - 1, zf - 1), g(x1, y1, z1, xf - 1, yf - 1, zf - 1), u);
return lerp(lerp(a, b, v), lerp(c, d, v), w);
}
}
export function makeWorley(cells, rnd) {
const pts = new Float32Array(cells * cells * cells * 3);
for (let i = 0; i < pts.length; i++) pts[i] = rnd();
return { cells, pts };
}
// tileable F1 distance in cell units; u,v,w in [0,1)
export function worley3(W, u, v, w) {
const c = W.cells, pts = W.pts;
const x = u * c, y = v * c, z = w * c;
const xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z);
let md = 9;
for (let dz = -1; dz <= 1; dz++) {
const cz = zi + dz, wz = wrap(cz, c);
for (let dy = -1; dy <= 1; dy++) {
const cy = yi + dy, wy = wrap(cy, c);
for (let dx = -1; dx <= 1; dx++) {
const cx = xi + dx, wx = wrap(cx, c);
const idx = ((wz * c + wy) * c + wx) * 3;
const fx = cx + pts[idx] - x, fy = cy + pts[idx + 1] - y, fz = cz + pts[idx + 2] - z;
const d = fx * fx + fy * fy + fz * fz;
if (d < md) md = d;
}
}
}
return Math.sqrt(md);
}
import * as THREE from 'three';
const VERT = /* glsl */ `
attribute float aSize;
attribute vec4 aColor;
uniform float uScale;
varying vec4 vColor;
varying float vSeed;
void main() {
vec4 mv = modelViewMatrix * vec4(position, 1.0);
gl_Position = projectionMatrix * mv;
gl_PointSize = min(aSize * uScale / max(-mv.z, 0.1), 1024.0);
vColor = aColor;
vSeed = fract(position.x * 0.137 + position.z * 0.071);
}
`;
const FRAG = /* glsl */ `
varying vec4 vColor;
varying float vSeed;
void main() {
vec2 p = gl_PointCoord - 0.5;
float r = length(p) * 2.0;
float ang = atan(p.y, p.x);
float wob = 0.85 + 0.15 * sin(ang * 5.0 + vSeed * 40.0);
float a = 1.0 - smoothstep(0.35 * wob, 1.0 * wob, r);
if (a <= 0.0) discard;
gl_FragColor = vec4(vColor.rgb, vColor.a * a);
}
`;
// CPU particle pool rendered as one Points draw call.
export class Particles {
constructor(max, additive) {
this.max = max;
this.count = 0;
this.p = new Float32Array(max * 3);
this.v = new Float32Array(max * 3);
this.life = new Float32Array(max);
this.maxLife = new Float32Array(max);
this.s0 = new Float32Array(max);
this.s1 = new Float32Array(max);
this.c0 = new Float32Array(max * 3);
this.c1 = new Float32Array(max * 3);
this.a0 = new Float32Array(max);
this.drag = new Float32Array(max);
this.grav = new Float32Array(max);
const g = new THREE.BufferGeometry();
this.aPos = new THREE.BufferAttribute(new Float32Array(max * 3), 3).setUsage(THREE.DynamicDrawUsage);
this.aSize = new THREE.BufferAttribute(new Float32Array(max), 1).setUsage(THREE.DynamicDrawUsage);
this.aColor = new THREE.BufferAttribute(new Float32Array(max * 4), 4).setUsage(THREE.DynamicDrawUsage);
g.setAttribute('position', this.aPos);
g.setAttribute('aSize', this.aSize);
g.setAttribute('aColor', this.aColor);
g.setDrawRange(0, 0);
this.uniforms = { uScale: { value: 500 } };
this.points = new THREE.Points(g, new THREE.ShaderMaterial({
uniforms: this.uniforms,
vertexShader: VERT,
fragmentShader: FRAG,
transparent: true,
depthWrite: false,
blending: additive ? THREE.AdditiveBlending : THREE.NormalBlending,
}));
this.points.frustumCulled = false;
this.points.renderOrder = additive ? 3 : 2;
this.geometry = g;
}
setScale(heightPx, fovDeg) {
this.uniforms.uScale.value = heightPx / (2 * Math.tan(THREE.MathUtils.degToRad(fovDeg) / 2));
}
clear() {
this.count = 0;
}
// o: { life, size:[s0,s1], color:[r,g,b], color1:[r,g,b], alpha, drag, gravity }
emit(pos, vel, o) {
if (this.count >= this.max) return;
const i = this.count++;
const i3 = i * 3;
this.p[i3] = pos.x; this.p[i3 + 1] = pos.y; this.p[i3 + 2] = pos.z;
this.v[i3] = vel.x; this.v[i3 + 1] = vel.y; this.v[i3 + 2] = vel.z;
this.life[i] = 0;
this.maxLife[i] = o.life;
this.s0[i] = o.size[0];
this.s1[i] = o.size[1];
const c1 = o.color1 || o.color;
this.c0[i3] = o.color[0]; this.c0[i3 + 1] = o.color[1]; this.c0[i3 + 2] = o.color[2];
this.c1[i3] = c1[0]; this.c1[i3 + 1] = c1[1]; this.c1[i3 + 2] = c1[2];
this.a0[i] = o.alpha ?? 1;
this.drag[i] = o.drag ?? 0.5;
this.grav[i] = o.gravity ?? 0;
}
update(dt) {
const P = this.aPos.array, S = this.aSize.array, C = this.aColor.array;
let i = 0;
while (i < this.count) {
this.life[i] += dt;
if (this.life[i] >= this.maxLife[i]) {
this.kill(i);
continue;
}
const i3 = i * 3;
const dr = Math.exp(-this.drag[i] * dt);
this.v[i3] *= dr;
this.v[i3 + 1] = this.v[i3 + 1] * dr - this.grav[i] * dt;
this.v[i3 + 2] *= dr;
this.p[i3] += this.v[i3] * dt;
this.p[i3 + 1] += this.v[i3 + 1] * dt;
this.p[i3 + 2] += this.v[i3 + 2] * dt;
const t = this.life[i] / this.maxLife[i];
P[i3] = this.p[i3]; P[i3 + 1] = this.p[i3 + 1]; P[i3 + 2] = this.p[i3 + 2];
S[i] = this.s0[i] + (this.s1[i] - this.s0[i]) * Math.sqrt(t);
const i4 = i * 4;
C[i4] = this.c0[i3] + (this.c1[i3] - this.c0[i3]) * t;
C[i4 + 1] = this.c0[i3 + 1] + (this.c1[i3 + 1] - this.c0[i3 + 1]) * t;
C[i4 + 2] = this.c0[i3 + 2] + (this.c1[i3 + 2] - this.c0[i3 + 2]) * t;
C[i4 + 3] = this.a0[i] * Math.min(1, t * 12) * (1 - t);
i++;
}
this.geometry.setDrawRange(0, this.count);
this.aPos.needsUpdate = this.aSize.needsUpdate = this.aColor.needsUpdate = true;
}
kill(i) {
const last = --this.count;
if (i === last) return;
const i3 = i * 3, l3 = last * 3;
for (let k = 0; k < 3; k++) {
this.p[i3 + k] = this.p[l3 + k];
this.v[i3 + k] = this.v[l3 + k];
this.c0[i3 + k] = this.c0[l3 + k];
this.c1[i3 + k] = this.c1[l3 + k];
}
this.life[i] = this.life[last];
this.maxLife[i] = this.maxLife[last];
this.s0[i] = this.s0[last];
this.s1[i] = this.s1[last];
this.a0[i] = this.a0[last];
this.drag[i] = this.drag[last];
this.grav[i] = this.grav[last];
}
}
const tmpV = new THREE.Vector3();
const tmpP = new THREE.Vector3();
const rnd = (a, b) => a + Math.random() * (b - a);
// Effect presets used by gameplay code.
export class FX {
constructor(scene) {
this.fire = new Particles(4000, true);
this.smoke = new Particles(9000, false);
scene.add(this.smoke.points, this.fire.points);
}
setScale(h, fov) {
this.fire.setScale(h, fov);
this.smoke.setScale(h, fov);
}
update(dt) {
this.fire.update(dt);
this.smoke.update(dt);
}
clear() {
this.fire.clear();
this.smoke.clear();
}
explosion(pos, vel, scale = 1) {
this.fire.emit(pos, vel, { life: 0.35, size: [40 * scale, 140 * scale], color: [12, 9, 6], color1: [4, 1.5, 0.4], alpha: 1, drag: 3 });
for (let i = 0; i < 26; i++) {
tmpV.randomDirection().multiplyScalar(rnd(15, 70) * scale).addScaledVector(vel, 0.3);
this.fire.emit(pos, tmpV, { life: rnd(0.6, 1.4), size: [rnd(8, 18) * scale, rnd(30, 55) * scale], color: [6, 3, 0.8], color1: [0.6, 0.1, 0.02], drag: 2.2 });
}
for (let i = 0; i < 26; i++) {
tmpV.randomDirection().multiplyScalar(rnd(10, 40) * scale).addScaledVector(vel, 0.25);
tmpV.y += 6;
this.smoke.emit(pos, tmpV, { life: rnd(3, 6), size: [rnd(15, 25) * scale, rnd(70, 120) * scale], color: [0.12, 0.11, 0.1], color1: [0.42, 0.42, 0.44], alpha: 0.8, drag: 1.2 });
}
for (let i = 0; i < 20; i++) {
tmpV.randomDirection().multiplyScalar(rnd(80, 220)).addScaledVector(vel, 0.4);
this.fire.emit(pos, tmpV, { life: rnd(0.8, 1.8), size: [2, 1], color: [8, 5, 2], color1: [2, 0.4, 0.1], drag: 0.6, gravity: 30 });
}
}
smallBlast(pos) {
this.fire.emit(pos, tmpV.set(0, 0, 0), { life: 0.25, size: [10, 40], color: [10, 7, 4], color1: [2, 0.6, 0.2], drag: 2 });
for (let i = 0; i < 6; i++) {
tmpV.randomDirection().multiplyScalar(rnd(5, 15));
this.smoke.emit(pos, tmpV, { life: rnd(1.5, 3), size: [6, 30], color: [0.3, 0.3, 0.3], color1: [0.5, 0.5, 0.52], alpha: 0.6, drag: 1 });
}
}
spark(pos) {
this.fire.emit(pos, tmpV.set(0, 0, 0), { life: 0.12, size: [6, 14], color: [8, 6, 3], drag: 0 });
}
missileTrail(pos, prev) {
for (let k = 0; k < 2; k++) {
tmpP.lerpVectors(prev, pos, k / 2);
tmpV.randomDirection().multiplyScalar(2);
this.smoke.emit(tmpP, tmpV, { life: rnd(2.2, 3.2), size: [2.5, 16], color: [0.85, 0.86, 0.88], color1: [0.6, 0.62, 0.66], alpha: 0.55, drag: 0.8 });
}
this.fire.emit(pos, tmpV.set(0, 0, 0), { life: 0.05, size: [3, 2], color: [10, 6, 3], drag: 0 });
}
vapor(pos, prev, strength) {
for (let k = 0; k < 3; k++) {
tmpP.lerpVectors(prev, pos, k / 3);
this.smoke.emit(tmpP, tmpV.set(0, 0, 0), { life: 0.5 + strength * 0.4, size: [0.5, 2.5], color: [1.4, 1.4, 1.45], alpha: 0.35 * strength, drag: 0 });
}
}
burning(pos, vel) {
tmpV.copy(vel).multiplyScalar(0.2);
this.fire.emit(pos, tmpV, { life: rnd(0.2, 0.5), size: [6, 16], color: [6, 2.5, 0.6], color1: [1, 0.2, 0.05], drag: 2 });
tmpV.randomDirection().multiplyScalar(4).addScaledVector(vel, 0.1);
this.smoke.emit(pos, tmpV, { life: rnd(2, 4), size: [6, 40], color: [0.08, 0.08, 0.08], color1: [0.3, 0.3, 0.32], alpha: 0.7, drag: 1 });
}
damageSmoke(pos, vel) {
tmpV.copy(vel).multiplyScalar(0.1);
this.smoke.emit(pos, tmpV, { life: rnd(1, 2), size: [2, 14], color: [0.15, 0.15, 0.15], color1: [0.35, 0.35, 0.36], alpha: 0.5, drag: 1 });
}
}
import * as THREE from 'three';
import { FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
import { QUALITY } from './config.js';
import { makeCloudMaterial, FS_VERT } from './clouds.js';
const COMPOSITE_FRAG = /* glsl */ `
uniform sampler2D tScene;
uniform sampler2D tCloud;
uniform sampler2D tDepth;
uniform vec2 uLowRes;
uniform float uNear;
uniform float uFar;
varying vec2 vUv;
float linZ(float d) {
float z = d * 2.0 - 1.0;
return (2.0 * uNear * uFar) / (uFar + uNear - z * (uFar - uNear));
}
void main() {
vec3 scene = texture2D(tScene, vUv).rgb;
float dc = linZ(texture2D(tDepth, vUv).r);
vec2 p = vUv * uLowRes - 0.5;
vec2 f = fract(p);
vec2 b = (floor(p) + 0.5) / uLowRes;
vec4 acc = vec4(0.0);
float ws = 0.0;
// Depth-aware upsample keeps half-res clouds from bleeding over aircraft silhouettes.
for (int j = 0; j < 2; j++) {
for (int i = 0; i < 2; i++) {
vec2 o = vec2(float(i), float(j));
vec2 uv = b + o / uLowRes;
vec4 c = texture2D(tCloud, uv);
float dl = linZ(texture2D(tDepth, uv).r);
vec2 bw = mix(1.0 - f, f, o);
float w = bw.x * bw.y / (0.02 + abs(dl - dc) / dc) + 1e-5;
acc += c * w;
ws += w;
}
}
vec4 cl = acc / ws;
gl_FragColor = vec4(scene * cl.a + cl.rgb, 1.0);
}
`;
const FINAL_FRAG = /* glsl */ `
uniform sampler2D tColor;
uniform sampler2D tDrops;
uniform vec2 uRes;
uniform vec2 uFlow;
uniform float uTime;
uniform float uWet;
uniform float uStreak;
uniform float uDamage;
uniform float uExposure;
uniform float uWhite;
varying vec2 vUv;
vec3 aces(vec3 x) {
return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0);
}
float h11(float n) { return fract(sin(n * 127.1) * 43758.5453); }
void main() {
vec2 uv = vUv;
vec4 dr = texture2D(tDrops, uv);
vec2 n = (dr.xy - 0.5) * 4.0;
float mask = dr.a;
// Radial water streaks racing outward from the flight path.
vec2 asp = vec2(uRes.x / uRes.y, 1.0);
vec2 d = (uv - uFlow) * asp;
float r = length(d);
float ang = atan(d.y, d.x) / 6.2831853 * 110.0;
float lid = floor(ang);
float lf = fract(ang);
float rnd = h11(lid);
float s = fract(r * (0.7 + rnd) - uTime * (0.8 + rnd * 1.2) + rnd * 7.0);
float seg = smoothstep(0.0, 0.03, s) * (1.0 - smoothstep(0.03, 0.35, s));
float lane = 1.0 - smoothstep(0.0, 0.22, abs(lf - 0.5));
float streak = seg * lane * step(0.6, rnd) * smoothstep(0.12, 0.5, r) * uStreak;
vec2 dir = d / max(r, 1e-4);
vec2 off = -n * mask * 0.02 + dir / asp * streak * 0.006;
vec3 col = texture2D(tColor, uv + off).rgb;
if (uWet > 0.01) {
vec2 px = 3.0 / uRes * uWet;
vec3 bl = texture2D(tColor, uv + off + vec2(px.x, 0.0)).rgb
+ texture2D(tColor, uv + off - vec2(px.x, 0.0)).rgb
+ texture2D(tColor, uv + off + vec2(0.0, px.y)).rgb
+ texture2D(tColor, uv + off - vec2(0.0, px.y)).rgb;
col = mix(col, bl * 0.25, uWet * 0.55);
}
col *= 1.0 + mask * (0.15 * n.y - 0.06);
col += pow(max(n.y * mask, 0.0), 3.0) * 0.5;
col += streak * 0.10;
col = mix(col, col * vec3(1.5, 0.35, 0.3) + vec3(0.25, 0.0, 0.0), uDamage * 0.6);
col = aces(col * uExposure);
col = mix(col, vec3(1.0), uWhite);
vec2 q = uv - 0.5;
col *= 1.0 - dot(q, q) * 0.55;
col = pow(col, vec3(1.0 / 2.2));
gl_FragColor = vec4(col, 1.0);
}
`;
export class Pipeline {
constructor(renderer, noise, weather, uniforms, rain) {
this.renderer = renderer;
this.rain = rain;
const depth = new THREE.DepthTexture(1, 1);
depth.type = THREE.FloatType;
this.sceneRT = new THREE.WebGLRenderTarget(1, 1, {
type: THREE.HalfFloatType,
depthTexture: depth,
samples: 4,
});
this.cloudRT = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, depthBuffer: false });
this.compRT = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, depthBuffer: false });
this.dropRT = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, depthBuffer: false });
this.cloudMat = makeCloudMaterial(noise, weather, uniforms);
this.cloudMat.uniforms.tDepth.value = depth;
this.cloudQuad = new FullScreenQuad(this.cloudMat);
this.compMat = new THREE.ShaderMaterial({
uniforms: {
tScene: { value: this.sceneRT.texture },
tCloud: { value: this.cloudRT.texture },
tDepth: { value: depth },
uLowRes: { value: new THREE.Vector2() },
uNear: { value: 1 },
uFar: { value: 1 },
},
vertexShader: FS_VERT,
fragmentShader: COMPOSITE_FRAG,
depthTest: false,
depthWrite: false,
});
this.compQuad = new FullScreenQuad(this.compMat);
this.finalMat = new THREE.ShaderMaterial({
uniforms: {
tColor: { value: this.compRT.texture },
tDrops: { value: this.dropRT.texture },
uRes: { value: new THREE.Vector2() },
uFlow: { value: new THREE.Vector2(0.5, 0.5) },
uTime: uniforms.uTime,
uWet: { value: 0 },
uStreak: { value: 0 },
uDamage: { value: 0 },
uExposure: { value: 0.8 },
uWhite: { value: 0 },
},
vertexShader: FS_VERT,
fragmentShader: FINAL_FRAG,
depthTest: false,
depthWrite: false,
});
this.finalQuad = new FullScreenQuad(this.finalMat);
}
setSize(w, h) {
const pr = this.renderer.getPixelRatio();
const W = Math.floor(w * pr), H = Math.floor(h * pr);
const cw = Math.max(1, Math.floor(W * QUALITY.cloudScale)), ch = Math.max(1, Math.floor(H * QUALITY.cloudScale));
this.sceneRT.setSize(W, H);
this.compRT.setSize(W, H);
this.cloudRT.setSize(cw, ch);
this.dropRT.setSize(Math.floor(W / 2), Math.floor(H / 2));
this.rain.setSize(Math.floor(W / 2), Math.floor(H / 2));
this.compMat.uniforms.uLowRes.value.set(cw, ch);
this.finalMat.uniforms.uRes.value.set(W, H);
}
render(scene, camera) {
const r = this.renderer;
camera.updateMatrixWorld();
r.setRenderTarget(this.sceneRT);
r.setClearColor(0x000000, 1);
r.clear();
r.render(scene, camera);
const cu = this.cloudMat.uniforms;
cu.uInvProj.value.copy(camera.projectionMatrixInverse);
cu.uCamWorld.value.copy(camera.matrixWorld);
cu.uCamPos.value.copy(camera.position);
r.setRenderTarget(this.cloudRT);
this.cloudQuad.render(r);
this.compMat.uniforms.uNear.value = camera.near;
this.compMat.uniforms.uFar.value = camera.far;
r.setRenderTarget(this.compRT);
this.compQuad.render(r);
this.rain.render(r, this.dropRT);
const fu = this.finalMat.uniforms;
fu.uWet.value = this.rain.wet;
fu.uStreak.value = this.rain.streak;
r.setRenderTarget(null);
this.finalQuad.render(r);
}
}
import * as THREE from 'three';
import { buildFighter } from './aircraft.js';
import { clamp, lerp, damp } from './config.js';
const AX = new THREE.Vector3(1, 0, 0);
const AY = new THREE.Vector3(0, 1, 0);
const AZ = new THREE.Vector3(0, 0, 1);
const qTmp = new THREE.Quaternion();
const vTmp = new THREE.Vector3();
const vPrev = new THREE.Vector3();
export const CRUISE = 230;
export class Player {
constructor(scene, game) {
this.game = game;
this.mesh = buildFighter({ withMissiles: true });
scene.add(this.mesh);
this.pos = new THREE.Vector3();
this.quat = new THREE.Quaternion();
this.vel = new THREE.Vector3();
this.forward = new THREE.Vector3(0, 0, -1);
this.up = new THREE.Vector3(0, 1, 0);
this.rates = { p: 0, r: 0, y: 0 };
this.hitRadius = 10;
this.reset(new THREE.Vector3(0, 2800, 12000), 0);
}
reset(pos, heading) {
this.pos.copy(pos);
this.quat.setFromAxisAngle(AY, heading);
this.speed = CRUISE;
this.throttle = 0;
this.hp = 100;
this.alive = true;
this.gLoad = 1;
this.rates.p = this.rates.r = this.rates.y = 0;
this.mesh.visible = true;
this.damageFlash = 0;
this.syncMesh();
}
get damage() {
return 100 - this.hp;
}
applyDamage(amount) {
if (!this.alive) return;
this.hp = Math.max(0, this.hp - amount);
this.damageFlash = 1;
if (this.hp <= 0) this.destroy();
}
destroy() {
this.alive = false;
this.mesh.visible = false;
this.game.fx.explosion(this.pos, this.vel, 1.2);
this.game.audio.explosion(0);
this.game.mission.onPlayerDown();
}
// Autopilot used behind the title screen.
updateAuto(dt) {
this.rates.p = 0.05;
this.rates.r = 0;
this.integrate(dt, 0.12, 0, 0, 0);
}
update(dt, input) {
if (!this.alive) return;
const authority = clamp((this.speed - 60) / 170, 0.3, 1.15);
const highG = input.throttle < -0.3 && input.pitch > 0.3 ? 1.5 : 1;
const tp = input.pitch * 1.2 * authority * highG;
const tr = input.roll * 3.0;
const ty = input.yaw * 0.4;
this.rates.p += (tp - this.rates.p) * damp(6, dt);
this.rates.r += (tr - this.rates.r) * damp(8, dt);
this.rates.y += (ty - this.rates.y) * damp(4, dt);
this.integrate(dt, this.rates.p, this.rates.r, this.rates.y, input.throttle);
this.checkGround();
}
integrate(dt, p, r, y, throttle) {
this.quat.multiply(qTmp.setFromAxisAngle(AX, p * dt));
this.quat.multiply(qTmp.setFromAxisAngle(AZ, -r * dt));
this.quat.multiply(qTmp.setFromAxisAngle(AY, -y * dt));
this.quat.normalize();
this.forward.set(0, 0, -1).applyQuaternion(this.quat);
this.up.set(0, 1, 0).applyQuaternion(this.quat);
this.throttle += (throttle - this.throttle) * damp(3, dt);
const target = throttle >= 0 ? lerp(CRUISE, 390, throttle) : lerp(CRUISE, 110, -throttle);
const k = target > this.speed ? 0.45 : 0.9;
this.speed += (target - this.speed) * k * dt;
this.speed -= 9.81 * this.forward.y * 0.85 * dt;
this.speed -= Math.abs(p) * this.speed * 0.06 * dt;
// Stall: below ~95 m/s the nose falls toward the ground.
if (this.speed < 95) {
const s = (95 - this.speed) / 40;
vTmp.set(0, -1, 0).applyQuaternion(qTmp.copy(this.quat).invert());
const pitchDown = Math.atan2(-vTmp.y, -vTmp.z) > 0 ? -1 : 1;
this.quat.multiply(qTmp.setFromAxisAngle(AX, pitchDown * s * 0.8 * dt));
}
this.speed = clamp(this.speed, 70, 430);
this.gLoad = 1 + (p * this.speed) / 9.81;
vPrev.copy(this.pos);
this.vel.copy(this.forward).multiplyScalar(this.speed);
this.pos.addScaledVector(this.vel, dt);
if (this.pos.y > 14000) this.pos.y = 14000;
this.prevPos = vPrev;
this.syncMesh();
}
checkGround() {
const floor = this.game.terrain.floorAt(this.pos.x, this.pos.z);
if (this.pos.y < floor + 3) {
this.pos.y = floor + 3;
this.hp = 0;
this.destroy();
}
}
syncMesh() {
this.mesh.position.copy(this.pos);
this.mesh.quaternion.copy(this.quat);
}
updateVisuals(dt, time, fx) {
const u = this.mesh.userData;
u.flameUniforms.uTime.value = time;
u.flameUniforms.uPower.value = clamp(0.35 + this.throttle * 0.9, 0.15, 1.3);
for (const f of u.flames) f.scale.z = 0.5 + Math.max(0, this.throttle) * 1.1;
this.damageFlash = Math.max(0, this.damageFlash - dt * 1.5);
if (!this.alive) return;
const g = Math.abs(this.gLoad);
const wet = this.game.inCloud > 0.05;
if (g > 4.5 || wet) {
const s = clamp((g - 4.5) / 3, 0, 1) + (wet ? 0.6 : 0);
for (const tip of u.wingtips) {
const a = tip.clone().applyQuaternion(this.quat).add(this.pos);
const b = a.clone().addScaledVector(this.vel, -1 / 60);
fx.vapor(a, b, Math.min(1, s));
}
}
if (this.hp < 50) {
const n = u.nozzles[0].clone().applyQuaternion(this.quat).add(this.pos);
fx.damageSmoke(n, this.vel);
}
}
}
import * as THREE from 'three';
import { clamp } from './config.js';
const MAX_DROPS = 320;
const DROP_VERT = /* glsl */ `
attribute vec2 iPos;
attribute vec3 iShape;
attribute float iAngle;
attribute float iAlpha;
varying vec2 vL;
varying vec3 vShape;
varying float vAlpha;
void main() {
vec2 local = position.xy * iShape.xy;
float c = cos(iAngle), s = sin(iAngle);
vec2 rp = vec2(local.x * c - local.y * s, local.x * s + local.y * c);
vL = local;
vShape = iShape;
vAlpha = iAlpha;
gl_Position = projectionMatrix * modelViewMatrix * vec4(iPos + rp, 0.0, 1.0);
}
`;
// Teardrop height field: round head in front, tapering tail behind. Normal comes from screen-space derivatives.
const DROP_FRAG = /* glsl */ `
varying vec2 vL;
varying vec3 vShape;
varying float vAlpha;
void main() {
float hl = vShape.x, R = vShape.z;
vec2 hc = vec2(hl - R, 0.0);
vec2 dh = (vL - hc) / R;
float hh = 1.0 - dot(dh, dh);
float tx = clamp((hc.x - vL.x) / max(hc.x + hl, 1e-3), 0.0, 1.0);
float tw = R * 0.55 * (1.0 - tx);
float ht = (vL.x < hc.x && tw > 0.01) ? (1.0 - pow(vL.y / tw, 2.0)) * (1.0 - tx) * 0.6 : 0.0;
float h = max(max(hh, ht), 0.0);
if (h <= 0.0) discard;
vec2 g = vec2(dFdx(h), dFdy(h)) * R;
float a = smoothstep(0.0, 0.2, h) * vAlpha;
gl_FragColor = vec4(clamp(g * 0.25 + 0.5, 0.0, 1.0), h, a);
}
`;
// Screen-space water droplets that bead up inside clouds and get blown outward by the airflow.
export class ScreenRain {
constructor() {
this.drops = [];
this.spawnAcc = 0;
this.wet = 0;
this.streak = 0;
this.scene = new THREE.Scene();
this.camera = new THREE.OrthographicCamera(0, 1, 1, 0, -1, 1);
const base = new THREE.PlaneGeometry(2, 2);
const g = new THREE.InstancedBufferGeometry();
g.index = base.index;
g.setAttribute('position', base.getAttribute('position'));
this.aPos = new THREE.InstancedBufferAttribute(new Float32Array(MAX_DROPS * 2), 2);
this.aShape = new THREE.InstancedBufferAttribute(new Float32Array(MAX_DROPS * 3), 3);
this.aAngle = new THREE.InstancedBufferAttribute(new Float32Array(MAX_DROPS), 1);
this.aAlpha = new THREE.InstancedBufferAttribute(new Float32Array(MAX_DROPS), 1);
for (const a of [this.aPos, this.aShape, this.aAngle, this.aAlpha]) a.setUsage(THREE.DynamicDrawUsage);
g.setAttribute('iPos', this.aPos);
g.setAttribute('iShape', this.aShape);
g.setAttribute('iAngle', this.aAngle);
g.setAttribute('iAlpha', this.aAlpha);
g.instanceCount = 0;
this.geometry = g;
const mesh = new THREE.Mesh(g, new THREE.ShaderMaterial({
vertexShader: DROP_VERT,
fragmentShader: DROP_FRAG,
transparent: true,
depthTest: false,
depthWrite: false,
}));
mesh.frustumCulled = false;
this.scene.add(mesh);
}
setSize(w, h) {
this.w = w;
this.h = h;
this.camera.right = w;
this.camera.top = h;
this.camera.updateProjectionMatrix();
}
clear() {
this.drops.length = 0;
this.wet = 0;
this.streak = 0;
}
// inCloud: 0..1, speed: m/s, flow: screen uv the airflow radiates from
update(dt, inCloud, speed, flow) {
const { w, h } = this;
const sF = clamp((speed - 60) / 260, 0, 1.4);
const k = w / 960;
this.wet += ((inCloud > 0.05 ? Math.min(1, inCloud * 1.5) : 0) - this.wet) * (1 - Math.exp(-dt * (inCloud > 0.05 ? 1.5 : 0.45)));
this.streak += ((inCloud > 0.05 ? sF : 0) - this.streak) * (1 - Math.exp(-dt * 2.0));
this.spawnAcc += inCloud * (30 + 140 * sF) * dt;
while (this.spawnAcc >= 1 && this.drops.length < MAX_DROPS) {
this.spawnAcc -= 1;
const r = (1.5 + Math.pow(Math.random(), 2.5) * 7) * k;
this.drops.push({
x: Math.random() * w, y: Math.random() * h, vx: 0, vy: 0,
r, life: 0, maxLife: 2.5 + Math.random() * 3,
stick: Math.random() * 0.6 * Math.max(0.15, 1.2 - sF),
});
}
if (this.spawnAcc > 1) this.spawnAcc = 0;
const fx = flow.x * w, fy = flow.y * h;
const diag = Math.hypot(w, h) * 0.5;
let n = 0;
for (let i = this.drops.length - 1; i >= 0; i--) {
const d = this.drops[i];
d.life += dt;
if (d.stick > 0) {
d.stick -= dt;
} else {
let dx = d.x - fx, dy = d.y - fy;
const dl = Math.hypot(dx, dy) || 1;
dx /= dl; dy /= dl;
const acc = (120 + 2600 * sF) * (0.25 + dl / diag) * (d.r / (4 * k)) * k;
d.vx += dx * acc * dt;
d.vy += dy * acc * dt - 90 * k * dt;
const drag = Math.exp(-dt * 1.2);
d.vx *= drag; d.vy *= drag;
d.x += d.vx * dt;
d.y += d.vy * dt;
}
const m = 60 * k;
if (d.life > d.maxLife || d.x < -m || d.y < -m || d.x > w + m || d.y > h + m) {
this.drops[i] = this.drops[this.drops.length - 1];
this.drops.pop();
continue;
}
const v = Math.hypot(d.vx, d.vy);
const hl = d.r + Math.min(v * 0.05, d.r * 9);
const fade = Math.min(1, d.life / 0.15) * Math.min(1, (d.maxLife - d.life) / 0.6);
this.aPos.array[n * 2] = d.x;
this.aPos.array[n * 2 + 1] = d.y;
this.aShape.array[n * 3] = hl;
this.aShape.array[n * 3 + 1] = d.r;
this.aShape.array[n * 3 + 2] = d.r;
this.aAngle.array[n] = v > 1 ? Math.atan2(d.vy, d.vx) : 0;
this.aAlpha.array[n] = fade;
n++;
}
this.geometry.instanceCount = n;
for (const a of [this.aPos, this.aShape, this.aAngle, this.aAlpha]) a.needsUpdate = true;
}
render(renderer, target) {
renderer.setRenderTarget(target);
renderer.setClearColor(0x808000, 0);
renderer.clear(true, false, false);
renderer.render(this.scene, this.camera);
}
}
import * as THREE from 'three';
import { buildMissile } from './aircraft.js';
const SEEKER_ANGLE = 0.5;
const SEEKER_RANGE = 3400;
const LOCK_TIME = 0.45;
const GUN_RATE = 18;
const BULLET_SPEED = 1100;
const MAX_BULLETS = 300;
const vA = new THREE.Vector3();
const vB = new THREE.Vector3();
const vC = new THREE.Vector3();
const qA = new THREE.Quaternion();
const FWD = new THREE.Vector3(0, 0, -1);
function segmentSphere(a, b, c, r) {
vA.subVectors(b, a);
const len2 = vA.lengthSq();
const t = len2 > 0 ? Math.max(0, Math.min(1, vB.subVectors(c, a).dot(vA) / len2)) : 0;
vC.copy(a).addScaledVector(vA, t);
return vC.distanceToSquared(c) <= r * r;
}
class Missile {
constructor(owner, pos, dir, speed, target, def, mesh) {
this.owner = owner;
this.pos = pos.clone();
this.prev = pos.clone();
this.dir = dir.clone().normalize();
this.speed = speed;
this.target = target;
this.def = def;
this.mesh = mesh;
this.life = 0;
this.lost = false;
this.dead = false;
}
}
const PLAYER_MSL = { maxSpeed: 650, accel: 320, turn: 2.6, life: 7, prox: 18, damage: 100 };
const ENEMY_MSL = { maxSpeed: 560, accel: 260, turn: 1.55, life: 8, prox: 15, damage: 34 };
export class Weapons {
constructor(game) {
this.game = game;
this.missiles = [];
this.bullets = [];
this.tracerGeo = new THREE.BufferGeometry();
this.tracerPos = new THREE.BufferAttribute(new Float32Array(MAX_BULLETS * 6), 3).setUsage(THREE.DynamicDrawUsage);
this.tracerGeo.setAttribute('position', this.tracerPos);
this.tracers = new THREE.LineSegments(this.tracerGeo, new THREE.LineBasicMaterial({
color: new THREE.Color(6, 4.5, 2),
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
}));
this.tracers.frustumCulled = false;
game.scene.add(this.tracers);
this.reset();
}
reset() {
for (const m of this.missiles) this.game.scene.remove(m.mesh);
this.missiles.length = 0;
this.bullets.length = 0;
this.gunAmmo = 1600;
this.missileAmmo = 64;
this.pylonReady = [0, 0];
this.nextPylon = 0;
this.gunCd = 0;
this.muzzle = 0;
this.target = null;
this.lockProgress = 0;
this.locked = false;
this.lockState = 'none';
}
get alertMissile() {
let best = null, bd = Infinity;
for (const m of this.missiles) {
if (m.owner === 'player' || m.dead || m.lost) continue;
const d = m.pos.distanceTo(this.game.player.pos);
if (d < bd) { bd = d; best = m; }
}
return best ? { missile: best, dist: bd } : null;
}
incomingFor(e) {
for (const m of this.missiles) {
if (m.owner === 'player' && m.target === e && !m.lost && !m.dead) return m;
}
return null;
}
update(dt, input) {
const p = this.game.player;
if (p.alive) {
this.updateTargeting(dt, input);
this.updateGun(dt, input);
this.updatePylons(dt);
if (input.missile) this.firePlayerMissile();
}
this.updateMissiles(dt);
this.updateBullets(dt);
}
candidates() {
return this.game.enemies.list.filter((e) => e.alive);
}
scoreTarget(e) {
const p = this.game.player;
vA.subVectors(e.pos, p.pos);
const d = vA.length();
const ang = p.forward.angleTo(vA);
return ang * 3000 + d;
}
updateTargeting(dt, input) {
const list = this.candidates();
if (!this.target?.alive) this.target = null;
if (!this.target && list.length) this.target = list.reduce((a, b) => (this.scoreTarget(a) < this.scoreTarget(b) ? a : b));
if (input.switchTarget && list.length > 1) {
const sorted = list.sort((a, b) => this.scoreTarget(a) - this.scoreTarget(b));
const i = sorted.indexOf(this.target);
this.target = sorted[(i + 1) % sorted.length];
this.lockProgress = 0;
}
const t = this.target;
if (!t) {
this.lockProgress = 0;
this.locked = false;
this.lockState = 'none';
return;
}
const p = this.game.player;
vA.subVectors(t.pos, p.pos);
const d = vA.length();
this.targetDist = d;
const inSeeker = d < SEEKER_RANGE && p.forward.angleTo(vA) < SEEKER_ANGLE;
if (inSeeker) this.lockProgress = Math.min(1, this.lockProgress + dt / LOCK_TIME);
else this.lockProgress = Math.max(0, this.lockProgress - dt * 4);
this.locked = this.lockProgress >= 1;
if (this.locked) this.lockState = 'lock';
else if (inSeeker) this.lockState = 'seek';
else this.lockState = 'none';
}
updatePylons(dt) {
const u = this.game.player.mesh.userData;
for (let i = 0; i < 2; i++) {
this.pylonReady[i] = Math.max(0, this.pylonReady[i] - dt);
u.pylonMissiles[i].visible = this.pylonReady[i] <= 0 && this.missileAmmo > i;
}
}
firePlayerMissile() {
if (this.missileAmmo <= 0) return;
let i = this.nextPylon;
if (this.pylonReady[i] > 0) i = 1 - i;
if (this.pylonReady[i] > 0) return;
const p = this.game.player;
const u = p.mesh.userData;
const pos = u.pylons[i].clone().applyQuaternion(p.quat).add(p.pos);
const dir = p.forward.clone();
const target = this.locked ? this.target : null;
const mesh = buildMissile();
this.game.scene.add(mesh);
const m = new Missile('player', pos, dir, p.speed, target, PLAYER_MSL, mesh);
m.dropVel = p.up.clone().multiplyScalar(-12);
this.missiles.push(m);
this.missileAmmo--;
this.pylonReady[i] = 1.6;
this.nextPylon = 1 - i;
this.game.audio.missileLaunch();
}
launchEnemyMissile(e, target) {
const pos = e.pos.clone().addScaledVector(e.forward, 6);
const mesh = buildMissile(0x9a9a8a);
this.game.scene.add(mesh);
this.missiles.push(new Missile('enemy', pos, e.forward, e.speed, target, ENEMY_MSL, mesh));
if (Math.random() < 0.35) this.game.mission.radioEnemyLaunch(e);
}
updateMissiles(dt) {
const g = this.game;
for (let i = this.missiles.length - 1; i >= 0; i--) {
const m = this.missiles[i];
m.life += dt;
m.prev.copy(m.pos);
m.speed = Math.min(m.def.maxSpeed, m.speed + m.def.accel * dt);
const boosting = m.life > 0.25;
if (boosting) this.guide(m, dt);
m.pos.addScaledVector(m.dir, m.speed * dt);
if (!boosting && m.dropVel) m.pos.addScaledVector(m.dropVel, dt);
m.mesh.position.copy(m.pos);
m.mesh.quaternion.copy(qA.setFromUnitVectors(FWD, m.dir));
if (boosting) g.fx.missileTrail(m.pos, m.prev);
this.checkMissileHit(m);
if (!m.dead && m.pos.y < g.terrain.floorAt(m.pos.x, m.pos.z)) {
g.fx.smallBlast(m.pos);
m.dead = true;
}
if (!m.dead && m.life > m.def.life) {
g.fx.smallBlast(m.pos);
if (m.owner === 'player' && m.target && !m.lost) g.hud.message('MISSED', 'amber');
m.dead = true;
}
if (m.dead) {
g.scene.remove(m.mesh);
this.missiles.splice(i, 1);
}
}
}
guide(m, dt) {
const t = m.target;
if (!t || m.lost || t.alive === false) return;
vA.subVectors(t.pos, m.pos);
const d = vA.length();
if (m.dir.angleTo(vA) > 1.4) {
m.lost = true;
if (m.owner === 'player') this.game.hud.message('MISSED', 'amber');
return;
}
const tgo = d / Math.max(m.speed, 200);
vB.copy(t.pos).addScaledVector(t.vel, tgo).sub(m.pos).normalize();
const ang = m.dir.angleTo(vB);
if (ang > 1e-4) {
const maxA = m.def.turn * dt;
vC.crossVectors(m.dir, vB).normalize();
m.dir.applyAxisAngle(vC, Math.min(ang, maxA)).normalize();
}
}
checkMissileHit(m) {
const g = this.game;
if (m.owner === 'enemy') {
const p = g.player;
if (p.alive && segmentSphere(m.prev, m.pos, p.pos, m.def.prox)) {
m.dead = true;
g.fx.explosion(m.pos, p.vel, 0.6);
g.audio.explosion(0);
g.audio.hit();
g.chase.addShake(1.2);
p.applyDamage(m.def.damage);
g.mission.onPlayerHit();
}
return;
}
const targets = m.target ? [m.target] : this.candidates();
for (const e of targets) {
if (!e.alive) continue;
const r = m.target ? m.def.prox + e.hitRadius * 0.5 : e.hitRadius;
if (!segmentSphere(m.prev, m.pos, e.pos, r)) continue;
m.dead = true;
g.fx.smallBlast(m.pos);
const killed = g.enemies.damage(e, m.def.damage, true);
g.hud.message(killed ? 'DESTROYED' : 'HIT', killed ? 'red' : 'green');
return;
}
}
updateGun(dt, input) {
const p = this.game.player;
this.gunCd -= dt;
if (!input.gun || this.gunAmmo <= 0) {
this.game.audio.gun(false);
return;
}
this.game.audio.gun(true);
while (this.gunCd <= 0 && this.gunAmmo > 0) {
this.gunCd += 1 / GUN_RATE;
this.gunAmmo--;
this.muzzle = 1 - this.muzzle;
const dir = p.forward.clone();
const t = this.target;
if (t?.alive) {
vA.subVectors(t.pos, p.pos);
const d = vA.length();
const lead = vB.copy(t.pos).addScaledVector(t.vel, d / BULLET_SPEED).sub(p.pos).normalize();
if (d < 1500 && dir.angleTo(lead) < 0.07) dir.copy(lead);
}
dir.x += (Math.random() - 0.5) * 0.006;
dir.y += (Math.random() - 0.5) * 0.006;
dir.normalize();
const pos = new THREE.Vector3(this.muzzle ? 0.9 : -0.9, 0.2, -6).applyQuaternion(p.quat).add(p.pos);
const vel = dir.multiplyScalar(BULLET_SPEED).add(p.vel);
if (this.bullets.length < MAX_BULLETS) this.bullets.push({ pos, prev: pos.clone(), vel, life: 0 });
this.game.fx.spark(pos);
}
}
updateBullets(dt) {
const g = this.game;
const arr = this.tracerPos.array;
let n = 0;
for (let i = this.bullets.length - 1; i >= 0; i--) {
const b = this.bullets[i];
b.life += dt;
b.prev.copy(b.pos);
b.pos.addScaledVector(b.vel, dt);
let dead = b.life > 1.6;
for (const e of this.candidates()) {
if (dead) break;
if (segmentSphere(b.prev, b.pos, e.pos, e.hitRadius)) {
dead = true;
g.fx.spark(b.pos);
if (g.enemies.damage(e, 7, true)) g.hud.message('DESTROYED', 'red');
}
}
if (!dead && b.pos.y < g.terrain.floorAt(b.pos.x, b.pos.z)) dead = true;
if (dead) {
this.bullets[i] = this.bullets[this.bullets.length - 1];
this.bullets.pop();
continue;
}
const k = n * 6;
arr[k] = b.pos.x; arr[k + 1] = b.pos.y; arr[k + 2] = b.pos.z;
arr[k + 3] = b.pos.x - b.vel.x * 0.02;
arr[k + 4] = b.pos.y - b.vel.y * 0.02;
arr[k + 5] = b.pos.z - b.vel.z * 0.02;
n++;
}
this.tracerGeo.setDrawRange(0, n * 2);
this.tracerPos.needsUpdate = true;
}
}
export { SEEKER_ANGLE, SEEKER_RANGE };
import * as THREE from 'three';
import { Perlin } from './noise.js';
import { WORLD, clamp, smoothstep } from './config.js';
// 2D weather map: R = coverage, G = cloud top height. Shared by GPU (clouds, shadows) and CPU (in-cloud test).
export class Weather {
constructor() {
const res = WORLD.weatherRes;
this.res = res;
this.cov = new Float32Array(res * res);
this.type = new Float32Array(res * res);
const pa = new Perlin(5), pb = new Perlin(6);
const data = new Uint8Array(res * res * 4);
for (let v = 0; v < res; v++) {
for (let u = 0; u < res; u++) {
const x = u / res, y = v / res;
const n = fbmPeriodic(pa, x, y, 4, 5);
const t = fbmPeriodic(pb, x, y, 3, 3);
const cov = smoothstep(-0.3, 0.22, n);
const type = clamp(t * 1.1 + 0.5, 0, 1);
const i = v * res + u;
this.cov[i] = Math.round(cov * 255) / 255;
this.type[i] = Math.round(type * 255) / 255;
data[i * 4] = Math.round(cov * 255);
data[i * 4 + 1] = Math.round(type * 255);
data[i * 4 + 3] = 255;
}
}
const tex = new THREE.DataTexture(data, res, res, THREE.RGBAFormat, THREE.UnsignedByteType);
tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
tex.magFilter = THREE.LinearFilter;
tex.minFilter = THREE.LinearFilter;
tex.needsUpdate = true;
this.texture = tex;
}
// Bilinear sample matching GPU LinearFilter + RepeatWrapping.
sample(x, z, out) {
const res = this.res;
const fu = (x / WORLD.weatherSize) * res - 0.5;
const fv = (z / WORLD.weatherSize) * res - 0.5;
const iu = Math.floor(fu), iv = Math.floor(fv);
const tu = fu - iu, tv = fv - iv;
const u0 = ((iu % res) + res) % res, u1 = (u0 + 1) % res;
const v0 = ((iv % res) + res) % res, v1 = (v0 + 1) % res;
const bl = (arr) => {
const a = arr[v0 * res + u0], b = arr[v0 * res + u1];
const c = arr[v1 * res + u0], d = arr[v1 * res + u1];
return (a + (b - a) * tu) * (1 - tv) + (c + (d - c) * tu) * tv;
};
out.cov = bl(this.cov);
out.type = bl(this.type);
return out;
}
// Rough CPU estimate (0..1) of how deep inside a cloud the point is.
cloudAmount(p) {
const w = this.sample(p.x, p.z, this._tmp || (this._tmp = {}));
const top = WORLD.cloudBottom + (WORLD.cloudTop - WORLD.cloudBottom) * (0.45 + 0.55 * w.type);
const h = (p.y - WORLD.cloudBottom) / (top - WORLD.cloudBottom);
if (h <= 0 || h >= 1 || w.cov < 0.03) return 0;
const hg = smoothstep(0, 0.12, h) * (1 - smoothstep(0.45, 1, h));
const base = ((0.8 * hg - (1 - w.cov)) / w.cov) * w.cov;
return clamp(base * 4, 0, 1);
}
}
function fbmPeriodic(p, x, y, baseFreq, octaves) {
let s = 0, amp = 1, norm = 0, f = baseFreq;
for (let o = 0; o < octaves; o++) {
s += p.noise2(x * f, y * f, f) * amp;
norm += amp;
amp *= 0.5;
f *= 2;
}
return s / norm;
}
import * as THREE from 'three';
import { Perlin } from './noise.js';
import { WORLD, BASE_POS, SUN_DIR, SUN_COLOR, clamp, lerp, smoothstep } from './config.js';
import { ATMOSPHERE, NOISE2 } from './shaders/common.js';
export function makeSharedUniforms(weather) {
return {
uSunDir: { value: SUN_DIR },
uSunColor: { value: new THREE.Vector3(SUN_COLOR.r, SUN_COLOR.g, SUN_COLOR.b) },
uCamPos: { value: new THREE.Vector3() },
tWeather: { value: weather.texture },
uWeatherSize: { value: WORLD.weatherSize },
uCloudMid: { value: (WORLD.cloudBottom + WORLD.cloudTop) * 0.5 },
uSea: { value: WORLD.seaLevel },
uTime: { value: 0 },
};
}
const WORLD_VERT = /* glsl */ `
varying vec3 vWorld;
varying vec3 vNormal;
void main() {
vec4 wp = modelMatrix * vec4(position, 1.0);
vWorld = wp.xyz;
vNormal = normalize(mat3(modelMatrix) * normal);
gl_Position = projectionMatrix * viewMatrix * wp;
}
`;
const CLOUD_SHADOW = /* glsl */ `
uniform sampler2D tWeather;
uniform float uWeatherSize;
uniform float uCloudMid;
float cloudShadow(vec3 wp) {
vec3 sp = wp + uSunDir * ((uCloudMid - wp.y) / max(uSunDir.y, 0.1));
float cov = texture2D(tWeather, sp.xz / uWeatherSize).r;
return 1.0 - 0.8 * smoothstep(0.2, 0.6, cov);
}
`;
const TERRAIN_FRAG = /* glsl */ `
uniform vec3 uCamPos;
uniform float uSea;
varying vec3 vWorld;
varying vec3 vNormal;
${ATMOSPHERE}
${NOISE2}
${CLOUD_SHADOW}
void main() {
vec2 xz = vWorld.xz;
float dn = fbm2(xz * 0.012);
float e = 0.35;
float gx = fbm2((xz + vec2(e, 0.0)) * 0.012) - dn;
float gz = fbm2((xz + vec2(0.0, e)) * 0.012) - dn;
vec3 n = normalize(normalize(vNormal) + vec3(-gx, 0.0, -gz) * 6.0);
float slope = 1.0 - n.y;
float h = vWorld.y + (dn - 0.5) * 180.0;
vec3 grass = mix(vec3(0.06, 0.10, 0.04), vec3(0.12, 0.13, 0.06), vnoise(xz * 0.002));
vec3 rock = mix(vec3(0.16, 0.15, 0.14), vec3(0.24, 0.21, 0.18), vnoise(xz * 0.01));
vec3 snow = vec3(0.85, 0.88, 0.94);
vec3 sand = vec3(0.34, 0.31, 0.24);
vec3 col = grass;
col = mix(col, sand, 1.0 - smoothstep(uSea + 4.0, uSea + 30.0, vWorld.y));
col = mix(col, rock, smoothstep(0.22, 0.42, slope + (dn - 0.5) * 0.25));
col = mix(col, rock, smoothstep(900.0, 1400.0, h) * 0.7);
float snowAmt = smoothstep(1550.0, 1850.0, h) * (1.0 - smoothstep(0.45, 0.7, slope));
col = mix(col, snow, snowAmt);
float shadow = cloudShadow(vWorld);
float ndl = max(dot(n, uSunDir), 0.0);
vec3 amb = mix(vec3(0.18, 0.20, 0.24), vec3(0.34, 0.44, 0.60), n.y * 0.5 + 0.5);
vec3 lit = col * (uSunColor * ndl * shadow * 2.4 + amb * (0.55 + 0.45 * shadow));
vec3 toP = vWorld - uCamPos;
float dist = length(toP);
vec3 rd = toP / dist;
vec3 hv = normalize(uSunDir - rd);
lit += snowAmt * uSunColor * pow(max(dot(n, hv), 0.0), 40.0) * 0.4 * shadow;
lit = mix(lit, fogColor(rd), heightFog(uCamPos, rd, dist));
gl_FragColor = vec4(lit, 1.0);
}
`;
const WATER_FRAG = /* glsl */ `
uniform vec3 uCamPos;
uniform float uTime;
varying vec3 vWorld;
${ATMOSPHERE}
${NOISE2}
${CLOUD_SHADOW}
void main() {
vec2 xz = vWorld.xz;
float a = vnoise(xz * 0.02 + uTime * 0.05);
float b = vnoise(xz * 0.05 - uTime * 0.08);
vec3 n = normalize(vec3((a - 0.5) * 0.12, 1.0, (b - 0.5) * 0.12));
vec3 toP = vWorld - uCamPos;
float dist = length(toP);
vec3 rd = toP / dist;
vec3 r = reflect(rd, n);
r.y = abs(r.y);
float fres = 0.02 + 0.98 * pow(1.0 - max(dot(-rd, n), 0.0), 5.0);
float shadow = cloudShadow(vWorld);
vec3 deep = vec3(0.01, 0.04, 0.06) * (0.4 + 0.6 * shadow);
vec3 col = mix(deep, skyColor(r) * (0.5 + 0.5 * shadow), fres);
col += uSunColor * pow(max(dot(r, uSunDir), 0.0), 600.0) * 8.0 * shadow;
col = mix(col, fogColor(rd), heightFog(uCamPos, rd, dist));
gl_FragColor = vec4(col, 1.0);
}
`;
const SKY_VERT = /* glsl */ `
varying vec3 vDir;
void main() {
vDir = normalize(position);
vec4 p = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
gl_Position = p.xyww;
}
`;
const SKY_FRAG = /* glsl */ `
varying vec3 vDir;
${ATMOSPHERE}
void main() {
vec3 rd = normalize(vDir);
vec3 col = skyColor(rd);
float sd = dot(rd, uSunDir);
col += uSunColor * smoothstep(0.99975, 0.99992, sd) * 40.0;
gl_FragColor = vec4(col, 1.0);
}
`;
export class Terrain {
constructor(uniforms) {
const N = WORLD.terrainSegments;
const S = WORLD.terrainSize;
this.n = N;
this.cell = S / N;
this.half = S / 2;
this.heights = new Float32Array((N + 1) * (N + 1));
const p = new Perlin(42), p2 = new Perlin(99);
for (let j = 0; j <= N; j++) {
for (let i = 0; i <= N; i++) {
this.heights[j * (N + 1) + i] = heightFn(-this.half + i * this.cell, -this.half + j * this.cell, p, p2);
}
}
this.mesh = new THREE.Mesh(this.buildGeometry(), new THREE.ShaderMaterial({
uniforms,
vertexShader: WORLD_VERT,
fragmentShader: TERRAIN_FRAG,
}));
this.mesh.frustumCulled = false;
}
buildGeometry() {
const N = this.n, W = N + 1, H = this.heights, c = this.cell;
const pos = new Float32Array(W * W * 3);
const nor = new Float32Array(W * W * 3);
const at = (i, j) => H[clamp(j, 0, N) * W + clamp(i, 0, N)];
for (let j = 0; j <= N; j++) {
for (let i = 0; i <= N; i++) {
const k = (j * W + i) * 3;
pos[k] = -this.half + i * c;
pos[k + 1] = at(i, j);
pos[k + 2] = -this.half + j * c;
const nx = -(at(i + 1, j) - at(i - 1, j)) / (2 * c);
const nz = -(at(i, j + 1) - at(i, j - 1)) / (2 * c);
const l = Math.hypot(nx, 1, nz);
nor[k] = nx / l; nor[k + 1] = 1 / l; nor[k + 2] = nz / l;
}
}
const idx = new Uint32Array(N * N * 6);
let o = 0;
for (let j = 0; j < N; j++) {
for (let i = 0; i < N; i++) {
const a = j * W + i, b = a + 1, cc = a + W, d = cc + 1;
idx[o++] = a; idx[o++] = cc; idx[o++] = b;
idx[o++] = b; idx[o++] = cc; idx[o++] = d;
}
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
g.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
g.setIndex(new THREE.BufferAttribute(idx, 1));
return g;
}
heightAt(x, z) {
const N = this.n, W = N + 1;
const fx = (x + this.half) / this.cell, fz = (z + this.half) / this.cell;
if (fx < 0 || fz < 0 || fx >= N || fz >= N) return -300;
const i = Math.floor(fx), j = Math.floor(fz);
const tx = fx - i, tz = fz - j;
const H = this.heights;
const a = H[j * W + i], b = H[j * W + i + 1], c = H[(j + 1) * W + i], d = H[(j + 1) * W + i + 1];
return lerp(lerp(a, b, tx), lerp(c, d, tx), tz);
}
// Ground or sea, whichever is higher.
floorAt(x, z) {
return Math.max(this.heightAt(x, z), WORLD.seaLevel);
}
}
function heightFn(x, z, p, p2) {
let base = 0, amp = 1, f = 1 / 9000;
for (let o = 0; o < 4; o++) { base += p.noise2(x * f + 31.7, z * f - 12.1) * amp; amp *= 0.5; f *= 2; }
base = base * 260 + 150;
const m = p2.noise2(x / 18000 + 3.1, z / 18000 - 7.3) + 0.5 * p2.noise2(x / 9000 + 1.7, z / 9000 + 4.2);
const mask = smoothstep(-0.2, 0.45, m);
let r = 0, w = 1;
amp = 1; f = 1 / 6500;
for (let o = 0; o < 6; o++) {
let n = 1 - Math.abs(p.noise2(x * f + 11.3, z * f - 5.7));
n *= n;
n *= w;
w = clamp(n * 1.8, 0, 1);
r += n * amp;
amp *= 0.5;
f *= 2.03;
}
let h = base + mask * Math.pow(r / 1.3, 1.6) * 1800;
const db = Math.hypot(x - BASE_POS.x, z - BASE_POS.z);
h = lerp(h, BASE_POS.y, smoothstep(3800, 1700, db));
const e = Math.max(Math.abs(x), Math.abs(z));
return lerp(h, -300, smoothstep(17000, 23500, e));
}
export function makeWater(uniforms) {
const g = new THREE.PlaneGeometry(400000, 400000, 1, 1);
g.rotateX(-Math.PI / 2);
const m = new THREE.Mesh(g, new THREE.ShaderMaterial({
uniforms,
vertexShader: WORLD_VERT,
fragmentShader: WATER_FRAG,
}));
m.position.y = WORLD.seaLevel;
m.frustumCulled = false;
return m;
}
export function makeSky(uniforms, radius = 200000) {
const m = new THREE.Mesh(
new THREE.SphereGeometry(radius, 48, 24),
new THREE.ShaderMaterial({
uniforms,
vertexShader: SKY_VERT,
fragmentShader: SKY_FRAG,
side: THREE.BackSide,
depthWrite: false,
}),
);
m.frustumCulled = false;
m.renderOrder = -10;
return m;
}
export function makeAirBase() {
const g = new THREE.Group();
const tarmac = new THREE.MeshStandardMaterial({ color: 0x3b3d40, roughness: 0.9 });
const bldg = new THREE.MeshStandardMaterial({ color: 0x777a72, roughness: 0.8 });
const stripe = new THREE.MeshStandardMaterial({ color: 0xdedede, roughness: 0.7 });
const runway = new THREE.Mesh(new THREE.BoxGeometry(60, 1, 3000), tarmac);
g.add(runway);
for (let z = -1400; z <= 1400; z += 100) {
const s = new THREE.Mesh(new THREE.BoxGeometry(2, 1.1, 40), stripe);
s.position.set(0, 0.05, z);
g.add(s);
}
const apron = new THREE.Mesh(new THREE.BoxGeometry(300, 1, 600), tarmac);
apron.position.set(220, 0, 0);
g.add(apron);
for (let i = 0; i < 5; i++) {
const h = new THREE.Mesh(new THREE.BoxGeometry(50, 18, 60), bldg);
h.position.set(400, 9, -240 + i * 120);
g.add(h);
}
const tower = new THREE.Mesh(new THREE.CylinderGeometry(6, 8, 45, 10), bldg);
tower.position.set(160, 22, 380);
g.add(tower);
g.position.copy(BASE_POS);
g.position.y += 0.5;
return g;
}
// Shared sky / fog model so terrain, water and clouds blend into the same atmosphere.
export const ATMOSPHERE = /* glsl */ `
uniform vec3 uSunDir;
uniform vec3 uSunColor;
vec3 skyColor(vec3 rd) {
float y = rd.y;
vec3 zenith = vec3(0.09, 0.22, 0.52);
vec3 horizon = vec3(0.56, 0.66, 0.80);
vec3 ground = vec3(0.34, 0.38, 0.44);
vec3 col = y > 0.0
? mix(horizon, zenith, pow(y, 0.5))
: mix(horizon, ground, pow(min(-y * 3.0, 1.0), 0.6));
float sd = max(dot(rd, uSunDir), 0.0);
col += uSunColor * (0.30 * pow(sd, 6.0) + 0.55 * pow(sd, 48.0));
return col;
}
vec3 fogColor(vec3 rd) {
return skyColor(normalize(vec3(rd.x, max(rd.y, 0.02), rd.z)));
}
float heightFog(vec3 ro, vec3 rd, float dist) {
const float a = 0.000035;
const float b = 0.00028;
float k = rd.y * b;
float base = a * exp(-ro.y * b);
float od = abs(k) < 1e-7 ? base * dist : base * (1.0 - exp(-dist * k)) / k;
return 1.0 - exp(-max(od, 0.0));
}
`;
export const NOISE2 = /* glsl */ `
float hash12(vec2 p) {
vec3 p3 = fract(vec3(p.xyx) * 0.1031);
p3 += dot(p3, p3.yzx + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
float vnoise(vec2 p) {
vec2 i = floor(p), f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x),
mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y);
}
float fbm2(vec2 p) {
float s = 0.0, a = 0.5;
for (int i = 0; i < 4; i++) { s += a * vnoise(p); p = p * 2.03 + 17.1; a *= 0.5; }
return s;
}
`;
html, body {
margin: 0;
height: 100%;
overflow: hidden;
background: #000;
font-family: Menlo, Consolas, "DejaVu Sans Mono", monospace;
color: #9dffb5;
}
canvas { position: fixed; inset: 0; width: 100%; height: 100%; display: block; }
#hud { pointer-events: none; }
.overlay {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: radial-gradient(ellipse at center, rgba(0, 10, 6, 0.35), rgba(0, 0, 0, 0.75));
}
.hidden { display: none !important; }
.panel {
max-width: 640px;
padding: 32px 40px;
border: 1px solid rgba(140, 255, 170, 0.5);
background: rgba(0, 18, 10, 0.55);
box-shadow: 0 0 40px rgba(80, 255, 140, 0.12) inset;
}
.panel.small { text-align: center; min-width: 360px; }
.kicker { letter-spacing: 0.4em; font-size: 12px; opacity: 0.7; }
h1 { margin: 4px 0 18px; font-size: 44px; letter-spacing: 0.25em; font-weight: 400; }
h2 { margin: 0 0 16px; font-size: 28px; letter-spacing: 0.2em; font-weight: 400; }
.brief { font-size: 13px; line-height: 1.6; opacity: 0.9; margin-bottom: 18px; }
.controls { width: 100%; border-collapse: collapse; font-size: 12px; }
.controls td { padding: 3px 6px; border-bottom: 1px solid rgba(140, 255, 170, 0.15); }
.controls td:first-child { opacity: 0.7; }
.loading { margin-top: 20px; font-size: 13px; opacity: 0.8; }
.start { margin-top: 20px; font-size: 16px; letter-spacing: 0.2em; animation: blink 1.2s steps(2) infinite; }
.stats { font-size: 14px; line-height: 1.8; white-space: pre; text-align: left; display: inline-block; }
@keyframes blink { 50% { opacity: 0.35; } }
Click the game to give it keyboard focus, or open it full screen. Quality presets use the q URL parameter: ?q=low, ?q=high (default), ?q=ultra.
- Built an arcade flight-combat game in three.js with one mission: find and destroy enemy fighters hiding in a storm front, then stop a bomber strike on the air base.
- Rendered volumetric clouds by raymarching a 3D noise texture driven by a 2D weather map, composited in a multi-pass render pipeline.
- Added screen-space rain with a water-droplet simulation, procedural terrain, sea and sky shaders, and baked Blender models for the aircraft.
- Wrote an arcade flight model, enemy AI (fighter, ace, bomber), missiles and guns, with keyboard and gamepad input.