Prompt specification
Build or customize the Three.js 3D scene "Standing-wave mode selector" 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: Standing-wave mode selector
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/standing-wave-mode-selector-x1588
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing standing waves and resonant modes. Allow choosing integer modes on an ideal fixed-end string; compute frequencies from tension, linear density, and length and show the associated node count correctly. Voxel style.
Working Three.js Starter (standing-wave-mode-selector-x1588):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#07101d">
<title>Voxel Resonance — Standing Waves on a Fixed-End String</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: rgba(10, 20, 34, 0.91);
--panel-soft: rgba(19, 34, 53, 0.72);
--border: rgba(132, 198, 222, 0.17);
--text: #edf8ff;
--muted: #8faabd;
--cyan: #51e6ff;
--cyan-dark: #0d7f9b;
--amber: #ffbd59;
--violet: #ae8cff;
--green: #6cf0b4;
--shadow: 0 20px 70px rgba(0, 0, 0, 0.45);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
bottom: 18px;
left: 18px;
width: 360px;
overflow: auto;
padding: 20px;
border: 1px solid var(--border);
border-radius: 22px;
background:
linear-gradient(145deg, rgba(21, 40, 60, 0.84), rgba(7, 15, 27, 0.94)),
var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(81, 230, 255, 0.32) transparent;
}
.panel::-webkit-scrollbar {
width: 5px;
}
.panel::-webkit-scrollbar-thumb {
border-radius: 20px;
background: rgba(81, 230, 255, 0.3);
}
.eyebrow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
color: var(--cyan);
font-size: 0.68rem;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.live-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 8px;
border: 1px solid rgba(108, 240, 180, 0.25);
border-radius: 999px;
background: rgba(108, 240, 180, 0.07);
color: var(--green);
font-size: 0.61rem;
letter-spacing: 0.08em;
white-space: nowrap;
}
.live-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 10px var(--green);
}
h1 {
margin: 0;
font-size: clamp(1.65rem, 3vw, 2.2rem);
line-height: 1;
letter-spacing: -0.045em;
}
.subtitle {
margin: 10px 0 18px;
color: var(--muted);
font-size: 0.82rem;
line-height: 1.55;
}
.section {
padding: 15px 0;
border-top: 1px solid var(--border);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
color: #c7dbe6;
}
.section-title span:last-child {
color: #68879a;
font-size: 0.62rem;
letter-spacing: 0.05em;
}
.field-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
}
.field label {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 0.65rem;
font-weight: 700;
line-height: 1.25;
}
.input-wrap {
position: relative;
}
.input-wrap input {
width: 100%;
height: 40px;
padding: 0 31px 0 10px;
border: 1px solid rgba(139, 188, 212, 0.2);
border-radius: 10px;
outline: none;
background: rgba(3, 10, 20, 0.66);
color: var(--text);
font-size: 0.8rem;
font-weight: 700;
transition: border-color 160ms, box-shadow 160ms;
}
.input-wrap input:focus {
border-color: rgba(81, 230, 255, 0.65);
box-shadow: 0 0 0 3px rgba(81, 230, 255, 0.08);
}
.unit {
position: absolute;
top: 50%;
right: 8px;
transform: translateY(-50%);
color: #668497;
font-size: 0.61rem;
font-weight: 700;
pointer-events: none;
}
.mode-row {
display: grid;
grid-template-columns: 42px 74px 42px;
justify-content: center;
align-items: center;
gap: 10px;
}
.square-button {
width: 42px;
height: 42px;
padding: 0;
border: 1px solid rgba(81, 230, 255, 0.23);
border-radius: 11px;
background: rgba(81, 230, 255, 0.08);
color: var(--cyan);
font-size: 1.35rem;
font-weight: 500;
cursor: pointer;
transition: background 150ms, transform 150ms, border-color 150ms;
}
.square-button:hover {
border-color: rgba(81, 230, 255, 0.55);
background: rgba(81, 230, 255, 0.15);
transform: translateY(-1px);
}
#modeInput {
width: 74px;
height: 44px;
padding: 0 6px;
border: 1px solid rgba(81, 230, 255, 0.4);
border-radius: 11px;
outline: none;
background: rgba(3, 10, 20, 0.76);
color: var(--cyan);
text-align: center;
font-size: 1.05rem;
font-weight: 850;
-moz-appearance: textfield;
}
#modeInput::-webkit-outer-spin-button,
#modeInput::-webkit-inner-spin-button {
margin: 0;
-webkit-appearance: none;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 15px 0 5px;
border-radius: 10px;
outline: none;
background: linear-gradient(
90deg,
var(--cyan) 0%,
var(--cyan) var(--range-fill, 16.7%),
rgba(119, 158, 180, 0.18) var(--range-fill, 16.7%)
);
appearance: none;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #07101d;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan), 0 0 14px rgba(81, 230, 255, 0.45);
appearance: none;
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #07101d;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan);
}
.range-labels {
display: flex;
justify-content: space-between;
color: #5f7b8d;
font-size: 0.6rem;
font-weight: 700;
}
.frequency-card {
position: relative;
overflow: hidden;
padding: 16px;
border: 1px solid rgba(81, 230, 255, 0.22);
border-radius: 16px;
background:
radial-gradient(circle at 95% 0%, rgba(81, 230, 255, 0.13), transparent 46%),
rgba(3, 12, 23, 0.66);
}
.frequency-label {
color: var(--muted);
font-size: 0.66rem;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.frequency-value {
margin: 5px 0 1px;
color: var(--cyan);
font-size: clamp(2rem, 5vw, 2.65rem);
font-weight: 850;
letter-spacing: -0.06em;
line-height: 1;
text-shadow: 0 0 30px rgba(81, 230, 255, 0.18);
}
.frequency-note {
color: #7895a6;
font-size: 0.67rem;
}
.equation {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 6px;
margin-top: 13px;
color: #bad3df;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.78rem;
}
.equation .result {
width: 100%;
padding-top: 8px;
border-top: 1px solid rgba(81, 230, 255, 0.1);
color: var(--text);
font-size: 0.69rem;
}
.metrics {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.metric {
min-height: 69px;
padding: 11px 12px;
border: 1px solid rgba(135, 182, 206, 0.13);
border-radius: 12px;
background: rgba(14, 28, 44, 0.55);
}
.metric-label {
color: #7896a8;
font-size: 0.61rem;
font-weight: 750;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.metric-value {
margin-top: 4px;
font-size: 1.12rem;
font-weight: 800;
letter-spacing: -0.03em;
}
.metric-detail {
margin-top: 2px;
color: #638094;
font-size: 0.58rem;
}
.node-value {
color: var(--amber);
}
.antinode-value {
color: var(--violet);
}
.spectrum-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 7px;
}
.harmonic {
position: relative;
overflow: hidden;
min-height: 55px;
padding: 9px 10px;
border: 1px solid rgba(130, 173, 195, 0.13);
border-radius: 10px;
background: rgba(11, 23, 37, 0.66);
text-align: left;
cursor: pointer;
transition: border-color 150ms, background 150ms, transform 150ms;
}
.harmonic:hover {
border-color: rgba(81, 230, 255, 0.38);
background: rgba(21, 43, 60, 0.8);
transform: translateY(-1px);
}
.harmonic.active {
border-color: rgba(81, 230, 255, 0.68);
background: rgba(23, 69, 84, 0.52);
box-shadow: inset 0 0 24px rgba(81, 230, 255, 0.06);
}
.harmonic-top {
position: relative;
z-index: 1;
display: flex;
justify-content: space-between;
gap: 6px;
font-size: 0.64rem;
font-weight: 800;
}
.harmonic-index {
color: var(--cyan);
}
.harmonic-freq {
color: #9bb3c1;
font-size: 0.59rem;
}
.harmonic-bar {
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 3px;
background: rgba(114, 148, 166, 0.1);
}
.harmonic-bar i {
display: block;
height: 100%;
background: linear-gradient(90deg, #217d99, var(--cyan));
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
color: #8ca7b8;
font-size: 0.64rem;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.legend-swatch {
width: 9px;
height: 9px;
border-radius: 2px;
box-shadow: 0 0 9px currentColor;
}
.swatch-wave {
color: var(--cyan);
background: var(--cyan);
}
.swatch-node {
color: var(--amber);
background: var(--amber);
}
.swatch-anti {
color: var(--violet);
background: var(--violet);
}
.physics-note {
padding: 11px 12px;
border-left: 2px solid var(--green);
border-radius: 0 9px 9px 0;
background: rgba(108, 240, 180, 0.055);
color: #8daa9c;
font-size: 0.66rem;
line-height: 1.55;
}
.physics-note strong {
color: #c9e8d7;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.action-button {
min-height: 40px;
border: 1px solid rgba(130, 175, 198, 0.2);
border-radius: 11px;
background: rgba(17, 34, 50, 0.7);
color: #c2d7e2;
font-size: 0.7rem;
font-weight: 800;
cursor: pointer;
transition: background 150ms, border-color 150ms, transform 150ms;
}
.action-button:hover {
border-color: rgba(81, 230, 255, 0.45);
background: rgba(28, 59, 76, 0.82);
transform: translateY(-1px);
}
.action-button.primary {
border-color: rgba(81, 230, 255, 0.38);
background: rgba(81, 230, 255, 0.12);
color: var(--cyan);
}
.status-card {
position: fixed;
z-index: 5;
top: 22px;
right: 24px;
display: flex;
align-items: center;
gap: 10px;
padding: 10px 14px;
border: 1px solid rgba(130, 175, 198, 0.15);
border-radius: 999px;
background: rgba(7, 16, 29, 0.7);
color: #a7bfcc;
font-size: 0.69rem;
font-weight: 750;
backdrop-filter: blur(10px);
}
.status-card strong {
color: var(--cyan);
}
.camera-help {
position: fixed;
z-index: 5;
right: 24px;
bottom: 20px;
padding: 9px 12px;
border: 1px solid rgba(130, 175, 198, 0.13);
border-radius: 10px;
background: rgba(7, 16, 29, 0.66);
color: #6f8b9c;
font-size: 0.64rem;
backdrop-filter: blur(10px);
}
.camera-help kbd {
padding: 2px 5px;
border: 1px solid rgba(130, 175, 198, 0.18);
border-radius: 4px;
background: rgba(130, 175, 198, 0.06);
color: #a9c1cf;
font-family: inherit;
font-size: 0.58rem;
}
@media (max-width: 760px) {
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 53vh;
padding: 16px;
border-radius: 18px;
}
.status-card {
top: 12px;
right: 12px;
left: 12px;
justify-content: center;
}
.camera-help {
top: 58px;
right: 12px;
bottom: auto;
}
.field-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.frequency-value {
font-size: 2rem;
}
}
@media (max-width: 430px) {
.field-grid {
grid-template-columns: 1fr;
}
.spectrum-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.camera-help {
display: none;
}
}
</style>
</head>
<body>
<div id="stage" aria-label="Interactive 3D standing-wave visualization"></div>
<aside class="panel" aria-label="Standing wave controls">
<div class="eyebrow">
<span>Voxel acoustics / 01</span>
<span class="live-badge">
<span class="live-dot"></span>
LIVE MODEL
</span>
</div>
<h1>Resonance Lab</h1>
<p class="subtitle">
Explore the resonant modes of an ideal string fixed at both ends.
Every visible element is built from cubic voxels.
</p>
<section class="section">
<div class="section-title">
<span>String properties</span>
<span>SI units</span>
</div>
<div class="field-grid">
<div class="field">
<label for="tensionInput">Tension</label>
<div class="input-wrap">
<input
id="tensionInput"
type="number"
min="1"
max="5000"
step="1"
value="120"
aria-label="String tension in newtons"
>
<span class="unit">N</span>
</div>
</div>
<div class="field">
<label for="densityInput">Linear density</label>
<div class="input-wrap">
<input
id="densityInput"
type="number"
min="0.001"
max="5"
step="0.001"
value="0.060"
aria-label="Linear mass density in kilograms per meter"
>
<span class="unit">kg/m</span>
</div>
</div>
<div class="field">
<label for="lengthInput">Length</label>
<div class="input-wrap">
<input
id="lengthInput"
type="number"
min="0.1"
max="20"
step="0.1"
value="1.5"
aria-label="String length in meters"
>
<span class="unit">m</span>
</div>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<span>Resonant mode</span>
<span>integer n</span>
</div>
<div class="mode-row">
<button id="modeDown" class="square-button" type="button" aria-label="Previous mode">−</button>
<input
id="modeInput"
type="number"
min="1"
max="12"
step="1"
value="3"
aria-label="Resonant mode number"
>
<button id="modeUp" class="square-button" type="button" aria-label="Next mode">+</button>
</div>
<input
id="modeRange"
type="range"
min="1"
max="12"
step="1"
value="3"
aria-label="Choose resonant mode"
>
<div class="range-labels">
<span>n = 1</span>
<span>n = 12</span>
</div>
</section>
<section class="section">
<div class="frequency-card" aria-live="polite">
<div class="frequency-label">Resonant frequency</div>
<div id="frequencyValue" class="frequency-value">44.72 Hz</div>
<div id="frequencyNote" class="frequency-note">Mode 3 · three half-wavelengths fit the string</div>
<div class="equation" aria-label="Resonant frequency formula">
<span>f<sub>n</sub></span>
<span>=</span>
<span>n / 2L</span>
<span>× √(T / μ)</span>
<span id="equationResult" class="result"></span>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<span>Mode anatomy</span>
<span>spatial counts</span>
</div>
<div class="metrics">
<div class="metric">
<div class="metric-label">Nodes</div>
<div id="nodesValue" class="metric-value node-value">4</div>
<div id="internalNodes" class="metric-detail">including both fixed ends</div>
</div>
<div class="metric">
<div class="metric-label">Antinodes</div>
<div id="antinodesValue" class="metric-value antinode-value">3</div>
<div class="metric-detail">maximum displacement</div>
</div>
<div class="metric">
<div class="metric-label">Wavelength</div>
<div id="wavelengthValue" class="metric-value">1.000 m</div>
<div class="metric-detail">λ = 2L / n</div>
</div>
<div class="metric">
<div class="metric-label">Wave speed</div>
<div id="speedValue" class="metric-value">44.7 m/s</div>
<div class="metric-detail">v = √(T / μ)</div>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<span>Harmonic spectrum</span>
<span>click to select</span>
</div>
<div id="spectrum" class="spectrum-grid"></div>
</section>
<section class="section">
<div class="section-title">
<span>Voxel key</span>
</div>
<div class="legend">
<span class="legend-item">
<span class="legend-swatch swatch-wave"></span>
String
</span>
<span class="legend-item">
<span class="legend-swatch swatch-node"></span>
Node
</span>
<span class="legend-item">
<span class="legend-swatch swatch-anti"></span>
Antinode
</span>
</div>
</section>
<section class="section">
<div class="physics-note">
<strong>Correct fixed-end count:</strong>
mode n contains n antinodes and n + 1 nodes when the two fixed
endpoints are included. There are n − 1 internal nodes.
Motion is slowed for visibility; displayed frequencies remain physical.
</div>
</section>
<section class="section">
<div class="button-row">
<button id="pauseButton" class="action-button primary" type="button">Pause motion</button>
<button id="cameraButton" class="action-button" type="button">Reset camera</button>
</div>
</section>
</aside>
<div class="status-card" aria-live="polite">
<span>Mode <strong id="statusMode">03</strong></span>
<span>•</span>
<span><strong id="statusFrequency">44.72 Hz</strong></span>
</div>
<div class="camera-help">
<kbd>Drag</kbd> orbit · <kbd>Wheel</kbd> zoom · <kbd>Double-click</kbd> reset
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and application state
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const tensionInput = document.getElementById("tensionInput");
const densityInput = document.getElementById("densityInput");
const lengthInput = document.getElementById("lengthInput");
const modeInput = document.getElementById("modeInput");
const modeRange = document.getElementById("modeRange");
const modeDown = document.getElementById("modeDown");
const modeUp = document.getElementById("modeUp");
const pauseButton = document.getElementById("pauseButton");
const cameraButton = document.getElementById("cameraButton");
const spectrum = document.getElementById("spectrum");
const frequencyValue = document.getElementById("frequencyValue");
const frequencyNote = document.getElementById("frequencyNote");
const equationResult = document.getElementById("equationResult");
const nodesValue = document.getElementById("nodesValue");
const internalNodes = document.getElementById("internalNodes");
const antinodesValue = document.getElementById("antinodesValue");
const wavelengthValue = document.getElementById("wavelengthValue");
const speedValue = document.getElementById("speedValue");
const statusMode = document.getElementById("statusMode");
const statusFrequency = document.getElementById("statusFrequency");
const MAX_MODE = 12;
const SLOW_MOTION = 0.035;
const STRING_HALF_LENGTH = 5;
const state = {
tension: 120,
density: 0.060,
length: 1.5,
mode: 3,
amplitude: 0.78,
playing: true
};
let currentFrequency = 0;
let waveSpeed = 0;
let simulationTime = 0;
// -------------------------------------------------------------------------
// Renderer, scene, and camera
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101d);
scene.fog = new THREE.Fog(0x07101d, 14, 31);
const camera = new THREE.PerspectiveCamera(46, 1, 0.1, 100);
const hemisphere = new THREE.HemisphereLight(0x9bdcff, 0x111322, 2.15);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(4, 8, 5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x36d8ff, 2.0);
rimLight.position.set(-5, 3, -5);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffa84c, 15, 9, 2);
warmLight.position.set(4.5, 1.2, 2.7);
scene.add(warmLight);
// Direct camera controls: no addon imports.
const cameraState = {
radius: 12.5,
theta: 0.16,
phi: 1.17,
target: new THREE.Vector3(0.75, -0.2, 0)
};
function updateCamera() {
const aspect = camera.aspect;
const portraitFactor = aspect < 1
? 1 + (1 / Math.max(aspect, 0.45) - 1) * 1.08
: 1;
const radius = cameraState.radius * portraitFactor;
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + radius * Math.cos(cameraState.phi),
cameraState.target.z + radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.radius = 12.5;
cameraState.theta = 0.16;
cameraState.phi = 1.17;
updateCamera();
}
// -------------------------------------------------------------------------
// Voxel geometry
// -------------------------------------------------------------------------
const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
const waveMaterial = new THREE.MeshStandardMaterial({
color: 0x50e4ff,
roughness: 0.32,
metalness: 0.18,
emissive: 0x075166,
emissiveIntensity: 0.72
});
const nodeMaterial = new THREE.MeshStandardMaterial({
color: 0xffb84f,
roughness: 0.3,
metalness: 0.15,
emissive: 0x7a3100,
emissiveIntensity: 0.85
});
const antinodeMaterial = new THREE.MeshStandardMaterial({
color: 0xb18aff,
roughness: 0.28,
metalness: 0.2,
emissive: 0x321266,
emissiveIntensity: 0.9
});
const ghostMaterial = new THREE.MeshStandardMaterial({
color: 0x264a5c,
roughness: 0.8,
metalness: 0.05,
transparent: true,
opacity: 0.55
});
const supportMaterial = new THREE.MeshStandardMaterial({
color: 0x385064,
roughness: 0.65,
metalness: 0.35
});
const clampMaterial = new THREE.MeshStandardMaterial({
color: 0x5b7285,
roughness: 0.42,
metalness: 0.48
});
// Animated string: 241 small cubes.
const WAVE_SEGMENTS = 240;
const waveMesh = new THREE.InstancedMesh(
boxGeometry,
waveMaterial,
WAVE_SEGMENTS + 1
);
waveMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
waveMesh.castShadow = true;
waveMesh.receiveShadow = true;
waveMesh.frustumCulled = false;
scene.add(waveMesh);
// Dotted equilibrium reference.
const GHOST_COUNT = 81;
const ghostMesh = new THREE.InstancedMesh(
boxGeometry,
ghostMaterial,
GHOST_COUNT
);
ghostMesh.frustumCulled = false;
scene.add(ghostMesh);
// Maximum number of visible nodes and antinodes.
const nodeMesh = new THREE.InstancedMesh(
boxGeometry,
nodeMaterial,
MAX_MODE + 1
);
nodeMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
nodeMesh.castShadow = true;
nodeMesh.frustumCulled = false;
scene.add(nodeMesh);
const antinodeMesh = new THREE.InstancedMesh(
boxGeometry,
antinodeMaterial,
MAX_MODE
);
antinodeMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
antinodeMesh.castShadow = true;
antinodeMesh.frustumCulled = false;
scene.add(antinodeMesh);
const dummy = new THREE.Object3D();
function buildGhostLine() {
for (let i = 0; i < GHOST_COUNT; i++) {
const u = i / (GHOST_COUNT - 1);
dummy.position.set(
-STRING_HALF_LENGTH + u * STRING_HALF_LENGTH * 2,
0,
-0.22
);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(0.085, 0.045, 0.045);
dummy.updateMatrix();
ghostMesh.setMatrixAt(i, dummy.matrix);
}
ghostMesh.instanceMatrix.needsUpdate = true;
}
buildGhostLine();
// Voxel floor.
const tileGeometry = new THREE.BoxGeometry(0.47, 0.08, 0.47);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.94,
metalness: 0.02
});
const tileColumns = 25;
const tileRows = 13;
const floorMesh = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
tileColumns * tileRows
);
floorMesh.receiveShadow = true;
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let row = 0; row < tileRows; row++) {
for (let column = 0; column < tileColumns; column++) {
dummy.position.set(
(column - (tileColumns - 1) / 2) * 0.49,
-1.62,
(row - (tileRows - 1) / 2) * 0.49
);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
floorMesh.setMatrixAt(tileIndex, dummy.matrix);
const checker = (column + row) % 2;
const hue = 0.56 + checker * 0.008;
const lightness = 0.075 + ((column * 7 + row * 3) % 4) * 0.006;
tileColor.setHSL(hue, 0.29, lightness);
floorMesh.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
floorMesh.instanceMatrix.needsUpdate = true;
if (floorMesh.instanceColor) {
floorMesh.instanceColor.needsUpdate = true;
}
scene.add(floorMesh);
function addBlock(parent, x, y, z, sx, sy, sz, material) {
const mesh = new THREE.Mesh(boxGeometry, material);
mesh.position.set(x, y, z);
mesh.scale.set(sx, sy, sz);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Fixed-end supports, assembled from voxel blocks.
const supports = new THREE.Group();
scene.add(supports);
for (const side of [-1, 1]) {
for (let i = 0; i < 7; i++) {
addBlock(
supports,
side * 5.22,
-1.44 + i * 0.235,
0,
0.23,
0.23,
0.27,
supportMaterial
);
}
addBlock(
supports,
side * 5.12,
0.16,
0,
0.35,
0.17,
0.27,
clampMaterial
);
addBlock(
supports,
side * 5.28,
-0.48,
0,
0.38,
0.12,
0.42,
clampMaterial
);
}
// -------------------------------------------------------------------------
// Physics and UI
// -------------------------------------------------------------------------
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
function formatFrequency(hz) {
if (hz >= 1000) {
return `${(hz / 1000).toFixed(hz >= 10000 ? 1 : 2)} kHz`;
}
return `${hz.toFixed(hz < 10 ? 2 : 1)} Hz`;
}
function formatLength(meters) {
if (meters < 0.1) {
return `${(meters * 100).toFixed(1)} cm`;
}
return `${meters.toFixed(3)} m`;
}
function createSpectrumButtons() {
for (let n = 1; n <= MAX_MODE; n++) {
const button = document.createElement("button");
button.type = "button";
button.className = "harmonic";
button.dataset.mode = String(n);
button.innerHTML = `
<span class="harmonic-top">
<span class="harmonic-index">n = ${n}</span>
<span class="harmonic-freq"></span>
</span>
<span class="harmonic-bar"><i></i></span>
`;
spectrum.appendChild(button);
}
}
createSpectrumButtons();
function updateSpectrum() {
const maxFrequency =
MAX_MODE * Math.sqrt(state.tension / state.density) /
(2 * state.length);
spectrum.querySelectorAll(".harmonic").forEach((button) => {
const n = Number(button.dataset.mode);
const frequency =
n * Math.sqrt(state.tension / state.density) /
(2 * state.length);
button.classList.toggle("active", n === state.mode);
button.setAttribute(
"aria-label",
`Select mode ${n}, ${formatFrequency(frequency)}`
);
button.querySelector(".harmonic-freq").textContent =
formatFrequency(frequency);
const width = 8 + 92 * Math.sqrt(frequency / maxFrequency);
button.querySelector(".harmonic-bar i").style.width = `${width}%`;
});
}
function updateNodeMarkers() {
nodeMesh.count = state.mode + 1;
for (let i = 0; i <= state.mode; i++) {
const x =
-STRING_HALF_LENGTH +
(i / state.mode) * STRING_HALF_LENGTH * 2;
dummy.position.set(x, 0, 0.17);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(0.17, 0.17, 0.17);
dummy.updateMatrix();
nodeMesh.setMatrixAt(i, dummy.matrix);
}
nodeMesh.instanceMatrix.needsUpdate = true;
antinodeMesh.count = state.mode;
}
function updatePhysics(resetTime = true) {
waveSpeed = Math.sqrt(state.tension / state.density);
currentFrequency =
state.mode * waveSpeed / (2 * state.length);
const wavelength = 2 * state.length / state.mode;
if (resetTime) {
simulationTime = 0;
}
frequencyValue.textContent = formatFrequency(currentFrequency);
frequencyNote.textContent =
`Mode ${state.mode} · ` +
`${state.mode} half-wavelength${state.mode === 1 ? "" : "s"} fit the string`;
equationResult.textContent =
`= (${state.mode} / ${(2 * state.length).toFixed(2)} m) ` +
`× √(${state.tension.toFixed(1)} N / ${state.density.toFixed(3)} kg/m)`;
nodesValue.textContent = String(state.mode + 1);
internalNodes.textContent =
`${state.mode + 1} total · ${state.mode - 1} internal`;
antinodesValue.textContent = String(state.mode);
wavelengthValue.textContent = formatLength(wavelength);
speedValue.textContent = `${waveSpeed.toFixed(1)} m/s`;
statusMode.textContent = String(state.mode).padStart(2, "0");
statusFrequency.textContent = formatFrequency(currentFrequency);
modeInput.value = String(state.mode);
modeRange.value = String(state.mode);
modeRange.style.setProperty(
"--range-fill",
`${((state.mode - 1) / (MAX_MODE - 1)) * 100}%`
);
updateNodeMarkers();
updateSpectrum();
}
function setMode(mode) {
state.mode = clamp(Math.round(mode), 1, MAX_MODE);
updatePhysics(true);
}
function commitPhysicalInputs() {
const tension = clamp(
Number.parseFloat(tensionInput.value),
1,
5000
);
const density = clamp(
Number.parseFloat(densityInput.value),
0.001,
5
);
const length = clamp(
Number.parseFloat(lengthInput.value),
0.1,
20
);
state.tension = tension;
state.density = density;
state.length = length;
tensionInput.value = String(tension);
densityInput.value = String(density);
lengthInput.value = String(length);
updatePhysics(true);
}
[tensionInput, densityInput, lengthInput].forEach((input) => {
input.addEventListener("input", () => {
const value = Number.parseFloat(input.value);
if (Number.isFinite(value)) {
// Update live only while the value is in a sensible range.
if (value >= 1 && value <= 5000) {
state.tension = value;
} else if (value >= 0.001 && value <= 5) {
state.density = value;
} else if (value >= 0.1 && value <= 20) {
state.length = value;
}
updatePhysics(true);
}
});
input.addEventListener("change", commitPhysicalInputs);
});
modeInput.addEventListener("change", () => {
const value = Number.parseInt(modeInput.value, 10);
setMode(Number.isFinite(value) ? value : state.mode);
});
modeRange.addEventListener("input", () => {
setMode(Number(modeRange.value));
});
modeDown.addEventListener("click", () => {
setMode(state.mode - 1);
});
modeUp.addEventListener("click", () => {
setMode(state.mode + 1);
});
spectrum.addEventListener("click", (event) => {
const button = event.target.closest(".harmonic");
if (button) {
setMode(Number(button.dataset.mode));
}
});
pauseButton.addEventListener("click", () => {
state.playing = !state.playing;
pauseButton.textContent = state.playing
? "Pause motion"
: "Resume motion";
});
cameraButton.addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Direct pointer, wheel, and touch camera controls
// -------------------------------------------------------------------------
const pointers = new Map();
let lastPinchDistance = 0;
const canvas = renderer.domElement;
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
lastPinchDistance = 0;
}
});
canvas.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) {
return;
}
const current = {
x: event.clientX,
y: event.clientY
};
pointers.set(event.pointerId, current);
if (pointers.size === 1) {
const dx = current.x - previous.x;
const dy = current.y - previous.y;
cameraState.theta -= dx * 0.006;
cameraState.phi = clamp(
cameraState.phi + dy * 0.005,
0.55,
1.48
);
updateCamera();
} else if (pointers.size === 2) {
const points = Array.from(pointers.values());
const dx = points[0].x - points[1].x;
const dy = points[0].y - points[1].y;
const distance = Math.hypot(dx, dy);
if (lastPinchDistance > 0) {
cameraState.radius = clamp(
cameraState.radius * (lastPinchDistance / distance),
7,
20
);
updateCamera();
}
lastPinchDistance = distance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) {
lastPinchDistance = 0;
}
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener("lostpointercapture", releasePointer);
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7,
20
);
updateCamera();
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
cameraState.target.x = width > 900 ? 0.75 : 0;
updateCamera();
}
window.addEventListener("resize", resize);
resize();
updatePhysics(false);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (state.playing) {
simulationTime += delta;
}
const phase =
simulationTime *
Math.PI * 2 *
currentFrequency *
SLOW_MOTION;
const oscillation = Math.cos(phase);
const spacing =
(STRING_HALF_LENGTH * 2) / WAVE_SEGMENTS;
// The physical standing-wave shape is:
// y(x,t) = A sin(n*pi*x/L) cos(omega*t)
for (let i = 0; i <= WAVE_SEGMENTS; i++) {
const u = i / WAVE_SEGMENTS;
const shape = Math.sin(state.mode * Math.PI * u);
const y = state.amplitude * shape * oscillation;
const x =
-STRING_HALF_LENGTH +
u * STRING_HALF_LENGTH * 2;
dummy.position.set(x, y, 0);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(
Math.max(0.072, spacing * 1.34),
0.105,
0.115
);
dummy.updateMatrix();
waveMesh.setMatrixAt(i, dummy.matrix);
}
waveMesh.instanceMatrix.needsUpdate = true;
// Antinodes sit halfway between adjacent nodes.
for (let i = 0; i < state.mode; i++) {
const u = (i + 0.5) / state.mode;
const x =
-STRING_HALF_LENGTH +
u * STRING_HALF_LENGTH * 2;
dummy.position.set(
x,
state.amplitude * oscillation,
0.21
);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(0.13, 0.13, 0.13);
dummy.updateMatrix();
antinodeMesh.setMatrixAt(i, dummy.matrix);
}
antinodeMesh.instanceMatrix.needsUpdate = true;
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```