Prompt specification
Build or customize the Three.js 3D scene "Wave speed and frequency 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: Wave speed and frequency explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/wave-speed-and-frequency-explorer-x1600
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a voxel traveling-wave explorer. Arrange a long row of marked particles, each moving vertically while the wave pattern travels horizontally. Add separate frequency and propagation-speed controls; changing either must update wavelength consistently with v = f times lambda. Show a second faint row at the particles' equilibrium positions, and trace one selected particle's motion so it is clear that the particles do not travel along with the pattern. Use an analytic sinusoidal wave and display the chosen units. A side ruler can mark one wavelength. Keep the cubic particles distinct even at the shortest allowed wavelength.
Working Three.js Starter (wave-speed-and-frequency-explorer-x1600):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Traveling-Wave Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #06101d;
--panel: #0a1728;
--panel-2: #0e2035;
--border: rgba(151, 190, 232, 0.16);
--text: #e8f2ff;
--muted: #92a8c1;
--cyan: #55e5ff;
--blue: #7898ff;
--gold: #ffd166;
--pink: #ff5bd8;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
width: 100%;
height: 100%;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 35%, #122642 0%, #071322 48%, #040a13 100%);
}
#viewport canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#viewport canvas:active {
cursor: grabbing;
}
.scene-header {
position: absolute;
z-index: 2;
top: 22px;
left: 24px;
pointer-events: none;
}
.eyebrow {
margin-bottom: 5px;
color: var(--cyan);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.scene-header h2 {
margin: 0;
font-size: clamp(1.1rem, 2vw, 1.55rem);
font-weight: 700;
letter-spacing: -0.02em;
}
.scene-header p {
margin: 6px 0 0;
color: var(--muted);
font-size: 0.84rem;
}
.scene-chips {
position: absolute;
z-index: 2;
top: 24px;
right: 22px;
display: flex;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
pointer-events: none;
}
.chip {
padding: 7px 10px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(5, 14, 27, 0.76);
backdrop-filter: blur(10px);
color: #c9d9eb;
font-size: 0.74rem;
font-variant-numeric: tabular-nums;
}
.chip strong {
color: var(--cyan);
}
.scene-help {
position: absolute;
z-index: 2;
left: 24px;
bottom: 22px;
display: flex;
gap: 16px;
align-items: center;
padding: 10px 13px;
border: 1px solid var(--border);
border-radius: 12px;
background: rgba(5, 14, 27, 0.74);
backdrop-filter: blur(10px);
color: var(--muted);
font-size: 0.76rem;
pointer-events: none;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
}
.legend-item {
display: inline-flex;
gap: 7px;
align-items: center;
white-space: nowrap;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 2px;
box-shadow: 0 0 10px currentColor;
}
.swatch.particle {
color: var(--cyan);
background: var(--cyan);
}
.swatch.equilibrium {
color: #8293a7;
background: #8293a7;
opacity: 0.65;
}
.swatch.crest {
color: var(--pink);
background: var(--pink);
border-radius: 50%;
}
.swatch.trace {
color: var(--gold);
background: var(--gold);
}
aside {
position: relative;
z-index: 3;
height: 100%;
overflow-y: auto;
padding: 25px 23px 28px;
border-left: 1px solid var(--border);
background:
linear-gradient(180deg, rgba(14, 32, 53, 0.98), rgba(7, 18, 32, 0.99));
box-shadow: -20px 0 50px rgba(0, 0, 0, 0.18);
}
aside h1 {
margin: 0;
font-size: 1.55rem;
line-height: 1.12;
letter-spacing: -0.035em;
}
.intro {
margin: 10px 0 20px;
color: var(--muted);
font-size: 0.87rem;
line-height: 1.55;
}
.card {
margin-top: 14px;
padding: 16px;
border: 1px solid var(--border);
border-radius: 15px;
background: rgba(4, 13, 25, 0.44);
}
.card-title {
margin: 0 0 13px;
color: #d9e8f8;
font-size: 0.78rem;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.control + .control {
margin-top: 18px;
}
.control-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
}
.control-heading label {
color: #dce9f8;
font-size: 0.86rem;
font-weight: 650;
}
output {
color: var(--cyan);
font-size: 0.88rem;
font-weight: 750;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 20px;
margin: 0;
accent-color: var(--cyan);
cursor: pointer;
}
.range-labels {
display: flex;
justify-content: space-between;
margin-top: 3px;
color: #70869f;
font-size: 0.68rem;
font-variant-numeric: tabular-nums;
}
.equation {
margin-top: 15px;
padding: 13px;
border: 1px solid rgba(85, 229, 255, 0.18);
border-radius: 11px;
background: rgba(24, 90, 116, 0.12);
text-align: center;
font-size: 1rem;
font-weight: 750;
font-variant-numeric: tabular-nums;
}
.equation .speed {
color: var(--cyan);
}
.equation .frequency {
color: var(--blue);
}
.equation .wavelength {
color: var(--gold);
}
.operator {
margin: 0 4px;
color: #9cb0c7;
}
.subtext {
margin: 8px 0 0;
color: var(--muted);
font-size: 0.72rem;
line-height: 1.45;
}
.readout-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 9px;
}
.readout {
padding: 11px;
border: 1px solid rgba(151, 190, 232, 0.1);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.readout span {
display: block;
margin-bottom: 4px;
color: #7f96af;
font-size: 0.67rem;
font-weight: 700;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.readout strong {
color: #e9f4ff;
font-size: 0.95rem;
font-variant-numeric: tabular-nums;
}
.ruler-heading {
display: flex;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
color: #dce9f8;
font-size: 0.8rem;
}
.ruler-heading strong {
color: var(--gold);
font-variant-numeric: tabular-nums;
}
.ruler-scale {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
gap: 9px;
align-items: center;
color: #7890a9;
font-size: 0.65rem;
font-variant-numeric: tabular-nums;
}
.ruler-track {
position: relative;
height: 24px;
border-right: 1px solid #6c8198;
border-left: 1px solid #6c8198;
background:
repeating-linear-gradient(
90deg,
transparent 0,
transparent 19px,
rgba(145, 170, 196, 0.16) 20px
);
}
.ruler-fill {
position: relative;
width: 24%;
min-width: 4px;
height: 100%;
border-right: 2px solid var(--gold);
background: linear-gradient(90deg, rgba(255, 209, 102, 0.13), rgba(255, 209, 102, 0.32));
transition: width 120ms ease-out;
}
.ruler-fill::after {
position: absolute;
top: 3px;
right: -4px;
width: 0;
height: 0;
border-top: 9px solid var(--gold);
border-right: 4px solid transparent;
border-left: 4px solid transparent;
content: "";
}
.ruler-note {
margin-top: 9px;
color: #8198b0;
font-size: 0.7rem;
line-height: 1.45;
}
.law {
color: #bfd0e3;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.78rem;
line-height: 1.65;
}
.law .accent {
color: var(--cyan);
}
.callout {
margin-top: 13px;
padding-left: 12px;
border-left: 3px solid var(--gold);
color: #c6d5e5;
font-size: 0.78rem;
line-height: 1.55;
}
.buttons {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 14px;
}
button {
min-height: 39px;
padding: 8px 9px;
border: 1px solid var(--border);
border-radius: 10px;
background: #10243a;
color: #d9e8f7;
font-size: 0.75rem;
font-weight: 700;
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
button:hover {
border-color: rgba(85, 229, 255, 0.45);
background: #16314d;
}
button:active {
transform: translateY(1px);
}
.units {
margin: 16px 2px 0;
color: #6f869f;
font-size: 0.68rem;
line-height: 1.5;
}
#loading {
position: absolute;
z-index: 5;
inset: 0;
display: grid;
place-items: center;
background: #06101d;
color: var(--muted);
font-size: 0.85rem;
transition: opacity 300ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 900px) {
html,
body {
overflow: auto;
}
#app {
display: block;
height: auto;
min-height: 100%;
}
#viewport {
height: 64vh;
min-height: 470px;
}
aside {
height: auto;
border-top: 1px solid var(--border);
border-left: 0;
}
.scene-chips {
top: auto;
right: 16px;
bottom: 80px;
}
.scene-help {
right: 16px;
left: 16px;
}
}
</style>
</head>
<body>
<div id="app">
<main id="viewport" aria-label="Interactive three-dimensional traveling-wave scene">
<div class="scene-header">
<div class="eyebrow">Interactive wave laboratory</div>
<h2>Transverse traveling wave</h2>
<p>Each voxel oscillates vertically while the pattern moves to the right.</p>
</div>
<div class="scene-chips">
<div class="chip">λ <strong id="sceneLambda">12.00 m</strong></div>
<div class="chip">Direction <strong>+x</strong></div>
<div class="chip">Units <strong>m · s · Hz</strong></div>
</div>
<div class="scene-help">
<div class="legend">
<span class="legend-item">
<i class="swatch particle"></i> particles
</span>
<span class="legend-item">
<i class="swatch equilibrium"></i> equilibrium row
</span>
<span class="legend-item">
<i class="swatch crest"></i> moving crest
</span>
<span class="legend-item">
<i class="swatch trace"></i> selected history
</span>
</div>
<span>Drag to orbit · Wheel to zoom · Click a cube to select it</span>
</div>
<div id="loading">Loading the wave explorer…</div>
</main>
<aside>
<div class="eyebrow">Three.js core</div>
<h1>Voxel Traveling-Wave Explorer</h1>
<p class="intro">
Explore a sinusoidal transverse wave. The particles stay at fixed
horizontal positions; only their vertical displacement changes.
</p>
<section class="card">
<h2 class="card-title">Wave controls</h2>
<div class="control">
<div class="control-heading">
<label for="frequency">Frequency</label>
<output id="frequencyValue" for="frequency">1.00 Hz</output>
</div>
<input
id="frequency"
type="range"
min="0.5"
max="2.5"
step="0.05"
value="1"
>
<div class="range-labels">
<span>0.50 Hz</span>
<span>2.50 Hz</span>
</div>
</div>
<div class="control">
<div class="control-heading">
<label for="speed">Propagation speed</label>
<output id="speedValue" for="speed">12.0 m/s</output>
</div>
<input
id="speed"
type="range"
min="5"
max="25"
step="0.5"
value="12"
>
<div class="range-labels">
<span>5.0 m/s</span>
<span>25.0 m/s</span>
</div>
</div>
<div class="equation" aria-live="polite">
<span class="speed" id="equationSpeed">12.0</span>
<span class="operator">m/s =</span>
<span class="frequency" id="equationFrequency">1.00</span>
<span class="operator">Hz ×</span>
<span class="wavelength" id="equationWavelength">12.00</span>
<span class="operator">m</span>
</div>
<p class="subtext" id="densityNote"></p>
</section>
<section class="card">
<h2 class="card-title">One-wavelength ruler</h2>
<div class="ruler-heading">
<span>Marked distance</span>
<strong id="rulerValue">12.00 m</strong>
</div>
<div class="ruler-scale">
<span>0</span>
<div class="ruler-track">
<div class="ruler-fill" id="rulerFill"></div>
</div>
<span>50 m</span>
</div>
<p class="ruler-note">
The side ruler uses a fixed 0–50 m scale. A matching bracket is drawn
directly on the 3D x-axis.
</p>
</section>
<section class="card">
<h2 class="card-title">Live measurements</h2>
<div class="readout-grid">
<div class="readout">
<span>Wavelength</span>
<strong id="wavelengthReadout">12.00 m</strong>
</div>
<div class="readout">
<span>Period</span>
<strong id="periodReadout">1.00 s</strong>
</div>
<div class="readout">
<span>Selected x</span>
<strong id="selectedXReadout">48.00 m</strong>
</div>
<div class="readout">
<span>Selected y</span>
<strong id="selectedYReadout">0.00 m</strong>
</div>
</div>
</section>
<section class="card">
<h2 class="card-title">Analytic wave law</h2>
<div class="law">
y(x,t) = A sin(kx − φ)<br>
<span class="accent">k = 2π/λ</span>,
dφ/dt = 2πf<br>
phase speed = ω/k = fλ = v
</div>
<div class="callout">
The gold trace belongs to one particle and remains at a fixed x.
The magenta crest moves horizontally with the pattern. Click any
voxel to change the traced particle.
</div>
<div class="buttons">
<button id="pauseButton" type="button">Pause</button>
<button id="traceButton" type="button">Reset trace</button>
<button id="cameraButton" type="button">Reset view</button>
</div>
</section>
<p class="units">
Units: horizontal position, wavelength, and amplitude in metres (m);
time and period in seconds (s); frequency in hertz (Hz); propagation
speed in metres per second (m/s).
</p>
</aside>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene and model
// -------------------------------------------------------------------------
const viewport = document.querySelector("#viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071321);
scene.fog = new THREE.Fog(0x071321, 125, 230);
const camera = new THREE.PerspectiveCamera(
42,
viewport.clientWidth / viewport.clientHeight,
0.1,
500
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.domElement.setAttribute(
"aria-label",
"Voxel particles oscillating in a horizontally traveling sinusoidal wave"
);
viewport.prepend(renderer.domElement);
const LENGTH = 96; // metres
const PARTICLE_COUNT = 121;
const DX = LENGTH / (PARTICLE_COUNT - 1);
const AMPLITUDE = 2.8; // metres
const state = {
frequency: 1.0, // Hz
speed: 12.0, // m/s
selectedIndex: 60,
phase: 0,
running: true
};
let wavelength = state.speed / state.frequency;
let waveNumber = (2 * Math.PI) / wavelength;
let selectedY = 0;
const cameraTarget = new THREE.Vector3(LENGTH * 0.5, -0.8, 0);
const cameraSpherical = new THREE.Spherical(112, 1.18, 0);
function applyCamera() {
camera.position.setFromSpherical(cameraSpherical).add(cameraTarget);
camera.lookAt(cameraTarget);
}
applyCamera();
// Lighting
scene.add(new THREE.HemisphereLight(0xb8ddff, 0x08111e, 1.9));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.5);
keyLight.position.set(20, 42, 65);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x876dff, 1.4);
rimLight.position.set(85, 18, -40);
scene.add(rimLight);
const cyanLight = new THREE.PointLight(0x38dfff, 32, 90, 2);
cyanLight.position.set(15, 8, 18);
scene.add(cyanLight);
// Ground reference grid
const grid = new THREE.GridHelper(
104,
26,
0x315879,
0x173047
);
grid.position.set(LENGTH * 0.5, -6.2, 0);
grid.material.transparent = true;
grid.material.opacity = 0.44;
grid.material.depthWrite = false;
scene.add(grid);
// Faint equilibrium guide and small equilibrium markers
const equilibriumLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(LENGTH, 0, 0)
]),
new THREE.LineBasicMaterial({
color: 0x7e91a7,
transparent: true,
opacity: 0.16
})
);
scene.add(equilibriumLine);
const equilibriumGeometry = new THREE.SphereGeometry(0.085, 8, 6);
const equilibriumMaterial = new THREE.MeshBasicMaterial({
color: 0x9aabbc,
transparent: true,
opacity: 0.42,
depthWrite: false
});
const equilibriumMesh = new THREE.InstancedMesh(
equilibriumGeometry,
equilibriumMaterial,
PARTICLE_COUNT
);
const instanceDummy = new THREE.Object3D();
for (let i = 0; i < PARTICLE_COUNT; i++) {
instanceDummy.position.set(i * DX, 0, 0.34);
instanceDummy.updateMatrix();
equilibriumMesh.setMatrixAt(i, instanceDummy.matrix);
}
equilibriumMesh.instanceMatrix.needsUpdate = true;
equilibriumMesh.frustumCulled = false;
scene.add(equilibriumMesh);
// Main cubic particles
const particleGeometry = new THREE.BoxGeometry(1, 1, 1);
const vertexColorMultiplier = new Float32Array(particleGeometry.attributes.position.count * 3).fill(1);
particleGeometry.setAttribute("color", new THREE.BufferAttribute(vertexColorMultiplier, 3));
const particleMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.3,
metalness: 0.12,
vertexColors: true
});
const particleMesh = new THREE.InstancedMesh(
particleGeometry,
particleMaterial,
PARTICLE_COUNT
);
particleMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
particleMesh.frustumCulled = false;
particleMesh.renderOrder = 2;
const color = new THREE.Color();
for (let i = 0; i < PARTICLE_COUNT; i++) {
if (i % 10 === 0) {
color.set(0x55e5ff);
} else {
color.setHSL(0.61 + (i % 3) * 0.008, 0.72, 0.61);
}
particleMesh.setColorAt(i, color);
}
particleMesh.instanceColor.needsUpdate = true;
scene.add(particleMesh);
// Dark expanded back faces give each voxel a crisp individual outline.
const outlineGeometry = new THREE.BoxGeometry(1, 1, 1);
const outlineMaterial = new THREE.MeshBasicMaterial({
color: 0x020711,
side: THREE.BackSide
});
const outlineMesh = new THREE.InstancedMesh(
outlineGeometry,
outlineMaterial,
PARTICLE_COUNT
);
outlineMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
outlineMesh.frustumCulled = false;
outlineMesh.renderOrder = 1;
scene.add(outlineMesh);
// Selected-particle box
const selectedMarker = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({
color: 0xfff4c7,
wireframe: true,
transparent: true,
opacity: 0.96,
depthTest: false
})
);
selectedMarker.renderOrder = 12;
scene.add(selectedMarker);
// Fixed-x guide behind the selected particle
const selectedStemGeometry = new THREE.BufferGeometry();
selectedStemGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(6), 3)
);
const selectedStem = new THREE.Line(
selectedStemGeometry,
new THREE.LineBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.3,
depthTest: false
})
);
selectedStem.renderOrder = 10;
scene.add(selectedStem);
// History of the selected particle. It is explicitly vertical.
const MAX_TRACE_POINTS = 360;
const tracePositions = new Float32Array(MAX_TRACE_POINTS * 3);
const traceGeometry = new THREE.BufferGeometry();
traceGeometry.setAttribute(
"position",
new THREE.BufferAttribute(tracePositions, 3)
);
traceGeometry.setDrawRange(0, 0);
const traceLine = new THREE.Line(
traceGeometry,
new THREE.LineBasicMaterial({
color: 0xffd166,
linewidth: 1,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
traceLine.frustumCulled = false;
traceLine.renderOrder = 11;
scene.add(traceLine);
let tracePoints = [];
// Moving crest marker
const crestMarker = new THREE.Mesh(
new THREE.TorusGeometry(0.5, 0.075, 8, 32),
new THREE.MeshBasicMaterial({
color: 0xff5bd8,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
crestMarker.renderOrder = 13;
scene.add(crestMarker);
const crestStemGeometry = new THREE.BufferGeometry();
crestStemGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(6), 3)
);
const crestStem = new THREE.Line(
crestStemGeometry,
new THREE.LineBasicMaterial({
color: 0xff5bd8,
transparent: true,
opacity: 0.3,
depthTest: false
})
);
crestStem.renderOrder = 9;
scene.add(crestStem);
// Arrow showing the direction in which the pattern propagates
const directionArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(5, AMPLITUDE + 1.65, -1),
8,
0xff5bd8,
1.1,
0.65
);
scene.add(directionArrow);
// -------------------------------------------------------------------------
// Text sprites, created with core Three.js CanvasTexture
// -------------------------------------------------------------------------
function createLabel(
initialText,
textColor = "#e8f2ff",
worldWidth = 8,
background = "rgba(4, 13, 26, 0.82)"
) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 96;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(worldWidth, worldWidth * (96 / 512), 1);
sprite.renderOrder = 20;
function setText(text) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = background;
context.strokeStyle = "rgba(255,255,255,0.14)";
context.lineWidth = 2;
context.beginPath();
context.moveTo(14, 13);
context.lineTo(498, 13);
context.lineTo(498, 83);
context.lineTo(14, 83);
context.closePath();
context.fill();
context.stroke();
let fontSize = 38;
context.font = `700 ${fontSize}px system-ui, sans-serif`;
while (
context.measureText(text).width > 465 &&
fontSize > 20
) {
fontSize -= 2;
context.font = `700 ${fontSize}px system-ui, sans-serif`;
}
context.fillStyle = textColor;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 49);
texture.needsUpdate = true;
}
setText(initialText);
sprite.userData.setText = setText;
return sprite;
}
const selectedLabel = createLabel(
"selected particle · x fixed",
"#ffe39a",
10
);
scene.add(selectedLabel);
const crestLabel = createLabel(
"crest moves with the pattern →",
"#ff8de7",
12
);
scene.add(crestLabel);
const rulerLabel = createLabel(
"one wavelength",
"#ffe39a",
11
);
scene.add(rulerLabel);
const xAxisLabel = createLabel("x (m) →", "#b8cbe0", 7);
xAxisLabel.position.set(LENGTH + 3, -4.7, 2);
scene.add(xAxisLabel);
const plusLabel = createLabel("+A", "#91a8bf", 3.5);
plusLabel.position.set(-2.3, AMPLITUDE, 0);
scene.add(plusLabel);
const minusLabel = createLabel("−A", "#91a8bf", 3.5);
minusLabel.position.set(-2.3, -AMPLITUDE, 0);
scene.add(minusLabel);
for (let x = 0; x <= LENGTH; x += 16) {
const label = createLabel(`${x} m`, "#7890a8", 4.1);
label.position.set(x, -4.65, 1.4);
scene.add(label);
}
// Bracket drawn directly on the 3D scene, spanning exactly one wavelength.
const rulerGeometry = new THREE.BufferGeometry();
rulerGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(18), 3)
);
const rulerLine = new THREE.LineSegments(
rulerGeometry,
new THREE.LineBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.9,
depthTest: false
})
);
rulerLine.renderOrder = 15;
scene.add(rulerLine);
// -------------------------------------------------------------------------
// UI and derived physical quantities
// -------------------------------------------------------------------------
const frequencyInput = document.querySelector("#frequency");
const speedInput = document.querySelector("#speed");
const frequencyValue = document.querySelector("#frequencyValue");
const speedValue = document.querySelector("#speedValue");
const equationSpeed = document.querySelector("#equationSpeed");
const equationFrequency = document.querySelector("#equationFrequency");
const equationWavelength = document.querySelector("#equationWavelength");
const wavelengthReadout = document.querySelector("#wavelengthReadout");
const periodReadout = document.querySelector("#periodReadout");
const sceneLambda = document.querySelector("#sceneLambda");
const rulerValue = document.querySelector("#rulerValue");
const rulerFill = document.querySelector("#rulerFill");
const densityNote = document.querySelector("#densityNote");
const selectedXReadout = document.querySelector("#selectedXReadout");
const selectedYReadout = document.querySelector("#selectedYReadout");
const RULER_MAX = 50; // metres; the largest possible wavelength is 50 m
function updateRulerGeometry() {
const y = -5.25;
const z = 4.2;
const halfTick = 0.34;
const values = [
0, y, z,
wavelength, y, z,
0, y - halfTick, z,
0, y + halfTick, z,
wavelength, y - halfTick, z,
wavelength, y + halfTick, z
];
rulerGeometry.attributes.position.array.set(values);
rulerGeometry.attributes.position.needsUpdate = true;
rulerGeometry.computeBoundingSphere();
rulerLabel.position.set(wavelength * 0.5, y - 0.85, z);
rulerLabel.userData.setText(`one wavelength = ${wavelength.toFixed(2)} m`);
}
function updateDerivedValues() {
wavelength = state.speed / state.frequency;
waveNumber = (2 * Math.PI) / wavelength;
frequencyValue.textContent = `${state.frequency.toFixed(2)} Hz`;
speedValue.textContent = `${state.speed.toFixed(1)} m/s`;
equationSpeed.textContent = state.speed.toFixed(1);
equationFrequency.textContent = state.frequency.toFixed(2);
equationWavelength.textContent = wavelength.toFixed(2);
wavelengthReadout.textContent = `${wavelength.toFixed(2)} m`;
periodReadout.textContent = `${(1 / state.frequency).toFixed(2)} s`;
sceneLambda.textContent = `${wavelength.toFixed(2)} m`;
rulerValue.textContent = `${wavelength.toFixed(2)} m`;
rulerFill.style.width = `${(wavelength / RULER_MAX) * 100}%`;
densityNote.textContent =
`${(wavelength / DX).toFixed(1)} particle spacings per wavelength. ` +
`Voxel width is reduced automatically at short wavelengths so the cubes remain distinct.`;
updateRulerGeometry();
}
frequencyInput.addEventListener("input", () => {
state.frequency = Number(frequencyInput.value);
updateDerivedValues();
});
speedInput.addEventListener("input", () => {
state.speed = Number(speedInput.value);
updateDerivedValues();
});
updateDerivedValues();
// -------------------------------------------------------------------------
// Selected particle and trace
// -------------------------------------------------------------------------
function selectedX() {
return state.selectedIndex * DX;
}
function updateSelectedGuide() {
const x = selectedX();
const positions = selectedStemGeometry.attributes.position.array;
positions[0] = x;
positions[1] = -AMPLITUDE;
positions[2] = 0.35;
positions[3] = x;
positions[4] = AMPLITUDE;
positions[5] = 0.35;
selectedStemGeometry.attributes.position.needsUpdate = true;
selectedStemGeometry.computeBoundingSphere();
selectedLabel.userData.setText(
`selected particle · x = ${x.toFixed(2)} m`
);
}
function resetTrace() {
tracePoints.length = 0;
traceGeometry.setDrawRange(0, 0);
}
function selectParticle(index) {
state.selectedIndex = THREE.MathUtils.clamp(
Math.round(index),
0,
PARTICLE_COUNT - 1
);
updateSelectedGuide();
resetTrace();
}
function recordTrace() {
tracePoints.push(new THREE.Vector3(selectedX(), selectedY, 0.38));
if (tracePoints.length > MAX_TRACE_POINTS) {
tracePoints.shift();
}
for (let i = 0; i < tracePoints.length; i++) {
const point = tracePoints[i];
tracePositions[i * 3] = point.x;
tracePositions[i * 3 + 1] = point.y;
tracePositions[i * 3 + 2] = point.z;
}
traceGeometry.attributes.position.needsUpdate = true;
traceGeometry.setDrawRange(0, tracePoints.length);
traceGeometry.computeBoundingSphere();
}
selectParticle(state.selectedIndex);
// -------------------------------------------------------------------------
// Wave update
// -------------------------------------------------------------------------
function updateWave() {
// Keep a visible horizontal gap between every pair of cubes.
// At the shortest allowed wavelength (2 m), cubes are about 0.36 m wide
// while their horizontal spacing remains 0.8 m.
const cubeSize = Math.min(
0.48,
DX * 0.58,
wavelength / 5.5
);
for (let i = 0; i < PARTICLE_COUNT; i++) {
const x = i * DX;
const y =
AMPLITUDE * Math.sin(waveNumber * x - state.phase);
instanceDummy.position.set(x, y, 0);
instanceDummy.scale.setScalar(cubeSize);
instanceDummy.updateMatrix();
particleMesh.setMatrixAt(i, instanceDummy.matrix);
instanceDummy.scale.setScalar(cubeSize * 1.12);
instanceDummy.updateMatrix();
outlineMesh.setMatrixAt(i, instanceDummy.matrix);
if (i === state.selectedIndex) {
selectedY = y;
}
}
particleMesh.instanceMatrix.needsUpdate = true;
outlineMesh.instanceMatrix.needsUpdate = true;
selectedMarker.position.set(selectedX(), selectedY, 0);
selectedMarker.scale.setScalar(cubeSize * 1.48);
selectedMarker.rotation.y = state.phase * 0.15;
selectedLabel.position.set(
selectedX(),
selectedY + Math.max(1.6, cubeSize * 3.4),
0.5
);
// A crest occurs where kx - phase = 0 modulo 2π.
const crestX = state.phase / waveNumber;
crestMarker.position.set(crestX, AMPLITUDE, 0.42);
crestMarker.rotation.z = state.phase * 0.2;
crestLabel.position.set(crestX, AMPLITUDE + 2.25, 0.55);
const crestPositions = crestStemGeometry.attributes.position.array;
crestPositions[0] = crestX;
crestPositions[1] = 0;
crestPositions[2] = 0.4;
crestPositions[3] = crestX;
crestPositions[4] = AMPLITUDE;
crestPositions[5] = 0.4;
crestStemGeometry.attributes.position.needsUpdate = true;
crestStemGeometry.computeBoundingSphere();
selectedXReadout.textContent = `${selectedX().toFixed(2)} m`;
selectedYReadout.textContent = `${selectedY.toFixed(2)} m`;
}
// -------------------------------------------------------------------------
// Custom camera controls (no addons)
// -------------------------------------------------------------------------
let dragging = false;
let pointerStartX = 0;
let pointerStartY = 0;
let previousPointerX = 0;
let previousPointerY = 0;
let dragDistance = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
pointerStartX = event.clientX;
pointerStartY = event.clientY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
dragDistance = 0;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
dragDistance += Math.abs(dx) + Math.abs(dy);
cameraSpherical.theta -= dx * 0.006;
cameraSpherical.phi = THREE.MathUtils.clamp(
cameraSpherical.phi - dy * 0.004,
0.35,
1.52
);
applyCamera();
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
renderer.domElement.addEventListener("pointerup", (event) => {
if (!dragging) return;
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
const wasClick =
Math.abs(event.clientX - pointerStartX) +
Math.abs(event.clientY - pointerStartY) <
6;
if (!wasClick) return;
const bounds = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - bounds.left) / bounds.width) * 2 - 1;
pointer.y =
-((event.clientY - bounds.top) / bounds.height) * 2 + 1;
camera.updateMatrixWorld();
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObject(particleMesh, false)[0];
if (hit && Number.isInteger(hit.instanceId)) {
selectParticle(hit.instanceId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraSpherical.radius = THREE.MathUtils.clamp(
cameraSpherical.radius + event.deltaY * 0.055,
65,
170
);
applyCamera();
},
{ passive: false }
);
function resetCamera() {
cameraSpherical.set(112, 1.18, 0);
applyCamera();
}
renderer.domElement.addEventListener("dblclick", resetCamera);
document.querySelector("#cameraButton").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Buttons
// -------------------------------------------------------------------------
const pauseButton = document.querySelector("#pauseButton");
function togglePause() {
state.running = !state.running;
pauseButton.textContent = state.running ? "Pause" : "Resume";
}
pauseButton.addEventListener("click", togglePause);
document.querySelector("#traceButton").addEventListener("click", () => {
resetTrace();
});
window.addEventListener("keydown", (event) => {
const tag = event.target?.tagName?.toLowerCase();
if (event.code === "Space" && tag !== "input" && tag !== "button") {
event.preventDefault();
togglePause();
}
});
// -------------------------------------------------------------------------
// Resize and animation loop
// -------------------------------------------------------------------------
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(viewport);
resize();
const clock = new THREE.Clock();
let sampleAccumulator = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (state.running) {
// Integrating phase makes slider changes smooth rather than teleporting
// the waveform. At every moment d(phase)/dt = 2*pi*f.
state.phase =
(state.phase + 2 * Math.PI * state.frequency * dt) %
(2 * Math.PI);
sampleAccumulator += dt;
if (sampleAccumulator >= 1 / 30) {
sampleAccumulator %= 1 / 30;
recordTrace();
}
}
updateWave();
renderer.render(scene, camera);
}
updateWave();
recordTrace();
animate();
document.querySelector("#loading").classList.add("hidden");
</script>
</body>
</html>
```