Prompt specification
Build or customize the Three.js 3D scene "Velocity Direction Changes the Outcome" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Velocity Direction Changes the Outcome
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/velocity-direction-changes-the-outcome-x3800
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing a controlled orbit experiment varying launch direction at fixed speed and position. Compare resulting trajectories and conservation diagnostics under the same two-body assumptions. Voxel style.
Working Three.js Starter (velocity-direction-changes-the-outcome-x3800):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Orbital Laboratory</title>
<style>
:root {
--bg: #061018;
--panel: rgba(8, 21, 32, 0.94);
--panel-solid: #0a1a27;
--line: #24485c;
--line-bright: #3d7086;
--text: #e7f4f8;
--muted: #83a6b4;
--cyan: #58e6ff;
--green: #a6ff60;
--orange: #ffad42;
--pink: #ff5fa2;
--purple: #b58cff;
--yellow: #ffe15a;
--red: #ff6262;
--shadow: 6px 6px 0 rgba(0, 0, 0, 0.42);
}
* {
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: "Courier New", Courier, monospace;
}
body {
user-select: none;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#viewport canvas:active {
cursor: grabbing;
}
.pixel-panel {
background: var(--panel);
border: 2px solid var(--line-bright);
box-shadow: var(--shadow);
backdrop-filter: blur(8px);
}
header {
position: fixed;
top: 18px;
left: 20px;
z-index: 10;
pointer-events: none;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
letter-spacing: 0.24em;
text-transform: uppercase;
margin-bottom: 5px;
}
h1 {
margin: 0;
font-size: clamp(19px, 2.2vw, 30px);
line-height: 1;
letter-spacing: -0.04em;
text-transform: uppercase;
text-shadow: 3px 3px 0 #123044;
}
#status {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 10px;
padding: 6px 9px;
border: 1px solid var(--line);
background: rgba(6, 16, 24, 0.86);
color: var(--muted);
font-size: 10px;
letter-spacing: 0.08em;
}
#statusDot {
width: 7px;
height: 7px;
background: var(--cyan);
box-shadow: 0 0 10px var(--cyan);
}
#statusDot.busy {
background: var(--yellow);
box-shadow: 0 0 10px var(--yellow);
}
#statusDot.warn {
background: var(--orange);
box-shadow: 0 0 10px var(--orange);
}
#controls {
position: fixed;
top: 120px;
left: 20px;
z-index: 12;
width: 304px;
max-height: calc(100vh - 145px);
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: var(--line-bright) var(--panel-solid);
}
#diagnostics {
position: fixed;
top: 20px;
right: 20px;
z-index: 12;
width: min(410px, calc(100vw - 40px));
max-height: calc(100vh - 40px);
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: var(--line-bright) var(--panel-solid);
}
.panel-body {
padding: 14px;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
color: var(--cyan);
font-size: 11px;
font-weight: bold;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.section-number {
color: #557b8e;
}
.rule {
height: 2px;
background: var(--line);
margin: 13px 0;
}
.control-block {
margin: 12px 0;
}
.control-label {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 12px;
margin-bottom: 7px;
font-size: 11px;
}
.control-label output {
color: var(--yellow);
font-weight: bold;
white-space: nowrap;
}
.control-help {
color: var(--muted);
font-size: 10px;
line-height: 1.45;
margin-top: 5px;
}
input[type="range"] {
width: 100%;
height: 18px;
margin: 0;
appearance: none;
background: transparent;
cursor: ew-resize;
}
input[type="range"]::-webkit-slider-runnable-track {
height: 6px;
background: #173345;
border: 1px solid #31566a;
}
input[type="range"]::-webkit-slider-thumb {
appearance: none;
width: 12px;
height: 16px;
margin-top: -6px;
background: var(--cyan);
border: 2px solid #d9fbff;
box-shadow: 2px 2px 0 #07131d;
}
input[type="range"]::-moz-range-track {
height: 5px;
background: #173345;
border: 1px solid #31566a;
}
input[type="range"]::-moz-range-thumb {
width: 10px;
height: 14px;
border: 2px solid #d9fbff;
border-radius: 0;
background: var(--cyan);
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
button {
appearance: none;
border: 1px solid var(--line-bright);
border-radius: 0;
background: #102635;
color: var(--text);
padding: 9px 8px;
font: 700 10px/1.2 "Courier New", Courier, monospace;
letter-spacing: 0.05em;
text-transform: uppercase;
cursor: pointer;
box-shadow: 3px 3px 0 #030b12;
transition: transform 80ms, background 80ms, color 80ms;
}
button:hover {
background: #19394b;
color: #ffffff;
transform: translate(-1px, -1px);
}
button:active {
transform: translate(2px, 2px);
box-shadow: 1px 1px 0 #030b12;
}
button.primary {
background: var(--cyan);
border-color: #d6faff;
color: #041019;
}
button.primary:hover {
background: #9cf3ff;
}
button.danger {
color: #ffb1b1;
}
.wide {
grid-column: 1 / -1;
}
.preset-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.preset-grid button {
min-height: 38px;
padding: 6px 4px;
font-size: 9px;
}
.switch-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 9px 0;
color: var(--muted);
font-size: 10px;
}
.switch-row label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
}
input[type="checkbox"] {
width: 14px;
height: 14px;
margin: 0;
accent-color: var(--cyan);
border-radius: 0;
}
.assumption-list {
margin: 0;
padding: 0;
list-style: none;
color: var(--muted);
font-size: 10px;
line-height: 1.65;
}
.assumption-list li {
display: flex;
justify-content: space-between;
gap: 12px;
border-bottom: 1px dotted #28495a;
padding: 3px 0;
}
.assumption-list strong {
color: var(--text);
font-weight: normal;
}
.cohort-box {
padding: 9px;
background: #071722;
border-left: 3px solid var(--cyan);
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.cohort-box strong {
color: var(--yellow);
}
#diagnosticTable {
width: 100%;
border-collapse: collapse;
font-size: 9px;
white-space: nowrap;
}
#diagnosticTable th {
padding: 6px 4px;
border-bottom: 1px solid var(--line-bright);
color: #78a1b1;
font-weight: normal;
text-align: right;
}
#diagnosticTable th:first-child,
#diagnosticTable th:nth-child(2) {
text-align: left;
}
#diagnosticTable td {
padding: 7px 4px;
border-bottom: 1px solid #173344;
text-align: right;
}
#diagnosticTable td:first-child,
#diagnosticTable td:nth-child(2) {
text-align: left;
}
#diagnosticTable tbody tr {
cursor: pointer;
}
#diagnosticTable tbody tr:hover {
background: #102a39;
}
#diagnosticTable tbody tr.selected {
background: #15384a;
box-shadow: inset 3px 0 0 var(--cyan);
}
.case-cell {
display: flex;
align-items: center;
gap: 6px;
}
.case-swatch {
width: 8px;
height: 8px;
flex: 0 0 auto;
box-shadow: 0 0 7px currentColor;
}
.state {
display: inline-block;
padding: 2px 4px;
border: 1px solid currentColor;
font-size: 8px;
}
.state.bound {
color: var(--green);
}
.state.escaped,
.state.escaping {
color: var(--orange);
}
.state.impact {
color: var(--red);
}
.chart-title {
display: flex;
justify-content: space-between;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
margin: 4px 0 5px;
text-transform: uppercase;
}
.chart {
display: block;
width: 100%;
height: 92px;
background: #06131c;
border: 1px solid #234354;
}
#selectedSummary {
margin-top: 10px;
padding: 9px;
background: #071722;
border-left: 3px solid var(--yellow);
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
#selectedSummary strong {
color: var(--text);
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 12px;
color: var(--muted);
font-size: 9px;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.legend-swatch {
width: 8px;
height: 8px;
}
#cameraHelp {
position: fixed;
right: 20px;
bottom: 18px;
z-index: 8;
padding: 8px 10px;
color: #7698a6;
background: rgba(5, 14, 21, 0.78);
border: 1px solid #1c3c4e;
font-size: 9px;
pointer-events: none;
}
.world-label {
position: fixed;
z-index: 7;
padding: 3px 6px;
color: var(--text);
background: rgba(4, 12, 18, 0.75);
border: 1px solid #31596d;
font-size: 9px;
letter-spacing: 0.08em;
pointer-events: none;
transform: translate(-50%, -50%);
white-space: nowrap;
}
#planetLabel {
color: var(--orange);
}
#launchLabel {
color: var(--yellow);
}
@media (max-width: 980px) {
#controls {
width: 272px;
}
#diagnostics {
width: 360px;
}
#cameraHelp {
display: none;
}
}
@media (max-width: 700px) {
header {
top: 10px;
left: 10px;
}
h1 {
font-size: 18px;
}
#controls {
top: auto;
bottom: 10px;
left: 10px;
width: calc(50vw - 15px);
max-height: 48vh;
}
#diagnostics {
top: 82px;
right: 10px;
width: calc(50vw - 15px);
max-height: calc(100vh - 165px);
}
.panel-body {
padding: 10px;
}
.preset-grid {
grid-template-columns: 1fr 1fr;
}
.assumption-list,
.control-help,
.legend {
font-size: 8px;
}
#diagnosticTable {
font-size: 8px;
}
#diagnosticTable th,
#diagnosticTable td {
padding: 5px 2px;
}
.world-label {
display: none;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<header>
<div class="eyebrow">Newtonian two-body laboratory</div>
<h1>Voxel Orbital Lab</h1>
<div id="status">
<span id="statusDot"></span>
<span id="statusText">READY · FIXED SITE R₀ = +6.000</span>
</div>
</header>
<section id="controls" class="pixel-panel">
<div class="panel-body">
<div class="section-title">
<span>Launch Control</span>
<span class="section-number">01</span>
</div>
<div class="control-block">
<div class="control-label">
<span>Fixed speed v₀</span>
<output id="speedOutput">0.340</output>
</div>
<input id="speed" type="range" min="0.12" max="0.75" step="0.005" value="0.34">
<div class="control-help">
<span id="speedRatio">0.833 v_circular</span> · Changing speed clears the current cohort.
</div>
</div>
<div class="rule"></div>
<div class="section-title">
<span>Local Direction Frame</span>
<span class="section-number">02</span>
</div>
<div class="control-block">
<div class="control-label">
<span>Heading θ</span>
<output id="headingOutput">0°</output>
</div>
<input id="heading" type="range" min="-180" max="180" step="1" value="0">
<div class="control-help">Rotates around the outward radial axis. 0° = +Z tangent.</div>
</div>
<div class="control-block">
<div class="control-label">
<span>Elevation φ</span>
<output id="elevationOutput">0°</output>
</div>
<input id="elevation" type="range" min="-90" max="90" step="1" value="0">
<div class="control-help">Tilts from tangent: −90° inward, +90° radially outward.</div>
</div>
<div class="control-block">
<div class="control-label">
<span>Direction Presets</span>
<output>FIXED r₀</output>
</div>
<div class="preset-grid">
<button data-heading="0" data-elevation="0">Tangent +Z</button>
<button data-heading="180" data-elevation="0">Tangent −Z</button>
<button data-heading="0" data-elevation="90">Outward</button>
<button data-heading="0" data-elevation="-90">Inward</button>
<button data-heading="45" data-elevation="25">Oblique</button>
<button data-heading="-45" data-elevation="-20">Retro tilt</button>
</div>
</div>
<div class="button-grid">
<button id="launchCurrent" class="primary wide">Launch Current Direction</button>
<button id="runSweep" class="wide">Run 5-Way Elevation Sweep</button>
<button id="clearCases" class="danger wide">Clear Comparison</button>
</div>
<div class="rule"></div>
<div class="section-title">
<span>Display</span>
<span class="section-number">03</span>
</div>
<div class="switch-row">
<label><input id="showVectors" type="checkbox" checked> Velocity preview</label>
<label><input id="showGrid" type="checkbox" checked> Grid</label>
</div>
<div class="cohort-box" id="cohortSummary">
No cases yet. All trajectories in a comparison use the same speed and launch position.
</div>
<div class="rule"></div>
<div class="section-title">
<span>Shared Assumptions</span>
<span class="section-number">A</span>
</div>
<ul class="assumption-list">
<li><span>Gravitational parameter</span><strong>μ = 1.000</strong></li>
<li><span>Launch position</span><strong>(+6, 0, 0)</strong></li>
<li><span>Body collision radius</span><strong>1.150</strong></li>
<li><span>Forces</span><strong>Point gravity only</strong></li>
<li><span>Integrator</span><strong>Velocity Verlet</strong></li>
<li><span>Time step / horizon</span><strong>0.04 / 190</strong></li>
<li><span>Drag / thrust / perturbations</span><strong>None</strong></li>
</ul>
</div>
</section>
<section id="diagnostics" class="pixel-panel">
<div class="panel-body">
<div class="section-title">
<span>Trajectory Diagnostics</span>
<span class="section-number">02</span>
</div>
<div class="cohort-box" id="diagnosticSummary" style="margin-bottom:12px">
Awaiting launch cases.
</div>
<div style="overflow-x:auto">
<table id="diagnosticTable">
<thead>
<tr>
<th>Case</th>
<th>State</th>
<th>a</th>
<th>e</th>
<th>|h|</th>
<th>Δε</th>
<th>Δh</th>
</tr>
</thead>
<tbody id="diagnosticRows"></tbody>
</table>
</div>
<div id="selectedSummary">
Select a case row to inspect its derived orbital elements.
</div>
<div class="rule"></div>
<div class="chart-title">
<span>Relative energy error</span>
<span>ppm</span>
</div>
<canvas id="energyPlot" class="chart"></canvas>
<div class="chart-title" style="margin-top:10px">
<span>Angular-momentum vector error</span>
<span>ppm</span>
</div>
<canvas id="momentumPlot" class="chart"></canvas>
<div class="rule"></div>
<div class="section-title">
<span>Case Legend</span>
<span class="section-number">L</span>
</div>
<div class="legend" id="legend"></div>
<div class="control-help" style="margin-top:10px">
Δε is scaled by max(|ε₀|, μ/r₀). Δh is the norm of the
angular-momentum vector error relative to its initial value.
Lower values indicate better conservation.
</div>
</div>
</section>
<div id="planetLabel" class="world-label">MASS μ = 1</div>
<div id="launchLabel" class="world-label">FIXED SITE</div>
<div id="cameraHelp">DRAG: ORBIT · WHEEL: ZOOM · SHIFT/DRAG: PAN · DOUBLE-CLICK: RESET</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/*
Voxel Orbital Laboratory
Physics:
- Newtonian point-mass gravity: a = -mu r / |r|^3
- Fixed launch position and a speed shared by every case in a cohort
- No drag, thrust, atmosphere, or third-body perturbations
- Velocity Verlet / leapfrog integration
- A trajectory terminates on the finite visual body radius or at r = 28
Visualization:
- Three.js core only
- Voxel trails are instanced cubes
- Camera controls are implemented directly below
*/
const MU = 1.0;
const START_RADIUS = 6.0;
const BODY_RADIUS = 1.15;
const ESCAPE_DISPLAY_RADIUS = 28.0;
const DT = 0.04;
const DURATION = 190.0;
const MAX_STEPS = Math.ceil(DURATION / DT);
const SAMPLE_EVERY = 6;
const START_POSITION = new THREE.Vector3(START_RADIUS, 0, 0);
const RADIAL = START_POSITION.clone().normalize();
const TANGENT = new THREE.Vector3(0, 0, 1);
const SIDE = new THREE.Vector3().crossVectors(RADIAL, TANGENT).normalize();
const PALETTE = [
0x58e6ff,
0xffad42,
0xa6ff60,
0xff5fa2,
0xb58cff,
0xffe15a,
0x68ffbe
];
const viewport = document.getElementById("viewport");
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.setClearColor(0x061018, 1);
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x061018, 0.009);
const camera = new THREE.PerspectiveCamera(
48,
window.innerWidth / window.innerHeight,
0.05,
180
);
const cameraState = {
radius: 23,
theta: 0.78,
phi: 1.03,
target: new THREE.Vector3(),
dragging: false,
panning: false,
pointerX: 0,
pointerY: 0
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
updateCamera();
scene.add(new THREE.AmbientLight(0x88bbcc, 1.35));
const keyLight = new THREE.DirectionalLight(0xc9f4ff, 3.0);
keyLight.position.set(8, 12, 6);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xff884d, 1.8);
rimLight.position.set(-10, 3, -7);
scene.add(rimLight);
/* -------------------------------------------------------------------------- */
/* Voxel environment */
/* -------------------------------------------------------------------------- */
const voxelGeometry = new THREE.BoxGeometry(1, 1, 1);
function createVoxelPlanet() {
const spacing = 0.22;
const half = spacing * 0.5;
const voxels = [];
const range = 7;
for (let x = -range; x <= range; x++) {
for (let y = -range; y <= range; y++) {
for (let z = -range; z <= range; z++) {
const p = new THREE.Vector3(x * spacing, y * spacing, z * spacing);
if (p.length() > 1.03) continue;
const neighborOffsets = [
[1, 0, 0], [-1, 0, 0],
[0, 1, 0], [0, -1, 0],
[0, 0, 1], [0, 0, -1]
];
const isSurface = neighborOffsets.some(([dx, dy, dz]) => {
const q = p.clone().add(new THREE.Vector3(dx, dy, dz).multiplyScalar(spacing));
return q.length() > 1.03;
});
if (isSurface) voxels.push(p);
}
}
}
const material = new THREE.MeshStandardMaterial({
roughness: 0.82,
metalness: 0.16,
vertexColors: true
});
const mesh = new THREE.InstancedMesh(voxelGeometry, material, voxels.length);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
voxels.forEach((p, index) => {
dummy.position.copy(p);
dummy.scale.set(half * 1.84, half * 1.84, half * 1.84);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
const latitude = p.y / 1.05;
const checker = (Math.floor(p.x / spacing) + Math.floor(p.z / spacing)) % 2;
color.set(0x1b637b);
color.lerp(new THREE.Color(0x2aa5bd), Math.max(0, latitude));
if (checker === 0) color.lerp(new THREE.Color(0x0b3448), 0.18);
mesh.setColorAt(index, color);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.instanceColor.needsUpdate = true;
scene.add(mesh);
return mesh;
}
const planet = createVoxelPlanet();
const grid = new THREE.GridHelper(40, 40, 0x315c70, 0x183747);
grid.material.transparent = true;
grid.material.opacity = 0.52;
grid.position.y = -0.02;
scene.add(grid);
function createVoxelStars() {
const count = 260;
const material = new THREE.MeshBasicMaterial({ color: 0x9dd8e5 });
const mesh = new THREE.InstancedMesh(voxelGeometry, material, count);
const dummy = new THREE.Object3D();
for (let i = 0; i < count; i++) {
const radius = 34 + Math.random() * 42;
const theta = Math.random() * Math.PI * 2;
const phi = Math.acos(2 * Math.random() - 1);
dummy.position.set(
radius * Math.sin(phi) * Math.cos(theta),
radius * Math.cos(phi),
radius * Math.sin(phi) * Math.sin(theta)
);
const s = 0.025 + Math.random() * 0.075;
dummy.scale.set(s, s, s);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
}
mesh.instanceMatrix.needsUpdate = true;
scene.add(mesh);
}
createVoxelStars();
function createLaunchMarker() {
const group = new THREE.Group();
group.position.copy(START_POSITION);
const core = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.34, 0.34),
new THREE.MeshBasicMaterial({ color: 0xffe15a })
);
group.add(core);
const bracketMaterial = new THREE.MeshBasicMaterial({ color: 0xffad42 });
const barGeometry = new THREE.BoxGeometry(0.52, 0.065, 0.065);
const sideGeometry = new THREE.BoxGeometry(0.065, 0.52, 0.065);
for (const signY of [-1, 1]) {
for (const signZ of [-1, 1]) {
const bar = new THREE.Mesh(barGeometry, bracketMaterial);
bar.position.set(0, signY * 0.28, signZ * 0.28);
group.add(bar);
}
}
for (const signX of [-1, 1]) {
for (const signZ of [-1, 1]) {
const bar = new THREE.Mesh(sideGeometry, bracketMaterial);
bar.position.set(signX * 0.28, 0, signZ * 0.28);
group.add(bar);
}
}
scene.add(group);
}
createLaunchMarker();
const previewArrow = new THREE.InstancedMesh(
voxelGeometry,
new THREE.MeshBasicMaterial({ color: 0xf2fdff }),
18
);
previewArrow.frustumCulled = false;
scene.add(previewArrow);
/* -------------------------------------------------------------------------- */
/* State and small DOM helpers */
/* -------------------------------------------------------------------------- */
const cases = [];
let selectedCaseId = null;
let caseCounter = 0;
const speedInput = document.getElementById("speed");
const headingInput = document.getElementById("heading");
const elevationInput = document.getElementById("elevation");
const speedOutput = document.getElementById("speedOutput");
const headingOutput = document.getElementById("headingOutput");
const elevationOutput = document.getElementById("elevationOutput");
const speedRatio = document.getElementById("speedRatio");
const diagnosticRows = document.getElementById("diagnosticRows");
const diagnosticSummary = document.getElementById("diagnosticSummary");
const selectedSummary = document.getElementById("selectedSummary");
const cohortSummary = document.getElementById("cohortSummary");
const legend = document.getElementById("legend");
const statusText = document.getElementById("statusText");
const statusDot = document.getElementById("statusDot");
const energyPlot = document.getElementById("energyPlot");
const momentumPlot = document.getElementById("momentumPlot");
function setStatus(message, mode = "") {
statusText.textContent = message;
statusDot.className = mode;
}
function hexCss(value) {
return "#" + value.toString(16).padStart(6, "0");
}
function signedDegrees(value) {
const rounded = Math.round(value);
return `${rounded > 0 ? "+" : ""}${rounded}°`;
}
function updateControlReadouts() {
const speed = Number(speedInput.value);
const heading = Number(headingInput.value);
const elevation = Number(elevationInput.value);
const circularSpeed = Math.sqrt(MU / START_RADIUS);
speedOutput.textContent = speed.toFixed(3);
headingOutput.textContent = signedDegrees(heading);
elevationOutput.textContent = signedDegrees(elevation);
speedRatio.textContent = `${(speed / circularSpeed).toFixed(3)} v_circular`;
}
function directionFromAngles(headingDegrees, elevationDegrees) {
const h = THREE.MathUtils.degToRad(headingDegrees);
const e = THREE.MathUtils.degToRad(elevationDegrees);
const tangentDirection = new THREE.Vector3()
.addScaledVector(TANGENT, Math.cos(h))
.addScaledVector(SIDE, Math.sin(h));
return new THREE.Vector3()
.addScaledVector(tangentDirection, Math.cos(e))
.addScaledVector(RADIAL, Math.sin(e))
.normalize();
}
function updatePreviewArrow() {
const direction = directionFromAngles(
Number(headingInput.value),
Number(elevationInput.value)
);
const dummy = new THREE.Object3D();
const cubeSize = 0.095;
let index = 0;
for (let i = 0; i < 10; i++) {
dummy.position.copy(START_POSITION).addScaledVector(direction, 0.35 + i * 0.095);
dummy.scale.set(cubeSize, cubeSize, cubeSize);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
previewArrow.setMatrixAt(index++, dummy.matrix);
}
const side = new THREE.Vector3(0, 1, 0).cross(direction);
if (side.lengthSq() < 0.001) side.set(1, 0, 0).cross(direction);
side.normalize();
const secondSide = new THREE.Vector3().crossVectors(direction, side).normalize();
const tip = START_POSITION.clone().addScaledVector(direction, 1.36);
const headOffsets = [
[0, 0],
[0.14, 0], [-0.14, 0],
[0.28, 0], [-0.28, 0],
[0.13, 0.13], [-0.13, 0.13]
];
for (const [a, b] of headOffsets) {
dummy.position.copy(tip)
.addScaledVector(side, a)
.addScaledVector(secondSide, b);
dummy.scale.set(cubeSize, cubeSize, cubeSize);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
previewArrow.setMatrixAt(index++, dummy.matrix);
}
previewArrow.count = index;
previewArrow.instanceMatrix.needsUpdate = true;
}
/* -------------------------------------------------------------------------- */
/* Two-body simulation */
/* -------------------------------------------------------------------------- */
function accelerationAt(position) {
const radiusSquared = Math.max(position.lengthSq(), 1e-12);
const radius = Math.sqrt(radiusSquared);
return position.clone().multiplyScalar(-MU / (radiusSquared * radius));
}
function specificEnergy(position, velocity) {
return velocity.lengthSq() * 0.5 - MU / position.length();
}
function angularMomentum(position, velocity) {
return new THREE.Vector3().crossVectors(position, velocity);
}
function orbitalElements(energy, hMagnitude) {
const bound = energy < -1e-10;
const a = bound ? -MU / (2 * energy) : null;
const eccentricity = Math.sqrt(Math.max(
0,
1 + (2 * energy * hMagnitude * hMagnitude) / (MU * MU)
));
return {
bound,
a,
e: eccentricity,
periapsis: bound ? a * (1 - eccentricity) : null,
apoapsis: bound ? a * (1 + eccentricity) : null,
period: bound ? 2 * Math.PI * Math.sqrt(a * a * a / MU) : null
};
}
function simulateTrajectory(direction) {
const position = START_POSITION.clone();
const velocity = direction.clone().multiplyScalar(Number(speedInput.value));
const previousPosition = position.clone();
const initialEnergy = specificEnergy(position, velocity);
const initialMomentum = angularMomentum(position, velocity);
const initialMomentumMagnitude = initialMomentum.length();
const initialElements = orbitalElements(initialEnergy, initialMomentumMagnitude);
const points = [position.clone()];
const energyHistory = [0];
const momentumHistory = [0];
let maxEnergyErrorPpm = 0;
let maxMomentumErrorPpm = 0;
let outcome = initialElements.bound ? "BOUND" : "ESCAPING";
let finalEnergy = initialEnergy;
let finalMomentum = initialMomentum.clone();
let acceleration = accelerationAt(position);
for (let step = 0; step < MAX_STEPS; step++) {
previousPosition.copy(position);
position.addScaledVector(velocity, DT);
position.addScaledVector(acceleration, 0.5 * DT * DT);
const nextAcceleration = accelerationAt(position);
velocity.addScaledVector(acceleration, 0.5 * DT);
velocity.addScaledVector(nextAcceleration, 0.5 * DT);
acceleration.copy(nextAcceleration);
const radius = position.length();
let collided = false;
if (radius <= BODY_RADIUS) {
const previousRadius = previousPosition.length();
const fraction = THREE.MathUtils.clamp(
(previousRadius - BODY_RADIUS) /
Math.max(previousRadius - radius, 1e-9),
0,
1
);
position.copy(previousPosition).lerp(position, fraction);
collided = true;
outcome = "IMPACT";
} else if (radius >= ESCAPE_DISPLAY_RADIUS) {
outcome = "ESCAPED";
}
finalEnergy = specificEnergy(position, velocity);
finalMomentum = angularMomentum(position, velocity);
const energyScale = Math.max(Math.abs(initialEnergy), MU / START_RADIUS);
const energyErrorPpm = Math.abs(finalEnergy - initialEnergy) / energyScale * 1e6;
let momentumErrorPpm = 0;
if (initialMomentumMagnitude > 1e-8) {
momentumErrorPpm = finalMomentum.distanceTo(initialMomentum) /
initialMomentumMagnitude * 1e6;
}
maxEnergyErrorPpm = Math.max(maxEnergyErrorPpm, energyErrorPpm);
maxMomentumErrorPpm = Math.max(maxMomentumErrorPpm, momentumErrorPpm);
if (step % SAMPLE_EVERY === 0 || collided || outcome === "ESCAPED") {
points.push(position.clone());
energyHistory.push(energyErrorPpm);
momentumHistory.push(momentumErrorPpm);
}
if (collided || outcome === "ESCAPED") break;
}
if (!initialElements.bound && outcome !== "ESCAPED") outcome = "ESCAPING";
if (initialElements.bound && outcome === "BOUND" && points.length > 2) {
// The finite simulation window is intentionally reported separately from
// the analytical bound/unbound classification.
outcome = "BOUND";
}
return {
points,
energyHistory,
momentumHistory,
initialEnergy,
finalEnergy,
initialMomentumMagnitude,
maxEnergyErrorPpm,
maxMomentumErrorPpm,
elements: initialElements,
outcome
};
}
/* -------------------------------------------------------------------------- */
/* Trajectory rendering */
/* -------------------------------------------------------------------------- */
function createTrajectoryVisual(result, color) {
const group = new THREE.Group();
const lineGeometry = new THREE.BufferGeometry().setFromPoints(result.points);
const lineMaterial = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.24
});
const line = new THREE.Line(lineGeometry, lineMaterial);
group.add(line);
const voxelMaterial = new THREE.MeshBasicMaterial({ color });
const voxels = new THREE.InstancedMesh(
voxelGeometry,
voxelMaterial,
result.points.length
);
voxels.frustumCulled = false;
const dummy = new THREE.Object3D();
result.points.forEach((point, index) => {
dummy.position.copy(point);
dummy.scale.set(0.078, 0.078, 0.078);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
voxels.setMatrixAt(index, dummy.matrix);
});
voxels.instanceMatrix.needsUpdate = true;
group.add(voxels);
scene.add(group);
return { group, lineGeometry, lineMaterial, voxelMaterial };
}
function disposeCaseVisual(visual) {
scene.remove(visual.group);
visual.lineGeometry.dispose();
visual.lineMaterial.dispose();
visual.voxelMaterial.dispose();
}
function addCase(name, heading, elevation) {
if (cases.length >= 7) {
setStatus("COHORT FULL · CLEAR OR SELECT A ROW", "warn");
return;
}
const color = PALETTE[caseCounter % PALETTE.length];
const direction = directionFromAngles(heading, elevation);
const result = simulateTrajectory(direction);
const visual = createTrajectoryVisual(result, color);
const item = {
id: ++caseCounter,
name,
heading,
elevation,
color,
direction,
result,
visual
};
cases.push(item);
selectedCaseId = item.id;
setStatus(`${cases.length} CASE${cases.length === 1 ? "" : "S"} · SAME v₀ AND r₀`);
updateDiagnostics();
}
function clearCases() {
for (const item of cases) disposeCaseVisual(item.visual);
cases.length = 0;
selectedCaseId = null;
updateDiagnostics();
setStatus("READY · FIXED SITE R₀ = +6.000");
}
/* -------------------------------------------------------------------------- */
/* Diagnostics UI */
/* -------------------------------------------------------------------------- */
function formatNumber(value, digits = 3) {
return Number.isFinite(value) ? value.toFixed(digits) : "—";
}
function stateClass(outcome) {
if (outcome === "BOUND") return "bound";
if (outcome === "IMPACT") return "impact";
return outcome.toLowerCase();
}
function updateDiagnostics() {
diagnosticRows.innerHTML = "";
legend.innerHTML = "";
if (cases.length === 0) {
diagnosticSummary.textContent = "Awaiting launch cases.";
cohortSummary.innerHTML =
"No cases yet. All trajectories in a comparison use the same speed and launch position.";
selectedSummary.textContent =
"Select a case row to inspect its derived orbital elements.";
drawDiagnosticCharts();
return;
}
const speed = Number(speedInput.value);
const circularSpeed = Math.sqrt(MU / START_RADIUS);
diagnosticSummary.innerHTML =
`<strong>${cases.length} cases</strong> share v₀ = ${speed.toFixed(3)} ` +
`(${(speed / circularSpeed).toFixed(3)} v_circ), r₀ = (6, 0, 0), μ = 1.`;
cohortSummary.innerHTML =
`<strong>FIXED COHORT:</strong> ${cases.length} launches · v₀ = ${speed.toFixed(3)} · ` +
`r₀ = (6, 0, 0). The site and speed never vary within this comparison.`;
for (const item of cases) {
const { result } = item;
const { elements } = result;
const row = document.createElement("tr");
row.dataset.caseId = item.id;
if (item.id === selectedCaseId) row.classList.add("selected");
row.innerHTML = `
<td>
<div class="case-cell" title="${item.name}">
<span class="case-swatch" style="background:${hexCss(item.color)};color:${hexCss(item.color)}"></span>
<span>${item.name}</span>
</div>
</td>
<td><span class="state ${stateClass(result.outcome)}">${result.outcome}</span></td>
<td>${formatNumber(elements.a, 2)}</td>
<td>${formatNumber(elements.e, 3)}</td>
<td>${formatNumber(result.initialMomentumMagnitude, 2)}</td>
<td title="Maximum relative specific-energy error">${formatNumber(result.maxEnergyErrorPpm, 2)}</td>
<td title="Maximum relative angular-momentum vector error">${formatNumber(result.maxMomentumErrorPpm, 2)}</td>
`;
row.addEventListener("click", () => {
selectedCaseId = item.id;
updateDiagnostics();
});
diagnosticRows.appendChild(row);
const legendItem = document.createElement("div");
legendItem.className = "legend-item";
legendItem.innerHTML =
`<span class="legend-swatch" style="background:${hexCss(item.color)}"></span>` +
`<span>${item.name}</span>`;
legend.appendChild(legendItem);
}
const selected = cases.find(item => item.id === selectedCaseId) || cases[cases.length - 1];
const e = selected.result.elements;
if (selected) {
const orbitText = e.bound
? `a = ${formatNumber(e.a, 3)} · e = ${formatNumber(e.e, 4)} · ` +
`rₚ = ${formatNumber(e.periapsis, 3)} · rₐ = ${formatNumber(e.apoapsis, 3)} · ` +
`T = ${formatNumber(e.period, 2)} time units`
: `Unbound trajectory · e = ${formatNumber(e.e, 4)} · ` +
`ε = ${formatNumber(selected.result.initialEnergy, 5)}`;
selectedSummary.innerHTML =
`<strong>${selected.name}</strong><br>${orbitText}<br>` +
`Outcome: <strong>${selected.result.outcome}</strong> · ` +
`θ = ${signedDegrees(selected.heading)} · φ = ${signedDegrees(selected.elevation)}`;
}
drawDiagnosticCharts();
}
/* -------------------------------------------------------------------------- */
/* Conservation charts */
/* -------------------------------------------------------------------------- */
function prepareChart(canvas) {
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const width = Math.max(1, Math.floor(canvas.clientWidth));
const height = Math.max(1, Math.floor(canvas.clientHeight));
if (canvas.width !== Math.floor(width * dpr) ||
canvas.height !== Math.floor(height * dpr)) {
canvas.width = Math.floor(width * dpr);
canvas.height = Math.floor(height * dpr);
}
const ctx = canvas.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "#06131c";
ctx.fillRect(0, 0, width, height);
return { ctx, width, height };
}
function drawHistoryPlot(canvas, historyKey, title) {
const { ctx, width, height } = prepareChart(canvas);
const padding = { left: 28, right: 7, top: 8, bottom: 15 };
const plotWidth = width - padding.left - padding.right;
const plotHeight = height - padding.top - padding.bottom;
let maxValue = 0;
for (const item of cases) {
for (const value of item.result[historyKey]) {
maxValue = Math.max(maxValue, Math.abs(value));
}
}
maxValue = Math.max(maxValue, 1) * 1.15;
ctx.strokeStyle = "#193848";
ctx.lineWidth = 1;
ctx.setLineDash([]);
for (let i = 0; i <= 4; i++) {
const x = padding.left + plotWidth * i / 4;
const y = padding.top + plotHeight * i / 4;
ctx.beginPath();
ctx.moveTo(x, padding.top);
ctx.lineTo(x, padding.top + plotHeight);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(padding.left, y);
ctx.lineTo(padding.left + plotWidth, y);
ctx.stroke();
}
ctx.strokeStyle = "#547385";
ctx.setLineDash([3, 3]);
ctx.beginPath();
ctx.moveTo(padding.left, padding.top + plotHeight / 2);
ctx.lineTo(padding.left + plotWidth, padding.top + plotHeight / 2);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = "#6f98a7";
ctx.font = "8px Courier New";
ctx.textAlign = "right";
ctx.fillText(
maxValue.toFixed(maxValue < 10 ? 1 : 0),
padding.left - 4,
padding.top + 4
);
ctx.fillText("0", padding.left - 4, padding.top + plotHeight / 2 + 3);
ctx.fillText(
(-maxValue).toFixed(maxValue < 10 ? 1 : 0),
padding.left - 4,
padding.top + plotHeight
);
ctx.textAlign = "left";
ctx.fillText(title, padding.left + 3, padding.top + 8);
for (const item of cases) {
const values = item.result[historyKey];
if (!values.length) continue;
ctx.strokeStyle = hexCss(item.color);
ctx.lineWidth = 1.6;
ctx.beginPath();
values.forEach((value, index) => {
const x = padding.left + plotWidth * index / Math.max(1, values.length - 1);
const y = padding.top + plotHeight * (0.5 - value / (2 * maxValue));
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
}
ctx.fillStyle = "#527787";
ctx.textAlign = "left";
ctx.fillText("0", padding.left, height - 3);
ctx.textAlign = "right";
ctx.fillText("TIME", width - padding.right, height - 3);
}
function drawDiagnosticCharts() {
drawHistoryPlot(energyPlot, "energyHistory", "ENERGY");
drawHistoryPlot(momentumPlot, "momentumHistory", "ANGULAR MOMENTUM");
}
/* -------------------------------------------------------------------------- */
/* Controls */
/* -------------------------------------------------------------------------- */
speedInput.addEventListener("input", () => {
updateControlReadouts();
if (cases.length) {
clearCases();
setStatus("SPEED CHANGED · COHORT CLEARED", "warn");
}
});
headingInput.addEventListener("input", () => {
updateControlReadouts();
updatePreviewArrow();
});
elevationInput.addEventListener("input", () => {
updateControlReadouts();
updatePreviewArrow();
});
document.querySelectorAll("[data-heading]").forEach(button => {
button.addEventListener("click", () => {
headingInput.value = button.dataset.heading;
elevationInput.value = button.dataset.elevation;
updateControlReadouts();
updatePreviewArrow();
setStatus("DIRECTION SET · READY TO LAUNCH");
});
});
document.getElementById("launchCurrent").addEventListener("click", () => {
const heading = Number(headingInput.value);
const elevation = Number(elevationInput.value);
const number = cases.filter(item =>
item.heading === heading && item.elevation === elevation
).length + 1;
addCase(`T${signedDegrees(heading)} E${signedDegrees(elevation)} #${number}`, heading, elevation);
});
document.getElementById("runSweep").addEventListener("click", () => {
clearCases();
const heading = Number(headingInput.value);
const elevations = [-32, -16, 0, 16, 32];
for (const elevation of elevations) {
addCase(
`E${signedDegrees(elevation)}`,
heading,
elevation
);
}
setStatus("5-WAY SWEEP · IDENTICAL v₀ AND r₀");
});
document.getElementById("clearCases").addEventListener("click", clearCases);
document.getElementById("showVectors").addEventListener("change", event => {
previewArrow.visible = event.target.checked;
});
document.getElementById("showGrid").addEventListener("change", event => {
grid.visible = event.target.checked;
});
/* -------------------------------------------------------------------------- */
/* Direct camera controls */
/* -------------------------------------------------------------------------- */
const canvas = renderer.domElement;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
cameraState.dragging = true;
cameraState.panning = event.button === 2 || event.shiftKey;
cameraState.pointerX = event.clientX;
cameraState.pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!cameraState.dragging) return;
const dx = event.clientX - cameraState.pointerX;
const dy = event.clientY - cameraState.pointerY;
cameraState.pointerX = event.clientX;
cameraState.pointerY = event.clientY;
if (cameraState.panning) {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const scale = cameraState.radius * 0.0014;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(up, dy * scale);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.006,
0.12,
Math.PI - 0.12
);
}
updateCamera();
});
function endPointerDrag(event) {
cameraState.dragging = false;
cameraState.panning = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointerDrag);
canvas.addEventListener("pointercancel", endPointerDrag);
canvas.addEventListener("wheel", event => {
event.preventDefault();
const factor = Math.exp(event.deltaY * 0.0012);
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * factor,
7,
75
);
updateCamera();
}, { passive: false });
canvas.addEventListener("dblclick", () => {
cameraState.radius = 23;
cameraState.theta = 0.78;
cameraState.phi = 1.03;
cameraState.target.set(0, 0, 0);
updateCamera();
});
/* -------------------------------------------------------------------------- */
/* Projected labels and resize */
/* -------------------------------------------------------------------------- */
function placeWorldLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
if (!visible) {
element.style.display = "none";
return;
}
element.style.display = "block";
element.style.left = `${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
drawDiagnosticCharts();
}
window.addEventListener("resize", onResize);
/* -------------------------------------------------------------------------- */
/* Animation */
/* -------------------------------------------------------------------------- */
updateControlReadouts();
updatePreviewArrow();
updateDiagnostics();
let previousTime = performance.now();
function animate(time) {
requestAnimationFrame(animate);
const delta = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
planet.rotation.y += delta * 0.075;
placeWorldLabel(
document.getElementById("planetLabel"),
new THREE.Vector3(0, 1.55, 0)
);
placeWorldLabel(
document.getElementById("launchLabel"),
START_POSITION.clone().add(new THREE.Vector3(0, 0.72, 0))
);
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```