Prompt specification
Build or customize the Three.js 3D scene "Dispersion parameter explorer" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Dispersion parameter explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/dispersion-parameter-explorer-x1536
Scene Description Prompt:
Dispersion parameter explorer. Let users adjust a small table of wavelength-dependent refractive indices; trace rays through the prism and compare resulting separation while preserving physically ordered illustrative values. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (dispersion-parameter-explorer-x1536):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dispersion Parameter Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #07101c;
--panel: #0b1524;
--panel-2: #101d2e;
--line: rgba(148, 174, 207, 0.17);
--text: #edf5ff;
--muted: #8fa3ba;
--cyan: #55d8ff;
--lime: #a8ef78;
--orange: #ffb65c;
--danger: #ff7b84;
}
* {
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,
select,
input[type="number"] {
color: var(--text);
}
.app {
display: grid;
grid-template-columns: 350px minmax(0, 1fr);
width: 100%;
height: 100%;
}
.panel {
position: relative;
z-index: 2;
overflow-y: auto;
padding: 25px 24px 30px;
background:
linear-gradient(180deg, rgba(20, 38, 57, 0.44), transparent 28%),
var(--panel);
border-right: 1px solid var(--line);
box-shadow: 18px 0 55px rgba(0, 0, 0, 0.17);
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 14px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.eyebrow::before {
width: 18px;
height: 1px;
background: currentColor;
content: "";
}
h1 {
margin: 0;
font-size: clamp(29px, 3vw, 39px);
font-weight: 680;
letter-spacing: -0.045em;
line-height: 0.98;
}
.intro {
margin: 16px 0 23px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.section {
padding: 18px 0;
border-top: 1px solid var(--line);
}
.section:first-of-type {
border-top: 0;
padding-top: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.section-title h2 {
margin: 0;
font-size: 11px;
font-weight: 780;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.section-title p {
margin: 0;
color: var(--muted);
font-size: 11px;
}
select {
width: 100%;
height: 40px;
padding: 0 35px 0 12px;
border: 1px solid var(--line);
border-radius: 8px;
outline: none;
background: var(--panel-2);
cursor: pointer;
}
select:focus,
input:focus {
border-color: rgba(85, 216, 255, 0.75);
box-shadow: 0 0 0 3px rgba(85, 216, 255, 0.08);
}
.table-wrap {
overflow: hidden;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(7, 16, 28, 0.38);
}
table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
}
th {
height: 33px;
padding: 0 11px;
border-bottom: 1px solid var(--line);
color: #71869e;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.12em;
text-align: left;
text-transform: uppercase;
}
th:last-child,
td:last-child {
text-align: right;
}
td {
height: 43px;
padding: 0 10px;
border-bottom: 1px solid rgba(148, 174, 207, 0.09);
font-size: 12px;
transition: background 150ms ease;
}
tr:last-child td {
border-bottom: 0;
}
tbody tr:hover,
tbody tr.is-active {
background: rgba(85, 216, 255, 0.055);
}
.wavelength {
display: flex;
align-items: center;
gap: 9px;
color: #dce8f4;
font-variant-numeric: tabular-nums;
}
.swatch {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--swatch);
box-shadow: 0 0 10px var(--swatch);
}
.lambda-unit {
color: #6e8299;
font-size: 10px;
}
.n-input {
width: 86px;
height: 29px;
padding: 0 8px;
border: 1px solid rgba(148, 174, 207, 0.16);
border-radius: 6px;
outline: none;
background: rgba(255, 255, 255, 0.035);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
font-variant-numeric: tabular-nums;
text-align: right;
}
.lock-note {
display: flex;
gap: 9px;
margin-top: 10px;
color: #748aa2;
font-size: 10px;
line-height: 1.45;
}
.lock-note strong {
display: block;
margin-bottom: 2px;
color: var(--lime);
font-size: 9px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.range-row {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 13px;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.range-value {
min-width: 48px;
padding: 5px 7px;
border: 1px solid var(--line);
border-radius: 6px;
color: #c8d7e7;
background: rgba(255, 255, 255, 0.025);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
text-align: center;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
button {
min-height: 39px;
padding: 0 12px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.035);
color: #c9d8e7;
font-size: 11px;
font-weight: 650;
cursor: pointer;
transition:
border-color 150ms ease,
background 150ms ease,
transform 150ms ease;
}
button:hover {
border-color: rgba(85, 216, 255, 0.48);
background: rgba(85, 216, 255, 0.075);
}
button:active {
transform: translateY(1px);
}
button.primary {
border-color: rgba(85, 216, 255, 0.35);
color: #dff7ff;
background: rgba(85, 216, 255, 0.11);
}
button.text-button {
min-height: 29px;
padding: 0 9px;
border-color: transparent;
color: var(--muted);
background: transparent;
font-size: 10px;
}
details {
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
summary {
color: #b9c9d9;
cursor: pointer;
font-weight: 650;
}
details p {
margin: 9px 0 0;
}
.viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 54% 40%, rgba(28, 78, 104, 0.2), transparent 43%),
var(--bg);
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.hud-top {
position: absolute;
top: 20px;
right: 20px;
left: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
pointer-events: none;
}
.status-pill {
display: flex;
align-items: center;
gap: 8px;
min-height: 31px;
padding: 0 11px;
border: 1px solid var(--line);
border-radius: 999px;
color: #aebfd0;
background: rgba(7, 16, 28, 0.68);
backdrop-filter: blur(12px);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.status-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--lime);
box-shadow: 0 0 10px var(--lime);
}
.metrics {
display: grid;
grid-template-columns: repeat(3, minmax(120px, 1fr));
gap: 8px;
pointer-events: auto;
}
.metric {
min-width: 126px;
padding: 11px 12px 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(8, 19, 32, 0.74);
backdrop-filter: blur(13px);
}
.metric-label {
margin-bottom: 5px;
color: #71879f;
font-size: 8px;
font-weight: 750;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.metric-value {
color: #edf7ff;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 18px;
font-variant-numeric: tabular-nums;
letter-spacing: -0.04em;
}
.metric-value.accent {
color: var(--cyan);
}
.metric-detail {
margin-top: 4px;
color: #637a93;
font-size: 8px;
}
.hud-bottom {
position: absolute;
right: 20px;
bottom: 18px;
left: 20px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 18px;
pointer-events: none;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
max-width: 580px;
padding: 10px 13px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(7, 16, 28, 0.64);
backdrop-filter: blur(12px);
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
color: #9eb1c6;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
}
.legend-line {
width: 15px;
height: 2px;
border-radius: 2px;
background: var(--swatch);
box-shadow: 0 0 8px var(--swatch);
}
.reference-chip[hidden] {
display: none;
}
.reference-chip .legend-line {
height: 0;
border-top: 1px dashed #91a4b8;
background: transparent;
box-shadow: none;
}
.view-help {
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 9px;
color: #6f849b;
background: rgba(7, 16, 28, 0.58);
backdrop-filter: blur(10px);
font-size: 9px;
line-height: 1.45;
text-align: right;
}
.toast {
position: absolute;
bottom: 82px;
left: 50%;
max-width: min(420px, calc(100% - 40px));
padding: 9px 13px;
border: 1px solid rgba(168, 239, 120, 0.25);
border-radius: 8px;
color: #d9efd0;
background: rgba(12, 27, 35, 0.92);
box-shadow: 0 10px 35px rgba(0, 0, 0, 0.3);
font-size: 10px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 8px);
transition:
opacity 180ms ease,
transform 180ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.loading {
position: absolute;
inset: 0;
display: grid;
place-items: center;
z-index: 5;
color: var(--muted);
background: var(--bg);
font-size: 11px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
@media (max-width: 980px) {
.app {
grid-template-columns: 310px minmax(0, 1fr);
}
.panel {
padding: 22px 18px;
}
.metrics {
grid-template-columns: 1fr;
}
.metric {
min-width: 150px;
}
.view-help {
display: none;
}
}
@media (max-width: 760px) {
html,
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
grid-template-columns: 1fr;
grid-template-rows: auto 65vh;
}
.panel {
max-height: 48vh;
border-right: 0;
border-bottom: 1px solid var(--line);
}
.viewport {
min-height: 65vh;
}
.hud-top {
top: 12px;
right: 12px;
left: 12px;
}
.status-pill {
display: none;
}
.metrics {
width: 100%;
grid-template-columns: repeat(3, 1fr);
}
.metric {
min-width: 0;
padding: 9px;
}
.metric-value {
font-size: 14px;
}
.metric-detail {
display: none;
}
.hud-bottom {
right: 12px;
bottom: 12px;
left: 12px;
}
.legend {
width: 100%;
justify-content: center;
}
}
</style>
</head>
<body>
<div class="app">
<aside class="panel">
<div class="eyebrow">Optical Lab / 01</div>
<h1>Dispersion<br />Parameter Explorer</h1>
<p class="intro">
Edit a wavelength-dependent refractive-index profile, trace the spectrum
through a triangular prism, and inspect the separation at the detector.
</p>
<section class="section">
<div class="section-title">
<h2>Material Profile</h2>
<p>Illustrative</p>
</div>
<select id="preset" aria-label="Refractive index profile">
<option value="crown">Crown glass</option>
<option value="flint">Higher-contrast flint</option>
<option value="soft">Soft contrast</option>
<option value="custom" disabled>Custom / edited</option>
</select>
</section>
<section class="section">
<div class="section-title">
<h2>Refractive Index Table</h2>
<p>n(λ)</p>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Wavelength</th>
<th>Index</th>
</tr>
</thead>
<tbody id="tableBody"></tbody>
</table>
</div>
<div class="lock-note">
<div>
<strong>Normal dispersion</strong>
</div>
<div>
Values are clamped so n decreases as wavelength increases. The table
represents an ordered illustrative profile, not vendor data.
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Incident Beam</h2>
<p>Vertical position</p>
</div>
<div class="range-row">
<input
id="beamHeight"
type="range"
min="-0.35"
max="0.70"
step="0.01"
value="0.35"
aria-label="Incident beam vertical position"
/>
<output id="beamValue" class="range-value">+0.35</output>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Comparison</h2>
<button id="clearReference" class="text-button" hidden>Clear</button>
</div>
<div class="button-row">
<button id="pinReference" class="primary">Pin current profile</button>
<button id="resetProfile">Reset values</button>
</div>
</section>
<section class="section">
<details>
<summary>Model notes</summary>
<p>
Rays are traced in the prism cross-section using vector Snell
refraction at entry and exit. The detector is 25 mm per scene unit.
The prism is a low-poly triangular solid; the camera can be dragged
and zoomed directly.
</p>
</details>
</section>
</aside>
<main class="viewport" id="viewport">
<canvas id="scene" aria-label="Interactive prism dispersion visualization"></canvas>
<div id="loading" class="loading">Loading optical model…</div>
<div class="hud-top">
<div class="status-pill">
<span class="status-dot"></span>
<span id="statusText">Snell-law ray trace</span>
</div>
<div class="metrics">
<div class="metric">
<div class="metric-label">Detector spread</div>
<div id="spreadMetric" class="metric-value accent">—</div>
<div id="spreadDetail" class="metric-detail">450–650 nm</div>
</div>
<div class="metric">
<div class="metric-label">Mean deviation</div>
<div id="deviationMetric" class="metric-value">—</div>
<div class="metric-detail">from incident direction</div>
</div>
<div class="metric">
<div class="metric-label">Reference Δ</div>
<div id="referenceMetric" class="metric-value">—</div>
<div id="referenceDetail" class="metric-detail">No profile pinned</div>
</div>
</div>
</div>
<div class="hud-bottom">
<div id="legend" class="legend"></div>
<div class="view-help">
Drag to orbit · wheel to zoom<br />
Double-click to reset view
</div>
</div>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const MM_PER_UNIT = 25;
const SCREEN_X = 3.72;
const SOURCE_X = -3.18;
const MIN_INDEX = 1.0;
const MAX_INDEX = 2.2;
const MIN_INDEX_STEP = 0.0005;
const profiles = {
crown: [1.525, 1.517, 1.512, 1.508, 1.505],
flint: [1.620, 1.609, 1.602, 1.598, 1.595],
soft: [1.510, 1.507, 1.505, 1.504, 1.503]
};
const rows = [
{ lambda: 450, n: 1.525, color: "#7067ff" },
{ lambda: 500, n: 1.517, color: "#25cbb4" },
{ lambda: 550, n: 1.512, color: "#88ed58" },
{ lambda: 600, n: 1.508, color: "#ffae3d" },
{ lambda: 650, n: 1.505, color: "#ff5962" }
];
const prismVertices = [
new THREE.Vector2(-1.0, -0.65),
new THREE.Vector2(1.0, -0.65),
new THREE.Vector2(0.0, 1.5)
];
const dom = {
viewport: document.getElementById("viewport"),
canvas: document.getElementById("scene"),
tableBody: document.getElementById("tableBody"),
preset: document.getElementById("preset"),
beamHeight: document.getElementById("beamHeight"),
beamValue: document.getElementById("beamValue"),
pinReference: document.getElementById("pinReference"),
clearReference: document.getElementById("clearReference"),
resetProfile: document.getElementById("resetProfile"),
spreadMetric: document.getElementById("spreadMetric"),
spreadDetail: document.getElementById("spreadDetail"),
deviationMetric: document.getElementById("deviationMetric"),
referenceMetric: document.getElementById("referenceMetric"),
referenceDetail: document.getElementById("referenceDetail"),
legend: document.getElementById("legend"),
statusText: document.getElementById("statusText"),
toast: document.getElementById("toast"),
loading: document.getElementById("loading")
};
let baseline = null;
let hoverIndex = null;
let currentTraces = [];
let referenceTraces = [];
let toastTimer;
const renderer = new THREE.WebGLRenderer({
canvas: dom.canvas,
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101c);
const camera = new THREE.OrthographicCamera(-5, 5, 3, -3, 0.1, 100);
const cameraTarget = new THREE.Vector3(0.15, -0.65, 0);
const cameraState = {
azimuth: -0.065,
elevation: 0.055,
zoom: 1
};
scene.add(new THREE.HemisphereLight(0xb8e7ff, 0x182238, 1.7));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-3, 6, 8);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x58cfff, 2.2);
rimLight.position.set(5, -2, 3);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffa85c, 12, 8, 2);
warmLight.position.set(2.8, 0.6, 2.5);
scene.add(warmLight);
const currentGroup = new THREE.Group();
const referenceGroup = new THREE.Group();
scene.add(currentGroup, referenceGroup);
const sourceGroup = new THREE.Group();
scene.add(sourceGroup);
function createTable() {
dom.tableBody.innerHTML = rows
.map(
(row, index) => `
<tr data-index="${index}">
<td>
<div class="wavelength">
<span class="swatch" style="--swatch:${row.color}"></span>
<span>${row.lambda}</span>
<span class="lambda-unit">nm</span>
</div>
</td>
<td>
<input
class="n-input"
type="number"
min="${MIN_INDEX}"
max="${MAX_INDEX}"
step="0.0001"
value="${row.n.toFixed(4)}"
data-index="${index}"
aria-label="Refractive index at ${row.lambda} nanometers"
/>
</td>
</tr>
`
)
.join("");
dom.tableBody.querySelectorAll(".n-input").forEach((input) => {
input.addEventListener("input", () => {
const index = Number(input.dataset.index);
const requested = Number.parseFloat(input.value);
if (!Number.isFinite(requested)) return;
const upper =
index === 0
? MAX_INDEX
: rows[index - 1].n - MIN_INDEX_STEP;
const lower =
index === rows.length - 1
? MIN_INDEX
: rows[index + 1].n + MIN_INDEX_STEP;
const constrained = Math.min(upper, Math.max(lower, requested));
const wasClamped = Math.abs(constrained - requested) > 1e-8;
rows[index].n = Number(constrained.toFixed(4));
input.value = rows[index].n.toFixed(4);
if (wasClamped) {
showToast("Value adjusted to preserve the normal-dispersion ordering.");
}
dom.preset.value = "custom";
updateModel();
});
});
dom.tableBody.querySelectorAll("tbody tr").forEach((tr) => {
const index = Number(tr.dataset.index);
tr.addEventListener("pointerenter", () => {
hoverIndex = index;
updateRayEmphasis();
});
tr.addEventListener("pointerleave", () => {
hoverIndex = null;
updateRayEmphasis();
});
});
}
function createLegend() {
dom.legend.innerHTML =
rows
.map(
(row) => `
<div class="legend-item">
<span class="legend-line" style="--swatch:${row.color}"></span>
<span>${row.lambda} nm</span>
</div>
`
)
.join("") +
`
<div id="referenceLegend" class="legend-item reference-chip" hidden>
<span class="legend-line"></span>
<span>Pinned profile</span>
</div>
`;
}
function showToast(message) {
clearTimeout(toastTimer);
dom.toast.textContent = message;
dom.toast.classList.add("show");
toastTimer = setTimeout(() => {
dom.toast.classList.remove("show");
}, 2300);
}
function createPrismGeometry(vertices, depth) {
const positions = [];
const indices = [];
for (const z of [depth / 2, -depth / 2]) {
for (const vertex of vertices) {
positions.push(vertex.x, vertex.y, z);
}
}
indices.push(0, 1, 2);
indices.push(5, 4, 3);
for (let i = 0; i < 3; i++) {
const j = (i + 1) % 3;
indices.push(i, 3 + i, 3 + j);
indices.push(i, 3 + j, j);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function addEnvironment() {
const gridVertices = [];
const xMin = -4.1;
const xMax = 4.2;
const yMin = -3.5;
const yMax = 2.1;
for (let x = xMin; x <= xMax + 0.001; x += 0.5) {
gridVertices.push(x, yMin, -0.58, x, yMax, -0.58);
}
for (let y = yMin; y <= yMax + 0.001; y += 0.5) {
gridVertices.push(xMin, y, -0.58, xMax, y, -0.58);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x254058,
transparent: true,
opacity: 0.24
})
);
scene.add(grid);
const prism = new THREE.Mesh(
createPrismGeometry(prismVertices, 0.64),
new THREE.MeshPhongMaterial({
color: 0x75d7ff,
emissive: 0x092b40,
emissiveIntensity: 0.5,
transparent: true,
opacity: 0.3,
side: THREE.DoubleSide,
depthWrite: false,
shininess: 85,
flatShading: true
})
);
prism.renderOrder = 2;
scene.add(prism);
const edgePoints = [];
for (const z of [0.325, -0.325]) {
for (let i = 0; i < 3; i++) {
const a = prismVertices[i];
const b = prismVertices[(i + 1) % 3];
edgePoints.push(
new THREE.Vector3(a.x, a.y, z),
new THREE.Vector3(b.x, b.y, z)
);
}
}
const edgeGeometry = new THREE.BufferGeometry().setFromPoints(edgePoints);
const edges = new THREE.LineSegments(
edgeGeometry,
new THREE.LineBasicMaterial({
color: 0xa6eaff,
transparent: true,
opacity: 0.82
})
);
edges.renderOrder = 3;
scene.add(edges);
const pedestal = new THREE.Mesh(
new THREE.BoxGeometry(2.25, 0.16, 0.9),
new THREE.MeshStandardMaterial({
color: 0x17273a,
roughness: 0.76,
metalness: 0.22,
flatShading: true
})
);
pedestal.position.set(0, -0.86, -0.03);
scene.add(pedestal);
const detector = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 6.05, 0.72),
new THREE.MeshStandardMaterial({
color: 0x16263a,
roughness: 0.7,
metalness: 0.35,
flatShading: true
})
);
detector.position.set(3.79, -0.72, -0.06);
scene.add(detector);
const detectorEdge = new THREE.Mesh(
new THREE.BoxGeometry(0.145, 6.08, 0.75),
new THREE.MeshBasicMaterial({
color: 0x4b718d,
wireframe: true,
transparent: true,
opacity: 0.32
})
);
detectorEdge.position.copy(detector.position);
scene.add(detectorEdge);
const tickPoints = [];
for (let y = -3.5; y <= 2.001; y += 0.25) {
const major = Math.abs(y % 1) < 0.01;
tickPoints.push(
new THREE.Vector3(3.69, y, 0.36),
new THREE.Vector3(3.69 - (major ? 0.12 : 0.065), y, 0.36)
);
}
const tickGeometry = new THREE.BufferGeometry().setFromPoints(tickPoints);
scene.add(
new THREE.LineSegments(
tickGeometry,
new THREE.LineBasicMaterial({
color: 0x6d91aa,
transparent: true,
opacity: 0.42
})
)
);
}
function addSource() {
const housing = new THREE.Mesh(
new THREE.CylinderGeometry(0.22, 0.25, 0.52, 8, 1, false),
new THREE.MeshStandardMaterial({
color: 0x23374a,
roughness: 0.55,
metalness: 0.45,
flatShading: true
})
);
housing.rotation.z = Math.PI / 2;
housing.position.x = -3.49;
sourceGroup.add(housing);
const collar = new THREE.Mesh(
new THREE.CylinderGeometry(0.17, 0.17, 0.1, 8, 1, false),
new THREE.MeshStandardMaterial({
color: 0x70879a,
roughness: 0.42,
metalness: 0.65,
flatShading: true
})
);
collar.rotation.z = Math.PI / 2;
collar.position.x = -3.19;
sourceGroup.add(collar);
const lensMaterial = new THREE.MeshBasicMaterial({
color: 0xf5fbff,
transparent: true,
opacity: 0.95,
toneMapped: false
});
const lens = new THREE.Mesh(
new THREE.CylinderGeometry(0.125, 0.125, 0.035, 8),
lensMaterial
);
lens.rotation.z = Math.PI / 2;
lens.position.x = -3.115;
sourceGroup.add(lens);
const glow = new THREE.Mesh(
new THREE.CircleGeometry(0.27, 8),
new THREE.MeshBasicMaterial({
color: 0x8adfff,
transparent: true,
opacity: 0.09,
side: THREE.DoubleSide,
depthWrite: false,
toneMapped: false
})
);
glow.rotation.y = Math.PI / 2;
glow.position.x = -3.09;
sourceGroup.add(glow);
sourceGroup.userData.lens = lensMaterial;
}
function cross2(a, b) {
return a.x * b.y - a.y * b.x;
}
function hitPolygon(origin, direction, skippedEdge = -1) {
let closest = null;
for (let i = 0; i < prismVertices.length; i++) {
if (i === skippedEdge) continue;
const a = prismVertices[i];
const b = prismVertices[(i + 1) % prismVertices.length];
const edge = b.clone().sub(a);
const denominator = cross2(direction, edge);
if (Math.abs(denominator) < 1e-9) continue;
const originToA = a.clone().sub(origin);
const t = cross2(originToA, edge) / denominator;
const u = cross2(originToA, direction) / denominator;
if (
t > 1e-4 &&
u >= -1e-6 &&
u <= 1 + 1e-6 &&
(!closest || t < closest.t)
) {
closest = {
t,
edge: i,
point: origin.clone().addScaledVector(direction, t)
};
}
}
return closest;
}
function refract(direction, edgeIndex, entering, refractiveIndex) {
const a = prismVertices[edgeIndex];
const b = prismVertices[(edgeIndex + 1) % prismVertices.length];
const edge = b.clone().sub(a);
// Polygon winding is counterclockwise, so this is the outward normal.
const outward = new THREE.Vector2(edge.y, -edge.x).normalize();
const normal = entering ? outward.clone().multiplyScalar(-1) : outward;
const eta = entering ? 1 / refractiveIndex : refractiveIndex;
const normalComponent = direction.dot(normal);
const tangent = direction
.clone()
.addScaledVector(normal, -normalComponent);
const k = 1 - eta * eta * tangent.lengthSq();
if (k < 0) return null;
return tangent
.multiplyScalar(eta)
.addScaledVector(normal, Math.sqrt(k))
.normalize();
}
function traceRay(refractiveIndex, beamY) {
const origin = new THREE.Vector2(SOURCE_X, beamY);
const incident = new THREE.Vector2(1, 0);
const entryHit = hitPolygon(origin, incident);
if (!entryHit) return null;
const insideDirection = refract(
incident,
entryHit.edge,
true,
refractiveIndex
);
if (!insideDirection) {
return { tir: true, entry: entryHit.point };
}
const exitHit = hitPolygon(
entryHit.point,
insideDirection,
entryHit.edge
);
if (!exitHit) return null;
const outgoingDirection = refract(
insideDirection,
exitHit.edge,
false,
refractiveIndex
);
if (!outgoingDirection) {
return {
tir: true,
entry: entryHit.point,
exit: exitHit.point
};
}
const screenT =
(SCREEN_X - exitHit.point.x) / outgoingDirection.x;
if (!Number.isFinite(screenT) || screenT <= 0) return null;
const screenPoint = exitHit.point
.clone()
.addScaledVector(outgoingDirection, screenT);
return {
tir: false,
entry: entryHit.point,
exit: exitHit.point,
screen: screenPoint,
outgoingDirection,
incident
};
}
function addCylinderSegment(group, start, end, color, options = {}) {
const {
radius = 0.016,
opacity = 0.9,
glow = true,
z = 0.07,
coreMaterial = null
} = options;
const a = new THREE.Vector3(start.x, start.y, z);
const b = new THREE.Vector3(end.x, end.y, z);
const direction = b.clone().sub(a);
const length = direction.length();
if (length < 1e-6) return [];
const material =
coreMaterial ||
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity,
toneMapped: false
});
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
6,
1,
false
);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
group.add(mesh);
const materials = [material];
if (glow) {
const glowMaterial = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.085,
depthWrite: false,
toneMapped: false
});
const glowGeometry = new THREE.CylinderGeometry(
radius * 3.3,
radius * 3.3,
length,
6,
1,
false
);
const glowMesh = new THREE.Mesh(glowGeometry, glowMaterial);
glowMesh.position.copy(mesh.position);
glowMesh.quaternion.copy(mesh.quaternion);
group.add(glowMesh);
materials.push(glowMaterial);
}
return materials;
}
function disposeGroup(group) {
group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach((material) => material.dispose());
}
});
group.clear();
}
let rayMaterials = [];
function rebuildCurrentRays(traces) {
disposeGroup(currentGroup);
rayMaterials = [];
if (!traces.length || traces.some((trace) => !trace || trace.tir)) {
return;
}
const firstEntry = traces[0].entry;
addCylinderSegment(
currentGroup,
new THREE.Vector2(SOURCE_X, firstEntry.y),
firstEntry,
0xf3fbff,
{
radius: 0.022,
opacity: 0.96,
z: 0.055
}
);
traces.forEach((trace, index) => {
const color = rows[index].color;
const internalMaterials = addCylinderSegment(
currentGroup,
trace.entry,
trace.exit,
color,
{
radius: 0.014,
opacity: 0.84,
z: 0.055
}
);
const outputMaterials = addCylinderSegment(
currentGroup,
trace.exit,
trace.screen,
color,
{
radius: 0.016,
opacity: 0.94,
z: 0.07
}
);
rayMaterials.push([...internalMaterials, ...outputMaterials]);
const entryJoint = new THREE.Mesh(
new THREE.SphereGeometry(0.035, 8, 5),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.9,
toneMapped: false
})
);
entryJoint.position.set(trace.entry.x, trace.entry.y, 0.065);
currentGroup.add(entryJoint);
const detectorDot = new THREE.Mesh(
new THREE.SphereGeometry(0.046, 8, 5),
new THREE.MeshBasicMaterial({
color,
toneMapped: false
})
);
detectorDot.position.set(trace.screen.x, trace.screen.y, 0.09);
currentGroup.add(detectorDot);
});
const validScreens = traces.map((trace) => trace.screen.y);
const minimum = Math.min(...validScreens);
const maximum = Math.max(...validScreens);
const bracketPoints = [
new THREE.Vector3(3.61, minimum, 0.18),
new THREE.Vector3(3.61, maximum, 0.18),
new THREE.Vector3(3.53, minimum, 0.18),
new THREE.Vector3(3.61, minimum, 0.18),
new THREE.Vector3(3.53, maximum, 0.18),
new THREE.Vector3(3.61, maximum, 0.18)
];
const bracket = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(bracketPoints),
new THREE.LineBasicMaterial({
color: 0xe8f6ff,
transparent: true,
opacity: 0.8
})
);
currentGroup.add(bracket);
updateRayEmphasis();
}
function rebuildReferenceRays(traces) {
disposeGroup(referenceGroup);
if (!traces.length) return;
traces.forEach((trace, index) => {
if (!trace || trace.tir) return;
const points = [
new THREE.Vector3(SOURCE_X, trace.entry.y, 0.11),
new THREE.Vector3(trace.entry.x, trace.entry.y, 0.11),
new THREE.Vector3(trace.exit.x, trace.exit.y, 0.11),
new THREE.Vector3(trace.screen.x, trace.screen.y, 0.11)
];
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
new THREE.LineDashedMaterial({
color: rows[index].color,
transparent: true,
opacity: 0.32,
dashSize: 0.1,
gapSize: 0.075,
depthWrite: false
})
);
line.computeLineDistances();
referenceGroup.add(line);
});
}
function updateRayEmphasis() {
rayMaterials.forEach((materials, index) => {
const selected = hoverIndex === null || hoverIndex === index;
materials.forEach((material, materialIndex) => {
const isGlow = materialIndex % 2 === 1;
const baseOpacity = isGlow ? 0.085 : 0.9;
material.opacity = selected
? baseOpacity
: isGlow
? 0.025
: 0.2;
});
});
dom.tableBody.querySelectorAll("tbody tr").forEach((tr) => {
tr.classList.toggle(
"is-active",
hoverIndex !== null && Number(tr.dataset.index) === hoverIndex
);
});
}
function updateMetrics() {
const valid = currentTraces.filter((trace) => trace && !trace.tir);
if (!valid.length) {
dom.spreadMetric.textContent = "TIR";
dom.deviationMetric.textContent = "—";
dom.statusText.textContent = "Total internal reflection";
return;
}
const screenY = valid.map((trace) => trace.screen.y);
const minimum = Math.min(...screenY);
const maximum = Math.max(...screenY);
const spreadMM = (maximum - minimum) * MM_PER_UNIT;
const deviations = valid.map((trace) =>
Math.acos(
THREE.MathUtils.clamp(
trace.outgoingDirection.dot(trace.incident),
-1,
1
)
) *
(180 / Math.PI)
);
const meanDeviation =
deviations.reduce((sum, value) => sum + value, 0) / deviations.length;
dom.spreadMetric.textContent = `${spreadMM.toFixed(2)} mm`;
dom.spreadDetail.textContent = `${rows[0].lambda}–${rows.at(-1).lambda} nm at detector`;
dom.deviationMetric.textContent = `${meanDeviation.toFixed(1)}°`;
dom.statusText.textContent = `${valid.length} rays traced`;
if (baseline) {
const baselineValid = referenceTraces.filter(
(trace) => trace && !trace.tir
);
if (baselineValid.length) {
const baselineY = baselineValid.map((trace) => trace.screen.y);
const baselineSpread =
(Math.max(...baselineY) - Math.min(...baselineY)) * MM_PER_UNIT;
const difference = spreadMM - baselineSpread;
const sign = difference >= 0 ? "+" : "−";
dom.referenceMetric.textContent = `${sign}${Math.abs(
difference
).toFixed(2)} mm`;
dom.referenceDetail.textContent = "versus pinned profile";
dom.referenceMetric.style.color =
difference >= 0 ? "#a8ef78" : "#ffb65c";
}
} else {
dom.referenceMetric.textContent = "—";
dom.referenceDetail.textContent = "No profile pinned";
dom.referenceMetric.style.color = "";
}
}
function updateModel() {
const beamY = Number(dom.beamHeight.value);
currentTraces = rows.map((row) => traceRay(row.n, beamY));
if (baseline) {
referenceTraces = baseline.values.map((value) =>
traceRay(value, beamY)
);
} else {
referenceTraces = [];
}
sourceGroup.position.y = beamY;
rebuildCurrentRays(currentTraces);
rebuildReferenceRays(referenceTraces);
updateMetrics();
const referenceLegend = document.getElementById("referenceLegend");
referenceLegend.hidden = !baseline;
dom.clearReference.hidden = !baseline;
dom.pinReference.textContent = baseline
? "Update pinned profile"
: "Pin current profile";
}
function updateCamera() {
const radius = 11.5;
const cosElevation = Math.cos(cameraState.elevation);
camera.position.set(
cameraTarget.x +
radius * Math.sin(cameraState.azimuth) * cosElevation,
cameraTarget.y + radius * Math.sin(cameraState.elevation),
cameraTarget.z +
radius * Math.cos(cameraState.azimuth) * cosElevation
);
camera.lookAt(cameraTarget);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = dom.viewport.clientWidth;
const height = dom.viewport.clientHeight;
const aspect = width / Math.max(height, 1);
renderer.setSize(width, height, false);
const viewHeight = Math.max(5.65, 8.55 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
updateCamera();
}
function resetView() {
cameraState.azimuth = -0.065;
cameraState.elevation = 0.055;
cameraState.zoom = 1;
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
dom.canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
dom.canvas.setPointerCapture(event.pointerId);
});
dom.canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.azimuth -= deltaX * 0.005;
cameraState.elevation = THREE.MathUtils.clamp(
cameraState.elevation + deltaY * 0.004,
-0.3,
0.36
);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && dom.canvas.hasPointerCapture(event.pointerId)) {
dom.canvas.releasePointerCapture(event.pointerId);
}
}
dom.canvas.addEventListener("pointerup", stopDragging);
dom.canvas.addEventListener("pointercancel", stopDragging);
dom.canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.72,
2.5
);
updateCamera();
},
{ passive: false }
);
dom.canvas.addEventListener("dblclick", resetView);
dom.preset.addEventListener("change", () => {
const values = profiles[dom.preset.value];
if (!values) return;
rows.forEach((row, index) => {
row.n = values[index];
});
dom.tableBody.querySelectorAll(".n-input").forEach((input, index) => {
input.value = rows[index].n.toFixed(4);
});
updateModel();
});
dom.beamHeight.addEventListener("input", () => {
const value = Number(dom.beamHeight.value);
dom.beamValue.textContent =
`${value >= 0 ? "+" : ""}${value.toFixed(2)}`;
updateModel();
});
dom.pinReference.addEventListener("click", () => {
baseline = {
values: rows.map((row) => row.n),
label: dom.preset.value
};
updateModel();
showToast("Current refractive-index profile pinned for comparison.");
});
dom.clearReference.addEventListener("click", () => {
baseline = null;
updateModel();
});
dom.resetProfile.addEventListener("click", () => {
const values = profiles.crown;
rows.forEach((row, index) => {
row.n = values[index];
});
dom.preset.value = "crown";
dom.tableBody.querySelectorAll(".n-input").forEach((input, index) => {
input.value = rows[index].n.toFixed(4);
});
updateModel();
showToast("Crown-glass values restored.");
});
createTable();
createLegend();
addEnvironment();
addSource();
resize();
updateModel();
new ResizeObserver(resize).observe(dom.viewport);
renderer.setAnimationLoop((time) => {
const pulse = 0.91 + Math.sin(time * 0.0024) * 0.07;
if (sourceGroup.userData.lens) {
sourceGroup.userData.lens.opacity = pulse;
}
renderer.render(scene, camera);
});
dom.loading.remove();
</script>
</body>
</html>
```