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

+338
View File
@@ -0,0 +1,338 @@
/*
* Orbital Flight Simulator - headless smoke test (plain Node, no deps).
* Stubs a minimal DOM/canvas, boots the real app, and pumps the RAF loop
* manually to verify it starts, loads a scenario, and responds to input.
* Run: node tests/smoke.js
*/
'use strict';
// ---- minimal DOM stub -------------------------------------------------------
var gradientStub = { addColorStop: function () {} };
function makeCtx() {
var target = {};
return new Proxy(target, {
get: function (t, prop) {
if (prop in t) return t[prop];
// any method is a no-op that returns a gradient stub (harmless for all
// our calls; createRadialGradient needs a return value with addColorStop)
return function () { return gradientStub; };
},
set: function (t, prop, val) { t[prop] = val; return true; }
});
}
function makeClassList() {
var set = {};
return {
add: function (c) { set[c] = true; },
remove: function (c) { delete set[c]; },
toggle: function (c, force) {
if (force === undefined) { set[c] = !set[c]; } else { set[c] = !!force; }
},
contains: function (c) { return !!set[c]; }
};
}
function makeEl(id) {
return {
id: id,
style: {},
textContent: '',
classList: makeClassList(),
clientWidth: 800,
clientHeight: 600,
width: 800,
height: 600,
listeners: {},
addEventListener: function (ev, fn) { (this.listeners[ev] = this.listeners[ev] || []).push(fn); },
removeEventListener: function () {},
getContext: function () { return makeCtx(); },
dispatch: function (ev, arg) {
var ls = this.listeners[ev] || [];
for (var i = 0; i < ls.length; i++) ls[i](arg || {});
}
};
}
var elements = {};
function el(id) {
if (!elements[id]) elements[id] = makeEl(id);
return elements[id];
}
var rafQueue = [];
var rafId = 0;
var fakeDocument = {
readyState: 'complete',
getElementById: function (id) { return el(id); },
addEventListener: function () {},
createElement: function () { return makeEl(''); }
};
// Install globals BEFORE loading app modules. window === the Node global so the
// app's (window.X = ...) globals land where this test can read them.
globalThis.__nodeSmoke = true;
globalThis.window = globalThis;
globalThis.document = fakeDocument;
globalThis.devicePixelRatio = 1;
globalThis.innerWidth = 800;
globalThis.innerHeight = 600;
globalThis.matchMedia = function () { return { matches: false }; };
globalThis.requestAnimationFrame = function (cb) { rafQueue.push(cb); return ++rafId; };
globalThis.cancelAnimationFrame = function () {};
// window-level listeners are stored so the test can dispatch e.g. 'blur'
var windowListeners = {};
globalThis.addEventListener = function (ev, fn) {
(windowListeners[ev] = windowListeners[ev] || []).push(fn);
};
globalThis.removeEventListener = function (ev, fn) {
var ls = windowListeners[ev];
if (ls) { var i = ls.indexOf(fn); if (i >= 0) ls.splice(i, 1); }
};
function dispatchWindowEvent(ev, arg) {
var ls = windowListeners[ev] || [];
for (var i = 0; i < ls.length; i++) ls[i](arg || {});
}
// ---- load app modules -------------------------------------------------------
var P = require('../js/physics.js');
require('../js/render.js');
require('../js/controls.js');
require('../js/ui.js');
require('../js/game.js');
var main = require('../js/main.js');
var passed = 0;
var failed = 0;
function check(name, cond, detail) {
if (cond) { passed++; console.log(' PASS ' + name); }
else { failed++; console.log(' FAIL ' + name + (detail ? ' -> ' + detail : '')); }
}
// Continuous monotonic clock so frame deltas (now - lastNow) stay correct
// across repeated pumps, exactly like a real requestAnimationFrame timestamp.
var clock = 0;
function pump(frames, dtMs) {
dtMs = dtMs || 16.7;
for (var i = 0; i < frames; i++) {
clock += dtMs;
var q = rafQueue;
rafQueue = [];
for (var j = 0; j < q.length; j++) q[j](clock);
}
}
console.log('Orbital sim smoke test');
var app = main.boot();
check('boot returns a game', !!app && !!app.game);
check('boot returns a renderer', !!app.renderer);
check('boot returns a ui', !!app.ui);
check('boot returns a controls', !!app.controls);
check('starts on the menu (no ship)', app.game.ship === null);
// pump a few frames on the menu
pump(5);
check('menu frames run without throwing', true);
// load a scenario
app.game.loadScenario('loworbit');
check('scenario loaded a ship', !!app.game.ship);
check('scenario loaded a station', !!app.game.station);
check('status is flying', app.game.status === 'flying');
check('ship starts in orbit (bound)', P.orbitInfo(app.game.world, app.game.ship.pos, app.game.ship.vel).bound);
// pump some frames
pump(30);
check('sim time advanced', app.game.simTime > 0);
check('camera tracks the ship', Math.abs(app.game.camera.x - app.game.ship.pos.x) < 5000);
// hold thrust and verify fuel is consumed
var f0 = app.game.ship.fuel;
app.controls.input.thrust = 1;
pump(30);
check('thrust burns fuel', app.game.ship.fuel < f0, 'fuel ' + app.game.ship.fuel + ' vs ' + f0);
app.controls.input.thrust = 0;
// stuck-key recovery: hold W via the real keydown handler, then simulate the
// window losing focus (blur) with no keyup — thrust must not stick
dispatchWindowEvent('keydown', { code: 'KeyW', repeat: false, preventDefault: function () {} });
check('thrust active while W held', app.controls.input.thrust === 1);
dispatchWindowEvent('blur', {});
check('blur clears stuck keys (thrust released)', app.controls.input.thrust === 0);
// pause / resume
var t0 = app.game.simTime;
app.game.togglePause();
check('paused flag set', app.game.paused === true);
pump(10);
check('sim frozen while paused', app.game.simTime === t0);
app.game.togglePause();
pump(10);
check('sim resumes', app.game.simTime > t0);
// reset
app.game.reset();
check('reset keeps the same scenario', app.game.scenarioId === 'loworbit');
check('reset restores fuel', app.game.ship.fuel === app.game.ship.maxFuel);
// zoom
var z0 = app.game.camera.targetZoom;
app.game.zoomBy(2);
check('zoom in increases target zoom', app.game.camera.targetZoom > z0);
app.game.zoomBy(0.1);
check('zoom out decreases target zoom', app.game.camera.targetZoom < z0);
// C key: toggle the camera between following the ship and centering on the planet
(function () {
app.game.loadScenario('loworbit');
pump(5); // let the camera settle on the ship
check('camera follows the ship by default', app.game.cameraFollowPlanet === false);
// press C -> center on the planet (static target, so the camera converges to it)
dispatchWindowEvent('keydown', { code: 'KeyC', repeat: false, preventDefault: function () {} });
check('C toggles the camera to the planet', app.game.cameraFollowPlanet === true);
pump(120);
check('camera pans to the planet after C',
Math.abs(app.game.camera.x) < 50 && Math.abs(app.game.camera.y) < 50,
'cam=(' + app.game.camera.x.toFixed(1) + ',' + app.game.camera.y.toFixed(1) + ')');
// press C again -> back to following the ship
dispatchWindowEvent('keydown', { code: 'KeyC', repeat: false, preventDefault: function () {} });
check('second C toggles the camera back to the ship', app.game.cameraFollowPlanet === false);
pump(120);
var s = app.game.ship;
var d = Math.sqrt(
(app.game.camera.x - s.pos.x) * (app.game.camera.x - s.pos.x) +
(app.game.camera.y - s.pos.y) * (app.game.camera.y - s.pos.y)
);
check('camera returns to the ship after the second C', d < 300, 'dist=' + d.toFixed(1));
})();
// time scale
app.game.setUserTimeScale(10);
check('user time scale set', app.game.userTimeScale === 10);
app.game.cycleTimeScale();
check('cycle time scale wraps', app.game.userTimeScale === 1);
// prediction
pump(5);
check('prediction produced points', app.game.prediction && app.game.prediction.points.length > 0);
app.game.togglePrediction();
check('prediction toggled off', app.game.showPrediction === false);
app.game.togglePrediction();
// Frame-rate independence through the REAL game loop: simulate the same real
// duration at two different refresh rates and require (nearly) identical ship
// states. A frame-rate-dependent integrator would diverge by meters here.
(function () {
function close(a, b, tol) {
var d = Math.abs(a - b);
var m = Math.max(Math.abs(a), Math.abs(b), 1);
return d <= tol * m;
}
function runAt(frameRate, realSeconds) {
app.game.loadScenario('loworbit'); // identical starting state each run
app.game.lastNow = 0;
clock = 0;
var dtMs = 1000 / frameRate;
var frames = Math.round(realSeconds * frameRate);
for (var i = 0; i < frames; i++) {
clock += dtMs;
var q = rafQueue;
rafQueue = [];
for (var j = 0; j < q.length; j++) q[j](clock);
}
var s = app.game.ship;
return { x: s.pos.x, y: s.pos.y, vx: s.vel.x, vy: s.vel.y };
}
var s60 = runAt(60, 2);
var s144 = runAt(144, 2);
check('frame-rate independence via real game loop (60 vs 144 fps)',
close(s60.x, s144.x, 1e-2) && close(s60.y, s144.y, 1e-2) &&
close(s60.vx, s144.vx, 1e-2) && close(s60.vy, s144.vy, 1e-2),
JSON.stringify(s60) + ' vs ' + JSON.stringify(s144));
})();
// ---- Surface Launch: "ready for launch" state ----
// The ship waits on the pad with the sim clock stopped until the player first
// thrusts. This gives the player time to get ready without a physics jump.
app.game.loadScenario('launch');
check('launch starts in the ready state (clock stopped)',
app.game.status === 'ready' && app.game.ship.state === 'ready');
(function () {
var s = app.game.ship;
var w = app.game.world;
var rx = s.pos.x - w.planet.x, ry = s.pos.y - w.planet.y;
var rl = Math.sqrt(rx * rx + ry * ry);
var dot = (Math.cos(s.angle) * rx + Math.sin(s.angle) * ry) / rl;
check('launch ship points radially outward (away from planet)', dot > 0.99, 'dot=' + dot);
})();
// (a) while waiting: ship stays put, clock stopped, no crash
(function () {
var s = app.game.ship;
var x0 = s.pos.x, y0 = s.pos.y, vx0 = s.vel.x, vy0 = s.vel.y;
pump(120); // ~2 s of waiting on the pad
check('ship stays stationary while waiting',
s.pos.x === x0 && s.pos.y === y0 && s.vel.x === vx0 && s.vel.y === vy0,
'pos=' + JSON.stringify({ x: s.pos.x, y: s.pos.y }));
check('no crash while waiting', app.game.status === 'ready');
check('sim clock stays stopped while waiting', app.game.simTime === 0);
})();
// (b) the first thrust input starts the flight and applies thrust immediately
(function () {
var s = app.game.ship;
var x0 = s.pos.x;
app.controls.input.thrust = 1;
pump(1); // the launch frame
app.controls.input.thrust = 0;
check('first thrust starts the flight', app.game.status === 'flying' && app.game.ship.state === 'flying');
check('thrust is applied on the launch frame (ship moves outward)',
s.pos.x > x0 || s.vel.x > 0, 'x0=' + x0.toFixed(2) + ' x=' + s.pos.x.toFixed(2) + ' vx=' + s.vel.x.toFixed(2));
})();
// (c) a long wait must not cause a physics jump when launch finally begins
(function () {
app.game.loadScenario('launch'); // fresh ready state
pump(300); // ~5 s of waiting
check('still ready after a long wait', app.game.status === 'ready' && app.game.simTime === 0);
app.controls.input.thrust = 1;
pump(1); // launch
app.controls.input.thrust = 0;
check('no physics jump after a long wait (clock restarts at ~0)',
app.game.simTime < 0.1, 'simTime=' + app.game.simTime);
})();
// (d) reset restores the waiting state
app.game.reset();
check('reset restores the ready state', app.game.status === 'ready' && app.game.ship.state === 'ready');
check('reset puts the ship back on the pad',
Math.abs(app.game.ship.pos.x - 1010) < 1e-9 && app.game.ship.pos.y === 0);
check('reset stops the clock', app.game.simTime === 0);
// (e) the other scenarios still start flying immediately
app.game.loadScenario('loworbit');
check('loworbit starts flying immediately', app.game.status === 'flying');
app.game.loadScenario('rendezvous');
check('rendezvous starts flying immediately', app.game.status === 'flying');
// leave the game in a flying scenario for the crash/dock tests below
app.game.loadScenario('loworbit');
// crash path: drop the ship into the planet (toward the center, i.e. -x)
app.game.ship.pos = { x: 1005, y: 0 };
app.game.ship.vel = { x: -300, y: 0 };
pump(60);
check('ship crashed into planet', app.game.status === 'crashed', 'status=' + app.game.status);
// dock path: place ship right on the station with matching velocity
app.game.loadScenario('loworbit');
var st = app.game.station;
app.game.ship.pos = { x: st.pos.x + 5, y: st.pos.y };
app.game.ship.vel = { x: st.vel.x, y: st.vel.y };
pump(30);
check('ship docked with station', app.game.status === 'docked', 'status=' + app.game.status);
// back to menu
app.game.toMenu();
check('toMenu clears the ship', app.game.ship === null);
console.log('');
console.log(passed + ' passed, ' + failed + ' failed');
if (failed > 0) process.exit(1);