Prompt specification
Build or customize the Three.js 3D scene "Move panels to redirect a reflection" 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: Move panels to redirect a reflection
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/move-panels-to-redirect-a-reflection-x2164
Scene Description Prompt:
Let users reposition two panels to redirect a marked early reflection away from a listener. Display path length changes while keeping sound source and listener fixed. Build this with Three.js from cdnjs as a voxel scene in one HTML file.
Working Three.js Starter (move-panels-to-redirect-a-reflection-x2164):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Early Reflection Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #080d18;
--panel: rgba(13, 21, 37, 0.9);
--line: rgba(154, 184, 220, 0.18);
--text: #e9f3ff;
--muted: #91a5bf;
--cyan: #52e5ff;
--pink: #ff65c7;
--green: #76f2ad;
--amber: #ffc86b;
--red: #ff667d;
}
* {
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);
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas.dragging {
cursor: grabbing;
}
header {
position: fixed;
top: 22px;
left: 24px;
z-index: 5;
pointer-events: none;
max-width: 420px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 7px;
height: 7px;
border-radius: 2px;
background: currentColor;
box-shadow: 0 0 14px currentColor;
content: "";
}
h1 {
margin: 0;
font-size: clamp(24px, 3vw, 39px);
line-height: 1;
letter-spacing: -0.045em;
}
header p {
max-width: 390px;
margin: 10px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
aside {
position: fixed;
top: 18px;
right: 18px;
z-index: 10;
width: min(360px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
overflow: auto;
padding: 16px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.38);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: #30445f transparent;
}
.section {
padding: 14px 0;
border-bottom: 1px solid var(--line);
}
.section:first-child {
padding-top: 0;
}
.section:last-child {
padding-bottom: 0;
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.fixed-badge {
padding: 4px 7px;
border: 1px solid rgba(118, 242, 173, 0.25);
border-radius: 999px;
color: var(--green);
background: rgba(118, 242, 173, 0.06);
font-size: 9px;
letter-spacing: 0.08em;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 72px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.025);
}
.metric-label {
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric-value {
margin-top: 5px;
font-variant-numeric: tabular-nums;
font-size: 22px;
font-weight: 750;
letter-spacing: -0.04em;
}
.metric-value.cyan {
color: var(--cyan);
}
.metric-value.pink {
color: var(--pink);
}
.metric-value.green {
color: var(--green);
}
.metric-sub {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.status {
margin-top: 10px;
padding: 12px;
border: 1px solid rgba(255, 200, 107, 0.3);
border-radius: 12px;
background: rgba(255, 200, 107, 0.07);
transition: border-color 160ms, background 160ms;
}
.status.hot {
border-color: rgba(255, 102, 125, 0.42);
background: rgba(255, 102, 125, 0.09);
}
.status.safe {
border-color: rgba(118, 242, 173, 0.38);
background: rgba(118, 242, 173, 0.08);
}
.status-title {
font-size: 12px;
font-weight: 850;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.status.hot .status-title {
color: var(--red);
}
.status.safe .status-title {
color: var(--green);
}
.status-copy {
margin-top: 4px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.meter {
height: 4px;
margin-top: 10px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
.meter > div {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--red), var(--amber), var(--green));
transition: width 100ms linear;
}
.panel-control {
margin-bottom: 13px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.018);
}
.panel-control:last-child {
margin-bottom: 0;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
font-size: 12px;
font-weight: 800;
}
.panel-key {
display: inline-grid;
width: 22px;
height: 22px;
margin-right: 7px;
place-items: center;
border-radius: 6px;
color: #061018;
vertical-align: middle;
}
.panel-key.a {
background: var(--cyan);
}
.panel-key.b {
background: var(--pink);
}
.panel-coords {
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.control-row {
display: grid;
grid-template-columns: 28px 1fr 56px;
align-items: center;
gap: 7px;
margin-top: 7px;
}
.control-row label {
color: var(--muted);
font-size: 10px;
font-weight: 750;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
#panel-b-range {
accent-color: var(--pink);
}
input[type="number"] {
width: 100%;
padding: 5px 6px;
border: 1px solid var(--line);
border-radius: 7px;
outline: 0;
color: var(--text);
background: rgba(0, 0, 0, 0.2);
font: inherit;
font-size: 11px;
font-variant-numeric: tabular-nums;
}
input[type="number"]:focus {
border-color: var(--cyan);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
min-height: 34px;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 9px;
color: var(--text);
background: rgba(255, 255, 255, 0.045);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition: background 120ms, border-color 120ms, transform 120ms;
}
button:hover {
border-color: rgba(82, 229, 255, 0.4);
background: rgba(82, 229, 255, 0.09);
}
button:active {
transform: translateY(1px);
}
button.primary {
border-color: rgba(82, 229, 255, 0.35);
color: #c9f8ff;
background: rgba(82, 229, 255, 0.1);
}
#history {
display: block;
width: 100%;
height: 64px;
overflow: visible;
}
.chart-label {
display: flex;
justify-content: space-between;
color: var(--muted);
font-size: 9px;
font-variant-numeric: tabular-nums;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 11px;
margin-top: 8px;
color: var(--muted);
font-size: 9px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend i {
width: 15px;
height: 2px;
background: currentColor;
}
.legend .ray {
color: var(--cyan);
}
.legend .direct {
color: var(--amber);
}
.legend .clearance {
color: var(--pink);
}
.tag {
position: fixed;
z-index: 4;
padding: 5px 8px;
border: 1px solid var(--line);
border-radius: 7px;
color: var(--text);
background: rgba(8, 13, 24, 0.86);
box-shadow: 0 6px 22px rgba(0, 0, 0, 0.25);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.08em;
pointer-events: none;
transform: translate(-50%, -100%);
white-space: nowrap;
}
.tag.source {
border-color: rgba(82, 229, 255, 0.35);
color: var(--cyan);
}
.tag.listener {
border-color: rgba(255, 200, 107, 0.38);
color: var(--amber);
}
.tag.panel-a {
border-color: rgba(82, 229, 255, 0.35);
color: var(--cyan);
}
.tag.panel-b {
border-color: rgba(255, 101, 199, 0.35);
color: var(--pink);
}
.tag.path {
color: #d9faff;
border-color: rgba(82, 229, 255, 0.4);
}
#help {
position: fixed;
bottom: 20px;
left: 24px;
z-index: 5;
max-width: 510px;
padding: 10px 13px;
border: 1px solid var(--line);
border-radius: 12px;
color: var(--muted);
background: rgba(8, 13, 24, 0.76);
backdrop-filter: blur(12px);
font-size: 11px;
line-height: 1.5;
pointer-events: none;
}
#help strong {
color: var(--text);
}
kbd {
padding: 1px 4px;
border: 1px solid var(--line);
border-radius: 4px;
color: var(--text);
background: rgba(255, 255, 255, 0.05);
font: inherit;
font-size: 9px;
}
@media (max-width: 760px) {
header {
top: 14px;
left: 14px;
}
header p {
display: none;
}
aside {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 47vh;
}
#help {
display: none;
}
.tag {
font-size: 8px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header>
<div class="eyebrow">Acoustic geometry sandbox</div>
<h1>Early Reflection Lab</h1>
<p>
Move the two voxel reflectors to steer a marked sound ray away from the
fixed listener. The source and direct source-to-listener route stay locked.
</p>
</header>
<aside>
<section class="section">
<div class="section-title">
Live measurements
<span class="fixed-badge">Endpoints locked</span>
</div>
<div class="metrics">
<div class="metric">
<div class="metric-label">Reflected path</div>
<div class="metric-value cyan" id="path-value">0.00 m</div>
<div class="metric-sub" id="path-change">Calculating…</div>
</div>
<div class="metric">
<div class="metric-label">Listener clearance</div>
<div class="metric-value pink" id="clearance-value">0.00 m</div>
<div class="metric-sub">Goal: at least 1.25 m</div>
</div>
<div class="metric">
<div class="metric-label">Fixed direct path</div>
<div class="metric-value" id="direct-value">0.00 m</div>
<div class="metric-sub">Source → listener</div>
</div>
<div class="metric">
<div class="metric-label">Relative delay</div>
<div class="metric-value green" id="delay-value">0.00 ms</div>
<div class="metric-sub">Compared with direct sound</div>
</div>
</div>
<div class="status" id="status">
<div class="status-title" id="status-title">Tracing reflection</div>
<div class="status-copy" id="status-copy">
Adjust the reflectors to increase the distance from the reflected ray.
</div>
<div class="meter"><div id="status-meter"></div></div>
</div>
</section>
<section class="section">
<div class="section-title">Reflector positions</div>
<div class="panel-control" id="panel-a-control">
<div class="panel-heading">
<span><span class="panel-key a">A</span>Panel A</span>
<span class="panel-coords" id="panel-a-coords"></span>
</div>
<div class="control-row">
<label for="panel-a-x">X</label>
<input id="panel-a-x" type="number" min="-5.4" max="5.4" step="0.1">
<label for="panel-a-z">Z</label>
<input id="panel-a-z" type="number" min="-3.4" max="3.4" step="0.1">
</div>
<div class="control-row">
<label for="panel-a-range">∠</label>
<input id="panel-a-range" type="range" min="-180" max="180" step="1">
<input id="panel-a-angle" type="number" min="-180" max="180" step="1">
</div>
</div>
<div class="panel-control" id="panel-b-control">
<div class="panel-heading">
<span><span class="panel-key b">B</span>Panel B</span>
<span class="panel-coords" id="panel-b-coords"></span>
</div>
<div class="control-row">
<label for="panel-b-x">X</label>
<input id="panel-b-x" type="number" min="-5.4" max="5.4" step="0.1">
<label for="panel-b-z">Z</label>
<input id="panel-b-z" type="number" min="-3.4" max="3.4" step="0.1">
</div>
<div class="control-row">
<label for="panel-b-range">∠</label>
<input id="panel-b-range" type="range" min="-180" max="180" step="1">
<input id="panel-b-angle" type="number" min="-180" max="180" step="1">
</div>
</div>
</section>
<section class="section">
<div class="section-title">Presets & camera</div>
<div class="button-row">
<button id="reset-button">Reset reflection</button>
<button id="safe-button" class="primary">Safe preset</button>
<button data-view="iso">Isometric</button>
<button data-view="top">Top view</button>
</div>
</section>
<section class="section">
<div class="section-title">
Path length history
<span id="history-range">—</span>
</div>
<svg id="history" viewBox="0 0 240 58" preserveAspectRatio="none">
<line
x1="0" y1="54" x2="240" y2="54"
stroke="rgba(154,184,220,.18)"
stroke-width="1"
/>
<polyline
id="history-line"
fill="none"
stroke="#52e5ff"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
<div class="chart-label">
<span>Earlier</span>
<span>Now</span>
</div>
<div class="legend">
<span class="ray"><i></i>Marked reflection</span>
<span class="direct"><i></i>Direct sound</span>
<span class="clearance"><i></i>Nearest approach</span>
</div>
</section>
</aside>
<div class="tag source" id="source-tag">SOURCE · FIXED</div>
<div class="tag listener" id="listener-tag">LISTENER · FIXED</div>
<div class="tag panel-a" id="panel-a-tag">REFLECTOR A</div>
<div class="tag panel-b" id="panel-b-tag">REFLECTOR B</div>
<div class="tag path" id="path-tag">MARKED EARLY REFLECTION</div>
<div id="help">
<strong>Drag</strong> either reflector to move it ·
<strong>Drag panels</strong> to reposition ·
<strong>Q / E</strong> rotates the selected reflector ·
<strong>Right-drag</strong> orbits · <strong>Wheel</strong> zooms
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene and renderer
// -------------------------------------------------------------------------
const sceneHost = document.querySelector("#scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x080d18);
scene.fog = new THREE.Fog(0x080d18, 17, 34);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneHost.appendChild(renderer.domElement);
const canvas = renderer.domElement;
scene.add(new THREE.HemisphereLight(0x9bcfff, 0x1a1830, 1.9));
const sun = new THREE.DirectionalLight(0xffefd4, 3.0);
sun.position.set(4, 11, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rimLight = new THREE.PointLight(0x3f8fff, 16, 18, 2);
rimLight.position.set(-5, 4, -2);
scene.add(rimLight);
const pinkLight = new THREE.PointLight(0xff45bd, 12, 14, 2);
pinkLight.position.set(4, 3, 2);
scene.add(pinkLight);
const room = {
width: 12.4,
depth: 8.4,
height: 5.2
};
const sourcePosition = new THREE.Vector3(-4.6, 1.4, -2.5);
const listenerPosition = new THREE.Vector3(4.4, 1.4, -1.8);
const directLength = sourcePosition.distanceTo(listenerPosition);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function box(w, h, d, material, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(w, h, d);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.76,
metalness: 0.04,
...options
});
}
// -------------------------------------------------------------------------
// Voxel room
// -------------------------------------------------------------------------
const floorMaterials = [
material(0x17243a),
material(0x1a2941),
material(0x142137),
material(0x1c2c45)
];
for (let ix = 0; ix < 13; ix++) {
for (let iz = 0; iz < 9; iz++) {
const x = -6 + ix;
const z = -4 + iz;
const mat = floorMaterials[(ix * 3 + iz * 5) % floorMaterials.length];
box(0.92, 0.12, 0.92, mat, x, -0.07, z);
}
}
const wallMaterials = [
material(0x263754),
material(0x2c3d5c),
material(0x22324e),
material(0x304363)
];
// Back wall.
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 16; col++) {
const x = -5.82 + col * 0.78;
const y = 0.35 + row * 0.63;
const mat = wallMaterials[(row + col * 2) % wallMaterials.length];
box(0.71, 0.55, 0.34, mat, x, y, -room.depth / 2 - 0.05);
}
}
// Left wall.
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 10; col++) {
const z = -3.75 + col * 0.83;
const y = 0.35 + row * 0.63;
const mat = wallMaterials[(row * 2 + col) % wallMaterials.length];
box(0.34, 0.55, 0.76, mat, -room.width / 2 - 0.05, y, z);
}
}
// Short voxel columns marking the open room corners.
const trimMaterial = material(0x3a5275, { emissive: 0x0b1a30, emissiveIntensity: 0.5 });
for (const x of [-6.05, 6.05]) {
for (const z of [-4.05, 4.05]) {
box(0.28, 5.25, 0.28, trimMaterial, x, 2.6, z);
}
}
// -------------------------------------------------------------------------
// Fixed source and listener
// -------------------------------------------------------------------------
const sourceGroup = new THREE.Group();
sourceGroup.position.set(sourcePosition.x, 0, sourcePosition.z);
scene.add(sourceGroup);
const sourceDark = material(0x152d42, { metalness: 0.25 });
const sourceBody = material(0x2b9bb3, {
emissive: 0x0b5265,
emissiveIntensity: 0.55
});
const sourceGlow = material(0x76f4ff, {
emissive: 0x3cecff,
emissiveIntensity: 2.2
});
box(1.0, 0.45, 1.0, sourceDark, 0, 0.22, 0, sourceGroup);
box(0.78, 1.05, 0.72, sourceBody, 0, 0.92, 0, sourceGroup);
box(0.5, 0.5, 0.10, sourceDark, 0, 1.25, 0.38, sourceGroup);
box(0.31, 0.31, 0.12, sourceGlow, 0, 1.25, 0.45, sourceGroup);
box(0.15, 0.15, 0.15, sourceGlow, 0, 1.68, 0, sourceGroup);
const listenerGroup = new THREE.Group();
listenerGroup.position.set(listenerPosition.x, 0, listenerPosition.z);
scene.add(listenerGroup);
const listenerDark = material(0x4b3527);
const listenerBody = material(0xa8723b, {
emissive: 0x3b1d08,
emissiveIntensity: 0.35
});
const listenerGlow = material(0xffc86b, {
emissive: 0xff9d2e,
emissiveIntensity: 1.7
});
box(0.9, 0.35, 0.9, listenerDark, 0, 0.17, 0, listenerGroup);
box(0.72, 1.05, 0.62, listenerBody, 0, 0.83, 0, listenerGroup);
box(0.73, 0.68, 0.66, listenerBody, 0, 1.62, 0, listenerGroup);
box(0.15, 0.34, 0.19, listenerGlow, -0.47, 1.61, 0, listenerGroup);
box(0.15, 0.34, 0.19, listenerGlow, 0.47, 1.61, 0, listenerGroup);
box(0.44, 0.12, 0.12, listenerGlow, 0, 1.47, 0.37, listenerGroup);
const listenerZone = new THREE.Mesh(
new THREE.BoxGeometry(1.28, 1.28, 1.28),
new THREE.MeshBasicMaterial({
color: 0xffbd60,
wireframe: true,
transparent: true,
opacity: 0.24
})
);
listenerZone.position.copy(listenerPosition);
scene.add(listenerZone);
// -------------------------------------------------------------------------
// Reflector panels
// -------------------------------------------------------------------------
const panelWidth = 2.73;
const panelHeight = 2.73;
const panelY = 1.55;
const panels = [];
const panelHitboxes = [];
function createPanel(index, hueA, hueB) {
const group = new THREE.Group();
group.position.y = panelY;
scene.add(group);
const frameMaterial = material(0x46617e, {
metalness: 0.35,
roughness: 0.45
});
const backing = box(
panelWidth + 0.16,
panelHeight + 0.16,
0.14,
frameMaterial,
0,
0,
-0.11,
group
);
const tiles = [];
const columns = 7;
const rows = 7;
const tileSize = 0.36;
const spacing = 0.39;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < columns; col++) {
const color = new THREE.Color(hueA).lerp(
new THREE.Color(hueB),
(row + col) / (columns + rows - 2)
);
const tileMaterial = material(color.getHex(), {
metalness: 0.08,
roughness: 0.63,
emissive: color.clone().multiplyScalar(0.12),
emissiveIntensity: 0.7
});
const tile = box(
tileSize,
tileSize,
0.17,
tileMaterial,
(col - (columns - 1) / 2) * spacing,
(row - (rows - 1) / 2) * spacing,
0.015,
group
);
tile.userData.panelIndex = index;
tiles.push(tile);
}
}
// A bright front marker communicates the reflecting face.
box(
0.42,
0.12,
0.22,
material(0xf3fbff, {
emissive: index === 0 ? 0x52e5ff : 0xff65c7,
emissiveIntensity: 1.8
}),
0,
panelHeight / 2 - 0.22,
0.12,
group
);
// Feet.
box(0.28, 0.25, 0.75, frameMaterial, -0.8, -panelHeight / 2 - 0.08, 0, group);
box(0.28, 0.25, 0.75, frameMaterial, 0.8, -panelHeight / 2 - 0.08, 0, group);
const edgeGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(panelWidth + 0.18, panelHeight + 0.18, 0.18)
);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x718aa8,
transparent: true,
opacity: 0.8
});
const frame = new THREE.LineSegments(edgeGeometry, edgeMaterial);
frame.position.z = -0.03;
group.add(frame);
const hitbox = new THREE.Mesh(
new THREE.BoxGeometry(panelWidth, panelHeight, 0.22),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
})
);
hitbox.userData.panelIndex = index;
group.add(hitbox);
panelHitboxes.push(hitbox);
const panel = {
index,
group,
frame,
tiles,
backing,
rotation: 0,
initialPosition: new THREE.Vector3(),
initialRotation: 0
};
panels.push(panel);
return panel;
}
createPanel(0, 0x1f7891, 0x52e5ff);
createPanel(1, 0x8a286f, 0xff65c7);
panels[0].group.position.x = -2.2;
panels[0].group.position.z = -1.2;
panels[0].rotation = THREE.MathUtils.degToRad(-29);
panels[1].group.position.x = 1.2;
panels[1].group.position.z = 0.95;
panels[1].rotation = THREE.MathUtils.degToRad(4);
panels.forEach((panel) => {
panel.initialPosition.copy(panel.group.position);
panel.initialRotation = panel.rotation;
panel.group.rotation.y = panel.rotation;
});
// -------------------------------------------------------------------------
// Acoustic path graphics
// -------------------------------------------------------------------------
const pathMaterial = new THREE.LineBasicMaterial({
color: 0x65edff,
transparent: true,
opacity: 0.95
});
const pathGlowMaterial = new THREE.LineBasicMaterial({
color: 0x42dfff,
transparent: true,
opacity: 0.18
});
const pathLine = new THREE.Line(new THREE.BufferGeometry(), pathMaterial);
const pathGlow = new THREE.Line(new THREE.BufferGeometry(), pathGlowMaterial);
scene.add(pathGlow, pathLine);
const directMaterial = new THREE.LineDashedMaterial({
color: 0xffc86b,
dashSize: 0.22,
gapSize: 0.14,
transparent: true,
opacity: 0.48
});
const directLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
sourcePosition,
listenerPosition
]),
directMaterial
);
directLine.computeLineDistances();
scene.add(directLine);
const clearanceMaterial = new THREE.LineDashedMaterial({
color: 0xff65c7,
dashSize: 0.10,
gapSize: 0.08,
transparent: true,
opacity: 0.75
});
const clearanceLine = new THREE.Line(
new THREE.BufferGeometry(),
clearanceMaterial
);
scene.add(clearanceLine);
const reflectionMarkers = [];
for (let i = 0; i < 2; i++) {
const marker = new THREE.Mesh(
new THREE.BoxGeometry(0.23, 0.23, 0.23),
new THREE.MeshBasicMaterial({
color: i === 0 ? 0x52e5ff : 0xff65c7
})
);
marker.visible = false;
scene.add(marker);
reflectionMarkers.push(marker);
}
const endMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.17, 0.17, 0.17),
new THREE.MeshBasicMaterial({ color: 0xffffff })
);
endMarker.visible = false;
scene.add(endMarker);
const pulse = new THREE.Mesh(
new THREE.BoxGeometry(0.17, 0.17, 0.17),
new THREE.MeshBasicMaterial({
color: 0xffffff,
emissive: 0x52e5ff
})
);
pulse.visible = false;
scene.add(pulse);
// -------------------------------------------------------------------------
// UI references
// -------------------------------------------------------------------------
const ui = {
path: document.querySelector("#path-value"),
pathChange: document.querySelector("#path-change"),
clearance: document.querySelector("#clearance-value"),
direct: document.querySelector("#direct-value"),
delay: document.querySelector("#delay-value"),
status: document.querySelector("#status"),
statusTitle: document.querySelector("#status-title"),
statusCopy: document.querySelector("#status-copy"),
statusMeter: document.querySelector("#status-meter"),
historyLine: document.querySelector("#history-line"),
historyRange: document.querySelector("#history-range"),
sourceTag: document.querySelector("#source-tag"),
listenerTag: document.querySelector("#listener-tag"),
panelATag: document.querySelector("#panel-a-tag"),
panelBTag: document.querySelector("#panel-b-tag"),
pathTag: document.querySelector("#path-tag")
};
ui.direct.textContent = `${directLength.toFixed(2)} m`;
const history = [];
function updatePanelUI(index) {
const panel = panels[index];
const prefix = index === 0 ? "panel-a" : "panel-b";
const degrees = Math.round(THREE.MathUtils.radToDeg(panel.rotation));
document.querySelector(`#${prefix}-x`).value = panel.group.position.x.toFixed(1);
document.querySelector(`#${prefix}-z`).value = panel.group.position.z.toFixed(1);
document.querySelector(`#${prefix}-range`).value = degrees;
document.querySelector(`#${prefix}-angle`).value = degrees;
document.querySelector(`#${prefix}-coords`).textContent =
`X ${panel.group.position.x.toFixed(1)} · Z ${panel.group.position.z.toFixed(1)}`;
}
function updateHistory(pathLength) {
history.push(pathLength);
if (history.length > 90) history.shift();
const min = Math.min(...history);
const max = Math.max(...history);
const spread = Math.max(0.2, max - min);
const low = min - spread * 0.12;
const high = max + spread * 0.12;
const points = history.map((value, index) => {
const x = history.length === 1 ? 0 : (index / (history.length - 1)) * 240;
const y = 52 - ((value - low) / (high - low)) * 46;
return `${x.toFixed(1)},${y.toFixed(1)}`;
});
ui.historyLine.setAttribute("points", points.join(" "));
ui.historyRange.textContent = `${min.toFixed(2)}–${max.toFixed(2)} m`;
}
// -------------------------------------------------------------------------
// Geometric ray tracing
// -------------------------------------------------------------------------
function reflect(direction, normal) {
return direction
.clone()
.addScaledVector(normal, -2 * direction.dot(normal))
.normalize();
}
function panelNormal(panel) {
panel.group.updateMatrixWorld(true);
return new THREE.Vector3(0, 0, 1)
.applyQuaternion(panel.group.quaternion)
.normalize();
}
function intersectPanel(origin, direction, panel) {
panel.group.updateMatrixWorld(true);
const normal = panelNormal(panel);
const denominator = direction.dot(normal);
if (Math.abs(denominator) < 0.00001) return null;
const t = panel.group.position.clone().sub(origin).dot(normal) / denominator;
if (t <= 0.025) return null;
const point = origin.clone().addScaledVector(direction, t);
const local = panel.group.worldToLocal(point.clone());
if (
Math.abs(local.x) > panelWidth / 2 + 0.06 ||
Math.abs(local.y) > panelHeight / 2 + 0.06
) {
return null;
}
return { point, t };
}
function roomExit(origin, direction) {
const candidates = [];
const halfWidth = room.width / 2;
const halfDepth = room.depth / 2;
if (direction.x > 0.00001) {
candidates.push((halfWidth - origin.x) / direction.x);
} else if (direction.x < -0.00001) {
candidates.push((-halfWidth - origin.x) / direction.x);
}
if (direction.z > 0.00001) {
candidates.push((halfDepth - origin.z) / direction.z);
} else if (direction.z < -0.00001) {
candidates.push((-halfDepth - origin.z) / direction.z);
}
if (direction.y > 0.00001) {
candidates.push((room.height - origin.y) / direction.y);
} else if (direction.y < -0.00001) {
candidates.push((0 - origin.y) / direction.y);
}
let nearest = Infinity;
for (const t of candidates) {
if (t > 0.01 && t < nearest) nearest = t;
}
if (!Number.isFinite(nearest)) {
return {
point: origin.clone().addScaledVector(direction, 20),
t: 20
};
}
return {
point: origin.clone().addScaledVector(direction, nearest),
t: nearest
};
}
function distanceToSegment(point, start, end) {
const segment = new THREE.Vector3().subVectors(end, start);
const lengthSquared = segment.lengthSq();
if (lengthSquared === 0) {
return {
distance: point.distanceTo(start),
point: start.clone()
};
}
const t = THREE.MathUtils.clamp(
new THREE.Vector3().subVectors(point, start).dot(segment) /
lengthSquared,
0,
1
);
const closest = start.clone().addScaledVector(segment, t);
return {
distance: point.distanceTo(closest),
point: closest
};
}
let currentPath = {
points: [],
segments: [],
length: 0,
clearance: 0,
closestPoint: listenerPosition.clone(),
pulseDistances: []
};
function traceReflection() {
const points = [sourcePosition.clone()];
// The marked ray is always aimed at the center of reflector A.
const hitA = panels[0].group.position.clone();
points.push(hitA);
const incomingA = hitA.clone().sub(sourcePosition).normalize();
const outgoingA = reflect(incomingA, panelNormal(panels[0]));
const hitB = intersectPanel(hitA, outgoingA, panels[1]);
const wallAfterA = roomExit(hitA, outgoingA);
if (hitB && hitB.t < wallAfterA.t) {
points.push(hitB.point);
const outgoingB = reflect(outgoingA, panelNormal(panels[1]));
const wallAfterB = roomExit(hitB.point, outgoingB);
points.push(wallAfterB.point);
} else {
points.push(wallAfterA.point);
}
const segments = [];
const pulseDistances = [0];
let totalLength = 0;
for (let i = 0; i < points.length - 1; i++) {
const length = points[i].distanceTo(points[i + 1]);
segments.push({
start: points[i],
end: points[i + 1],
length
});
totalLength += length;
pulseDistances.push(totalLength);
}
let clearance = Infinity;
let closestPoint = listenerPosition.clone();
for (const segment of segments) {
const result = distanceToSegment(
listenerPosition,
segment.start,
segment.end
);
if (result.distance < clearance) {
clearance = result.distance;
closestPoint = result.point;
}
}
currentPath = {
points,
segments,
length: totalLength,
clearance,
closestPoint,
pulseDistances
};
return currentPath;
}
function replaceLineGeometry(line, points) {
line.geometry.dispose();
line.geometry = new THREE.BufferGeometry().setFromPoints(points);
}
function updateMeasurements() {
const path = traceReflection();
replaceLineGeometry(pathLine, path.points);
replaceLineGeometry(pathGlow, path.points);
replaceLineGeometry(
clearanceLine,
[listenerPosition.clone(), path.closestPoint.clone()]
);
clearanceLine.computeLineDistances();
reflectionMarkers[0].visible = true;
reflectionMarkers[0].position.copy(path.points[1]);
if (path.points.length > 3) {
reflectionMarkers[1].visible = true;
reflectionMarkers[1].position.copy(path.points[2]);
} else {
reflectionMarkers[1].visible = false;
}
endMarker.visible = true;
endMarker.position.copy(path.points[path.points.length - 1]);
pulse.visible = true;
const relativeDelay = ((path.length - directLength) / 343) * 1000;
ui.path.textContent = `${path.length.toFixed(2)} m`;
ui.clearance.textContent = `${path.clearance.toFixed(2)} m`;
ui.delay.textContent = `${relativeDelay >= 0 ? "+" : ""}${relativeDelay.toFixed(2)} ms`;
const excess = path.length - directLength;
ui.pathChange.textContent =
`${excess >= 0 ? "+" : ""}${excess.toFixed(2)} m vs direct`;
if (path.clearance < 0.65) {
ui.status.className = "status hot";
ui.statusTitle.textContent = "Hot spot · reaches listener";
ui.statusCopy.textContent =
"The reflected ray passes through the listener zone. Reposition or rotate a panel.";
} else if (path.clearance < 1.25) {
ui.status.className = "status";
ui.statusTitle.textContent = "Near miss · increase clearance";
ui.statusCopy.textContent =
"The reflection is moving away, but it still passes too close to the listener.";
} else {
ui.status.className = "status safe";
ui.statusTitle.textContent = "Redirected · away from listener";
ui.statusCopy.textContent =
"The reflected ray clears the listener zone by more than 1.25 m.";
}
ui.statusMeter.style.width =
`${Math.min(100, (path.clearance / 1.4) * 100).toFixed(1)}%`;
updateHistory(path.length);
}
// -------------------------------------------------------------------------
// Panel controls
// -------------------------------------------------------------------------
let selectedPanel = 0;
function selectPanel(index) {
selectedPanel = index;
panels.forEach((panel, i) => {
panel.frame.material.color.set(
i === index ? 0xe4f8ff : 0x718aa8
);
panel.frame.material.opacity = i === index ? 1 : 0.6;
document.querySelector(
i === 0 ? "#panel-a-control" : "#panel-b-control"
).style.borderColor =
i === index
? i === 0
? "rgba(82,229,255,.4)"
: "rgba(255,101,199,.4)"
: "";
});
}
function setPanelRotation(index, radians) {
const panel = panels[index];
panel.rotation = radians;
panel.group.rotation.y = radians;
updatePanelUI(index);
updateMeasurements();
}
function setPanelPosition(index, x, z) {
const panel = panels[index];
panel.group.position.x = THREE.MathUtils.clamp(x, -5.4, 5.4);
panel.group.position.z = THREE.MathUtils.clamp(z, -3.4, 3.4);
panel.group.updateMatrixWorld(true);
updatePanelUI(index);
updateMeasurements();
}
panels.forEach((_, index) => {
const prefix = index === 0 ? "panel-a" : "panel-b";
const xInput = document.querySelector(`#${prefix}-x`);
const zInput = document.querySelector(`#${prefix}-z`);
const range = document.querySelector(`#${prefix}-range`);
const angle = document.querySelector(`#${prefix}-angle`);
function commitX() {
const value = Number(xInput.value);
if (Number.isFinite(value)) {
setPanelPosition(index, value, panels[index].group.position.z);
}
}
function commitZ() {
const value = Number(zInput.value);
if (Number.isFinite(value)) {
setPanelPosition(index, panels[index].group.position.x, value);
}
}
function commitAngle() {
const value = Number(angle.value);
if (Number.isFinite(value)) {
setPanelRotation(
index,
THREE.MathUtils.degToRad(THREE.MathUtils.clamp(value, -180, 180))
);
}
}
xInput.addEventListener("change", commitX);
zInput.addEventListener("change", commitZ);
angle.addEventListener("change", commitAngle);
range.addEventListener("input", () => {
angle.value = range.value;
commitAngle();
});
});
selectPanel(0);
// -------------------------------------------------------------------------
// Custom camera and panel dragging
// -------------------------------------------------------------------------
const orbit = {
radius: 15,
theta: 0.72,
phi: 0.92,
target: new THREE.Vector3(0, 1, 0)
};
function applyCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
applyCamera();
document.querySelectorAll("[data-view]").forEach((button) => {
button.addEventListener("click", () => {
if (button.dataset.view === "top") {
orbit.radius = 14;
orbit.theta = 0;
orbit.phi = 0.055;
orbit.target.set(0, 0.8, 0);
} else {
orbit.radius = 15;
orbit.theta = 0.72;
orbit.phi = 0.92;
orbit.target.set(0, 1, 0);
}
applyCamera();
});
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
let draggingPanel = null;
let dragOffset = new THREE.Vector3();
let orbiting = false;
let previousPointer = { x: 0, y: 0 };
function updatePointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", (event) => {
updatePointer(event);
if (event.button === 2) {
orbiting = true;
previousPointer = { x: event.clientX, y: event.clientY };
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
return;
}
if (event.button !== 0) return;
const hits = raycaster.intersectObjects(panelHitboxes, false);
if (hits.length) {
const index = hits[0].object.userData.panelIndex;
selectPanel(index);
draggingPanel = index;
const groundPoint = new THREE.Vector3();
raycaster.ray.intersectPlane(dragPlane, groundPoint);
dragOffset.set(
panels[index].group.position.x - groundPoint.x,
0,
panels[index].group.position.z - groundPoint.z
);
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
}
});
canvas.addEventListener("pointermove", (event) => {
updatePointer(event);
if (orbiting) {
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
previousPointer = { x: event.clientX, y: event.clientY };
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - dy * 0.005, 0.035, 1.42);
applyCamera();
return;
}
if (draggingPanel !== null) {
const groundPoint = new THREE.Vector3();
raycaster.ray.intersectPlane(dragPlane, groundPoint);
setPanelPosition(
draggingPanel,
groundPoint.x + dragOffset.x,
groundPoint.z + dragOffset.z
);
}
});
function endPointer(event) {
draggingPanel = null;
orbiting = false;
canvas.classList.remove("dragging");
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.009,
8.5,
24
);
applyCamera();
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement
) {
return;
}
if (event.key.toLowerCase() === "q" || event.key.toLowerCase() === "e") {
const sign = event.key.toLowerCase() === "q" ? -1 : 1;
setPanelRotation(
selectedPanel,
panels[selectedPanel].rotation + sign * THREE.MathUtils.degToRad(5)
);
}
});
// -------------------------------------------------------------------------
// Presets
// -------------------------------------------------------------------------
function applyPreset(safe) {
panels[0].group.position.set(-2.2, panelY, -1.2);
panels[1].group.position.set(1.2, panelY, 0.95);
panels[0].rotation = THREE.MathUtils.degToRad(-29);
panels[1].rotation = THREE.MathUtils.degToRad(safe ? -29 : 4);
panels.forEach((panel) => {
panel.group.rotation.y = panel.rotation;
});
panels.forEach((_, index) => updatePanelUI(index));
updateMeasurements();
}
document.querySelector("#reset-button").addEventListener("click", () => {
applyPreset(false);
});
document.querySelector("#safe-button").addEventListener("click", () => {
applyPreset(true);
});
// -------------------------------------------------------------------------
// Projected labels and animation
// -------------------------------------------------------------------------
function projectTag(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * innerWidth;
const y = (-projected.y * 0.5 + 0.5) * innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateLabels() {
projectTag(
ui.sourceTag,
new THREE.Vector3(sourcePosition.x, 2.55, sourcePosition.z)
);
projectTag(
ui.listenerTag,
new THREE.Vector3(listenerPosition.x, 2.65, listenerPosition.z)
);
projectTag(
ui.panelATag,
panels[0].group.position.clone().add(
new THREE.Vector3(0, panelHeight / 2 + 0.42, 0)
)
);
projectTag(
ui.panelBTag,
panels[1].group.position.clone().add(
new THREE.Vector3(0, panelHeight / 2 + 0.42, 0)
)
);
const points = currentPath.points;
if (points.length >= 2) {
const middle = points[1].clone().lerp(
points[points.length - 1],
0.36
);
middle.y += 0.35;
projectTag(ui.pathTag, middle);
}
}
const clock = new THREE.Clock();
function animatePulse(elapsed) {
const path = currentPath;
if (!path.pulseDistances.length || path.length <= 0) return;
const distance = (elapsed * 3.1) % path.length;
for (let i = 0; i < path.segments.length; i++) {
const startDistance = path.pulseDistances[i];
const endDistance = path.pulseDistances[i + 1];
if (distance >= startDistance && distance <= endDistance) {
const segment = path.segments[i];
const localDistance = distance - startDistance;
const t = segment.length > 0 ? localDistance / segment.length : 0;
pulse.position.lerpVectors(segment.start, segment.end, t);
pulse.rotation.x = elapsed * 4;
pulse.rotation.y = elapsed * 5;
break;
}
}
}
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
listenerZone.material.opacity = 0.18 + Math.sin(elapsed * 3) * 0.055;
sourceGlow.emissiveIntensity = 1.8 + Math.sin(elapsed * 4) * 0.35;
listenerGlow.emissiveIntensity = 1.35 + Math.sin(elapsed * 3 + 1) * 0.3;
animatePulse(elapsed);
updateLabels();
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
panels.forEach((_, index) => updatePanelUI(index));
updateMeasurements();
animate();
</script>
</body>
</html>
```