Initial commit: Orbiter Game

Interactive 2D orbital flight simulator (HTML/CSS/JS, no dependencies).
Newtonian gravity with RK4 integration, three scenarios (Surface Launch,
Low Orbit, Station Rendezvous), trajectory prediction, camera/zoom,
keyboard + touch controls, and automated unit + smoke tests.
This commit is contained in:
michael committed 2026-10-03 10:34:59 +00:00
commit b926fa2a78
11 files changed
+2337

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
/*
* Orbital Flight Simulator - input: keyboard + touch buttons.
* Produces a stable input object { thrust: 0..1, torque: -1..1 } each frame.
*/
(function (global) {
'use strict';
function Controls() {
this.input = { thrust: 0, torque: 0 };
this.keys = Object.create(null);
this.touch = { thrust: 0, torque: 0 };
}
Controls.prototype.attach = function (game, ui) {
var self = this;
var keydown = function (e) {
if (e.repeat) return;
var k = e.code;
self.keys[k] = true;
if (k === 'Space' || k === 'ArrowUp' || k === 'ArrowDown' || k === 'ArrowLeft' || k === 'ArrowRight') {
e.preventDefault();
}
self.update();
switch (k) {
case 'KeyP':
case 'Escape': game.togglePause(); break;
case 'KeyR': game.reset(); break;
case 'KeyT': game.togglePrediction(); break;
case 'KeyC': game.centerOnPlanet(); break;
case 'KeyH': ui.showTutorial(); break;
case 'Digit1': case 'Numpad1': game.setUserTimeScale(1); break;
case 'Digit2': case 'Numpad2': game.setUserTimeScale(2); break;
case 'Digit3': case 'Numpad3': game.setUserTimeScale(5); break;
case 'Digit4': case 'Numpad4': game.setUserTimeScale(10); break;
case 'Equal': case 'NumpadAdd': game.zoomBy(1.25); break;
case 'Minus': case 'NumpadSubtract': game.zoomBy(0.8); break;
}
};
var keyup = function (e) {
self.keys[e.code] = false;
self.update();
};
global.addEventListener('keydown', keydown);
global.addEventListener('keyup', keyup);
// If the window/tab loses focus mid-keypress, the keyup event is lost and
// thrust/rotation would stick. Clear everything on blur.
var clearInput = function () {
for (var k in self.keys) self.keys[k] = false;
self.touch.thrust = 0;
self.touch.torque = 0;
self.update();
};
global.addEventListener('blur', clearInput);
if (document && document.addEventListener) {
document.addEventListener('blur', clearInput);
document.addEventListener('visibilitychange', function () {
if (document.hidden) clearInput();
});
}
var canvas = document.getElementById('game');
if (canvas && canvas.addEventListener) {
canvas.addEventListener('wheel', function (e) {
e.preventDefault();
game.zoomBy(Math.exp(-e.deltaY * 0.0012));
}, { passive: false });
}
var bindHold = function (id, prop, value) {
var el = document.getElementById(id);
if (!el || !el.addEventListener) return;
var down = function (e) {
e.preventDefault();
self.touch[prop] = value;
self.update();
el.classList.add('active');
};
var up = function () {
self.touch[prop] = 0;
self.update();
el.classList.remove('active');
};
el.addEventListener('pointerdown', down);
el.addEventListener('pointerup', up);
el.addEventListener('pointercancel', up);
el.addEventListener('pointerleave', up);
};
bindHold('btn-thrust', 'thrust', 1);
bindHold('btn-left', 'torque', -1);
bindHold('btn-right', 'torque', 1);
var timeBtn = document.getElementById('btn-time');
if (timeBtn && timeBtn.addEventListener) {
timeBtn.addEventListener('click', function () { game.cycleTimeScale(); });
}
};
Controls.prototype.update = function () {
var k = this.keys;
var keyThrust = (k['KeyW'] || k['ArrowUp'] || k['Space']) ? 1 : 0;
var keyTorque = 0;
if (k['KeyA'] || k['ArrowLeft']) keyTorque -= 1;
if (k['KeyD'] || k['ArrowRight']) keyTorque += 1;
this.input.thrust = Math.max(keyThrust, this.touch.thrust);
this.input.torque = keyTorque !== 0 ? keyTorque : this.touch.torque;
};
global.Controls = Controls;
})(typeof window !== 'undefined' ? window : globalThis);
+363
View File
@@ -0,0 +1,363 @@
/*
* Orbital Flight Simulator - game orchestration.
* Owns the fixed-timestep loop, camera, time acceleration, scenarios,
* docking/landing/crash resolution, and visual exhaust particles.
*/
(function (global) {
'use strict';
var P = global.OrbitalPhysics;
var TIME_SCALES = [1, 2, 5, 10];
var SCENARIOS = {
launch: {
id: 'launch',
name: 'Surface Launch',
blurb: 'Liftoff from the launch pad. Establish a stable orbit.',
goal: 'orbit',
goalText: 'Goal: bound orbit with periapsis above 150 m',
setup: function (world) {
var R = world.planetRadius;
// ship sits on the +x axis; "away from the planet" is +x => angle 0
var ship = P.createShip({ x: R + 10, y: 0, angle: 0, fuel: 100 });
var r = 1800;
var v = Math.sqrt(world.mu / r);
var station = P.createStation({ x: 0, y: -r, vx: v, radius: 12 });
return { ship: ship, station: station };
}
},
loworbit: {
id: 'loworbit',
name: 'Low Orbit',
blurb: 'You are already orbiting. Rendezvous with the station.',
goal: 'station',
goalText: 'Goal: dock with the station (inside ring, low rel. speed)',
setup: function (world) {
var r = 1400;
var v = Math.sqrt(world.mu / r);
var ship = P.createShip({ x: r, y: 0, vy: v, angle: Math.PI / 2, fuel: 60 });
var rs = 1800;
var vs = Math.sqrt(world.mu / rs);
var station = P.createStation({ x: 0, y: -rs, vx: vs, radius: 12 });
return { ship: ship, station: station };
}
},
rendezvous: {
id: 'rendezvous',
name: 'Station Rendezvous',
blurb: 'You are on an elliptical orbit below the station. Match it and dock.',
goal: 'station',
goalText: 'Goal: dock with the station (inside ring, low rel. speed)',
setup: function (world) {
var r = 1600;
var v = Math.sqrt(world.mu / r) * 1.08;
var ship = P.createShip({ x: r, y: 0, vy: v, angle: Math.PI / 2, fuel: 80 });
var rs = 1800;
var vs = Math.sqrt(world.mu / rs);
var station = P.createStation({ x: 0, y: -rs, vx: vs, radius: 12 });
return { ship: ship, station: station };
}
}
};
function Game(renderer, ui) {
this.renderer = renderer;
this.ui = ui;
this.world = P.createWorld({});
this.ship = null;
this.station = null;
this.scenarioId = null;
this.status = 'idle'; // idle | ready | flying | landed | crashed | docked
this.paused = false;
this.userTimeScale = 1;
this.timeScale = 1;
this.accumulator = 0;
this.simTime = 0;
this.prediction = null;
this.showPrediction = true;
this.predictTimer = 0;
this.goalReached = false;
this.crashInfo = null;
this.exhaust = [];
this.camera = { x: 0, y: 0, zoom: 0.4, targetZoom: 0.4 };
this.cameraFollowPlanet = false;
this.lastNow = null;
this.frameDt = 0;
var self = this;
this.frame = function (now) { self.frameImpl(now); };
}
Game.prototype.defaultZoom = function () {
var minDim = Math.min(this.renderer.w, this.renderer.h);
return minDim / (this.world.planetRadius * 4.5);
};
Game.prototype.toMenu = function () {
this.status = 'idle';
this.ship = null;
this.station = null;
this.prediction = null;
this.exhaust = [];
if (this.ui) this.ui.hideHud();
};
Game.prototype.loadScenario = function (id) {
var sc = SCENARIOS[id];
if (!sc) return;
this.scenarioId = id;
var built = sc.setup(this.world);
this.ship = built.ship;
this.station = built.station;
// Surface Launch waits on the pad until the player first thrusts; the other
// scenarios start flying immediately.
var ready = sc.id === 'launch';
this.status = ready ? 'ready' : 'flying';
this.ship.state = ready ? 'ready' : 'flying';
this.paused = false;
this.userTimeScale = 1;
this.timeScale = 1;
this.accumulator = 0;
this.simTime = 0;
this.goalReached = false;
this.crashInfo = null;
this.exhaust = [];
this.camera.x = this.ship.pos.x;
this.camera.y = this.ship.pos.y;
this.camera.zoom = this.defaultZoom();
this.camera.targetZoom = this.camera.zoom;
this.cameraFollowPlanet = false;
this.updatePrediction(true);
this.ui.showScenario(sc);
};
// Begin the Surface Launch flight: called the first time the player thrusts
// while in the 'ready' state. The clock and accumulator are reset so a long
// wait on the pad cannot cause a physics jump when launch finally begins.
Game.prototype.beginLaunch = function () {
this.status = 'flying';
this.ship.state = 'flying';
this.accumulator = 0;
this.simTime = 0;
};
Game.prototype.reset = function () {
if (this.scenarioId) this.loadScenario(this.scenarioId);
};
Game.prototype.togglePause = function () {
if (this.status !== 'idle') this.paused = !this.paused;
};
Game.prototype.setUserTimeScale = function (s) {
this.userTimeScale = s;
};
Game.prototype.cycleTimeScale = function () {
var i = TIME_SCALES.indexOf(this.userTimeScale);
this.userTimeScale = TIME_SCALES[(i + 1) % TIME_SCALES.length];
};
Game.prototype.togglePrediction = function () {
this.showPrediction = !this.showPrediction;
if (!this.showPrediction) this.prediction = null;
};
Game.prototype.zoomBy = function (f) {
var minDim = Math.min(this.renderer.w, this.renderer.h);
var minZ = minDim / (this.world.planetRadius * 14);
var maxZ = 4;
this.camera.targetZoom = Math.min(maxZ, Math.max(minZ, this.camera.targetZoom * f));
};
// Toggle the camera target between following the ship and staying centered
// on the planet (press C). The planet is static, so "following" it simply
// keeps the whole scene in view; the camera pans smoothly (see updateCamera).
Game.prototype.centerOnPlanet = function () {
this.cameraFollowPlanet = !this.cameraFollowPlanet;
};
// Reduce time acceleration near the surface or while close to the station.
Game.prototype.effectiveTimeScale = function () {
var limit = 10;
var info = P.orbitInfo(this.world, this.ship.pos, this.ship.vel);
if (info.altitude < 600) limit = 1;
var d = Math.sqrt(
(this.ship.pos.x - this.station.pos.x) * (this.ship.pos.x - this.station.pos.x) +
(this.ship.pos.y - this.station.pos.y) * (this.ship.pos.y - this.station.pos.y)
);
if (d < 500) limit = Math.min(limit, 1);
return Math.min(this.userTimeScale, limit);
};
// One fixed physics tick.
Game.prototype.step = function (dt) {
var world = this.world;
var ship = this.ship;
var station = this.station;
P.stepStation(world, station, dt);
this.simTime += dt;
if (ship.state === 'docked') {
var dx0 = ship.pos.x - station.pos.x;
var dy0 = ship.pos.y - station.pos.y;
var d0 = Math.sqrt(dx0 * dx0 + dy0 * dy0) || 1;
var off0 = station.radius + ship.radius + 3;
ship.pos = { x: station.pos.x + (dx0 / d0) * off0, y: station.pos.y + (dy0 / d0) * off0 };
ship.vel = { x: station.vel.x, y: station.vel.y };
ship.time += dt;
return;
}
if (ship.state !== 'flying') return;
var input = this.controls ? this.controls.input : { thrust: 0, torque: 0 };
P.stepShip(world, ship, input, dt);
var c = P.checkSurface(world, ship);
if (c.type !== 'none') {
if (c.type === 'land') {
ship.state = 'landed';
var n = P.norm({ x: ship.pos.x - world.planet.x, y: ship.pos.y - world.planet.y });
var sr = world.planetRadius + ship.radius * 0.4;
ship.pos = { x: world.planet.x + n.x * sr, y: world.planet.y + n.y * sr };
ship.vel = { x: 0, y: 0 };
ship.angVel = 0;
ship.angle = Math.atan2(n.y, n.x) + Math.PI / 2;
this.status = 'landed';
} else {
ship.state = 'crashed';
this.status = 'crashed';
this.crashInfo = c;
}
return;
}
var dx = ship.pos.x - station.pos.x;
var dy = ship.pos.y - station.pos.y;
var d = Math.sqrt(dx * dx + dy * dy);
var rel = Math.sqrt(
(ship.vel.x - station.vel.x) * (ship.vel.x - station.vel.x) +
(ship.vel.y - station.vel.y) * (ship.vel.y - station.vel.y)
);
if (d < world.dockDistance && rel < world.dockSpeed) {
ship.state = 'docked';
this.status = 'docked';
var off = station.radius + ship.radius + 3;
ship.pos = { x: station.pos.x + (dx / (d || 1)) * off, y: station.pos.y + (dy / (d || 1)) * off };
ship.vel = { x: station.vel.x, y: station.vel.y };
return;
}
if (!this.goalReached && SCENARIOS[this.scenarioId].goal === 'orbit') {
var info = P.orbitInfo(world, ship.pos, ship.vel);
if (info.bound && info.periapsis > world.planetRadius + 150 && info.apoapsis < world.planetRadius * 5) {
this.goalReached = true;
this.ui._set('goal-text', 'ORBIT ACHIEVED — now dock with the station');
}
}
};
Game.prototype.updateExhaust = function (frameDt) {
var ship = this.ship;
if (ship && ship.state === 'flying' && this.controls && this.controls.input.thrust > 0 && ship.fuel > 0) {
var count = Math.max(1, Math.round(120 * frameDt));
var dx = Math.cos(ship.angle);
var dy = Math.sin(ship.angle);
for (var i = 0; i < count; i++) {
var spread = (Math.random() - 0.5) * 0.5;
var ca = Math.cos(spread);
var sa = Math.sin(spread);
var bx = dx * ca - dy * sa;
var by = dx * sa + dy * ca;
var spd = 250 + Math.random() * 150;
this.exhaust.push({
x: ship.pos.x - dx * 10,
y: ship.pos.y - dy * 10,
vx: ship.vel.x - bx * spd,
vy: ship.vel.y - by * spd,
life: 0.35 + Math.random() * 0.2,
maxLife: 0.55,
size: 1.5 + Math.random() * 2
});
}
}
for (var j = this.exhaust.length - 1; j >= 0; j--) {
var p = this.exhaust[j];
p.life -= frameDt;
if (p.life <= 0) { this.exhaust.splice(j, 1); continue; }
p.x += p.vx * frameDt;
p.y += p.vy * frameDt;
}
if (this.exhaust.length > 500) this.exhaust.splice(0, this.exhaust.length - 500);
};
Game.prototype.updateCamera = function (frameDt) {
if (!this.ship) return;
var cam = this.camera;
var k = 1 - Math.exp(-4 * frameDt);
var tx = this.cameraFollowPlanet ? this.world.planet.x : this.ship.pos.x;
var ty = this.cameraFollowPlanet ? this.world.planet.y : this.ship.pos.y;
cam.x += (tx - cam.x) * k;
cam.y += (ty - cam.y) * k;
cam.zoom += (cam.targetZoom - cam.zoom) * (1 - Math.exp(-8 * frameDt));
};
Game.prototype.updatePrediction = function (frameDt, force) {
if (!this.showPrediction) { this.prediction = null; return; }
this.predictTimer -= frameDt;
if (!force && this.predictTimer > 0) return;
this.predictTimer = 0.25;
if (this.ship && this.ship.state === 'flying') {
this.prediction = P.predictTrajectory(this.world, this.ship, {
dt: this.world.fixedDt * 2,
maxSteps: 3000,
sampleEvery: 3
});
} else {
this.prediction = null;
}
};
// Main loop: fixed-timestep accumulator so physics is frame-rate independent.
Game.prototype.frameImpl = function (now) {
if (this.lastNow === null) this.lastNow = now;
var frameDt = (now - this.lastNow) / 1000;
this.lastNow = now;
if (frameDt < 0) frameDt = 0;
if (frameDt > 0.25) frameDt = 0.25; // clamp hitches (tab switch etc.)
this.frameDt = frameDt;
// Surface Launch: the clock is stopped on the pad until the player first
// thrusts. Starting here (before the physics block) means the very first
// thrust is applied this same frame.
if (this.status === 'ready' && !this.paused &&
this.controls && this.controls.input.thrust > 0) {
this.beginLaunch();
}
if (!this.paused && this.status !== 'idle' && this.status !== 'ready') {
this.timeScale = this.effectiveTimeScale();
this.accumulator += frameDt * this.timeScale;
var dt = this.world.fixedDt;
var n = 0;
while (this.accumulator >= dt && n < 4000) {
this.step(dt);
this.accumulator -= dt;
n++;
}
if (n >= 4000) this.accumulator = 0; // spiral-of-death guard
}
this.updateExhaust(frameDt);
this.updateCamera(frameDt);
this.updatePrediction(frameDt);
this.renderer.render(this);
this.ui.update(this);
global.requestAnimationFrame(this.frame);
};
global.Game = Game;
global.SCENARIOS = SCENARIOS;
})(typeof window !== 'undefined' ? window : globalThis);
+44
View File
@@ -0,0 +1,44 @@
/*
* Orbital Flight Simulator - boot.
* Wires renderer, UI, game and controls together and starts the RAF loop.
* In Node (smoke test) boot() is exported and driven manually.
*/
(function (global) {
'use strict';
function boot() {
var canvas = document.getElementById('game');
var renderer = new global.Renderer(canvas);
var game = new global.Game(renderer, null);
var ui = new global.UI(game);
game.ui = ui;
var controls = new global.Controls();
game.controls = controls;
controls.attach(game, ui);
// start on the menu; ship is null until a scenario is chosen
ui.showMenu();
var coarse = global.matchMedia && global.matchMedia('(pointer: coarse)').matches;
var touch = document.getElementById('touch-controls');
if (touch) touch.classList.toggle('hidden', !coarse);
global.requestAnimationFrame(game.frame);
return { renderer: renderer, game: game, ui: ui, controls: controls };
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = { boot: boot };
}
global.BootOrbitalSim = boot;
// Auto-start in a real browser (skipped under the Node smoke test).
if (typeof window !== 'undefined' && !global.__nodeSmoke) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', boot);
} else {
boot();
}
}
})(typeof window !== 'undefined' ? window : globalThis);
+283
View File
@@ -0,0 +1,283 @@
/*
* Orbital Flight Simulator - physics core.
* Pure module: no DOM dependencies. Usable in the browser (window.OrbitalPhysics)
* and in Node (module.exports) for automated tests.
*
* Units: meters, seconds. Newtonian point-mass gravity: a = -mu * r_vec / |r|^3.
* Integration: classic RK4 on (pos, vel) with a FIXED timestep. Rotation is
* integrated with semi-implicit Euler (it is decoupled from the orbital motion).
*/
(function (global) {
'use strict';
var TAU = Math.PI * 2;
function len(v) { return Math.sqrt(v.x * v.x + v.y * v.y); }
function norm(v) {
var l = len(v);
return l > 1e-12 ? { x: v.x / l, y: v.y / l } : { x: 1, y: 0 };
}
function createWorld(opts) {
opts = opts || {};
return {
mu: opts.mu !== undefined ? opts.mu : 3e8,
planetRadius: opts.planetRadius !== undefined ? opts.planetRadius : 1000,
planet: { x: opts.planetX || 0, y: opts.planetY || 0 },
fixedDt: opts.fixedDt || 1 / 120,
landSpeed: opts.landSpeed !== undefined ? opts.landSpeed : 30,
landTangential: opts.landTangential !== undefined ? opts.landTangential : 50,
dockDistance: opts.dockDistance !== undefined ? opts.dockDistance : 20,
dockSpeed: opts.dockSpeed !== undefined ? opts.dockSpeed : 8
};
}
function createShip(opts) {
opts = opts || {};
var fuel = opts.fuel !== undefined ? opts.fuel : 100;
return {
pos: { x: opts.x || 0, y: opts.y || 0 },
vel: { x: opts.vx || 0, y: opts.vy || 0 },
angle: opts.angle || 0,
angVel: 0,
fuel: fuel,
maxFuel: fuel,
thrustAccel: opts.thrustAccel !== undefined ? opts.thrustAccel : 600,
fuelRate: opts.fuelRate !== undefined ? opts.fuelRate : 4,
radius: opts.radius !== undefined ? opts.radius : 6,
rotAccel: opts.rotAccel !== undefined ? opts.rotAccel : 5,
rotMax: opts.rotMax !== undefined ? opts.rotMax : 2.4,
state: 'flying',
time: 0
};
}
function createStation(opts) {
opts = opts || {};
return {
pos: { x: opts.x || 0, y: opts.y || 0 },
vel: { x: opts.vx || 0, y: opts.vy || 0 },
radius: opts.radius !== undefined ? opts.radius : 12,
angle: 0
};
}
// Newtonian gravity: acceleration toward the planet center, magnitude mu/r^2.
function gravityAt(world, pos) {
var dx = world.planet.x - pos.x;
var dy = world.planet.y - pos.y;
var r2 = dx * dx + dy * dy;
var r = Math.sqrt(r2);
var g = world.mu / r2;
return { x: (dx / r) * g, y: (dy / r) * g };
}
function accelAt(world, pos, angle, thrustMag) {
var g = gravityAt(world, pos);
if (thrustMag <= 0) return g;
return {
x: g.x + Math.cos(angle) * thrustMag,
y: g.y + Math.sin(angle) * thrustMag
};
}
// Classic RK4 step of the (pos, vel) state. The ship angle (and hence thrust
// direction) is held constant during the substep, which is exact to O(dt^2)
// for the rotation and negligible at our fixed dt.
function rk4Step(world, pos, vel, angle, thrustMag, dt) {
var k1v = accelAt(world, pos, angle, thrustMag);
var k1x = vel;
var p2 = { x: pos.x + k1x.x * dt * 0.5, y: pos.y + k1x.y * dt * 0.5 };
var v2 = { x: vel.x + k1v.x * dt * 0.5, y: vel.y + k1v.y * dt * 0.5 };
var k2v = accelAt(world, p2, angle, thrustMag);
var k2x = v2;
var p3 = { x: pos.x + k2x.x * dt * 0.5, y: pos.y + k2x.y * dt * 0.5 };
var v3 = { x: vel.x + k2v.x * dt * 0.5, y: vel.y + k2v.y * dt * 0.5 };
var k3v = accelAt(world, p3, angle, thrustMag);
var k3x = v3;
var p4 = { x: pos.x + k3x.x * dt, y: pos.y + k3x.y * dt };
var v4 = { x: vel.x + k3v.x * dt, y: vel.y + k3v.y * dt };
var k4v = accelAt(world, p4, angle, thrustMag);
var k4x = v4;
return {
pos: {
x: pos.x + (dt / 6) * (k1x.x + 2 * k2x.x + 2 * k3x.x + k4x.x),
y: pos.y + (dt / 6) * (k1x.y + 2 * k2x.y + 2 * k3x.y + k4x.y)
},
vel: {
x: vel.x + (dt / 6) * (k1v.x + 2 * k2v.x + 2 * k3v.x + k4v.x),
y: vel.y + (dt / 6) * (k1v.y + 2 * k2v.y + 2 * k3v.y + k4v.y)
}
};
}
// Advance the ship by dt. input = { thrust: 0..1, torque: -1..1 }.
function stepShip(world, ship, input, dt) {
input = input || { thrust: 0, torque: 0 };
if (ship.state !== 'flying') return;
var thrustLevel = Math.min(1, Math.max(0, input.thrust));
var wantsThrust = thrustLevel > 0 && ship.fuel > 0;
var thrustMag = wantsThrust ? ship.thrustAccel * thrustLevel : 0;
var s = rk4Step(world, ship.pos, ship.vel, ship.angle, thrustMag, dt);
ship.pos = s.pos;
ship.vel = s.vel;
if (input.torque > 0) {
ship.angVel = Math.min(ship.rotMax, ship.angVel + ship.rotAccel * dt);
} else if (input.torque < 0) {
ship.angVel = Math.max(-ship.rotMax, ship.angVel - ship.rotAccel * dt);
} else {
ship.angVel *= Math.max(0, 1 - 6 * dt);
if (Math.abs(ship.angVel) < 0.02) ship.angVel = 0;
}
ship.angle += ship.angVel * dt;
if (wantsThrust) {
ship.fuel = Math.max(0, ship.fuel - ship.fuelRate * thrustLevel * dt);
}
ship.time += dt;
}
// The station coasts on the same integrator (gravity only).
function stepStation(world, station, dt) {
var s = rk4Step(world, station.pos, station.vel, 0, 0, dt);
station.pos = s.pos;
station.vel = s.vel;
station.angle = (station.angle || 0) + dt * 0.3;
}
// Orbital elements from state vectors (two-body).
function orbitInfo(world, pos, vel) {
var dx = pos.x - world.planet.x;
var dy = pos.y - world.planet.y;
var r = Math.sqrt(dx * dx + dy * dy);
var v2 = vel.x * vel.x + vel.y * vel.y;
var speed = Math.sqrt(v2);
var energy = v2 / 2 - world.mu / r;
var bound = energy < 0;
var rv = (dx * vel.x + dy * vel.y) / r;
var h = dx * vel.y - dy * vel.x;
var eVec = {
x: ((v2 - world.mu / r) * dx - (dx * vel.x + dy * vel.y) * vel.x) / world.mu,
y: ((v2 - world.mu / r) * dy - (dx * vel.x + dy * vel.y) * vel.y) / world.mu
};
var e = Math.sqrt(eVec.x * eVec.x + eVec.y * eVec.y);
// semi-latus rectum p = h^2/mu (always >= 0). Periapsis = p/(1+e) is the
// correct positive closest-approach distance for BOTH ellipses and hyperbolas
// (the a*(1-e) / a*(e-1) forms go negative for unbound trajectories).
var p = (h * h) / world.mu;
var info = {
r: r,
speed: speed,
energy: energy,
bound: bound,
altitude: r - world.planetRadius,
radialVelocity: rv,
eccentricity: e,
h: h,
prograde: norm(vel)
};
if (bound) {
var a = -world.mu / (2 * energy);
info.semiMajor = a;
info.periapsis = p / (1 + e);
info.apoapsis = p / (1 - e);
info.period = TAU * Math.sqrt((a * a * a) / world.mu);
} else {
info.semiMajor = -world.mu / (2 * energy); // negative for hyperbola
info.periapsis = p / (1 + e); // positive closest-approach distance
info.apoapsis = Infinity;
info.period = Infinity;
info.escapeVelocity = Math.sqrt(2 * world.mu / r);
info.vinf = Math.sqrt(2 * energy);
}
return info;
}
// Surface interaction. Returns { type: 'none' | 'land' | 'crash', ... }.
function checkSurface(world, ship) {
var dx = ship.pos.x - world.planet.x;
var dy = ship.pos.y - world.planet.y;
var r = Math.sqrt(dx * dx + dy * dy);
var surfaceR = world.planetRadius + ship.radius * 0.4;
if (r > surfaceR) return { type: 'none' };
var n = { x: dx / r, y: dy / r }; // outward normal
var closing = -(ship.vel.x * n.x + ship.vel.y * n.y); // >0 when falling in
var tangent = Math.abs(ship.vel.x * -n.y + ship.vel.y * n.x);
// ship "down" vector; alignment near 1 means belly toward the surface
var down = { x: Math.cos(ship.angle + Math.PI / 2), y: Math.sin(ship.angle + Math.PI / 2) };
var align = -(down.x * n.x + down.y * n.y);
if (closing < world.landSpeed && tangent < world.landTangential && align > 0.5) {
return { type: 'land' };
}
return { type: 'crash', impactSpeed: Math.sqrt(ship.vel.x * ship.vel.x + ship.vel.y * ship.vel.y) };
}
// Coasting prediction using the EXACT same integrator as the simulation.
// Returns { points: [{x,y}], result: {type:'none'|'crash'|'land'|'far'} }.
function predictTrajectory(world, ship, opts) {
opts = opts || {};
var dt = opts.dt || world.fixedDt * 2;
var maxSteps = opts.maxSteps || 4000;
var sampleEvery = opts.sampleEvery || 4;
var maxRadius = opts.maxRadius || world.planetRadius * 12;
var pos = { x: ship.pos.x, y: ship.pos.y };
var vel = { x: ship.vel.x, y: ship.vel.y };
var points = [];
var result = { type: 'none' };
for (var i = 0; i < maxSteps; i++) {
var s = rk4Step(world, pos, vel, ship.angle, 0, dt);
pos = s.pos;
vel = s.vel;
if ((i + 1) % sampleEvery === 0) points.push({ x: pos.x, y: pos.y });
var r = Math.sqrt(
(pos.x - world.planet.x) * (pos.x - world.planet.x) +
(pos.y - world.planet.y) * (pos.y - world.planet.y)
);
if (r > maxRadius) { result = { type: 'far' }; break; }
var c = checkSurface(world, { pos: pos, vel: vel, angle: ship.angle, radius: ship.radius });
if (c.type !== 'none') {
result = c;
points.push({ x: pos.x, y: pos.y });
break;
}
}
return { points: points, result: result, dt: dt };
}
var api = {
TAU: TAU,
len: len,
norm: norm,
createWorld: createWorld,
createShip: createShip,
createStation: createStation,
gravityAt: gravityAt,
accelAt: accelAt,
rk4Step: rk4Step,
stepShip: stepShip,
stepStation: stepStation,
orbitInfo: orbitInfo,
checkSurface: checkSurface,
predictTrajectory: predictTrajectory
};
if (typeof module !== 'undefined' && module.exports) module.exports = api;
global.OrbitalPhysics = api;
})(typeof window !== 'undefined' ? window : globalThis);
+348
View File
@@ -0,0 +1,348 @@
/*
* Orbital Flight Simulator - canvas renderer.
* Pure drawing: reads game state, never mutates physics.
*/
(function (global) {
'use strict';
var P = global.OrbitalPhysics;
function Renderer(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.dpr = 1;
this.w = 800;
this.h = 600;
this.stars = [];
for (var i = 0; i < 350; i++) {
this.stars.push({
x: Math.random() * 2048,
y: Math.random() * 2048,
r: Math.random() * 1.3 + 0.4,
b: Math.random() * 0.6 + 0.25,
p: 0.03 + Math.random() * 0.12 // parallax factor
});
}
this.resize();
var self = this;
global.addEventListener('resize', function () { self.resize(); });
}
Renderer.prototype.resize = function () {
var dpr = global.devicePixelRatio || 1;
var w = this.canvas.clientWidth || global.innerWidth || 800;
var h = this.canvas.clientHeight || global.innerHeight || 600;
this.dpr = dpr;
this.w = w;
this.h = h;
this.canvas.width = Math.max(1, Math.round(w * dpr));
this.canvas.height = Math.max(1, Math.round(h * dpr));
};
Renderer.prototype.toScreen = function (x, y, cam) {
return {
x: (x - cam.x) * cam.zoom + this.w / 2,
y: (y - cam.y) * cam.zoom + this.h / 2
};
};
Renderer.prototype.render = function (game) {
var ctx = this.ctx;
ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0);
ctx.fillStyle = '#04060d';
ctx.fillRect(0, 0, this.w, this.h);
var cam = game.camera;
this.drawStars(cam);
this.drawPlanet(game);
this.drawTrajectory(game);
this.drawStation(game);
this.drawExhaust(game);
this.drawShip(game);
this.drawMarkers(game);
};
Renderer.prototype.drawStars = function (cam) {
var ctx = this.ctx;
var T = 2048;
for (var i = 0; i < this.stars.length; i++) {
var s = this.stars[i];
var ox = ((s.x - cam.x * s.p) % T + T) % T;
var oy = ((s.y - cam.y * s.p) % T + T) % T;
for (var dx = -T; dx <= this.w; dx += T) {
for (var dy = -T; dy <= this.h; dy += T) {
var x = ox + dx;
var y = oy + dy;
if (x < -2 || y < -2 || x > this.w + 2 || y > this.h + 2) continue;
ctx.globalAlpha = s.b;
ctx.fillStyle = '#cdd8ff';
ctx.fillRect(x, y, s.r, s.r);
}
}
}
ctx.globalAlpha = 1;
};
Renderer.prototype.drawPlanet = function (game) {
var ctx = this.ctx;
var cam = game.camera;
var world = game.world;
var c = this.toScreen(world.planet.x, world.planet.y, cam);
var R = world.planetRadius * cam.zoom;
if (c.x + R < -150 || c.y + R < -150 || c.x - R > this.w + 150 || c.y - R > this.h + 150) return;
// atmosphere glow
var glow = ctx.createRadialGradient(c.x, c.y, Math.max(0, R * 0.92), c.x, c.y, R * 1.18);
glow.addColorStop(0, 'rgba(90,160,255,0)');
glow.addColorStop(0.5, 'rgba(90,160,255,0.28)');
glow.addColorStop(1, 'rgba(90,160,255,0)');
ctx.fillStyle = glow;
ctx.beginPath();
ctx.arc(c.x, c.y, R * 1.18, 0, P.TAU);
ctx.fill();
// body
var g = ctx.createRadialGradient(c.x - R * 0.35, c.y - R * 0.35, R * 0.1, c.x, c.y, R);
g.addColorStop(0, '#7ec8e3');
g.addColorStop(0.4, '#3a7ca5');
g.addColorStop(0.75, '#1d4e6b');
g.addColorStop(1, '#0c2438');
ctx.fillStyle = g;
ctx.beginPath();
ctx.arc(c.x, c.y, R, 0, P.TAU);
ctx.fill();
// craters when zoomed in
if (R > 120) {
ctx.save();
ctx.beginPath();
ctx.arc(c.x, c.y, R, 0, P.TAU);
ctx.clip();
for (var i = 0; i < 14; i++) {
var a = (i * 137.5 * Math.PI) / 180;
var rr = (0.15 + 0.75 * ((i * 0.618) % 1)) * R;
var cx = c.x + Math.cos(a) * rr;
var cy = c.y + Math.sin(a) * rr;
var cr = (0.04 + 0.09 * ((i * 0.37) % 1)) * R;
ctx.fillStyle = 'rgba(10,30,45,0.35)';
ctx.beginPath();
ctx.arc(cx, cy, cr, 0, P.TAU);
ctx.fill();
}
ctx.restore();
}
};
Renderer.prototype.drawTrajectory = function (game) {
if (!game.prediction || game.prediction.points.length < 2) return;
var ctx = this.ctx;
var cam = game.camera;
var info = P.orbitInfo(game.world, game.ship.pos, game.ship.vel);
var res = game.prediction.result;
ctx.save();
ctx.setLineDash([6, 6]);
ctx.lineWidth = 1.5;
if (res.type === 'crash') ctx.strokeStyle = 'rgba(255,90,70,0.9)';
else if (info.bound) ctx.strokeStyle = 'rgba(90,255,160,0.8)';
else ctx.strokeStyle = 'rgba(255,170,60,0.8)';
ctx.beginPath();
var started = false;
for (var i = 0; i < game.prediction.points.length; i++) {
var p = game.prediction.points[i];
var s = this.toScreen(p.x, p.y, cam);
if (s.x < -50 || s.x > this.w + 50 || s.y < -50 || s.y > this.h + 50) { started = false; continue; }
if (!started) { ctx.moveTo(s.x, s.y); started = true; }
else ctx.lineTo(s.x, s.y);
}
ctx.stroke();
ctx.setLineDash([]);
if (res.type === 'crash' || res.type === 'land') {
var last = game.prediction.points[game.prediction.points.length - 1];
var ls = this.toScreen(last.x, last.y, cam);
ctx.strokeStyle = res.type === 'crash' ? '#ff5a46' : '#7dff9a';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(ls.x - 7, ls.y - 7);
ctx.lineTo(ls.x + 7, ls.y + 7);
ctx.moveTo(ls.x + 7, ls.y - 7);
ctx.lineTo(ls.x - 7, ls.y + 7);
ctx.stroke();
}
ctx.restore();
};
Renderer.prototype.drawStation = function (game) {
var st = game.station;
if (!st) return;
var ctx = this.ctx;
var cam = game.camera;
var s = this.toScreen(st.pos.x, st.pos.y, cam);
if (s.x < -150 || s.x > this.w + 150 || s.y < -150 || s.y > this.h + 150) return;
var R = Math.max(6, st.radius * cam.zoom);
ctx.save();
ctx.translate(s.x, s.y);
// docking ring
ctx.setLineDash([4, 4]);
ctx.strokeStyle = 'rgba(120,220,255,0.5)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.arc(0, 0, game.world.dockDistance * cam.zoom, 0, P.TAU);
ctx.stroke();
ctx.setLineDash([]);
ctx.rotate(st.angle);
var pw = R * 2.2;
var ph = R * 0.9;
ctx.fillStyle = '#2b6cb0';
ctx.strokeStyle = '#9ecbff';
ctx.lineWidth = 1;
ctx.fillRect(-pw - R * 0.4, -ph / 2, pw, ph);
ctx.strokeRect(-pw - R * 0.4, -ph / 2, pw, ph);
ctx.fillRect(R * 0.4, -ph / 2, pw, ph);
ctx.strokeRect(R * 0.4, -ph / 2, pw, ph);
ctx.strokeStyle = '#c8d6e5';
ctx.lineWidth = Math.max(1.5, R * 0.25);
ctx.beginPath();
ctx.moveTo(-R * 2.6, 0);
ctx.lineTo(R * 2.6, 0);
ctx.stroke();
ctx.fillStyle = '#dfe9f5';
ctx.beginPath();
ctx.arc(0, 0, R, 0, P.TAU);
ctx.fill();
ctx.strokeStyle = '#8fa8c4';
ctx.lineWidth = 1;
ctx.stroke();
ctx.restore();
ctx.fillStyle = 'rgba(150,220,255,0.9)';
ctx.font = '11px monospace';
ctx.textAlign = 'center';
ctx.fillText('STATION', s.x, s.y - R * 2.4 - 6);
};
Renderer.prototype.drawExhaust = function (game) {
var ctx = this.ctx;
var cam = game.camera;
for (var i = 0; i < game.exhaust.length; i++) {
var p = game.exhaust[i];
var s = this.toScreen(p.x, p.y, cam);
if (s.x < -20 || s.x > this.w + 20 || s.y < -20 || s.y > this.h + 20) continue;
var t = p.life / p.maxLife;
ctx.globalAlpha = t * 0.8;
ctx.fillStyle = t > 0.5 ? '#ffd166' : '#ff7b4f';
ctx.beginPath();
ctx.arc(s.x, s.y, p.size * (1.6 - t * 0.6), 0, P.TAU);
ctx.fill();
}
ctx.globalAlpha = 1;
};
Renderer.prototype.drawShip = function (game) {
var ship = game.ship;
if (!ship) return;
var ctx = this.ctx;
var cam = game.camera;
var s = this.toScreen(ship.pos.x, ship.pos.y, cam);
ctx.save();
ctx.translate(s.x, s.y);
ctx.rotate(ship.angle);
var L = 16;
var Wd = 8;
if (ship.state === 'crashed') ctx.globalAlpha = 0.5;
ctx.fillStyle = ship.state === 'crashed' ? '#666' : '#e8eef7';
ctx.strokeStyle = '#9fb4cc';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(L, 0);
ctx.lineTo(-L * 0.7, -Wd);
ctx.lineTo(-L * 0.4, 0);
ctx.lineTo(-L * 0.7, Wd);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.fillStyle = '#59d3ff';
ctx.beginPath();
ctx.arc(L * 0.25, 0, 2.5, 0, P.TAU);
ctx.fill();
ctx.restore();
};
Renderer.prototype.drawMarkers = function (game) {
var ship = game.ship;
if (!ship || ship.state !== 'flying') return;
var cam = game.camera;
var ctx = this.ctx;
var s = this.toScreen(ship.pos.x, ship.pos.y, cam);
// prograde (velocity) arrow
var v = ship.vel;
var sp = Math.sqrt(v.x * v.x + v.y * v.y);
if (sp > 1) {
var ux = v.x / sp;
var uy = v.y / sp;
var len = Math.min(90, 24 + sp * 0.12);
var ex = s.x + ux * len;
var ey = s.y + uy * len;
ctx.strokeStyle = 'rgba(90,220,255,0.9)';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(s.x + ux * 18, s.y + uy * 18);
ctx.lineTo(ex, ey);
ctx.stroke();
var hx = -uy;
var hy = ux;
ctx.fillStyle = 'rgba(90,220,255,0.9)';
ctx.beginPath();
ctx.moveTo(ex + ux * 7, ey + uy * 7);
ctx.lineTo(ex - ux * 2 + hx * 4, ey - uy * 2 + hy * 4);
ctx.lineTo(ex - ux * 2 - hx * 4, ey - uy * 2 - hy * 4);
ctx.closePath();
ctx.fill();
}
// off-screen station marker
var st = game.station;
if (st) {
var ss = this.toScreen(st.pos.x, st.pos.y, cam);
var d = Math.sqrt(
(st.pos.x - ship.pos.x) * (st.pos.x - ship.pos.x) +
(st.pos.y - ship.pos.y) * (st.pos.y - ship.pos.y)
);
if (ss.x < 0 || ss.x > this.w || ss.y < 0 || ss.y > this.h) {
var cx = this.w / 2;
var cy = this.h / 2;
var dx = ss.x - cx;
var dy = ss.y - cy;
var scale = Math.min(
(this.w / 2 - 24) / Math.abs(dx || 1e-9),
(this.h / 2 - 24) / Math.abs(dy || 1e-9)
);
var mx = cx + dx * scale;
var my = cy + dy * scale;
ctx.save();
ctx.translate(mx, my);
ctx.rotate(Math.atan2(dy, dx));
ctx.fillStyle = 'rgba(120,220,255,0.95)';
ctx.beginPath();
ctx.moveTo(10, 0);
ctx.lineTo(-6, -6);
ctx.lineTo(-6, 6);
ctx.closePath();
ctx.fill();
ctx.restore();
ctx.font = '10px monospace';
ctx.textAlign = 'center';
ctx.fillText(Math.round(d) + ' m', mx, my + 18);
}
}
};
global.Renderer = Renderer;
})(typeof window !== 'undefined' ? window : globalThis);
+215
View File
@@ -0,0 +1,215 @@
/*
* Orbital Flight Simulator - UI layer.
* Owns all DOM overlays (menu, tutorial, pause, end screens) and the HUD.
* Keeps a reference to the game and pushes state into the DOM each frame.
*/
(function (global) {
'use strict';
var P = global.OrbitalPhysics;
var TUTORIAL = [
{
title: 'Welcome, pilot',
body: 'You are in low orbit around a planet. Your goal is to reach the space station and dock with it.\n\n' +
'Use the controls to maneuver. Watch your fuel — it is limited.'
},
{
title: 'Thrust & rotation',
body: 'W / ↑ or the THRUST button fires your engine in the direction you are facing.\n' +
'A / D or ← / → rotate the ship.\n\n' +
'The cyan arrow shows your velocity (prograde). Burning along it speeds you up; burning opposite (retrograde) slows you down.'
},
{
title: 'Orbits & the flight path',
body: 'The dashed line is your predicted coast path (same physics as the sim).\n\n' +
'Green = a closed, bound orbit. Orange = you will escape the planet. The HUD shows periapsis (lowest) and apoapsis (highest) altitude.\n\n' +
'To raise an orbit, burn prograde. To lower it, burn retrograde.'
},
{
title: 'Time & docking',
body: 'Press 1–4 (or the WARP button) to change time acceleration. It automatically slows near the surface and near the station for precise docking.\n\n' +
'To dock: match the station orbit, then close the distance inside the blue ring while your relative velocity is low.\n\n' +
'Good luck. Press H anytime to re-read this.'
}
];
function UI(game) {
this.game = game;
this.el = {};
var ids = [
'hud', 'hud-left', 'hud-right', 'hud-top', 'hud-dock',
'alt', 'spd', 'fuel-text', 'fuel-bar',
'orbit-bound', 'orbit-peri', 'orbit-apo', 'orbit-ecc', 'orbit-period', 'timescale', 'auto-limit',
'scenario-name', 'goal-text', 'dock-dist', 'dock-rel',
'menu', 'btn-launch', 'btn-orbit', 'btn-rendez',
'tutorial', 'tut-title', 'tut-text', 'tut-step', 'tut-next', 'tut-skip',
'pause-overlay', 'ready-overlay', 'end-overlay', 'end-title', 'end-detail', 'end-reset', 'end-menu',
'btn-pause', 'btn-reset', 'btn-zoom-in', 'btn-zoom-out', 'btn-help',
'touch-controls', 'btn-thrust', 'btn-left', 'btn-right', 'btn-time'
];
for (var i = 0; i < ids.length; i++) {
this.el[ids[i]] = document.getElementById(ids[i]);
}
this.tutIndex = 0;
this.lastBound = null;
this._wire();
}
UI.prototype._wire = function () {
var self = this;
var g = this.game;
function on(id, ev, fn) {
var el = self.el[id];
if (el) el.addEventListener(ev, fn);
}
on('btn-launch', 'click', function () { self.hideMenu(); g.loadScenario('launch'); });
on('btn-orbit', 'click', function () { self.hideMenu(); g.loadScenario('loworbit'); });
on('btn-rendez', 'click', function () { self.hideMenu(); g.loadScenario('rendezvous'); });
on('tut-next', 'click', function () { self.nextTutorial(); });
on('tut-skip', 'click', function () { self.hideTutorial(); });
on('end-reset', 'click', function () { self.hideEnd(); g.reset(); });
on('end-menu', 'click', function () { self.hideEnd(); g.toMenu(); self.showMenu(); });
on('btn-pause', 'click', function () { g.togglePause(); });
on('btn-reset', 'click', function () { g.reset(); });
on('btn-zoom-in', 'click', function () { g.zoomBy(1.3); });
on('btn-zoom-out', 'click', function () { g.zoomBy(1 / 1.3); });
on('btn-help', 'click', function () { self.showTutorial(); });
};
UI.prototype._set = function (id, text) {
var el = this.el[id];
if (el) el.textContent = text;
};
UI.prototype.showMenu = function () {
if (this.el.menu) this.el.menu.classList.remove('hidden');
};
UI.prototype.hideMenu = function () {
if (this.el.menu) this.el.menu.classList.add('hidden');
};
UI.prototype.showScenario = function (sc) {
this._set('scenario-name', sc.name);
this._set('goal-text', sc.goalText);
if (this.el.hud) this.el.hud.classList.remove('hidden');
};
UI.prototype.hideHud = function () {
if (this.el.hud) this.el.hud.classList.add('hidden');
};
UI.prototype.showTutorial = function () {
this.tutIndex = 0;
this.renderTutorial();
if (this.el.tutorial) this.el.tutorial.classList.remove('hidden');
this.game.paused = true;
};
UI.prototype.hideTutorial = function () {
if (this.el.tutorial) this.el.tutorial.classList.add('hidden');
this.game.paused = false;
};
UI.prototype.nextTutorial = function () {
this.tutIndex++;
if (this.tutIndex >= TUTORIAL.length) { this.hideTutorial(); return; }
this.renderTutorial();
};
UI.prototype.renderTutorial = function () {
var t = TUTORIAL[this.tutIndex];
this._set('tut-title', t.title);
this._set('tut-text', t.body);
this._set('tut-step', (this.tutIndex + 1) + ' / ' + TUTORIAL.length);
var next = this.el['tut-next'];
if (next) next.textContent = this.tutIndex === TUTORIAL.length - 1 ? 'Start' : 'Next';
};
UI.prototype.showEnd = function (title, detail, success) {
this._set('end-title', title);
this._set('end-detail', detail);
var t = this.el['end-title'];
if (t) t.style.color = success ? '#7dff9a' : '#ff7b6b';
if (this.el['end-overlay']) this.el['end-overlay'].classList.remove('hidden');
};
UI.prototype.hideEnd = function () {
if (this.el['end-overlay']) this.el['end-overlay'].classList.add('hidden');
};
UI.prototype.update = function (game) {
var ship = game.ship;
if (!ship) return;
var world = game.world;
var info = P.orbitInfo(world, ship.pos, ship.vel);
this._set('alt', Math.max(0, info.altitude).toFixed(0) + ' m');
this._set('spd', info.speed.toFixed(1) + ' m/s');
var f = ship.maxFuel > 0 ? ship.fuel / ship.maxFuel : 0;
this._set('fuel-text', ship.fuel.toFixed(0) + ' / ' + ship.maxFuel.toFixed(0));
var bar = this.el['fuel-bar'];
if (bar) bar.style.width = (f * 100).toFixed(1) + '%';
var boundEl = this.el['orbit-bound'];
if (boundEl) {
if (info.bound) {
boundEl.textContent = 'BOUND ORBIT';
boundEl.style.color = '#7dff9a';
} else {
boundEl.textContent = 'ESCAPE TRAJECTORY';
boundEl.style.color = '#ffb347';
}
}
this._set('orbit-peri', info.bound ? Math.max(0, info.periapsis - world.planetRadius).toFixed(0) + ' m' : '—');
this._set('orbit-apo', info.bound ? Math.max(0, info.apoapsis - world.planetRadius).toFixed(0) + ' m' : '∞');
this._set('orbit-ecc', info.eccentricity.toFixed(3));
this._set('orbit-period', info.bound ? info.period.toFixed(1) + ' s' : '∞');
var limited = game.timeScale < game.userTimeScale;
this._set('timescale', game.timeScale.toFixed(0) + 'x' + (limited ? ' (auto)' : ''));
var auto = this.el['auto-limit'];
if (auto) auto.classList.toggle('hidden', !limited);
var st = game.station;
if (st && (game.scenarioId === 'rendezvous' || game.scenarioId === 'loworbit')) {
var d = Math.sqrt(
(st.pos.x - ship.pos.x) * (st.pos.x - ship.pos.x) +
(st.pos.y - ship.pos.y) * (st.pos.y - ship.pos.y)
);
var rel = Math.sqrt(
(st.vel.x - ship.vel.x) * (st.vel.x - ship.vel.x) +
(st.vel.y - ship.vel.y) * (st.vel.y - ship.vel.y)
);
this._set('dock-dist', 'STATION ' + d.toFixed(0) + ' m');
this._set('dock-rel', 'REL ' + rel.toFixed(1) + ' m/s');
if (this.el['hud-dock']) this.el['hud-dock'].classList.remove('hidden');
} else if (this.el['hud-dock']) {
this.el['hud-dock'].classList.add('hidden');
}
// end / status transitions
if (game.status === 'crashed' && this.lastBound !== 'crashed') {
this.lastBound = 'crashed';
this.showEnd('CRASHED', 'Impact speed ' + (game.crashInfo ? game.crashInfo.impactSpeed.toFixed(0) : '?') + ' m/s. The planet wins this round.', false);
} else if (game.status === 'docked' && this.lastBound !== 'docked') {
this.lastBound = 'docked';
this.showEnd('DOCKED', 'Rendezvous complete. Welcome aboard the station, pilot.', true);
} else if (game.status === 'landed' && this.lastBound !== 'landed') {
this.lastBound = 'landed';
this.showEnd('LANDED', 'You set down gently. A fine landing — but the mission is orbit.', true);
} else if (game.status === 'flying') {
this.lastBound = null;
this.hideEnd();
}
var pauseEl = this.el['pause-overlay'];
if (pauseEl) pauseEl.classList.toggle('hidden', !game.paused || this.el.tutorial && !this.el.tutorial.classList.contains('hidden'));
var readyEl = this.el['ready-overlay'];
if (readyEl) readyEl.classList.toggle('hidden', game.status !== 'ready');
};
global.UI = UI;
})(typeof window !== 'undefined' ? window : globalThis);