Prompt specification
Build or customize the Three.js 3D scene "Harmonic synthesis playground" 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: Harmonic synthesis playground
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/harmonic-synthesis-playground-x1548
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing Fourier components and musical harmonics. Let users adjust a small set of amplitudes and phases; compute the summed periodic waveform and spectrum consistently without implying that every real sound is stationary or periodic. Low-poly.
Working Three.js Starter (harmonic-synthesis-playground-x1548):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Harmonic Lab — Fourier Components</title>
<style>
:root {
color-scheme: dark;
--bg: #071018;
--panel: #0b1720;
--panel-2: #101f29;
--line: #213541;
--text: #edf4f5;
--muted: #8ca2ad;
--accent: #f2c66d;
--cyan: #55d6be;
--blue: #5aa9ff;
--coral: #ff7b72;
--yellow: #f6c85f;
--purple: #b892ff;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background:
radial-gradient(circle at 85% 5%, #162b35 0, transparent 36rem),
linear-gradient(145deg, #071018, #09141c 55%, #071018);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
height: 100vh;
overflow: hidden;
display: grid;
grid-template-columns: 330px minmax(0, 1fr);
grid-template-rows: 70px minmax(0, 1fr);
}
button,
input,
summary {
font: inherit;
}
button {
color: inherit;
}
header {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 24px;
border-bottom: 1px solid var(--line);
background: rgba(7, 16, 24, 0.9);
backdrop-filter: blur(16px);
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 38px;
height: 38px;
display: grid;
place-items: center;
border: 1px solid #43606c;
background: linear-gradient(135deg, #17313b, #0b1720);
clip-path: polygon(50% 0, 94% 24%, 94% 76%, 50% 100%, 6% 76%, 6% 24%);
color: var(--accent);
font-weight: 800;
letter-spacing: -0.06em;
}
h1,
h2,
p {
margin: 0;
}
h1 {
font-size: 17px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.subtitle {
color: var(--muted);
font-size: 12px;
margin-top: 2px;
}
.header-note {
color: var(--muted);
font-size: 12px;
text-align: right;
line-height: 1.5;
}
.header-note strong {
color: var(--text);
font-weight: 600;
}
aside {
min-height: 0;
overflow-y: auto;
padding: 20px 18px 24px;
border-right: 1px solid var(--line);
background: rgba(8, 18, 25, 0.76);
scrollbar-color: #2b4653 transparent;
}
.section {
padding-bottom: 18px;
margin-bottom: 18px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
margin-bottom: 0;
}
.eyebrow {
color: var(--accent);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
margin-bottom: 10px;
}
.equation {
padding: 12px;
border: 1px solid var(--line);
border-left: 3px solid var(--accent);
background: #0b1821;
color: #dce8eb;
font-family: Georgia, "Times New Roman", serif;
font-size: 16px;
line-height: 1.55;
}
.small-copy {
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.control-label,
.partial-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
font-size: 12px;
}
.control-label {
margin: 15px 0 7px;
}
output {
color: #d9e6e9;
font-variant-numeric: tabular-nums;
font-size: 11px;
}
input[type="range"] {
width: 100%;
margin: 3px 0 0;
accent-color: var(--accent);
cursor: pointer;
}
.range-ends {
display: flex;
justify-content: space-between;
color: #607985;
font-size: 9px;
margin-top: 2px;
}
.partials {
display: grid;
gap: 8px;
}
.partial {
padding: 11px 11px 9px;
border: 1px solid var(--line);
background: linear-gradient(135deg, rgba(17, 32, 42, 0.95), rgba(10, 22, 30, 0.95));
}
.partial-heading {
margin-bottom: 8px;
}
.partial-name {
display: flex;
align-items: center;
gap: 8px;
font-weight: 700;
}
.dot {
width: 8px;
height: 8px;
display: inline-block;
background: var(--c);
box-shadow: 0 0 12px color-mix(in srgb, var(--c) 55%, transparent);
}
.partial-frequency {
color: var(--muted);
font-size: 10px;
font-weight: 500;
font-variant-numeric: tabular-nums;
}
.mini-row {
display: grid;
grid-template-columns: 54px 1fr 48px;
align-items: center;
gap: 7px;
margin-top: 5px;
color: var(--muted);
font-size: 10px;
}
.mini-row output {
text-align: right;
}
.mini-row input {
margin: 0;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
}
.stat {
min-width: 0;
padding: 9px 7px;
border: 1px solid var(--line);
background: #0b1821;
}
.stat span {
display: block;
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.stat strong {
display: block;
margin-top: 4px;
font-size: 12px;
font-variant-numeric: tabular-nums;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.button-row {
display: flex;
gap: 8px;
margin-top: 14px;
}
.button {
appearance: none;
border: 1px solid #34505d;
background: #10232d;
padding: 8px 11px;
font-size: 11px;
cursor: pointer;
transition: background 120ms ease, border-color 120ms ease;
}
.button:hover {
background: #17313d;
border-color: #557482;
}
.button.primary {
color: #17140c;
border-color: var(--accent);
background: var(--accent);
font-weight: 750;
}
.button.primary:hover {
background: #ffd985;
}
details {
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
summary {
color: #dce7ea;
cursor: pointer;
}
details p {
margin-top: 8px;
}
.caution {
padding: 11px;
border: 1px solid #554b2e;
border-left: 3px solid var(--accent);
background: rgba(61, 49, 21, 0.22);
color: #c9c4af;
font-size: 11px;
line-height: 1.55;
}
.caution strong {
color: #f1d899;
display: block;
margin-bottom: 4px;
}
main {
min-width: 0;
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1.5fr) minmax(350px, 0.85fr);
gap: 14px;
padding: 14px 16px 16px;
}
.chart-card {
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
border: 1px solid var(--line);
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.18);
}
.chart-head {
min-height: 50px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 13px;
border-bottom: 1px solid var(--line);
background: rgba(13, 28, 37, 0.96);
}
.chart-head h2 {
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
white-space: nowrap;
}
.chart-head p {
color: var(--muted);
font-size: 10px;
margin-top: 3px;
}
.chart-tools {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 9px;
flex-wrap: wrap;
}
.legend {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
flex-wrap: wrap;
color: var(--muted);
font-size: 9px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 4px;
}
.legend i {
width: 12px;
height: 3px;
display: inline-block;
background: var(--c);
}
.segmented {
display: inline-flex;
border: 1px solid #304b58;
background: #09151d;
}
.segmented button {
appearance: none;
border: 0;
border-right: 1px solid #304b58;
background: transparent;
color: var(--muted);
padding: 6px 9px;
font-size: 10px;
cursor: pointer;
}
.segmented button:last-child {
border-right: 0;
}
.segmented button.active {
color: #101719;
background: var(--accent);
font-weight: 800;
}
.stage {
position: relative;
flex: 1;
min-height: 320px;
overflow: hidden;
background: #09151d;
}
.stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
.stage canvas:active {
cursor: grabbing;
}
.stage-note {
position: absolute;
z-index: 3;
left: 12px;
bottom: 10px;
color: #718994;
font-size: 9px;
pointer-events: none;
}
.world-label {
position: absolute;
z-index: 2;
transform: translate(-50%, -50%);
color: #8da5af;
font-size: 9px;
line-height: 1.25;
white-space: nowrap;
pointer-events: none;
text-align: center;
text-shadow: 0 1px 5px #061016;
}
.world-label strong {
display: block;
color: #d9e6e9;
font-size: 10px;
font-weight: 700;
}
.world-label.phase-label {
color: var(--accent);
}
@media (max-width: 1050px) {
body {
grid-template-columns: 300px minmax(0, 1fr);
}
main {
grid-template-columns: 1fr;
grid-template-rows: minmax(350px, 1.25fr) minmax(280px, 0.75fr);
}
}
@media (max-width: 720px) {
body {
height: auto;
min-height: 100vh;
display: block;
overflow: auto;
}
header {
position: sticky;
top: 0;
height: 64px;
padding: 0 14px;
}
.header-note {
display: none;
}
aside {
overflow: visible;
border-right: 0;
border-bottom: 1px solid var(--line);
padding: 17px 14px;
}
.partials {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
main {
display: block;
padding: 12px;
}
.chart-card {
height: 500px;
margin-bottom: 12px;
}
.chart-card:last-child {
margin-bottom: 0;
}
}
@media (max-width: 480px) {
.partials {
grid-template-columns: 1fr;
}
.chart-card {
height: 450px;
}
.chart-head {
align-items: flex-start;
}
.legend {
max-width: 150px;
}
}
</style>
</head>
<body>
<header>
<div class="brand">
<div class="brand-mark">∑</div>
<div>
<h1>Harmonic Lab</h1>
<p class="subtitle">Fourier components and musical partials</p>
</div>
</div>
<div class="header-note">
<strong>Five partials · one coherent coefficient set</strong><br />
Drag either chart to orbit · scroll to zoom · double-click to reset
</div>
</header>
<aside>
<section class="section">
<div class="eyebrow">Periodic Model</div>
<div class="equation">
x(t) = Σ A<sub>n</sub> cos(2π n f<sub>0</sub>t + φ<sub>n</sub>)
</div>
<p class="small-copy" style="margin-top: 9px;">
The waveform and the one-sided spectrum below use exactly these same
amplitudes and phases.
</p>
</section>
<section class="section">
<div class="eyebrow">Fundamental</div>
<label class="control-label" for="fundamental">
<span>Frequency f<sub>0</sub></span>
<output id="fundamentalOutput">220 Hz</output>
</label>
<input id="fundamental" type="range" min="55" max="440" step="1" value="220" />
<div class="range-ends"><span>55 Hz</span><span>440 Hz</span></div>
<p id="noteReadout" class="small-copy" style="margin-top: 7px;">
Nearest equal-tempered note: A3
</p>
</section>
<section class="section">
<div class="eyebrow">Harmonic Coefficients</div>
<div id="partialControls" class="partials"></div>
<div class="button-row">
<button id="resetCoefficients" class="button primary" type="button">
Reset coefficients
</button>
</div>
</section>
<section class="section">
<div class="eyebrow">Measured Model</div>
<div class="stats">
<div class="stat">
<span>Peak</span>
<strong id="peakValue">—</strong>
</div>
<div class="stat">
<span>RMS</span>
<strong id="rmsValue">—</strong>
</div>
<div class="stat">
<span>Period</span>
<strong id="periodValue">—</strong>
</div>
</div>
</section>
<section class="section">
<details>
<summary>Spectrum convention</summary>
<p>
The amplitude view is a one-sided spectrum: the bar at
n f<sub>0</sub> has height A<sub>n</sub>. The phase view shows
φ<sub>n</sub> from −π to π.
</p>
<p>
In a two-sided complex Fourier series, the coefficient at both
+n f<sub>0</sub> and −n f<sub>0</sub> has magnitude A<sub>n</sub>/2;
negative frequencies are omitted here for readability.
</p>
</details>
</section>
<div class="caution">
<strong>Model boundary</strong>
This is deliberately a stationary, periodic harmonic model. Real sounds
may be non-stationary, transient, noisy, or inharmonic, so this view is
not a general model of all real-world audio.
</div>
</aside>
<main>
<section class="chart-card">
<div class="chart-head">
<div>
<h2>Component Waveforms</h2>
<p>Individual partials and their exact sum over one period</p>
</div>
<div class="chart-tools">
<div id="waveLegend" class="legend"></div>
<button id="resetWaveView" class="button" type="button">Reset view</button>
</div>
</div>
<div id="waveStage" class="stage">
<div class="stage-note">Time increases left → right · playhead traverses one period</div>
</div>
</section>
<section class="chart-card">
<div class="chart-head">
<div>
<h2>Harmonic Spectrum</h2>
<p id="spectrumCaption">One-sided cosine amplitude spectrum</p>
</div>
<div class="chart-tools">
<div class="segmented" aria-label="Spectrum display mode">
<button id="amplitudeMode" class="active" type="button">Amplitude</button>
<button id="phaseMode" type="button">Phase</button>
</div>
<button id="resetSpectrumView" class="button" type="button">Reset view</button>
</div>
</div>
<div id="spectrumStage" class="stage">
<div class="stage-note">Frequencies are exact integer multiples of f<sub>0</sub></div>
</div>
</section>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const COLORS = [0x55d6be, 0x5aa9ff, 0xff7b72, 0xf6c85f, 0xb892ff];
const CSS_COLORS = ["#55d6be", "#5aa9ff", "#ff7b72", "#f6c85f", "#b892ff"];
const DEFAULTS = {
amplitudes: [1.0, 0.45, 0.28, 0.18, 0.12],
phases: [0, 20, -35, 15, -20]
};
const state = {
fundamental: 220,
amplitudes: [...DEFAULTS.amplitudes],
phases: [...DEFAULTS.phases],
spectrumMode: "amplitude",
waveScale: 1.6
};
const waveStage = document.querySelector("#waveStage");
const spectrumStage = document.querySelector("#spectrumStage");
// Separate core Three.js renderers keep the two responsive chart panels simple.
const waveRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
const spectrumRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
for (const renderer of [waveRenderer, spectrumRenderer]) {
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.domElement.setAttribute("aria-label", "Interactive three-dimensional harmonic chart");
}
waveStage.appendChild(waveRenderer.domElement);
spectrumStage.appendChild(spectrumRenderer.domElement);
const waveScene = new THREE.Scene();
waveScene.background = new THREE.Color(0x09151d);
const spectrumScene = new THREE.Scene();
spectrumScene.background = new THREE.Color(0x09151d);
const waveCamera = new THREE.OrthographicCamera(-6, 6, 5, -5, 0.1, 100);
const spectrumCamera = new THREE.OrthographicCamera(-4, 4, 3, -3, 0.1, 100);
waveScene.add(new THREE.HemisphereLight(0xd9f6ff, 0x182026, 1.8));
const waveLight = new THREE.DirectionalLight(0xffffff, 2.2);
waveLight.position.set(-4, 8, 7);
waveScene.add(waveLight);
spectrumScene.add(new THREE.HemisphereLight(0xe8fbff, 0x172129, 1.9));
const spectrumLight = new THREE.DirectionalLight(0xffffff, 2.4);
spectrumLight.position.set(5, 8, 8);
spectrumScene.add(spectrumLight);
const componentGroup = new THREE.Group();
const sumGroup = new THREE.Group();
const axisGroup = new THREE.Group();
waveScene.add(axisGroup, componentGroup, sumGroup);
const barGroup = new THREE.Group();
const phaseGroup = new THREE.Group();
const spectrumAxisGroup = new THREE.Group();
spectrumScene.add(spectrumAxisGroup, barGroup, phaseGroup);
const X_HALF = 4.8;
const WAVE_Y_HALF = 1.48;
const SUM_Z = 1.35;
const COMPONENT_Z = [0.5, -0.15, -0.8, -1.45, -2.1];
const SPECTRUM_X = [-2, -1, 0, 1, 2];
const PHASE_Y_HALF = 1.48;
const waveLabels = [];
const spectrumLabels = [];
const temporaryVector = new THREE.Vector3();
function makeLine(points, color, opacity = 1) {
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map((p) => new THREE.Vector3(...p))
);
const material = new THREE.LineBasicMaterial({
color,
transparent: opacity < 1,
opacity
});
return new THREE.Line(geometry, material);
}
function addWorldLabel(stage, text, position, className = "") {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.innerHTML = text;
stage.appendChild(element);
const label = { element, position: position.clone() };
waveLabels.push(label);
return label;
}
function addSpectrumLabel(text, position) {
const element = document.createElement("div");
element.className = "world-label";
element.innerHTML = text;
spectrumStage.appendChild(element);
const label = { element, position: position.clone() };
spectrumLabels.push(label);
return label;
}
// Waveform axes and one baseline for every component lane.
for (let i = 0; i < 5; i++) {
axisGroup.add(
makeLine(
[[-X_HALF, 0, COMPONENT_Z[i]], [X_HALF, 0, COMPONENT_Z[i]]],
0x28414c,
0.85
)
);
addWorldLabel(
waveStage,
`H${i + 1}`,
new THREE.Vector3(-X_HALF - 0.25, 0, COMPONENT_Z[i])
);
}
axisGroup.add(
makeLine(
[[-X_HALF, 0, SUM_Z], [X_HALF, 0, SUM_Z]],
0x36505b,
0.95
)
);
axisGroup.add(
makeLine(
[
[-X_HALF, -WAVE_Y_HALF - 0.18, SUM_Z],
[-X_HALF, WAVE_Y_HALF + 0.18, SUM_Z]
],
0x36505b,
0.95
)
);
axisGroup.add(
makeLine(
[
[-X_HALF, -WAVE_Y_HALF - 0.18, SUM_Z],
[X_HALF, -WAVE_Y_HALF - 0.18, SUM_Z]
],
0x36505b,
0.95
)
);
for (const t of [0, 0.5, 1]) {
const x = -X_HALF + t * X_HALF * 2;
axisGroup.add(
makeLine(
[[x, -WAVE_Y_HALF - 0.18, SUM_Z], [x, -WAVE_Y_HALF - 0.06, SUM_Z]],
0x58727d
)
);
}
addWorldLabel(
waveStage,
"0",
new THREE.Vector3(-X_HALF, -WAVE_Y_HALF - 0.35, SUM_Z)
);
addWorldLabel(
waveStage,
"π",
new THREE.Vector3(0, -WAVE_Y_HALF - 0.35, SUM_Z)
);
addWorldLabel(
waveStage,
"2π",
new THREE.Vector3(X_HALF, -WAVE_Y_HALF - 0.35, SUM_Z)
);
const scaleLabel = addWorldLabel(
waveStage,
"±1.00",
new THREE.Vector3(-X_HALF - 0.15, WAVE_Y_HALF, SUM_Z)
);
addWorldLabel(
waveStage,
"Σ SUM",
new THREE.Vector3(-X_HALF - 0.28, 0, SUM_Z)
).element.style.color = "#f2c66d";
// Spectrum axes.
spectrumAxisGroup.add(
makeLine(
[[-3.05, 0, 0], [3.05, 0, 0]],
0x36505b,
0.95
)
);
spectrumAxisGroup.add(
makeLine(
[[-3.05, -PHASE_Y_HALF - 0.18, 0], [-3.05, PHASE_Y_HALF + 0.18, 0]],
0x36505b,
0.95
)
);
const bars = [];
const phaseMarkers = [];
for (let i = 0; i < 5; i++) {
const color = COLORS[i];
const pivot = new THREE.Group();
pivot.position.x = SPECTRUM_X[i];
const geometry = new THREE.BoxGeometry(0.62, 1, 0.52);
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.08,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, material);
pivot.add(mesh);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x071018,
transparent: true,
opacity: 0.75
});
const edges = new THREE.LineSegments(new THREE.EdgesGeometry(geometry), edgeMaterial);
pivot.add(edges);
barGroup.add(pivot);
bars.push({ pivot, mesh, edges });
const stem = makeLine(
[[SPECTRUM_X[i], 0, 0.04], [SPECTRUM_X[i], 0, 0.04]],
color,
0.9
);
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.12, 0),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.18,
flatShading: true
})
);
marker.position.set(SPECTRUM_X[i], 0, 0.04);
phaseGroup.add(stem, marker);
phaseMarkers.push({ stem, marker });
addSpectrumLabel(
`H${i + 1}<strong>—</strong>`,
new THREE.Vector3(SPECTRUM_X[i], -PHASE_Y_HALF - 0.42, 0.08)
);
}
const phaseAxisLabels = [
addSpectrumLabel("−π", new THREE.Vector3(-3.3, -PHASE_Y_HALF, 0)),
addSpectrumLabel("0", new THREE.Vector3(-3.3, 0, 0)),
addSpectrumLabel("+π", new THREE.Vector3(-3.3, PHASE_Y_HALF, 0))
];
const amplitudeAxisLabel = addSpectrumLabel(
"A",
new THREE.Vector3(-3.3, 1.7, 0)
);
// Moving playhead on the summed curve.
const playhead = new THREE.Mesh(
new THREE.OctahedronGeometry(0.085, 0),
new THREE.MeshBasicMaterial({ color: 0xffe3a0 })
);
sumGroup.add(playhead);
function sampleValue(u, harmonicIndex = null) {
let value = 0;
if (harmonicIndex === null) {
for (let n = 0; n < 5; n++) {
const phase = THREE.MathUtils.degToRad(state.phases[n]);
value +=
state.amplitudes[n] *
Math.cos(2 * Math.PI * (n + 1) * u + phase);
}
} else {
const phase = THREE.MathUtils.degToRad(state.phases[harmonicIndex]);
value =
state.amplitudes[harmonicIndex] *
Math.cos(2 * Math.PI * (harmonicIndex + 1) * u + phase);
}
return value;
}
function curveFor(amplitude, phase, harmonic, z, scale) {
const points = [];
const segments = 128;
for (let j = 0; j <= segments; j++) {
const u = j / segments;
const phaseRadians = THREE.MathUtils.degToRad(phase);
const value =
amplitude * Math.cos(2 * Math.PI * harmonic * u + phaseRadians);
points.push(
new THREE.Vector3(
-X_HALF + u * X_HALF * 2,
(value / scale) * WAVE_Y_HALF,
z
)
);
}
return new THREE.CatmullRomCurve3(points, false, "catmullrom", 0);
}
function removeAndDispose(object) {
object.parent?.remove(object);
object.geometry?.dispose();
if (Array.isArray(object.material)) {
object.material.forEach((material) => material.dispose());
} else {
object.material?.dispose();
}
}
function rebuildWave() {
for (const child of [...componentGroup.children]) {
removeAndDispose(child);
}
for (const child of [...sumGroup.children]) {
if (child !== playhead) removeAndDispose(child);
}
const sumOfAmplitudes = state.amplitudes.reduce((sum, value) => sum + value, 0);
state.waveScale = Math.max(0.5, sumOfAmplitudes * 1.12);
for (let i = 0; i < 5; i++) {
const curve = curveFor(
state.amplitudes[i],
state.phases[i],
i + 1,
COMPONENT_Z[i],
state.waveScale
);
const geometry = new THREE.TubeGeometry(curve, 128, 0.017, 3, false);
const material = new THREE.MeshStandardMaterial({
color: COLORS[i],
roughness: 0.8,
metalness: 0.02,
flatShading: true
});
componentGroup.add(new THREE.Mesh(geometry, material));
}
const sumCurve = curveFor(
1,
0,
1,
SUM_Z,
state.waveScale
);
// Build the exact sum directly from all five coefficients.
const sumPoints = [];
for (let j = 0; j <= 160; j++) {
const u = j / 160;
sumPoints.push(
new THREE.Vector3(
-X_HALF + u * X_HALF * 2,
(sampleValue(u) / state.waveScale) * WAVE_Y_HALF,
SUM_Z
)
);
}
const exactCurve = new THREE.CatmullRomCurve3(
sumPoints,
false,
"catmullrom",
0
);
const sumGeometry = new THREE.TubeGeometry(exactCurve, 160, 0.033, 4, false);
const sumMaterial = new THREE.MeshStandardMaterial({
color: 0xf2c66d,
roughness: 0.62,
metalness: 0.08,
flatShading: true
});
sumGroup.add(new THREE.Mesh(sumGeometry, sumMaterial));
scaleLabel.element.innerHTML = `±${state.waveScale.toFixed(2)}`;
}
function rebuildSpectrum() {
const maxAmplitude = Math.max(...state.amplitudes, 0.5);
const amplitudeScale = maxAmplitude * 1.12;
for (let i = 0; i < 5; i++) {
const height = (state.amplitudes[i] / amplitudeScale) * PHASE_Y_HALF;
bars[i].mesh.scale.y = Math.max(height, 0.0001);
bars[i].mesh.position.y = height / 2;
bars[i].edges.scale.y = Math.max(height, 0.0001);
bars[i].edges.position.y = height / 2;
const phase = THREE.MathUtils.degToRad(state.phases[i]);
const phaseY = (phase / Math.PI) * PHASE_Y_HALF;
const positions = bars[i].pivot.position;
phaseMarkers[i].stem.geometry.setFromPoints([
new THREE.Vector3(positions.x, 0, 0.04),
new THREE.Vector3(positions.x, phaseY, 0.04)
]);
phaseMarkers[i].marker.position.y = phaseY;
const frequency = state.fundamental * (i + 1);
const phaseText = `${state.phases[i]}°`;
const amplitudeText = state.amplitudes[i].toFixed(2);
spectrumLabels[i].element.innerHTML =
state.spectrumMode === "amplitude"
? `H${i + 1}<strong>${amplitudeText}</strong><small>${frequency} Hz</small>`
: `H${i + 1}<strong>${phaseText}</strong><small>${frequency} Hz</small>`;
}
barGroup.visible = state.spectrumMode === "amplitude";
phaseGroup.visible = state.spectrumMode === "phase";
amplitudeAxisLabel.element.style.display =
state.spectrumMode === "amplitude" ? "" : "none";
for (const label of phaseAxisLabels) {
label.element.style.display =
state.spectrumMode === "phase" ? "" : "none";
}
}
function nearestNote(frequency) {
const midiFloat = 69 + 12 * Math.log2(frequency / 440);
const midi = Math.round(midiFloat);
const names = ["C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B"];
const note = names[(midi % 12 + 12) % 12];
const octave = Math.floor(midi / 12) - 1;
const cents = Math.round((midiFloat - midi) * 100);
const detune = cents ? ` ${cents > 0 ? "+" : ""}${cents}¢` : "";
return `${note}${octave}${detune}`;
}
function updateMetrics() {
let peak = 0;
const samples = 4096;
for (let i = 0; i < samples; i++) {
peak = Math.max(peak, Math.abs(sampleValue(i / samples)));
}
const rms = Math.sqrt(
state.amplitudes.reduce(
(sum, amplitude) => sum + (amplitude * amplitude) / 2,
0
)
);
document.querySelector("#peakValue").textContent = peak.toFixed(3);
document.querySelector("#rmsValue").textContent = rms.toFixed(3);
document.querySelector("#periodValue").textContent =
`${(1000 / state.fundamental).toFixed(2)} ms`;
}
function updateFundamentalReadout() {
document.querySelector("#fundamentalOutput").textContent =
`${state.fundamental} Hz`;
document.querySelector("#noteReadout").textContent =
`Nearest equal-tempered note: ${nearestNote(state.fundamental)}`;
}
function updateAll() {
rebuildWave();
rebuildSpectrum();
updateMetrics();
updateFundamentalReadout();
}
// Build the coefficient controls.
const partialControls = document.querySelector("#partialControls");
for (let i = 0; i < 5; i++) {
const row = document.createElement("div");
row.className = "partial";
row.innerHTML = `
<div class="partial-heading">
<div class="partial-name">
<span class="dot" style="--c:${CSS_COLORS[i]}"></span>
H${i + 1}
</div>
<span id="frequency-${i}" class="partial-frequency">
${state.fundamental * (i + 1)} Hz
</span>
</div>
<label class="mini-row" for="amplitude-${i}">
<span>Amplitude</span>
<input id="amplitude-${i}" type="range"
min="0" max="1" step="0.01" value="${state.amplitudes[i]}" />
<output id="amplitude-output-${i}">${state.amplitudes[i].toFixed(2)}</output>
</label>
<label class="mini-row" for="phase-${i}">
<span>Phase</span>
<input id="phase-${i}" type="range"
min="-180" max="180" step="1" value="${state.phases[i]}" />
<output id="phase-output-${i}">${state.phases[i]}°</output>
</label>
`;
partialControls.appendChild(row);
const amplitudeInput = row.querySelector(`#amplitude-${i}`);
const phaseInput = row.querySelector(`#phase-${i}`);
const amplitudeOutput = row.querySelector(`#amplitude-output-${i}`);
const phaseOutput = row.querySelector(`#phase-output-${i}`);
amplitudeInput.addEventListener("input", () => {
state.amplitudes[i] = Number(amplitudeInput.value);
amplitudeOutput.textContent = state.amplitudes[i].toFixed(2);
rebuildWave();
rebuildSpectrum();
updateMetrics();
});
phaseInput.addEventListener("input", () => {
state.phases[i] = Number(phaseInput.value);
phaseOutput.textContent = `${state.phases[i]}°`;
rebuildWave();
rebuildSpectrum();
});
}
const waveLegend = document.querySelector("#waveLegend");
waveLegend.innerHTML = state.amplitudes
.map(
(_, i) =>
`<span style="--c:${CSS_COLORS[i]}"><i></i>H${i + 1}</span>`
)
.join("") + `<span style="--c:#f2c66d"><i></i>Σ</span>`;
document.querySelector("#fundamental").addEventListener("input", (event) => {
state.fundamental = Number(event.target.value);
for (let i = 0; i < 5; i++) {
document.querySelector(`#frequency-${i}`).textContent =
`${state.fundamental * (i + 1)} Hz`;
}
rebuildSpectrum();
updateMetrics();
updateFundamentalReadout();
});
document.querySelector("#resetCoefficients").addEventListener("click", () => {
state.amplitudes = [...DEFAULTS.amplitudes];
state.phases = [...DEFAULTS.phases];
for (let i = 0; i < 5; i++) {
const amplitudeInput = document.querySelector(`#amplitude-${i}`);
const phaseInput = document.querySelector(`#phase-${i}`);
amplitudeInput.value = state.amplitudes[i];
phaseInput.value = state.phases[i];
document.querySelector(`#amplitude-output-${i}`).textContent =
state.amplitudes[i].toFixed(2);
document.querySelector(`#phase-output-${i}`).textContent =
`${state.phases[i]}°`;
}
updateAll();
});
function setSpectrumMode(mode) {
state.spectrumMode = mode;
const amplitudeButton = document.querySelector("#amplitudeMode");
const phaseButton = document.querySelector("#phaseMode");
const caption = document.querySelector("#spectrumCaption");
amplitudeButton.classList.toggle("active", mode === "amplitude");
phaseButton.classList.toggle("active", mode === "phase");
caption.textContent =
mode === "amplitude"
? "One-sided cosine amplitude spectrum"
: "One-sided phase spectrum, φₙ modulo 2π";
rebuildSpectrum();
}
document.querySelector("#amplitudeMode").addEventListener("click", () => {
setSpectrumMode("amplitude");
});
document.querySelector("#phaseMode").addEventListener("click", () => {
setSpectrumMode("phase");
});
// Direct camera controls: no addon imports are used.
function attachCameraControls({
renderer,
camera,
target,
radius,
initialAzimuth,
initialPolar,
onReset
}) {
let azimuth = initialAzimuth;
let polar = initialPolar;
let zoom = 1;
let dragging = false;
let lastX = 0;
let lastY = 0;
function applyCamera() {
camera.position.set(
target.x + radius * Math.sin(polar) * Math.sin(azimuth),
target.y + radius * Math.cos(polar),
target.z + radius * Math.sin(polar) * Math.cos(azimuth)
);
camera.lookAt(target);
camera.zoom = zoom;
camera.updateProjectionMatrix();
}
function reset() {
azimuth = initialAzimuth;
polar = initialPolar;
zoom = 1;
applyCamera();
onReset?.();
}
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
lastX = event.clientX;
lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
azimuth -= dx * 0.006;
polar = THREE.MathUtils.clamp(polar + dy * 0.004, 0.48, 1.49);
applyCamera();
});
function stopDragging(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
zoom = THREE.MathUtils.clamp(
zoom * Math.exp(-event.deltaY * 0.001),
0.65,
2.4
);
applyCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", reset);
applyCamera();
return { reset };
}
const waveControls = attachCameraControls({
renderer: waveRenderer,
camera: waveCamera,
target: new THREE.Vector3(0, 0, -0.38),
radius: 14,
initialAzimuth: 0,
initialPolar: 1.17
});
const spectrumControls = attachCameraControls({
renderer: spectrumRenderer,
camera: spectrumCamera,
target: new THREE.Vector3(0, 0, 0),
radius: 12,
initialAzimuth: 0,
initialPolar: 1.42
});
document.querySelector("#resetWaveView").addEventListener("click", () => {
waveControls.reset();
});
document.querySelector("#resetSpectrumView").addEventListener("click", () => {
spectrumControls.reset();
});
function resizeWave() {
const width = Math.max(1, waveStage.clientWidth);
const height = Math.max(1, waveStage.clientHeight);
const aspect = width / height;
const viewHeight = Math.max(5.7, 11.2 / aspect);
waveRenderer.setSize(width, height, false);
waveCamera.left = (-viewHeight * aspect) / 2;
waveCamera.right = (viewHeight * aspect) / 2;
waveCamera.top = viewHeight / 2;
waveCamera.bottom = -viewHeight / 2;
waveCamera.updateProjectionMatrix();
}
function resizeSpectrum() {
const width = Math.max(1, spectrumStage.clientWidth);
const height = Math.max(1, spectrumStage.clientHeight);
const aspect = width / height;
const viewHeight = Math.max(5.2, 7.2 / aspect);
spectrumRenderer.setSize(width, height, false);
spectrumCamera.left = (-viewHeight * aspect) / 2;
spectrumCamera.right = (viewHeight * aspect) / 2;
spectrumCamera.top = viewHeight / 2;
spectrumCamera.bottom = -viewHeight / 2;
spectrumCamera.updateProjectionMatrix();
}
const waveResizeObserver = new ResizeObserver(resizeWave);
const spectrumResizeObserver = new ResizeObserver(resizeSpectrum);
waveResizeObserver.observe(waveStage);
spectrumResizeObserver.observe(spectrumStage);
function projectLabel(label, camera, stage) {
temporaryVector.copy(label.position).project(camera);
const x = (temporaryVector.x * 0.5 + 0.5) * stage.clientWidth;
const y = (-temporaryVector.y * 0.5 + 0.5) * stage.clientHeight;
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
label.element.style.visibility =
temporaryVector.z > -1 && temporaryVector.z < 1 ? "visible" : "hidden";
}
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
const u = (elapsed * 0.17) % 1;
const x = -X_HALF + u * X_HALF * 2;
const y = (sampleValue(u) / state.waveScale) * WAVE_Y_HALF;
playhead.position.set(x, y, SUM_Z);
for (const label of waveLabels) {
projectLabel(label, waveCamera, waveStage);
}
for (const label of spectrumLabels) {
projectLabel(label, spectrumCamera, spectrumStage);
}
waveRenderer.render(waveScene, waveCamera);
spectrumRenderer.render(spectrumScene, spectrumCamera);
requestAnimationFrame(animate);
}
updateAll();
resizeWave();
resizeSpectrum();
animate();
</script>
</body>
</html>
```