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
@@ -0,0 +1,118 @@
|
||||
# Orbital Flight Simulator
|
||||
|
||||
A complete 2D orbital flight simulator in plain HTML/CSS/JavaScript — no
|
||||
external libraries, no build step. Newtonian gravity, RK4 integration,
|
||||
trajectory prediction, and a space station to rendezvous with and dock to.
|
||||
|
||||
## Run
|
||||
|
||||
Open `index.html` in a modern browser, or serve the folder:
|
||||
|
||||
```sh
|
||||
cd orbital-flight-simulator
|
||||
python3 -m http.server 8000
|
||||
# then open http://localhost:8000
|
||||
```
|
||||
|
||||
(Opening the file directly also works; there are no fetch/module imports.)
|
||||
|
||||
## Play
|
||||
|
||||
Pick a scenario from the menu:
|
||||
|
||||
- **Surface Launch** — liftoff from the planet; establish a bound orbit, then dock.
|
||||
- **Low Orbit** — you're already orbiting; rendezvous with the station.
|
||||
- **Station Rendezvous** — elliptical orbit below the station; match it and dock.
|
||||
|
||||
### Controls
|
||||
|
||||
| Key | Action |
|
||||
| --- | --- |
|
||||
| `W` / `↑` / `Space` | Thrust (hold) |
|
||||
| `A` / `←` | Rotate left |
|
||||
| `D` / `→` | Rotate right |
|
||||
| `1`–`4` | Time warp 1x / 2x / 5x / 10x |
|
||||
| `T` | Toggle predicted path |
|
||||
| `P` / `Esc` | Pause |
|
||||
| `R` | Restart scenario |
|
||||
| `H` | Tutorial |
|
||||
| `+` / `-` / wheel | Zoom |
|
||||
|
||||
Touch controls appear automatically on coarse-pointer devices.
|
||||
|
||||
### How to fly
|
||||
|
||||
- The **cyan arrow** is your velocity (prograde). Burn along it to raise your
|
||||
orbit, burn opposite (retrograde) to lower it.
|
||||
- The **dashed line** is your predicted coast path, computed with the exact
|
||||
same integrator as the simulation: green = bound orbit, orange = escape,
|
||||
red = crash.
|
||||
- The HUD shows altitude, speed, fuel, and orbital elements (periapsis,
|
||||
apoapsis, eccentricity, period).
|
||||
- Time acceleration **auto-limits to 1x** near the surface and near the
|
||||
station so you can dock precisely.
|
||||
- **Docking**: get inside the station's blue ring with low relative velocity.
|
||||
- **Landing** (launch scenario): slow vertical speed, low sideways speed,
|
||||
belly toward the surface.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
index.html page shell, HUD, overlays, script tags
|
||||
css/style.css dark space theme, HUD/overlay/touch styling
|
||||
js/physics.js pure physics core (no DOM) — see below
|
||||
js/render.js canvas renderer (stars, planet, ship, station, path)
|
||||
js/controls.js keyboard + touch input -> { thrust, torque }
|
||||
js/ui.js DOM HUD + overlays (menu, tutorial, pause, end)
|
||||
js/game.js fixed-timestep loop, camera, time warp, scenarios,
|
||||
docking/landing/crash, exhaust particles
|
||||
js/main.js boot(): wires everything, starts the RAF loop
|
||||
tests/test.js physics unit tests (plain Node)
|
||||
tests/smoke.js headless DOM-stub smoke test (plain Node)
|
||||
```
|
||||
|
||||
### Physics (`js/physics.js`)
|
||||
|
||||
- Point-mass Newtonian gravity: `a = -mu * r_vec / |r|^3`, `mu = 3e8`,
|
||||
planet radius `1000` (meters, seconds).
|
||||
- **RK4** integration on `(pos, vel)` with a **fixed timestep** of `1/120 s`.
|
||||
The ship angle (thrust direction) is held constant within a substep.
|
||||
- Rotation is integrated with semi-implicit Euler (decoupled from orbital
|
||||
motion), with a clamped angular velocity and damping.
|
||||
- The station coasts on the same RK4 integrator (gravity only).
|
||||
- Orbital elements (specific energy, eccentricity vector, periapsis,
|
||||
apoapsis, period) are derived from the state vector each frame.
|
||||
- Trajectory prediction re-runs the **identical** RK4 integrator in coast
|
||||
mode, so the predicted path always matches what actually happens.
|
||||
|
||||
### Frame-rate independence
|
||||
|
||||
The game loop is a fixed-timestep accumulator: each animation frame advances
|
||||
the simulation in whole `1/120 s` steps (scaled by the time-warp factor), so
|
||||
physics is identical regardless of display refresh rate. Verified by tests.
|
||||
|
||||
## Tests
|
||||
|
||||
No dependencies — plain Node:
|
||||
|
||||
```sh
|
||||
node tests/test.js # physics unit tests
|
||||
node tests/smoke.js # headless boot + interaction smoke test
|
||||
```
|
||||
|
||||
`tests/test.js` covers gravity magnitude/direction, energy conservation over
|
||||
10 orbits, frame-rate independence (identical chunking and substep
|
||||
tolerance), fuel consumption, surface collision (crash vs. landing vs.
|
||||
misaligned), trajectory-prediction accuracy against actual coasting, orbit
|
||||
classification (circular / elliptical / escape), and station orbit stability.
|
||||
|
||||
`tests/smoke.js` stubs a minimal DOM/canvas, boots the real application, and
|
||||
pumps the requestAnimationFrame loop manually to verify: boot, scenario load,
|
||||
fuel burn under thrust, pause/resume, reset, zoom, time-warp, trajectory
|
||||
prediction, crash, and docking.
|
||||
|
||||
## Tuning
|
||||
|
||||
All gameplay constants live in `js/physics.js` (`createWorld`/`createShip`
|
||||
defaults) and `js/game.js` (`SCENARIOS`). Change `mu`, `planetRadius`,
|
||||
`thrustAccel`, `fuelRate`, `dockDistance`, `dockSpeed`, etc. to re-balance.
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
/* Orbital Flight Simulator - dark space theme */
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: #04060d;
|
||||
font-family: 'Courier New', ui-monospace, monospace;
|
||||
color: #dfe9f5;
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
#game {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.hidden { display: none !important; }
|
||||
|
||||
/* ---------- HUD ---------- */
|
||||
#hud { position: fixed; inset: 0; pointer-events: none; z-index: 5; }
|
||||
|
||||
.panel {
|
||||
position: absolute;
|
||||
background: rgba(8, 14, 26, 0.72);
|
||||
border: 1px solid rgba(90, 160, 255, 0.25);
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
|
||||
.row { display: flex; gap: 10px; align-items: baseline; white-space: nowrap; }
|
||||
.label { color: #6f87a8; min-width: 44px; font-size: 11px; letter-spacing: 1px; }
|
||||
|
||||
#hud-top {
|
||||
top: 10px; left: 50%; transform: translateX(-50%);
|
||||
display: flex; gap: 16px; align-items: baseline;
|
||||
}
|
||||
#scenario-name { font-size: 14px; letter-spacing: 2px; color: #9ecbff; }
|
||||
.goal { color: #7dff9a; font-size: 12px; }
|
||||
|
||||
#hud-left { top: 10px; left: 10px; min-width: 170px; }
|
||||
#hud-right { top: 10px; right: 10px; min-width: 170px; text-align: left; }
|
||||
#hud-dock { bottom: 14px; left: 50%; transform: translateX(-50%); }
|
||||
|
||||
.fuel-row { margin-top: 4px; }
|
||||
.fuel-track {
|
||||
display: inline-block; width: 90px; height: 8px;
|
||||
background: rgba(255,255,255,0.12); border-radius: 4px; overflow: hidden;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.fuel-fill {
|
||||
display: block; height: 100%; width: 100%;
|
||||
background: linear-gradient(90deg, #ff7b4f, #ffd166, #7dff9a);
|
||||
}
|
||||
|
||||
.orbit-bound { font-size: 12px; letter-spacing: 1px; }
|
||||
#auto-limit { color: #ffb347; font-size: 11px; margin-top: 2px; }
|
||||
|
||||
/* ---------- Overlays ---------- */
|
||||
.overlay {
|
||||
position: fixed; inset: 0; z-index: 20;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
background: rgba(2, 4, 10, 0.78);
|
||||
}
|
||||
/* Ready-for-launch: lighter so the pad scene shows through, and it never
|
||||
blocks the touch THRUST button (which is what starts the launch). */
|
||||
#ready-overlay {
|
||||
background: rgba(2, 4, 10, 0.35);
|
||||
pointer-events: none;
|
||||
}
|
||||
.menu-box {
|
||||
max-width: 560px; width: calc(100% - 40px);
|
||||
background: rgba(10, 16, 30, 0.95);
|
||||
border: 1px solid rgba(90, 160, 255, 0.35);
|
||||
border-radius: 10px;
|
||||
padding: 28px 32px;
|
||||
text-align: center;
|
||||
box-shadow: 0 0 40px rgba(60, 130, 255, 0.15);
|
||||
}
|
||||
.menu-box h1 { font-size: 22px; letter-spacing: 3px; color: #9ecbff; margin-bottom: 8px; }
|
||||
.menu-box h2 { font-size: 20px; letter-spacing: 2px; margin-bottom: 12px; }
|
||||
.tagline { color: #6f87a8; font-size: 12px; margin-bottom: 22px; }
|
||||
.tut-text { white-space: pre-line; text-align: left; font-size: 13px; line-height: 1.7; margin-bottom: 18px; color: #c8d6e5; }
|
||||
.hint { color: #6f87a8; font-size: 11px; margin-top: 16px; }
|
||||
.menu-row { display: flex; gap: 12px; align-items: center; justify-content: center; }
|
||||
|
||||
/* ---------- Buttons ---------- */
|
||||
.btn {
|
||||
font-family: inherit; font-size: 13px; letter-spacing: 1px;
|
||||
color: #dfe9f5; background: rgba(90, 160, 255, 0.12);
|
||||
border: 1px solid rgba(90, 160, 255, 0.45);
|
||||
border-radius: 6px; padding: 10px 18px; cursor: pointer;
|
||||
transition: background 0.15s, transform 0.05s;
|
||||
}
|
||||
.btn:hover { background: rgba(90, 160, 255, 0.28); }
|
||||
.btn:active { transform: scale(0.97); }
|
||||
.btn.big { display: block; width: 100%; margin-bottom: 10px; padding: 13px; font-size: 14px; }
|
||||
.btn.ghost { background: transparent; }
|
||||
.btn.icon {
|
||||
width: 38px; height: 38px; padding: 0;
|
||||
font-size: 15px; line-height: 36px; text-align: center;
|
||||
}
|
||||
|
||||
#top-buttons {
|
||||
position: fixed; top: 10px; right: 200px; z-index: 15;
|
||||
display: flex; gap: 6px;
|
||||
}
|
||||
@media (max-width: 800px) { #top-buttons { right: 10px; top: auto; bottom: 10px; } }
|
||||
|
||||
/* ---------- Touch controls ---------- */
|
||||
#touch-controls {
|
||||
position: fixed; bottom: 18px; left: 0; right: 0; z-index: 15;
|
||||
display: flex; justify-content: space-between; align-items: flex-end;
|
||||
padding: 0 18px; pointer-events: none;
|
||||
}
|
||||
.tbtn {
|
||||
pointer-events: auto;
|
||||
font-family: inherit; font-size: 16px;
|
||||
color: #dfe9f5; background: rgba(90, 160, 255, 0.18);
|
||||
border: 1px solid rgba(90, 160, 255, 0.5);
|
||||
border-radius: 50%; width: 64px; height: 64px;
|
||||
touch-action: none;
|
||||
}
|
||||
.tbtn.active { background: rgba(90, 160, 255, 0.45); }
|
||||
.tbtn.thrust { width: 84px; height: 84px; background: rgba(255, 123, 79, 0.25); border-color: rgba(255, 123, 79, 0.6); }
|
||||
.tbtn.thrust.active { background: rgba(255, 123, 79, 0.55); }
|
||||
.tbtn.time { width: 52px; height: 52px; font-size: 11px; }
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
|
||||
<title>Orbital Flight Simulator</title>
|
||||
<link rel="stylesheet" href="css/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="game"></canvas>
|
||||
|
||||
<div id="hud" class="hidden">
|
||||
<div id="hud-top" class="panel">
|
||||
<span id="scenario-name">—</span>
|
||||
<span id="goal-text" class="goal"></span>
|
||||
</div>
|
||||
|
||||
<div id="hud-left" class="panel">
|
||||
<div class="row"><span class="label">ALT</span><span id="alt">0 m</span></div>
|
||||
<div class="row"><span class="label">VEL</span><span id="spd">0 m/s</span></div>
|
||||
<div class="row fuel-row">
|
||||
<span class="label">FUEL</span>
|
||||
<span class="fuel-track"><span id="fuel-bar" class="fuel-fill"></span></span>
|
||||
<span id="fuel-text">0</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="hud-right" class="panel">
|
||||
<div class="row"><span id="orbit-bound" class="orbit-bound">—</span></div>
|
||||
<div class="row"><span class="label">PERI</span><span id="orbit-peri">—</span></div>
|
||||
<div class="row"><span class="label">APO</span><span id="orbit-apo">—</span></div>
|
||||
<div class="row"><span class="label">ECC</span><span id="orbit-ecc">—</span></div>
|
||||
<div class="row"><span class="label">T</span><span id="orbit-period">—</span></div>
|
||||
<div class="row"><span class="label">WARP</span><span id="timescale">1x</span></div>
|
||||
<div id="auto-limit" class="hidden">auto time limit active</div>
|
||||
</div>
|
||||
|
||||
<div id="hud-dock" class="panel hidden">
|
||||
<div class="row"><span id="dock-dist">STATION —</span></div>
|
||||
<div class="row"><span id="dock-rel">REL —</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="menu" class="overlay">
|
||||
<div class="menu-box">
|
||||
<h1>ORBITAL FLIGHT SIMULATOR</h1>
|
||||
<p class="tagline">Newtonian gravity · RK4 integration · dock with the station</p>
|
||||
<button id="btn-launch" class="btn big">Surface Launch</button>
|
||||
<button id="btn-orbit" class="btn big">Low Orbit</button>
|
||||
<button id="btn-rendez" class="btn big">Station Rendezvous</button>
|
||||
<p class="hint">W/↑ thrust · A/D rotate · 1–4 time warp · T path · C center planet · P pause · R reset · H help</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="tutorial" class="overlay hidden">
|
||||
<div class="menu-box">
|
||||
<h2 id="tut-title">Welcome</h2>
|
||||
<p id="tut-text" class="tut-text"></p>
|
||||
<div class="menu-row">
|
||||
<span id="tut-step" class="hint"></span>
|
||||
<button id="tut-next" class="btn">Next</button>
|
||||
<button id="tut-skip" class="btn ghost">Skip</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="pause-overlay" class="overlay hidden">
|
||||
<div class="menu-box">
|
||||
<h2>PAUSED</h2>
|
||||
<p class="hint">P to resume · R to restart</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="ready-overlay" class="overlay hidden">
|
||||
<div class="menu-box">
|
||||
<h2>READY FOR LAUNCH</h2>
|
||||
<p class="tut-text">Press <b>W</b>, <b>↑</b>, <b>Space</b>, or the <b>THRUST</b> button to launch.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="end-overlay" class="overlay hidden">
|
||||
<div class="menu-box">
|
||||
<h2 id="end-title">—</h2>
|
||||
<p id="end-detail" class="tut-text"></p>
|
||||
<div class="menu-row">
|
||||
<button id="end-reset" class="btn">Restart</button>
|
||||
<button id="end-menu" class="btn ghost">Menu</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="top-buttons">
|
||||
<button id="btn-pause" class="btn icon" title="Pause (P)">II</button>
|
||||
<button id="btn-reset" class="btn icon" title="Reset (R)">R</button>
|
||||
<button id="btn-zoom-in" class="btn icon" title="Zoom in (+)">+</button>
|
||||
<button id="btn-zoom-out" class="btn icon" title="Zoom out (-)">−</button>
|
||||
<button id="btn-help" class="btn icon" title="Help (H)">?</button>
|
||||
</div>
|
||||
|
||||
<div id="touch-controls" class="hidden">
|
||||
<button id="btn-left" class="tbtn">←</button>
|
||||
<button id="btn-right" class="tbtn">→</button>
|
||||
<button id="btn-thrust" class="tbtn thrust">THRUST</button>
|
||||
<button id="btn-time" class="tbtn time">WARP</button>
|
||||
</div>
|
||||
|
||||
<script src="js/physics.js"></script>
|
||||
<script src="js/render.js"></script>
|
||||
<script src="js/controls.js"></script>
|
||||
<script src="js/ui.js"></script>
|
||||
<script src="js/game.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Vendored
+111
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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);
|
||||
@@ -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);
|
||||
+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