Prompt specification
Build or customize the Three.js 3D scene "Wave-sum counterfactual 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: Wave-sum counterfactual playground
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/wave-sum-counterfactual-playground-x1592
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts wave superposition and pulse addition. Provide amplitude, phase, and frequency controls for two analytic waves; display each component and the sum without adding unmodeled nonlinear interactions. Low-poly.
Working Three.js Starter (wave-sum-counterfactual-playground-x1592):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Analytic Wave Superposition</title>
<style>
:root {
color-scheme: dark;
--bg: #06101c;
--panel: rgba(9, 20, 34, 0.88);
--panel-border: rgba(151, 190, 221, 0.16);
--text: #eaf5ff;
--muted: #8da5ba;
--cyan: #39d7ff;
--pink: #ff58a6;
--gold: #ffd166;
--line: rgba(164, 202, 232, 0.15);
}
* {
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,
select {
font: inherit;
}
button {
color: inherit;
}
#app,
#app canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
#app canvas {
display: block;
touch-action: none;
cursor: grab;
}
#app canvas:active {
cursor: grabbing;
}
.vignette {
position: fixed;
inset: 0;
z-index: 1;
pointer-events: none;
background:
radial-gradient(circle at 45% 45%, transparent 30%, rgba(1, 7, 14, 0.42) 100%),
linear-gradient(90deg, rgba(4, 12, 22, 0.38), transparent 24%, transparent 72%, rgba(4, 12, 22, 0.35));
}
.glass {
background: var(--panel);
border: 1px solid var(--panel-border);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(18px) saturate(120%);
-webkit-backdrop-filter: blur(18px) saturate(120%);
}
header {
position: fixed;
z-index: 4;
top: 24px;
left: 26px;
max-width: 470px;
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 9px;
color: #a8c5dc;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 27px;
height: 1px;
content: "";
background: var(--cyan);
box-shadow: 0 0 10px var(--cyan);
}
h1 {
margin: 0;
font-size: clamp(29px, 3.1vw, 47px);
font-weight: 760;
letter-spacing: -0.045em;
line-height: 0.98;
}
header p {
max-width: 390px;
margin: 12px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
#panelToggle {
position: fixed;
z-index: 8;
top: 18px;
right: 18px;
display: none;
padding: 10px 14px;
border: 1px solid var(--panel-border);
border-radius: 10px;
background: rgba(9, 20, 34, 0.9);
cursor: pointer;
}
#panel {
position: fixed;
z-index: 6;
top: 18px;
right: 18px;
width: 334px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 18px;
border-radius: 16px;
scrollbar-width: thin;
scrollbar-color: rgba(125, 170, 205, 0.35) transparent;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 14px;
}
.panel-title strong {
font-size: 14px;
letter-spacing: 0.01em;
}
.panel-title span {
color: var(--muted);
font-size: 10px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 4px;
padding: 4px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(2, 9, 17, 0.42);
}
.segmented button {
padding: 8px 7px;
border: 0;
border-radius: 8px;
background: transparent;
color: var(--muted);
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition: 140ms ease;
}
.segmented button:hover {
color: var(--text);
}
.segmented button.active {
background: rgba(117, 180, 222, 0.16);
color: #f5fbff;
box-shadow: inset 0 0 0 1px rgba(158, 207, 242, 0.12);
}
.wave-card {
margin-top: 13px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(3, 11, 21, 0.38);
}
.wave-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
}
.wave-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.03em;
}
.dot {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
}
.dot.cyan {
color: var(--cyan);
}
.dot.pink {
color: var(--pink);
}
.dot.gold {
color: var(--gold);
}
.wave-summary {
color: var(--muted);
font-size: 9px;
font-variant-numeric: tabular-nums;
}
.control {
margin-top: 10px;
}
.control-label {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 5px;
color: #b9cadd;
font-size: 10px;
font-weight: 650;
}
output {
color: #eff8ff;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
border-radius: 99px;
outline: none;
appearance: none;
-webkit-appearance: none;
background: rgba(131, 171, 204, 0.2);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 14px;
height: 14px;
border: 2px solid #dff5ff;
border-radius: 50%;
appearance: none;
-webkit-appearance: none;
background: #152b3f;
box-shadow: 0 0 0 3px rgba(119, 193, 230, 0.12);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid #dff5ff;
border-radius: 50%;
background: #152b3f;
}
.direction-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 11px;
}
.direction-row > span {
color: #b9cadd;
font-size: 10px;
font-weight: 650;
}
.mini-segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 3px;
min-width: 104px;
padding: 3px;
border: 1px solid var(--line);
border-radius: 8px;
}
.mini-segmented button {
padding: 5px 7px;
border: 0;
border-radius: 5px;
background: transparent;
color: var(--muted);
font-size: 10px;
cursor: pointer;
}
.mini-segmented button.active {
background: rgba(136, 188, 225, 0.15);
color: white;
}
.pulse-only {
display: none;
}
body[data-mode="pulse"] .pulse-only {
display: block;
}
body[data-mode="pulse"] .pulse-only.flex {
display: flex;
}
.divider {
height: 1px;
margin: 15px 0;
background: var(--line);
}
.transport {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 11px;
}
.action {
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(126, 179, 216, 0.08);
color: #dcecf7;
font-size: 10px;
font-weight: 700;
cursor: pointer;
transition: 130ms ease;
}
.action:hover {
border-color: rgba(139, 199, 237, 0.32);
background: rgba(126, 179, 216, 0.15);
}
.action.primary {
color: #07121e;
background: #bdeaff;
}
.equation {
margin-top: 14px;
padding: 12px;
border: 1px solid rgba(255, 209, 102, 0.18);
border-radius: 11px;
background: rgba(255, 209, 102, 0.055);
}
.equation strong {
display: block;
margin-bottom: 5px;
color: var(--gold);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 13px;
}
.equation small {
display: block;
color: #9eb1c2;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
line-height: 1.55;
}
.linear-note {
margin-top: 10px;
color: #8299ad;
font-size: 9px;
line-height: 1.55;
}
.linear-note b {
color: #c4d6e5;
}
#legend {
position: fixed;
z-index: 4;
bottom: 20px;
left: 24px;
display: flex;
align-items: center;
gap: 17px;
padding: 11px 14px;
border-radius: 12px;
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
color: #c2d2df;
font-size: 10px;
font-weight: 700;
}
.legend-line {
width: 19px;
height: 3px;
border-radius: 99px;
background: currentColor;
box-shadow: 0 0 9px currentColor;
}
.legend-note {
padding-left: 15px;
border-left: 1px solid var(--line);
color: #7890a4;
font-size: 9px;
}
#probeCard {
position: fixed;
z-index: 4;
right: 24px;
bottom: 20px;
width: 220px;
padding: 12px 14px;
border-radius: 12px;
pointer-events: none;
}
.probe-head {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
color: #91a8ba;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.probe-row {
display: grid;
grid-template-columns: 10px 1fr auto;
align-items: center;
gap: 7px;
margin-top: 5px;
color: #aebfcd;
font-size: 10px;
}
.probe-row b {
color: #eef8ff;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.probe-equation {
margin-top: 8px;
padding-top: 7px;
border-top: 1px solid var(--line);
color: #8fa5b7;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
}
#cameraHint {
position: fixed;
z-index: 4;
right: 24px;
bottom: 152px;
color: rgba(164, 189, 208, 0.58);
font-size: 9px;
pointer-events: none;
}
#loading {
position: fixed;
z-index: 20;
inset: 0;
display: grid;
place-items: center;
background: var(--bg);
color: #a9c4d8;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
@media (max-width: 780px) {
header {
top: 18px;
left: 18px;
max-width: calc(100vw - 130px);
}
header p {
display: none;
}
h1 {
font-size: 28px;
}
#panelToggle {
display: block;
}
#panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 68vh;
transition: transform 180ms ease, opacity 180ms ease;
}
body.panel-closed #panel {
transform: translateY(calc(100% + 20px));
opacity: 0;
pointer-events: none;
}
#legend {
bottom: 14px;
left: 12px;
gap: 10px;
padding: 9px 11px;
}
.legend-note {
display: none;
}
#probeCard {
top: 95px;
right: 12px;
bottom: auto;
width: 188px;
}
#cameraHint {
display: none;
}
}
</style>
</head>
<body data-mode="sine">
<div id="app"></div>
<div class="vignette"></div>
<header>
<div class="eyebrow">Linear field laboratory</div>
<h1>Wave superposition</h1>
<p>
Two independently controlled analytic waves. Their displayed sum is evaluated
directly as <strong>y = y₁ + y₂</strong>, with no coupling or collision model.
</p>
</header>
<button id="panelToggle" type="button">Controls</button>
<aside id="panel" class="glass">
<div class="panel-title">
<strong>Field parameters</strong>
<span>Three.js / analytic</span>
</div>
<div class="segmented" id="modeControl">
<button type="button" class="active" data-mode="sine">Continuous</button>
<button type="button" data-mode="pulse">Pulse addition</button>
</div>
<section class="wave-card">
<div class="wave-head">
<span class="wave-name">
<i class="dot cyan"></i>
Wave A
</span>
<span class="wave-summary" id="a-summary"></span>
</div>
<div class="control">
<div class="control-label">
<label for="a-amp">Amplitude</label>
<output id="a-amp-out"></output>
</div>
<input id="a-amp" type="range" min="0" max="2.5" step="0.01" value="1.2">
</div>
<div class="control">
<div class="control-label">
<label for="a-phase">Phase</label>
<output id="a-phase-out"></output>
</div>
<input id="a-phase" type="range" min="-180" max="180" step="1" value="0">
</div>
<div class="control">
<div class="control-label">
<label for="a-freq">Frequency</label>
<output id="a-freq-out"></output>
</div>
<input id="a-freq" type="range" min="0.2" max="2" step="0.01" value="0.75">
</div>
<div class="direction-row">
<span>Travel direction</span>
<div class="mini-segmented" data-direction-group="0">
<button type="button" data-direction="1" class="active">→ Right</button>
<button type="button" data-direction="-1">← Left</button>
</div>
</div>
<div class="control pulse-only">
<div class="control-label">
<label for="a-width">Pulse width σ</label>
<output id="a-width-out"></output>
</div>
<input id="a-width" type="range" min="0.55" max="3" step="0.05" value="1.4">
</div>
</section>
<section class="wave-card">
<div class="wave-head">
<span class="wave-name">
<i class="dot pink"></i>
Wave B
</span>
<span class="wave-summary" id="b-summary"></span>
</div>
<div class="control">
<div class="control-label">
<label for="b-amp">Amplitude</label>
<output id="b-amp-out"></output>
</div>
<input id="b-amp" type="range" min="0" max="2.5" step="0.01" value="1">
</div>
<div class="control">
<div class="control-label">
<label for="b-phase">Phase</label>
<output id="b-phase-out"></output>
</div>
<input id="b-phase" type="range" min="-180" max="180" step="1" value="90">
</div>
<div class="control">
<div class="control-label">
<label for="b-freq">Frequency</label>
<output id="b-freq-out"></output>
</div>
<input id="b-freq" type="range" min="0.2" max="2" step="0.01" value="0.95">
</div>
<div class="direction-row">
<span>Travel direction</span>
<div class="mini-segmented" data-direction-group="1">
<button type="button" data-direction="1">→ Right</button>
<button type="button" data-direction="-1" class="active">← Left</button>
</div>
</div>
<div class="control pulse-only">
<div class="control-label">
<label for="b-width">Pulse width σ</label>
<output id="b-width-out"></output>
</div>
<input id="b-width" type="range" min="0.55" max="3" step="0.05" value="1.4">
</div>
</section>
<div class="divider"></div>
<div class="control">
<div class="control-label">
<label for="speed">Wave speed c</label>
<output id="speed-out"></output>
</div>
<input id="speed" type="range" min="0.6" max="4" step="0.05" value="2">
</div>
<div class="control">
<div class="control-label">
<label for="time">Simulation time</label>
<output id="time-out"></output>
</div>
<input id="time" type="range" min="0" max="12" step="0.01" value="0">
</div>
<div class="transport">
<button class="action primary" id="playButton" type="button">Pause</button>
<button class="action" id="resetTimeButton" type="button">Reset time</button>
<button class="action pulse-only" id="overlapButton" type="button">Jump to overlap</button>
<button class="action" id="resetCameraButton" type="button">Reset camera</button>
</div>
<div class="control">
<div class="control-label">
<label for="probe">Probe position x</label>
<output id="probe-out"></output>
</div>
<input id="probe" type="range" min="-9.5" max="9.5" step="0.05" value="0">
</div>
<div class="equation">
<strong>y(x,t) = y₁(x,t) + y₂(x,t)</strong>
<small id="formulaDetail"></small>
</div>
<div class="linear-note">
<b>Strictly linear.</b> The curves do not exchange energy, deform one another,
or generate additional harmonics. Every displayed value comes from the two
explicit analytic equations.
</div>
</aside>
<section id="legend" class="glass">
<span class="legend-item" style="color: var(--cyan)">
<i class="legend-line"></i> Wave A
</span>
<span class="legend-item" style="color: var(--pink)">
<i class="legend-line"></i> Wave B
</span>
<span class="legend-item" style="color: var(--gold)">
<i class="legend-line"></i> Linear sum
</span>
<span class="legend-note">240-segment low-poly rendering</span>
</section>
<section id="probeCard" class="glass">
<div class="probe-head">
<span>Point sample</span>
<span id="probe-x-out">x = 0.00</span>
</div>
<div class="probe-row">
<i class="dot cyan"></i><span>Wave A</span><b id="probe-a">0.000</b>
</div>
<div class="probe-row">
<i class="dot pink"></i><span>Wave B</span><b id="probe-b">0.000</b>
</div>
<div class="probe-row">
<i class="dot gold"></i><span>Sum</span><b id="probe-sum">0.000</b>
</div>
<div class="probe-equation" id="probe-equation">0.000 + 0.000 = 0.000</div>
</section>
<div id="cameraHint">Drag: orbit · Shift/right-drag: pan · Wheel: zoom</div>
<div id="loading">Loading analytic field…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const COLORS = {
cyan: 0x39d7ff,
pink: 0xff58a6,
gold: 0xffd166,
grid: 0x31506a
};
const state = {
mode: "sine",
speed: 2,
time: 0,
playing: true,
probeX: 0,
waves: [
{
amp: 1.2,
phaseDeg: 0,
freq: 0.75,
direction: 1,
width: 1.4,
center0: -2.4
},
{
amp: 1.0,
phaseDeg: 90,
freq: 0.95,
direction: -1,
width: 1.4,
center0: 2.4
}
]
};
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
} catch (error) {
$("loading").textContent = "WebGL is unavailable in this browser.";
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x06101c, 1);
renderer.outputColorSpace = THREE.SRGBColorSpace;
$("app").appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x06101c, 22, 48);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const X_MIN = -10;
const X_MAX = 10;
const Y_MIN = -4;
const Y_MAX = 4;
const SEGMENTS = 240;
const SAMPLE_COUNT = SEGMENTS + 1;
const xAt = (i) =>
X_MIN + ((X_MAX - X_MIN) * i) / SEGMENTS;
// -------------------------------------------------------------------------
// Backplate and low-poly grid
// -------------------------------------------------------------------------
const backplate = new THREE.Mesh(
new THREE.PlaneGeometry(21, 9),
new THREE.MeshBasicMaterial({
color: 0x0b1c2d,
transparent: true,
opacity: 0.38,
depthWrite: false
})
);
backplate.position.z = -0.65;
scene.add(backplate);
const gridPositions = [];
const gridColors = [];
const minorColor = new THREE.Color(0x274157);
const majorColor = new THREE.Color(0x42637e);
for (let x = X_MIN; x <= X_MAX; x += 1) {
const color = x % 5 === 0 ? majorColor : minorColor;
gridPositions.push(x, Y_MIN, -0.58, x, Y_MAX, -0.58);
gridColors.push(color.r, color.g, color.b, color.r, color.g, color.b);
}
for (let y = Y_MIN; y <= Y_MAX; y += 1) {
const color = y % 2 === 0 ? majorColor : minorColor;
gridPositions.push(X_MIN, y, -0.58, X_MAX, y, -0.58);
gridColors.push(color.r, color.g, color.b, color.r, color.g, color.b);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPositions, 3)
);
gridGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(gridColors, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.42,
depthWrite: false
})
);
grid.renderOrder = 0;
scene.add(grid);
const baselineGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(X_MIN, 0, -0.48),
new THREE.Vector3(X_MAX, 0, -0.48)
]);
const baseline = new THREE.Line(
baselineGeometry,
new THREE.LineBasicMaterial({
color: 0x9ab8ce,
transparent: true,
opacity: 0.65
})
);
scene.add(baseline);
const frameGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(X_MIN, Y_MIN, -0.5),
new THREE.Vector3(X_MIN, Y_MAX, -0.5),
new THREE.Vector3(X_MIN, Y_MAX, -0.5),
new THREE.Vector3(X_MAX, Y_MAX, -0.5),
new THREE.Vector3(X_MAX, Y_MAX, -0.5),
new THREE.Vector3(X_MAX, Y_MIN, -0.5)
]);
const frame = new THREE.LineSegments(
frameGeometry,
new THREE.LineBasicMaterial({
color: 0x5f819c,
transparent: true,
opacity: 0.32
})
);
scene.add(frame);
// -------------------------------------------------------------------------
// Dynamic ribbon meshes: low triangle count, but wider than WebGL lines.
// -------------------------------------------------------------------------
function createRibbon(color, width, z, opacity, renderOrder) {
const positions = new Float32Array(SAMPLE_COUNT * 2 * 3);
const indices = [];
for (let i = 0; i < SEGMENTS; i++) {
const a = i * 2;
const b = a + 1;
const c = a + 2;
const d = a + 3;
indices.push(a, b, c, b, d, c);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setIndex(indices);
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false
});
const mesh = new THREE.Mesh(geometry, material);
mesh.frustumCulled = false;
mesh.renderOrder = renderOrder;
scene.add(mesh);
return { geometry, positions, width, z };
}
const ribbonA = createRibbon(COLORS.cyan, 0.052, -0.035, 0.78, 2);
const ribbonB = createRibbon(COLORS.pink, 0.052, 0.000, 0.78, 3);
const ribbonSum = createRibbon(COLORS.gold, 0.090, 0.035, 1.0, 4);
function createEnvelopeLine(color) {
const positions = new Float32Array(SAMPLE_COUNT * 3);
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.18,
depthTest: false,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.frustumCulled = false;
line.renderOrder = 1;
line.visible = false;
scene.add(line);
return { geometry, positions, line };
}
const envelopes = [
{
upper: createEnvelopeLine(COLORS.cyan),
lower: createEnvelopeLine(COLORS.cyan)
},
{
upper: createEnvelopeLine(COLORS.pink),
lower: createEnvelopeLine(COLORS.pink)
}
];
// Faceted markers emphasize the low-poly visual language.
const markerCount = 19;
const sumMarkers = new THREE.InstancedMesh(
new THREE.OctahedronGeometry(0.095, 0),
new THREE.MeshBasicMaterial({
color: COLORS.gold,
depthTest: false
}),
markerCount
);
sumMarkers.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
sumMarkers.frustumCulled = false;
sumMarkers.renderOrder = 5;
scene.add(sumMarkers);
const markerDummy = new THREE.Object3D();
// -------------------------------------------------------------------------
// Probe visualization
// -------------------------------------------------------------------------
const probeGeometry = new THREE.BufferGeometry();
probeGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(6), 3)
);
const probeLine = new THREE.Line(
probeGeometry,
new THREE.LineBasicMaterial({
color: 0xe6f6ff,
transparent: true,
opacity: 0.32,
depthTest: false,
depthWrite: false
})
);
probeLine.frustumCulled = false;
probeLine.renderOrder = 5;
scene.add(probeLine);
function createProbeMarker(color) {
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
new THREE.MeshBasicMaterial({
color,
depthTest: false
})
);
marker.renderOrder = 6;
scene.add(marker);
return marker;
}
const probeMarkerA = createProbeMarker(COLORS.cyan);
const probeMarkerB = createProbeMarker(COLORS.pink);
const probeMarkerSum = createProbeMarker(COLORS.gold);
// -------------------------------------------------------------------------
// Analytic evaluation
//
// Continuous:
// y_i = A_i sin(k_i*x - s_i*omega_i*t + phi_i)
//
// Pulse:
// y_i = A_i exp(-0.5*((x-x_i(t))/sigma_i)^2)
// * sin(k_i*x - s_i*omega_i*t + phi_i)
//
// Sum:
// y = y_1 + y_2
// -------------------------------------------------------------------------
const valuesA = new Float32Array(SAMPLE_COUNT);
const valuesB = new Float32Array(SAMPLE_COUNT);
const valuesSum = new Float32Array(SAMPLE_COUNT);
const envelopeA = new Float32Array(SAMPLE_COUNT);
const envelopeB = new Float32Array(SAMPLE_COUNT);
function envelopeAt(wave, x, time) {
if (state.mode !== "pulse") return 1;
const center = wave.center0 + wave.direction * state.speed * time;
const normalized = (x - center) / wave.width;
return Math.exp(-0.5 * normalized * normalized);
}
function waveValue(wave, x, time) {
const omega = 2 * Math.PI * wave.freq;
const k = omega / state.speed;
const phase = wave.phaseDeg * Math.PI / 180;
const carrier = Math.sin(
k * x - wave.direction * omega * time + phase
);
return wave.amp * envelopeAt(wave, x, time) * carrier;
}
function updateRibbon(ribbon, values) {
const p = ribbon.positions;
for (let i = 0; i < SAMPLE_COUNT; i++) {
const previous = values[Math.max(0, i - 1)];
const next = values[Math.min(SAMPLE_COUNT - 1, i + 1)];
const dx = xAt(Math.min(SEGMENTS, i + 1)) -
xAt(Math.max(0, i - 1));
const dy = next - previous;
const length = Math.hypot(dx, dy) || 1;
const normalX = -dy / length;
const normalY = dx / length;
const halfWidth = ribbon.width * 0.5;
const x = xAt(i);
const y = values[i];
const offset = i * 6;
p[offset] = x + normalX * halfWidth;
p[offset + 1] = y + normalY * halfWidth;
p[offset + 2] = ribbon.z;
p[offset + 3] = x - normalX * halfWidth;
p[offset + 4] = y - normalY * halfWidth;
p[offset + 5] = ribbon.z;
}
ribbon.geometry.attributes.position.needsUpdate = true;
}
function updateEnvelopeLine(line, values, sign) {
const p = line.positions;
for (let i = 0; i < SAMPLE_COUNT; i++) {
const offset = i * 3;
p[offset] = xAt(i);
p[offset + 1] = sign * values[i];
p[offset + 2] = -0.12;
}
line.geometry.attributes.position.needsUpdate = true;
}
function updateSceneField() {
for (let i = 0; i < SAMPLE_COUNT; i++) {
const x = xAt(i);
envelopeA[i] = envelopeAt(state.waves[0], x, state.time);
envelopeB[i] = envelopeAt(state.waves[1], x, state.time);
valuesA[i] = waveValue(state.waves[0], x, state.time);
valuesB[i] = waveValue(state.waves[1], x, state.time);
// Exact analytic linear sum; no interaction terms are introduced.
valuesSum[i] = valuesA[i] + valuesB[i];
}
updateRibbon(ribbonA, valuesA);
updateRibbon(ribbonB, valuesB);
updateRibbon(ribbonSum, valuesSum);
const showEnvelope = state.mode === "pulse";
envelopes[0].upper.line.visible = showEnvelope;
envelopes[0].lower.line.visible = showEnvelope;
envelopes[1].upper.line.visible = showEnvelope;
envelopes[1].lower.line.visible = showEnvelope;
if (showEnvelope) {
for (let i = 0; i < SAMPLE_COUNT; i++) {
envelopeA[i] *= state.waves[0].amp;
envelopeB[i] *= state.waves[1].amp;
}
updateEnvelopeLine(envelopes[0].upper, envelopeA, 1);
updateEnvelopeLine(envelopes[0].lower, envelopeA, -1);
updateEnvelopeLine(envelopes[1].upper, envelopeB, 1);
updateEnvelopeLine(envelopes[1].lower, envelopeB, -1);
}
for (let i = 0; i < markerCount; i++) {
const x = X_MIN + ((X_MAX - X_MIN) * i) / (markerCount - 1);
const sampleIndex = Math.round(
((x - X_MIN) / (X_MAX - X_MIN)) * SEGMENTS
);
markerDummy.position.set(x, valuesSum[sampleIndex], 0.12);
markerDummy.scale.setScalar(0.8 + Math.min(1, Math.abs(valuesSum[sampleIndex]) / 2));
markerDummy.updateMatrix();
sumMarkers.setMatrixAt(i, markerDummy.matrix);
}
sumMarkers.instanceMatrix.needsUpdate = true;
}
function updateProbe() {
const x = state.probeX;
const yA = waveValue(state.waves[0], x, state.time);
const yB = waveValue(state.waves[1], x, state.time);
const ySum = yA + yB;
const positions = probeGeometry.attributes.position.array;
positions[0] = x;
positions[1] = Y_MIN;
positions[2] = 0.15;
positions[3] = x;
positions[4] = Y_MAX;
positions[5] = 0.15;
probeGeometry.attributes.position.needsUpdate = true;
probeMarkerA.position.set(x, yA, 0.18);
probeMarkerB.position.set(x, yB, 0.19);
probeMarkerSum.position.set(x, ySum, 0.20);
$("probe-a").textContent = formatValue(yA);
$("probe-b").textContent = formatValue(yB);
$("probe-sum").textContent = formatValue(ySum);
$("probe-equation").textContent =
`${formatValue(yA)} + ${formatValue(yB)} = ${formatValue(ySum)}`;
}
function formatValue(value) {
const normalized = Math.abs(value) < 0.0005 ? 0 : value;
return normalized.toFixed(3);
}
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, zoom, and pinch.
// No camera-control addon is used.
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(-0.45, 0, 0),
theta: 0,
phi: 1.37,
radius: 17.5,
fitScale: 1
};
const defaultCamera = {
theta: cameraState.theta,
phi: cameraState.phi,
radius: cameraState.radius,
target: cameraState.target.clone()
};
function updateCamera() {
const radius = cameraState.radius * cameraState.fitScale;
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.theta = defaultCamera.theta;
cameraState.phi = defaultCamera.phi;
cameraState.radius = defaultCamera.radius;
cameraState.target.copy(defaultCamera.target);
updateCamera();
}
const pointers = new Map();
let gesture = null;
let lastPinchDistance = 0;
const canvas = renderer.domElement;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
gesture = {
mode: event.button !== 0 || event.shiftKey ? "pan" : "orbit",
x: event.clientX,
y: event.clientY
};
} else if (pointers.size === 2) {
const points = [...pointers.values()];
lastPinchDistance = Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
gesture = null;
}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
const points = [...pointers.values()];
const distance = Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
if (lastPinchDistance > 0 && distance > 0) {
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * (lastPinchDistance / distance),
7,
38
);
}
lastPinchDistance = distance;
return;
}
if (!gesture) return;
const dx = event.clientX - gesture.x;
const dy = event.clientY - gesture.y;
gesture.x = event.clientX;
gesture.y = event.clientY;
if (gesture.mode === "orbit") {
cameraState.theta -= dx * 0.005;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.005,
0.22,
Math.PI - 0.22
);
} else {
const scale = cameraState.radius * 0.00125;
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
cameraState.target
.addScaledVector(right, -dx * scale)
.addScaledVector(up, dy * scale);
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
lastPinchDistance = 0;
if (pointers.size === 0) gesture = null;
else if (pointers.size === 1) {
const point = [...pointers.values()][0];
gesture = {
mode: "orbit",
x: point.x,
y: point.y
};
}
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7,
38
);
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Interface bindings
// -------------------------------------------------------------------------
function bindWaveRange(id, waveIndex, key, formatter) {
const input = $(id);
const output = $(`${id}-out`);
const render = () => {
output.textContent = formatter(state.waves[waveIndex][key]);
};
input.addEventListener("input", () => {
state.waves[waveIndex][key] = Number(input.value);
render();
updateWaveSummaries();
});
render();
}
bindWaveRange("a-amp", 0, "amp", value => value.toFixed(2));
bindWaveRange("a-phase", 0, "phaseDeg", value => `${value.toFixed(0)}°`);
bindWaveRange("a-freq", 0, "freq", value => `${value.toFixed(2)} Hz`);
bindWaveRange("a-width", 0, "width", value => `${value.toFixed(2)} units`);
bindWaveRange("b-amp", 1, "amp", value => value.toFixed(2));
bindWaveRange("b-phase", 1, "phaseDeg", value => `${value.toFixed(0)}°`);
bindWaveRange("b-freq", 1, "freq", value => `${value.toFixed(2)} Hz`);
bindWaveRange("b-width", 1, "width", value => `${value.toFixed(2)} units`);
function updateWaveSummaries() {
$("a-summary").textContent =
`${state.waves[0].amp.toFixed(2)} · ${state.waves[0].freq.toFixed(2)} Hz`;
$("b-summary").textContent =
`${state.waves[1].amp.toFixed(2)} · ${state.waves[1].freq.toFixed(2)} Hz`;
}
document.querySelectorAll("[data-direction-group]").forEach((group) => {
const waveIndex = Number(group.dataset.directionGroup);
group.querySelectorAll("[data-direction]").forEach((button) => {
button.addEventListener("click", () => {
state.waves[waveIndex].direction = Number(button.dataset.direction);
group.querySelectorAll("[data-direction]").forEach((item) => {
item.classList.toggle("active", item === button);
});
});
});
});
$("speed").addEventListener("input", (event) => {
state.speed = Number(event.target.value);
$("speed-out").textContent = `${state.speed.toFixed(2)} units/s`;
});
$("probe").addEventListener("input", (event) => {
state.probeX = Number(event.target.value);
$("probe-out").textContent = `x = ${state.probeX.toFixed(2)}`;
});
$("time").addEventListener("input", (event) => {
state.time = Number(event.target.value);
state.playing = false;
updatePlayButton();
});
function overlapTime() {
const a = state.waves[0];
const b = state.waves[1];
if (a.direction === b.direction) return 0;
return Math.abs(b.center0 - a.center0) / (2 * state.speed);
}
function updatePlayButton() {
$("playButton").textContent = state.playing ? "Pause" : "Play";
}
$("playButton").addEventListener("click", () => {
if (!state.playing && state.time >= 12) state.time = 0;
state.playing = !state.playing;
updatePlayButton();
});
$("resetTimeButton").addEventListener("click", () => {
state.time = state.mode === "pulse" ? overlapTime() : 0;
state.playing = true;
updatePlayButton();
});
$("overlapButton").addEventListener("click", () => {
state.time = overlapTime();
state.playing = true;
updatePlayButton();
});
$("resetCameraButton").addEventListener("click", resetCamera);
document.querySelectorAll("#modeControl [data-mode]").forEach((button) => {
button.addEventListener("click", () => setMode(button.dataset.mode));
});
function setMode(mode) {
state.mode = mode;
document.body.dataset.mode = mode;
document.querySelectorAll("#modeControl [data-mode]").forEach((button) => {
button.classList.toggle("active", button.dataset.mode === mode);
});
if (mode === "pulse") {
$("formulaDetail").innerHTML =
"yᵢ = Aᵢ exp[−½((x−xᵢ(t))/σᵢ)²] sin(kᵢx−sᵢωᵢt+φᵢ)<br>" +
"xᵢ(t)=xᵢ₀+sᵢct, kᵢ=ωᵢ/c";
state.time = overlapTime();
} else {
$("formulaDetail").innerHTML =
"yᵢ = Aᵢ sin(kᵢx−sᵢωᵢt+φᵢ)<br>" +
"ωᵢ=2πfᵢ, kᵢ=ωᵢ/c";
state.time = 0;
}
state.playing = true;
updatePlayButton();
}
$("panelToggle").addEventListener("click", () => {
document.body.classList.toggle("panel-closed");
});
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setSize(width, height);
camera.aspect = aspect;
camera.fov = aspect < 1 ? 55 : 42;
camera.updateProjectionMatrix();
cameraState.fitScale = aspect < 1
? Math.min(2.2, Math.max(1, 1.15 / aspect))
: 1;
updateCamera();
}
window.addEventListener("resize", resize);
let previousTime = performance.now();
let hudAccumulator = 0;
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (state.playing) {
state.time += delta;
if (state.time >= 12) {
state.time = 12;
state.playing = false;
updatePlayButton();
}
}
updateSceneField();
updateProbe();
updateCamera();
hudAccumulator += delta;
if (hudAccumulator > 0.05) {
hudAccumulator = 0;
$("time").value = state.time.toString();
$("time-out").textContent = `${state.time.toFixed(2)} s`;
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
updateWaveSummaries();
updatePlayButton();
$("speed-out").textContent = `${state.speed.toFixed(2)} units/s`;
$("probe-out").textContent = `x = ${state.probeX.toFixed(2)}`;
$("probe-x-out").textContent = `x = ${state.probeX.toFixed(2)}`;
setMode("sine");
resize();
$("loading").remove();
requestAnimationFrame(animate);
</script>
</body>
</html>
```