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:
commit
b926fa2a78
11 files changed
+2337
No files matched your search
+338
@@ -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);
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
/*
|
||||
* Orbital Flight Simulator - unit tests (plain Node, no dependencies).
|
||||
* Run: node tests/test.js
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var P = require('../js/physics.js');
|
||||
|
||||
var passed = 0;
|
||||
var failed = 0;
|
||||
|
||||
function isInf(x) { return x === Infinity || x === -Infinity; }
|
||||
|
||||
function approx(a, b, tol) {
|
||||
if (a !== a && b !== b) return true; // both NaN
|
||||
if (isInf(a) && isInf(b) && (a > 0) === (b > 0)) return true;
|
||||
var d = Math.abs(a - b);
|
||||
var m = Math.max(Math.abs(a), Math.abs(b), 1);
|
||||
return d <= tol * m;
|
||||
}
|
||||
|
||||
function vecClose(a, b, tol) {
|
||||
return approx(a.x, b.x, tol) && approx(a.y, b.y, tol);
|
||||
}
|
||||
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
passed++;
|
||||
console.log(' PASS ' + name);
|
||||
} catch (e) {
|
||||
failed++;
|
||||
console.log(' FAIL ' + name);
|
||||
console.log(' ' + (e && e.message ? e.message : e));
|
||||
}
|
||||
}
|
||||
|
||||
function assert(cond, msg) {
|
||||
if (!cond) throw new Error(msg || 'assertion failed');
|
||||
}
|
||||
|
||||
function assertClose(a, b, tol, msg) {
|
||||
if (!approx(a, b, tol)) {
|
||||
throw new Error((msg || 'close') + ': got ' + a + ', want ' + b + ' (tol ' + tol + ')');
|
||||
}
|
||||
}
|
||||
|
||||
var world = P.createWorld({}); // mu=3e8, R=1000
|
||||
|
||||
console.log('Orbital physics unit tests');
|
||||
|
||||
// ---- gravity ----
|
||||
test('gravity magnitude at r=1000 is mu/r^2', function () {
|
||||
var g = P.gravityAt(world, { x: 1000, y: 0 });
|
||||
assertClose(Math.sqrt(g.x * g.x + g.y * g.y), world.mu / 1e6, 1e-12, '|g|');
|
||||
});
|
||||
|
||||
test('gravity points toward the planet center', function () {
|
||||
var g = P.gravityAt(world, { x: 1000, y: 0 });
|
||||
assert(g.x < 0 && g.y === 0, 'should point -x');
|
||||
var g2 = P.gravityAt(world, { x: 0, y: -2000 });
|
||||
assert(g2.y > 0 && g2.x === 0, 'should point +y');
|
||||
});
|
||||
|
||||
// ---- energy conservation (RK4, circular orbit, 10 orbits) ----
|
||||
test('RK4 conserves orbital energy over 10 orbits', function () {
|
||||
var r = 1500;
|
||||
var v = Math.sqrt(world.mu / r);
|
||||
var ship = P.createShip({ x: r, y: 0, vy: v, fuel: 1000 });
|
||||
var e0 = P.orbitInfo(world, ship.pos, ship.vel).energy;
|
||||
var dt = world.fixedDt;
|
||||
var period = P.TAU * Math.sqrt((r * r * r) / world.mu);
|
||||
var steps = Math.round((10 * period) / dt);
|
||||
for (var i = 0; i < steps; i++) P.stepShip(world, ship, { thrust: 0, torque: 0 }, dt);
|
||||
var e1 = P.orbitInfo(world, ship.pos, ship.vel).energy;
|
||||
assertClose(e1, e0, 1e-4, 'energy drift over 10 orbits');
|
||||
});
|
||||
|
||||
// ---- frame-rate independence ----
|
||||
test('fixed-timestep accumulator is frame-rate independent', function () {
|
||||
// Mirrors Game.frameImpl: each frame adds its real dt to an accumulator and
|
||||
// runs as many fixed-dt steps as fit. The same real duration simulated at two
|
||||
// different frame rates must produce (nearly) identical physics — the result
|
||||
// depends only on total simulated time, not on the display refresh rate.
|
||||
function runLoop(frameRate, realSeconds) {
|
||||
var r = 1500;
|
||||
var v = Math.sqrt(world.mu / r);
|
||||
var ship = P.createShip({ x: r, y: 0, vy: v, fuel: 1000 });
|
||||
var dt = world.fixedDt;
|
||||
var frameDt = 1 / frameRate;
|
||||
var accumulator = 0;
|
||||
var elapsed = 0;
|
||||
var steps = 0;
|
||||
while (elapsed < realSeconds - 1e-12) {
|
||||
var step = Math.min(frameDt, realSeconds - elapsed);
|
||||
elapsed += step;
|
||||
accumulator += step;
|
||||
while (accumulator >= dt - 1e-12) {
|
||||
P.stepShip(world, ship, { thrust: 0, torque: 0 }, dt);
|
||||
accumulator -= dt;
|
||||
steps++;
|
||||
}
|
||||
}
|
||||
return { ship: ship, steps: steps };
|
||||
}
|
||||
var a = runLoop(60, 5);
|
||||
var b = runLoop(144, 5);
|
||||
// ~5 s of sim time => ~600 fixed steps; allow +/-1 for accumulator rounding
|
||||
assert(Math.abs(a.steps - b.steps) <= 1, 'step counts differ: ' + a.steps + ' vs ' + b.steps);
|
||||
assert(vecClose(a.ship.pos, b.ship.pos, 1e-3), 'positions differ: ' + JSON.stringify(a.ship.pos) + ' vs ' + JSON.stringify(b.ship.pos));
|
||||
assert(vecClose(a.ship.vel, b.ship.vel, 1e-3), 'velocities differ');
|
||||
});
|
||||
|
||||
test('different substep sizes stay close (tolerance)', function () {
|
||||
function run(dt) {
|
||||
var r = 1500;
|
||||
var v = Math.sqrt(world.mu / r);
|
||||
var ship = P.createShip({ x: r, y: 0, vy: v, fuel: 1000 });
|
||||
var total = 60;
|
||||
var steps = Math.round(total / dt);
|
||||
for (var i = 0; i < steps; i++) P.stepShip(world, ship, { thrust: 0, torque: 0 }, dt);
|
||||
return ship;
|
||||
}
|
||||
var a = run(1 / 120);
|
||||
var b = run(1 / 60);
|
||||
assert(vecClose(a.pos, b.pos, 1e-3), 'positions diverge: ' + JSON.stringify(a.pos) + ' vs ' + JSON.stringify(b.pos));
|
||||
assert(vecClose(a.vel, b.vel, 1e-3), 'velocities diverge');
|
||||
});
|
||||
|
||||
// ---- fuel ----
|
||||
test('thrust consumes fuel at fuelRate per second', function () {
|
||||
var ship = P.createShip({ x: 1500, y: 0, vy: Math.sqrt(world.mu / 1500), fuel: 100, angle: 0 });
|
||||
var f0 = ship.fuel;
|
||||
var dt = world.fixedDt;
|
||||
var n = Math.round(5 / dt); // 5 seconds of full thrust
|
||||
for (var i = 0; i < n; i++) P.stepShip(world, ship, { thrust: 1, torque: 0 }, dt);
|
||||
assertClose(f0 - ship.fuel, 5 * ship.fuelRate, 1e-6, 'fuel burned');
|
||||
});
|
||||
|
||||
test('fuel never goes negative and thrust stops at zero fuel', function () {
|
||||
var ship = P.createShip({ x: 1500, y: 0, vy: Math.sqrt(world.mu / 1500), fuel: 1, angle: 0 });
|
||||
var dt = world.fixedDt;
|
||||
for (var i = 0; i < 2000; i++) P.stepShip(world, ship, { thrust: 1, torque: 0 }, dt);
|
||||
assert(ship.fuel >= 0, 'fuel negative: ' + ship.fuel);
|
||||
assert(ship.fuel === 0, 'fuel should be exactly 0');
|
||||
});
|
||||
|
||||
test('no fuel means no thrust acceleration', function () {
|
||||
var ship = P.createShip({ x: 1500, y: 0, vy: Math.sqrt(world.mu / 1500), fuel: 0, angle: 0 });
|
||||
var v0 = P.len(ship.vel);
|
||||
P.stepShip(world, ship, { thrust: 1, torque: 0 }, world.fixedDt);
|
||||
// gravity is perpendicular-ish here, speed change is tiny but must not include thrust
|
||||
var info = P.orbitInfo(world, ship.pos, ship.vel);
|
||||
assert(info.speed < v0 + 1, 'speed jumped: ' + info.speed + ' vs ' + v0);
|
||||
});
|
||||
|
||||
// ---- collision ----
|
||||
// surfaceR = planetRadius + radius*0.4 = 1002.4, so the ship must be at r<=1002.4
|
||||
test('fast surface impact is a crash', function () {
|
||||
var ship = P.createShip({ x: 1001, y: 0, vx: -200, fuel: 100 }); // slamming in along -x
|
||||
var c = P.checkSurface(world, ship);
|
||||
assert(c.type === 'crash', 'expected crash, got ' + c.type);
|
||||
});
|
||||
|
||||
test('slow, aligned surface contact is a landing', function () {
|
||||
var ship = P.createShip({ x: 1001, y: 0, vy: -10, fuel: 100, angle: Math.PI / 2 }); // nose up, belly down
|
||||
var c = P.checkSurface(world, ship);
|
||||
assert(c.type === 'land', 'expected land, got ' + c.type);
|
||||
});
|
||||
|
||||
test('misaligned slow contact is a crash', function () {
|
||||
var ship = P.createShip({ x: 1001, y: 0, vy: -10, fuel: 100, angle: 0 }); // nose sideways
|
||||
var c = P.checkSurface(world, ship);
|
||||
assert(c.type === 'crash', 'expected crash, got ' + c.type);
|
||||
});
|
||||
|
||||
test('above the surface is no interaction', function () {
|
||||
var ship = P.createShip({ x: 1200, y: 0, vy: -100, fuel: 100 });
|
||||
var c = P.checkSurface(world, ship);
|
||||
assert(c.type === 'none', 'expected none, got ' + c.type);
|
||||
});
|
||||
|
||||
// ---- trajectory prediction ----
|
||||
test('coasting prediction matches actual coasting', function () {
|
||||
var r = 1500;
|
||||
var v = Math.sqrt(world.mu / r) * 1.02;
|
||||
var ship = P.createShip({ x: r, y: 0, vy: v, fuel: 100 });
|
||||
var pred = P.predictTrajectory(world, ship, { dt: world.fixedDt * 2, maxSteps: 300, sampleEvery: 3 });
|
||||
assert(pred.points.length > 10, 'too few points: ' + pred.points.length);
|
||||
|
||||
// points[k] is sampled after (k+1)*sampleEvery steps of dt
|
||||
var k = 50;
|
||||
var sampleEvery = 3;
|
||||
var dt = world.fixedDt * 2;
|
||||
var steps = (k + 1) * sampleEvery;
|
||||
var actual = P.createShip({ x: r, y: 0, vy: v, fuel: 100 });
|
||||
for (var i = 0; i < steps; i++) P.stepShip(world, actual, { thrust: 0, torque: 0 }, dt);
|
||||
assert(vecClose(pred.points[k], actual.pos, 1e-9),
|
||||
'prediction diverges: ' + JSON.stringify(pred.points[k]) + ' vs ' + JSON.stringify(actual.pos));
|
||||
});
|
||||
|
||||
test('prediction flags a crash for a falling ship', function () {
|
||||
var ship = P.createShip({ x: 1100, y: 0, vy: -50, fuel: 100 });
|
||||
var pred = P.predictTrajectory(world, ship, { dt: world.fixedDt * 2, maxSteps: 2000, sampleEvery: 2 });
|
||||
assert(pred.result.type === 'crash' || pred.result.type === 'land', 'expected surface hit, got ' + pred.result.type);
|
||||
});
|
||||
|
||||
test('prediction flags escape for an unbound ship', function () {
|
||||
var ship = P.createShip({ x: 1500, y: 0, vy: Math.sqrt(world.mu / 1500) * 1.5, fuel: 100 });
|
||||
var pred = P.predictTrajectory(world, ship, { dt: world.fixedDt * 2, maxSteps: 4000, sampleEvery: 4 });
|
||||
assert(pred.result.type === 'far', 'expected far/escape, got ' + pred.result.type);
|
||||
});
|
||||
|
||||
// ---- orbit classification ----
|
||||
test('circular orbit: e~0, bound, correct altitude', function () {
|
||||
var r = 1500;
|
||||
var v = Math.sqrt(world.mu / r);
|
||||
var info = P.orbitInfo(world, { x: r, y: 0 }, { x: 0, y: v });
|
||||
assert(info.bound, 'should be bound');
|
||||
assertClose(info.eccentricity, 0, 1e-9, 'eccentricity');
|
||||
assertClose(info.periapsis, r, 1e-6, 'periapsis');
|
||||
assertClose(info.apoapsis, r, 1e-6, 'apoapsis');
|
||||
assertClose(info.altitude, r - world.planetRadius, 1e-9, 'altitude');
|
||||
});
|
||||
|
||||
test('faster than circular gives an ellipse with higher apoapsis', function () {
|
||||
var r = 1500;
|
||||
var v = Math.sqrt(world.mu / r) * 1.1;
|
||||
var info = P.orbitInfo(world, { x: r, y: 0 }, { x: 0, y: v });
|
||||
assert(info.bound, 'should still be bound');
|
||||
assert(info.eccentricity > 0.05, 'ecc too small: ' + info.eccentricity);
|
||||
assert(info.apoapsis > r && info.periapsis < r, 'apo > r > peri');
|
||||
});
|
||||
|
||||
test('faster than escape gives an unbound trajectory', function () {
|
||||
var r = 1500;
|
||||
var v = Math.sqrt(2 * world.mu / r) * 1.1;
|
||||
var info = P.orbitInfo(world, { x: r, y: 0 }, { x: 0, y: v });
|
||||
assert(!info.bound, 'should be unbound');
|
||||
assert(info.energy > 0, 'energy should be positive');
|
||||
});
|
||||
|
||||
test('escape trajectory has a positive periapsis (closest approach)', function () {
|
||||
var r = 1500;
|
||||
var v = Math.sqrt(world.mu / r) * 1.5; // well above circular => unbound
|
||||
var info = P.orbitInfo(world, { x: r, y: 0 }, { x: 0, y: v });
|
||||
assert(!info.bound, 'should be unbound');
|
||||
assert(info.periapsis > 0, 'periapsis must be positive, got ' + info.periapsis);
|
||||
// purely tangential velocity => currently at periapsis (closest approach)
|
||||
assertClose(info.periapsis, r, 1e-6, 'periapsis equals current radius');
|
||||
});
|
||||
|
||||
test('station coasts on a stable circular orbit', function () {
|
||||
var rs = 1800;
|
||||
var vs = Math.sqrt(world.mu / rs);
|
||||
var st = P.createStation({ x: 0, y: -rs, vx: vs, radius: 12 });
|
||||
var dt = world.fixedDt;
|
||||
var period = P.TAU * Math.sqrt((rs * rs * rs) / world.mu);
|
||||
var steps = Math.round(period / dt);
|
||||
for (var i = 0; i < steps; i++) P.stepStation(world, st, dt);
|
||||
var rNow = Math.sqrt(st.pos.x * st.pos.x + st.pos.y * st.pos.y);
|
||||
assertClose(rNow, rs, 1e-3, 'station radius drift');
|
||||
});
|
||||
|
||||
// ---- summary ----
|
||||
console.log('');
|
||||
console.log(passed + ' passed, ' + failed + ' failed');
|
||||
if (failed > 0) process.exit(1);
|
||||
Reference in new issue
Block a user