Prompt specification
Build or customize the Three.js 3D scene "Echo-ranging model explorer" 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: Echo-ranging model explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/echo-ranging-model-explorer-x1544
Scene Description Prompt:
Allow moving a reflector and changing the stated propagation speed; compute distance from round-trip delay and explicitly distinguish one-way from two-way travel time. Build this with Three.js from cdnjs as a low-poly scene in one HTML file.
Working Three.js Starter (echo-ranging-model-explorer-x1544):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Round-Trip Distance Lab</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(12, 20, 30, 0.91);
--border: rgba(255, 255, 255, 0.14);
--muted: #a9bac9;
--cyan: #50d8ff;
--orange: #ffad45;
--green: #82e6a0;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #aec8d4;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#view {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#view:active {
cursor: grabbing;
}
.panel {
position: fixed;
top: 18px;
right: 18px;
width: min(390px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
overflow-y: auto;
padding: 20px;
color: #eef7ff;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 18px;
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(15px);
}
h1 {
margin: 0 0 6px;
font-size: 23px;
letter-spacing: -0.03em;
}
.intro {
margin: 0 0 18px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.field {
margin-top: 16px;
padding-top: 15px;
border-top: 1px solid rgba(255, 255, 255, 0.09);
}
label {
display: block;
margin-bottom: 8px;
font-size: 13px;
font-weight: 700;
}
.input-unit {
display: flex;
align-items: center;
gap: 8px;
}
input[type="number"] {
min-width: 0;
width: 100%;
padding: 10px 11px;
color: white;
background: rgba(255, 255, 255, 0.07);
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 9px;
outline: none;
font: inherit;
}
input[type="number"]:focus {
border-color: var(--cyan);
box-shadow: 0 0 0 3px rgba(80, 216, 255, 0.13);
}
input[type="range"] {
width: 100%;
margin: 12px 0 4px;
accent-color: var(--cyan);
}
.unit {
flex: 0 0 auto;
color: var(--muted);
font-size: 13px;
}
.range-labels {
display: flex;
justify-content: space-between;
color: #8295a7;
font-size: 10px;
}
.results {
display: grid;
gap: 9px;
margin-top: 18px;
}
.result {
padding: 11px 13px;
background: rgba(255, 255, 255, 0.055);
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 11px;
}
.result span {
display: block;
color: var(--muted);
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.result strong {
display: block;
margin: 3px 0;
font-size: 20px;
font-variant-numeric: tabular-nums;
}
.result code {
color: #9eb0bf;
font-size: 11px;
}
.result.primary {
background: rgba(80, 216, 255, 0.09);
border-color: rgba(80, 216, 255, 0.32);
}
.result.primary strong {
color: #b8efff;
font-size: 27px;
}
.note {
margin-top: 15px;
padding: 11px 12px;
color: #bfd0dc;
background: rgba(255, 173, 69, 0.08);
border-left: 3px solid var(--orange);
border-radius: 5px;
font-size: 12px;
line-height: 1.5;
}
.note strong {
color: #ffe0b5;
}
.error {
margin-top: 12px;
padding: 10px;
color: #ffd0d0;
background: rgba(255, 75, 75, 0.12);
border: 1px solid rgba(255, 75, 75, 0.3);
border-radius: 9px;
font-size: 12px;
line-height: 1.4;
}
[hidden] {
display: none !important;
}
button {
width: 100%;
margin-top: 15px;
padding: 10px 12px;
color: white;
background: rgba(255, 255, 255, 0.08);
border: 1px solid rgba(255, 255, 255, 0.17);
border-radius: 9px;
cursor: pointer;
font: inherit;
font-size: 12px;
font-weight: 700;
}
button:hover {
background: rgba(255, 255, 255, 0.13);
}
.legend {
position: fixed;
left: 18px;
bottom: 18px;
display: flex;
gap: 16px;
padding: 10px 13px;
color: white;
background: rgba(12, 20, 30, 0.82);
border: 1px solid var(--border);
border-radius: 10px;
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
font-size: 12px;
backdrop-filter: blur(10px);
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
}
.dot {
width: 9px;
height: 9px;
display: inline-block;
border-radius: 50%;
}
.dot.cyan {
background: var(--cyan);
box-shadow: 0 0 9px var(--cyan);
}
.dot.orange {
background: var(--orange);
box-shadow: 0 0 9px var(--orange);
}
.help {
position: fixed;
left: 18px;
top: 18px;
max-width: 310px;
padding: 10px 13px;
color: #eef7ff;
background: rgba(12, 20, 30, 0.78);
border: 1px solid var(--border);
border-radius: 10px;
font-size: 12px;
line-height: 1.5;
backdrop-filter: blur(10px);
}
@media (max-width: 720px) {
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 52vh;
padding: 15px;
border-radius: 14px;
}
.help {
top: 10px;
left: 10px;
max-width: calc(100vw - 20px);
}
.legend {
display: none;
}
}
</style>
</head>
<body>
<canvas id="view" aria-label="Interactive three-dimensional propagation scene"></canvas>
<div class="help">
<strong>Controls:</strong> drag the reflector to move it, drag empty space to orbit,
and use the mouse wheel to zoom.
</div>
<aside class="panel">
<h1>Round-Trip Distance Lab</h1>
<p class="intro">
Enter a measured echo delay and propagation speed. The reflector is placed
at the corresponding one-way distance.
</p>
<div class="field">
<label for="speedNumber">Stated propagation speed, v</label>
<div class="input-unit">
<input
id="speedNumber"
type="number"
min="100000"
max="1258925412"
step="1"
value="299792458"
inputmode="decimal"
>
<span class="unit">m/s</span>
</div>
<input
id="speedRange"
type="range"
min="5"
max="9.1"
step="0.001"
value="8.476820702"
aria-label="Propagation speed on a logarithmic scale"
>
<div class="range-labels">
<span>10⁵ m/s</span>
<span>10⁹·¹ m/s</span>
</div>
</div>
<div class="field">
<label for="delayNumber">Measured round-trip delay, T<sub>RT</sub></label>
<div class="input-unit">
<input
id="delayNumber"
type="number"
min="0"
step="any"
value="0.200138423"
inputmode="decimal"
>
<span class="unit">µs</span>
</div>
</div>
<div class="field">
<label for="distanceRange">Reflector position</label>
<input
id="distanceRange"
type="range"
min="1"
max="100"
step="0.01"
value="30"
>
<div class="range-labels">
<span>1 m</span>
<span>100 m</span>
</div>
</div>
<div class="results" aria-live="polite">
<div class="result">
<span>Two-way / round-trip travel time</span>
<strong id="twoWayOut">—</strong>
<code>T<sub>RT</sub> = outbound time + return time</code>
</div>
<div class="result">
<span>One-way travel time</span>
<strong id="oneWayOut">—</strong>
<code>T<sub>one-way</sub> = T<sub>RT</sub> / 2</code>
</div>
<div class="result primary">
<span>Distance computed from round-trip delay</span>
<strong id="distanceOut">—</strong>
<code>D = v × (T<sub>RT</sub> / 2)</code>
</div>
<div class="result">
<span>Total distance traveled by the pulse</span>
<strong id="pathOut">—</strong>
<code>v × T<sub>RT</sub> = 2D, not D</code>
</div>
</div>
<div class="note">
<strong>Important:</strong> the round-trip delay is the total elapsed time
for the pulse to reach the reflector and return. Multiplying it directly
by <em>v</em> gives the total path length, <em>2D</em>. Divide the delay
by two before multiplying by the propagation speed to obtain the
source-to-reflector distance.
</div>
<div id="errorBox" class="error" role="alert" hidden></div>
<button id="resetView" type="button">Reset camera view</button>
</aside>
<div class="legend">
<span><i class="dot cyan"></i>Outbound pulse</span>
<span><i class="dot orange"></i>Returning pulse</span>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const SPEED_MIN = 1e5;
const SPEED_MAX = 10 ** 9.1;
const DISTANCE_MIN = 1;
const DISTANCE_MAX = 100;
const state = {
speed: 299792458,
distance: 30
};
// -------------------------------------------------------------------------
// Renderer, scene, camera, and lights
// -------------------------------------------------------------------------
const canvas = $("view");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d3dc);
scene.fog = new THREE.Fog(0xb9d3dc, 105, 245);
const camera = new THREE.PerspectiveCamera(
48,
window.innerWidth / window.innerHeight,
0.1,
400
);
const cameraTarget = new THREE.Vector3(state.distance / 2, 2.7, 0);
const cameraTargetGoal = cameraTarget.clone();
let cameraYaw = -0.30;
let cameraPitch = 0.54;
let cameraRadius = Math.max(68, state.distance * 0.9);
const hemisphere = new THREE.HemisphereLight(0xe2f5ff, 0x40583b, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffedc7, 2.8);
sun.position.set(35, 85, 45);
sun.target.position.set(50, 0, 0);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -110;
sun.shadow.camera.right = 110;
sun.shadow.camera.top = 85;
sun.shadow.camera.bottom = -85;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 230;
sun.shadow.normalBias = 0.035;
scene.add(sun, sun.target);
// -------------------------------------------------------------------------
// Low-poly landscape
// -------------------------------------------------------------------------
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x718f63,
roughness: 1,
flatShading: true
});
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(240, 130),
groundMaterial
);
ground.rotation.x = -Math.PI / 2;
ground.position.x = 50;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(220, 44, 0x536c55, 0x607a5c);
grid.position.x = 50;
grid.position.y = 0.025;
grid.material.transparent = true;
grid.material.opacity = 0.55;
scene.add(grid);
const mountainMaterial = new THREE.MeshStandardMaterial({
color: 0x6e8790,
roughness: 1,
flatShading: true
});
function addMountain(x, z, radius, height, color) {
const material = mountainMaterial.clone();
material.color.setHex(color);
const mountain = new THREE.Mesh(
new THREE.ConeGeometry(radius, height, 5),
material
);
mountain.position.set(x, height / 2 - 0.2, z);
mountain.rotation.y = x * 0.13;
mountain.castShadow = true;
mountain.receiveShadow = true;
scene.add(mountain);
}
addMountain(-30, -46, 18, 29, 0x71848a);
addMountain(18, -52, 23, 38, 0x637b82);
addMountain(72, -48, 20, 31, 0x788b8f);
addMountain(126, -50, 25, 42, 0x667b83);
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x674d36,
roughness: 1,
flatShading: true
});
const foliageMaterial = new THREE.MeshStandardMaterial({
color: 0x315c43,
roughness: 1,
flatShading: true
});
function addTree(x, z, scale = 1) {
const tree = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.25, 0.38, 2.1, 5),
trunkMaterial
);
trunk.position.y = 1.05;
const foliage = new THREE.Mesh(
new THREE.ConeGeometry(1.45, 3.7, 6),
foliageMaterial
);
foliage.position.y = 3.2;
tree.add(trunk, foliage);
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
tree.traverse((object) => {
if (object.isMesh) {
object.castShadow = true;
object.receiveShadow = true;
}
});
scene.add(tree);
}
[
[-18, -20, 1.1],
[-7, -29, 0.8],
[8, -18, 1.0],
[22, -28, 0.75],
[39, -22, 1.15],
[55, -30, 0.9],
[83, -18, 1.0],
[110, -29, 1.2],
[132, -16, 0.85]
].forEach((values) => addTree(...values));
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x89928c,
roughness: 1,
flatShading: true
});
[
[-12, 13, 1.2],
[18, -8, 0.9],
[46, 17, 1.4],
[73, -9, 0.8],
[111, 14, 1.15]
].forEach(([x, z, scale]) => {
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(scale, 0),
rockMaterial
);
rock.position.set(x, scale * 0.45, z);
rock.rotation.set(x * 0.1, z * 0.2, x * 0.07);
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
});
// -------------------------------------------------------------------------
// Transmitter/source
// -------------------------------------------------------------------------
const sourceGroup = new THREE.Group();
scene.add(sourceGroup);
const sourceBaseMaterial = new THREE.MeshStandardMaterial({
color: 0x455662,
roughness: 0.8,
flatShading: true
});
const sourceBase = new THREE.Mesh(
new THREE.CylinderGeometry(2.7, 3.1, 1.2, 8),
sourceBaseMaterial
);
sourceBase.position.y = 0.6;
sourceGroup.add(sourceBase);
const sourceTower = new THREE.Mesh(
new THREE.CylinderGeometry(0.85, 1.25, 4.0, 6),
sourceBaseMaterial
);
sourceTower.position.y = 3.0;
sourceGroup.add(sourceTower);
const sourceEmitterMaterial = new THREE.MeshStandardMaterial({
color: 0x7de7ff,
emissive: 0x24bfe8,
emissiveIntensity: 1.6,
roughness: 0.35,
flatShading: true
});
const sourceEmitter = new THREE.Mesh(
new THREE.OctahedronGeometry(1.35, 0),
sourceEmitterMaterial
);
sourceEmitter.position.y = 5.3;
sourceGroup.add(sourceEmitter);
const sourceHaloMaterial = new THREE.MeshBasicMaterial({
color: 0x50d8ff,
wireframe: true,
transparent: true,
opacity: 0.35
});
const sourceHalo = new THREE.Mesh(
new THREE.SphereGeometry(2.15, 8, 6),
sourceHaloMaterial
);
sourceHalo.position.y = 5.3;
sourceGroup.add(sourceHalo);
const sourceLight = new THREE.PointLight(0x50d8ff, 8, 12, 2);
sourceLight.position.y = 5.3;
sourceGroup.add(sourceLight);
// -------------------------------------------------------------------------
// Reflector
// -------------------------------------------------------------------------
const reflectorGroup = new THREE.Group();
scene.add(reflectorGroup);
const reflectorBase = new THREE.Mesh(
new THREE.CylinderGeometry(2.0, 2.4, 0.9, 8),
sourceBaseMaterial
);
reflectorBase.position.y = 0.45;
reflectorGroup.add(reflectorBase);
const reflectorPost = new THREE.Mesh(
new THREE.CylinderGeometry(0.38, 0.55, 4.8, 6),
sourceBaseMaterial
);
reflectorPost.position.y = 3.0;
reflectorGroup.add(reflectorPost);
const panelMaterial = new THREE.MeshStandardMaterial({
color: 0xffb65c,
emissive: 0xb85d13,
emissiveIntensity: 0.18,
roughness: 0.55,
metalness: 0.18,
flatShading: true
});
const reflectorPanel = new THREE.Mesh(
new THREE.BoxGeometry(0.7, 6.2, 6.2),
panelMaterial
);
reflectorPanel.position.y = 5.3;
reflectorPanel.castShadow = true;
reflectorPanel.receiveShadow = true;
reflectorGroup.add(reflectorPanel);
const panelEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(reflectorPanel.geometry),
new THREE.LineBasicMaterial({ color: 0x5f3b20 })
);
panelEdges.position.copy(reflectorPanel.position);
reflectorGroup.add(panelEdges);
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(3.5, 0.11, 5, 18),
new THREE.MeshBasicMaterial({ color: 0xffb04a })
);
selectionRing.rotation.x = Math.PI / 2;
selectionRing.position.y = 0.14;
reflectorGroup.add(selectionRing);
// Transparent mesh used as a larger, easier drag target.
const reflectorPick = new THREE.Mesh(
new THREE.BoxGeometry(2.8, 9.5, 8.5),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
})
);
reflectorPick.position.y = 4.8;
reflectorGroup.add(reflectorPick);
// -------------------------------------------------------------------------
// Dynamic beam, measurement bracket, and labels
// -------------------------------------------------------------------------
const beamGeometry = new THREE.BufferGeometry();
beamGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(6), 3)
);
const beam = new THREE.Line(
beamGeometry,
new THREE.LineBasicMaterial({
color: 0xbbefff,
transparent: true,
opacity: 0.72
})
);
scene.add(beam);
const measureGeometry = new THREE.BufferGeometry();
measureGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(16 * 3), 3)
);
const measurement = new THREE.LineSegments(
measureGeometry,
new THREE.LineBasicMaterial({
color: 0xffd28a,
transparent: true,
opacity: 0.9
})
);
scene.add(measurement);
function createTextSprite(text, accent = "#50d8ff") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
function update(nextText) {
context.clearRect(0, 0, labelCanvas.width, labelCanvas.height);
context.fillStyle = "rgba(10, 18, 27, 0.84)";
context.fillRect(0, 0, labelCanvas.width, labelCanvas.height);
context.fillStyle = accent;
context.fillRect(0, 0, 10, labelCanvas.height);
context.fillStyle = "#ffffff";
context.font = "bold 43px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(
nextText,
labelCanvas.width / 2,
labelCanvas.height / 2,
labelCanvas.width - 36
);
texture.needsUpdate = true;
}
update(text);
return { sprite, update };
}
const sourceLabel = createTextSprite("SOURCE", "#50d8ff");
sourceLabel.sprite.position.set(0, 10.3, 0);
sourceLabel.sprite.scale.set(11.5, 2.9, 1);
scene.add(sourceLabel.sprite);
const reflectorLabel = createTextSprite("REFLECTOR", "#ffad45");
reflectorLabel.sprite.scale.set(14, 3.0, 1);
scene.add(reflectorLabel.sprite);
const distanceLabel = createTextSprite("30.00 m", "#ffe0a3");
distanceLabel.sprite.scale.set(13, 3.1, 1);
scene.add(distanceLabel.sprite);
function updateBeamAndMeasurement() {
const beamPositions = beamGeometry.attributes.position;
beamPositions.setXYZ(0, 0, 5.3, 0);
beamPositions.setXYZ(1, state.distance, 5.3, 0);
beamPositions.needsUpdate = true;
beamGeometry.computeBoundingSphere();
const positions = measureGeometry.attributes.position;
let index = 0;
const segment = (x1, y1, z1, x2, y2, z2) => {
positions.setXYZ(index++, x1, y1, z1);
positions.setXYZ(index++, x2, y2, z2);
};
segment(0, 0.08, 9, state.distance, 0.08, 9);
segment(0, 0.08, 7.5, 0, 0.08, 10.5);
segment(
state.distance,
0.08,
7.5,
state.distance,
0.08,
10.5
);
segment(0, 0.08, 9, 1.4, 0.08, 8.2);
segment(0, 0.08, 9, 1.4, 0.08, 9.8);
segment(
state.distance,
0.08,
9,
state.distance - 1.4,
0.08,
8.2
);
segment(
state.distance,
0.08,
9,
state.distance - 1.4,
0.08,
9.8
);
positions.needsUpdate = true;
measureGeometry.computeBoundingSphere();
reflectorLabel.sprite.position.x = state.distance;
distanceLabel.sprite.position.x = state.distance / 2;
distanceLabel.update(`${state.distance.toFixed(2)} m`);
}
// -------------------------------------------------------------------------
// Outbound and returning pulse visuals
// -------------------------------------------------------------------------
function createPulse(color) {
const group = new THREE.Group();
group.position.y = 5.3;
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 2.0,
roughness: 0.3,
transparent: true,
opacity: 0.95,
flatShading: true
});
const sphere = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.72, 0),
material
);
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.55, 1.45, 4),
material
);
group.add(sphere, arrow);
scene.add(group);
group.visible = false;
return { group, sphere, arrow, material };
}
const outboundPulse = createPulse(0x50d8ff);
outboundPulse.arrow.position.x = 1.35;
outboundPulse.arrow.rotation.z = -Math.PI / 2;
const returningPulse = createPulse(0xffad45);
returningPulse.arrow.position.x = -1.35;
returningPulse.arrow.rotation.z = Math.PI / 2;
// -------------------------------------------------------------------------
// Calculations and UI synchronization
// -------------------------------------------------------------------------
function formatDuration(seconds) {
if (seconds >= 1) {
return `${seconds.toFixed(6)} s`;
}
if (seconds >= 1e-3) {
return `${(seconds * 1e3).toFixed(6)} ms`;
}
if (seconds >= 1e-6) {
return `${(seconds * 1e6).toFixed(6)} µs`;
}
return `${(seconds * 1e9).toFixed(3)} ns`;
}
function showError(message) {
$("errorBox").textContent = message;
$("errorBox").hidden = false;
}
function clearError() {
$("errorBox").hidden = true;
$("errorBox").textContent = "";
}
function refreshDerivedValues(writeDelay = true) {
// Geometric round-trip time for the current reflector position.
const geometricRoundTrip = (2 * state.distance) / state.speed;
if (writeDelay) {
$("delayNumber").value = (geometricRoundTrip * 1e6).toFixed(9);
}
// Read back the displayed measured delay so the main result is explicitly
// calculated from the round-trip delay rather than directly from position.
const measuredRoundTripMicroseconds = Number($("delayNumber").value);
const roundTripSeconds = measuredRoundTripMicroseconds * 1e-6;
const oneWaySeconds = roundTripSeconds / 2;
// D = v * (T_RT / 2)
const distanceFromDelay = state.speed * oneWaySeconds;
// This is the full path traveled by the pulse: v * T_RT = 2D.
const totalPath = state.speed * roundTripSeconds;
$("twoWayOut").textContent = formatDuration(roundTripSeconds);
$("oneWayOut").textContent = formatDuration(oneWaySeconds);
$("distanceOut").textContent = `${distanceFromDelay.toFixed(3)} m`;
$("pathOut").textContent = `${totalPath.toFixed(3)} m`;
}
function syncDistanceGeometry() {
reflectorGroup.position.x = state.distance;
$("distanceRange").value = state.distance.toFixed(3);
updateBeamAndMeasurement();
cameraTargetGoal.x = state.distance / 2;
cameraRadius = Math.max(cameraRadius, state.distance * 0.9);
refreshDerivedValues(true);
}
function setDistance(distance) {
state.distance = THREE.MathUtils.clamp(
distance,
DISTANCE_MIN,
DISTANCE_MAX
);
syncDistanceGeometry();
}
function setSpeed(value) {
const speed = Number(value);
if (
!Number.isFinite(speed) ||
speed < SPEED_MIN ||
speed > SPEED_MAX
) {
showError(
`Propagation speed must be between ${SPEED_MIN.toLocaleString()} ` +
`and ${Math.floor(SPEED_MAX).toLocaleString()} m/s.`
);
$("speedNumber").value = state.speed;
return;
}
state.speed = speed;
$("speedNumber").value = Number(speed.toPrecision(12));
$("speedRange").value = Math.log10(speed);
clearError();
// Changing speed preserves reflector position and recalculates delay.
refreshDerivedValues(true);
}
function commitDelay() {
const roundTripMicroseconds = Number($("delayNumber").value);
const roundTripSeconds = roundTripMicroseconds * 1e-6;
const distance =
state.speed * (roundTripSeconds / 2);
if (
!Number.isFinite(roundTripMicroseconds) ||
roundTripMicroseconds <= 0 ||
!Number.isFinite(distance) ||
distance < DISTANCE_MIN ||
distance > DISTANCE_MAX
) {
showError(
"That delay would place the reflector outside the 1–100 m scene. " +
"Choose a delay that produces a distance in that range."
);
refreshDerivedValues(true);
return;
}
clearError();
state.distance = distance;
syncDistanceGeometry();
}
$("speedNumber").addEventListener("change", () => {
setSpeed($("speedNumber").value);
});
$("speedNumber").addEventListener("input", () => {
const speed = Number($("speedNumber").value);
if (Number.isFinite(speed) && speed >= SPEED_MIN && speed <= SPEED_MAX) {
$("speedRange").value = Math.log10(speed);
}
});
$("speedRange").addEventListener("input", () => {
setSpeed(10 ** Number($("speedRange").value));
});
$("delayNumber").addEventListener("change", commitDelay);
$("distanceRange").addEventListener("input", () => {
clearError();
setDistance(Number($("distanceRange").value));
});
// -------------------------------------------------------------------------
// Custom camera controls and reflector dragging
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const dragPoint = new THREE.Vector3();
let dragMode = null;
let lastPointerX = 0;
let lastPointerY = 0;
function updatePointer(event) {
const bounds = canvas.getBoundingClientRect();
pointer.x =
((event.clientX - bounds.left) / bounds.width) * 2 - 1;
pointer.y =
-((event.clientY - bounds.top) / bounds.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
canvas.addEventListener("pointerdown", (event) => {
updatePointer(event);
const hits = raycaster.intersectObject(reflectorPick, false);
if (hits.length > 0) {
dragMode = "reflector";
canvas.style.cursor = "ew-resize";
} else {
dragMode = "camera";
canvas.style.cursor = "grabbing";
}
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (dragMode === "reflector") {
updatePointer(event);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
clearError();
setDistance(dragPoint.x);
}
} else if (dragMode === "camera") {
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
cameraYaw -= deltaX * 0.005;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + deltaY * 0.004,
0.18,
1.35
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
}
});
function endPointerInteraction(event) {
dragMode = null;
canvas.style.cursor = "grab";
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointerInteraction);
canvas.addEventListener("pointercancel", endPointerInteraction);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
24,
190
);
},
{ passive: false }
);
$("resetView").addEventListener("click", () => {
cameraYaw = -0.30;
cameraPitch = 0.54;
cameraRadius = Math.max(68, state.distance * 0.9);
cameraTargetGoal.set(state.distance / 2, 2.7, 0);
cameraTarget.copy(cameraTargetGoal);
});
function updateCamera(delta) {
const smoothing = 1 - Math.exp(-delta * 7);
cameraTarget.lerp(cameraTargetGoal, smoothing);
const horizontalRadius = Math.cos(cameraPitch) * cameraRadius;
camera.position.set(
cameraTarget.x +
horizontalRadius * Math.sin(cameraYaw),
cameraTarget.y +
Math.sin(cameraPitch) * cameraRadius,
cameraTarget.z +
horizontalRadius * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let elapsed = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
elapsed += delta;
// The visual cycle is deliberately slowed for visibility. Numerical
// calculations always use the actual stated speed and round-trip delay.
const cycle = 4.2;
const phase = (elapsed % cycle) / cycle;
const outboundEnd = 0.38;
const returnStart = 0.50;
const returnEnd = 0.88;
outboundPulse.group.visible = false;
returningPulse.group.visible = false;
let arrivalFlash = 0;
if (phase < outboundEnd) {
const progress = phase / outboundEnd;
outboundPulse.group.visible = true;
outboundPulse.group.position.x = progress * state.distance;
} else if (phase < returnStart) {
// Brief pause at the reflector.
} else if (phase < returnEnd) {
const progress = (phase - returnStart) / (returnEnd - returnStart);
returningPulse.group.visible = true;
returningPulse.group.position.x =
state.distance * (1 - progress);
}
if (
phase >= outboundEnd - 0.025 &&
phase <= outboundEnd + 0.025
) {
arrivalFlash = 1;
}
if (
phase >= returnEnd - 0.025 &&
phase <= returnEnd + 0.025
) {
arrivalFlash = 1;
}
const sourceFlash =
phase < 0.025 ||
(phase > returnEnd - 0.025 && phase < returnEnd + 0.02)
? 1
: 0;
sourceEmitter.material.emissiveIntensity = 1.6 + sourceFlash * 3.2;
sourceLight.intensity = 8 + sourceFlash * 12;
sourceHalo.scale.setScalar(1 + sourceFlash * 0.7);
sourceHaloMaterial.opacity = 0.30 + sourceFlash * 0.45;
panelMaterial.emissiveIntensity = 0.18 + arrivalFlash * 1.3;
updateCamera(delta);
renderer.render(scene, camera);
}
// -------------------------------------------------------------------------
// Initialize and handle viewport changes
// -------------------------------------------------------------------------
$("speedRange").value = Math.log10(state.speed);
$("speedNumber").value = state.speed;
reflectorGroup.position.x = state.distance;
updateBeamAndMeasurement();
refreshDerivedValues(true);
window.addEventListener("resize", () => {
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
});
animate();
</script>
</body>
</html>
```