Prompt specification
Build or customize the Three.js 3D scene "Bond-angle exploration teaching rig" 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: Bond-angle exploration teaching rig
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/bond-angle-exploration-teaching-rig-x1964
Scene Description Prompt:
Please use Three.js from cdnjs for a voxel scene based on this idea: bond-angle exploration teaching rig. Let viewers rotate a molecule without changing connectivity and compare predefined geometries; preserve correct atom counts and clearly distinguish camera rotation from internal bond rotation. Return one self-contained HTML file.
Working Three.js Starter (bond-angle-exploration-teaching-rig-x1964):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bond Angle Lab — Voxel Molecular Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 21, 38, 0.88);
--panel-strong: rgba(14, 29, 50, 0.96);
--line: rgba(161, 190, 226, 0.16);
--text: #edf5ff;
--muted: #91a7c2;
--cyan: #38d6c6;
--yellow: #ffc857;
--violet: #8a74ff;
--orange: #ff994d;
--danger: #ff6f91;
--shadow: 0 18px 55px rgba(0, 0, 0, 0.34);
}
* {
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 {
font: inherit;
}
button {
color: inherit;
}
button:focus-visible,
input:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene.camera-dragging {
cursor: grabbing;
}
#scene.internal-mode {
cursor: crosshair;
}
#labels {
position: fixed;
inset: 0;
overflow: hidden;
pointer-events: none;
z-index: 2;
}
.world-label {
position: absolute;
top: 0;
left: 0;
padding: 4px 7px;
border: 1px solid rgba(255, 255, 255, 0.17);
border-radius: 6px;
background: rgba(5, 12, 23, 0.76);
box-shadow: 0 5px 14px rgba(0, 0, 0, 0.28);
color: #f6f9ff;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.04em;
white-space: nowrap;
transform: translate(-50%, -50%);
transition: opacity 120ms ease, border-color 120ms ease;
}
.world-label.center {
color: #d8d0ff;
border-color: rgba(138, 116, 255, 0.6);
}
.world-label.proximal {
color: #aef8ef;
border-color: rgba(56, 214, 198, 0.46);
}
.world-label.distal {
color: #ffe6a4;
border-color: rgba(255, 200, 87, 0.5);
}
.world-label.selected {
color: #fff;
border-color: var(--orange);
box-shadow: 0 0 0 2px rgba(255, 153, 77, 0.13);
}
#angleTag {
position: absolute;
top: 0;
left: 0;
padding: 6px 9px;
border: 1px solid rgba(255, 153, 77, 0.58);
border-radius: 8px;
background: rgba(32, 18, 12, 0.88);
color: #ffd7b5;
font-size: 11px;
font-weight: 800;
white-space: nowrap;
transform: translate(-50%, -50%);
pointer-events: none;
}
.topbar {
position: fixed;
z-index: 5;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
pointer-events: none;
}
.brand {
max-width: 540px;
pointer-events: auto;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: var(--cyan);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.eyebrow::before {
width: 22px;
height: 2px;
content: "";
background: var(--cyan);
box-shadow: 8px 0 18px rgba(56, 214, 198, 0.65);
}
h1 {
margin: 0;
font-size: clamp(24px, 3vw, 38px);
line-height: 1;
letter-spacing: -0.04em;
}
.subtitle {
max-width: 500px;
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.mode-switch {
display: flex;
gap: 4px;
padding: 4px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(9, 19, 34, 0.86);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
pointer-events: auto;
}
.mode-button {
min-width: 126px;
padding: 10px 13px;
border: 0;
border-radius: 9px;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 12px;
font-weight: 800;
transition: background 150ms ease, color 150ms ease, box-shadow 150ms ease;
}
.mode-button:hover {
color: var(--text);
background: rgba(255, 255, 255, 0.045);
}
.mode-button.active.camera {
color: #dffbff;
background: rgba(56, 214, 198, 0.16);
box-shadow: inset 0 0 0 1px rgba(56, 214, 198, 0.26);
}
.mode-button.active.internal {
color: #fff0df;
background: rgba(255, 153, 77, 0.17);
box-shadow: inset 0 0 0 1px rgba(255, 153, 77, 0.3);
}
.panel {
position: fixed;
z-index: 4;
top: 91px;
right: 20px;
width: 360px;
max-height: calc(100vh - 111px);
overflow: auto;
padding: 16px;
border: 1px solid var(--line);
border-radius: 17px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(140, 170, 205, 0.35) transparent;
}
.panel::-webkit-scrollbar {
width: 7px;
}
.panel::-webkit-scrollbar-thumb {
border-radius: 10px;
background: rgba(140, 170, 205, 0.3);
}
.section {
padding-bottom: 16px;
margin-bottom: 16px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
padding-bottom: 0;
margin-bottom: 0;
border-bottom: 0;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.section-heading h2 {
margin: 0;
color: #f2f7ff;
font-size: 12px;
font-weight: 850;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.section-heading small {
color: var(--muted);
font-size: 11px;
}
.mode-note {
min-height: 68px;
padding: 12px;
border: 1px solid rgba(56, 214, 198, 0.18);
border-radius: 11px;
background: rgba(56, 214, 198, 0.055);
}
.mode-note.internal {
border-color: rgba(255, 153, 77, 0.23);
background: rgba(255, 153, 77, 0.065);
}
.mode-note strong {
display: block;
margin-bottom: 5px;
font-size: 12px;
}
.mode-note p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.template-list {
display: grid;
gap: 8px;
}
.template {
display: grid;
grid-template-columns: 67px 1fr auto;
align-items: center;
gap: 10px;
width: 100%;
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
text-align: left;
cursor: pointer;
transition: border-color 150ms ease, background 150ms ease,
transform 150ms ease;
}
.template:hover {
border-color: rgba(161, 190, 226, 0.35);
background: rgba(255, 255, 255, 0.05);
transform: translateY(-1px);
}
.template.active {
border-color: rgba(138, 116, 255, 0.62);
background: rgba(138, 116, 255, 0.11);
}
.template svg {
width: 67px;
height: 51px;
overflow: visible;
}
.template .line {
stroke: #91a7c2;
stroke-width: 3;
stroke-linecap: square;
}
.template .node {
fill: var(--violet);
}
.template.active .line {
stroke: #c7bbff;
}
.template-name {
display: block;
margin-bottom: 4px;
font-size: 12px;
font-weight: 800;
}
.template-detail {
display: block;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.angle-pill {
padding: 6px 7px;
border: 1px solid rgba(138, 116, 255, 0.32);
border-radius: 8px;
color: #d9d1ff;
background: rgba(138, 116, 255, 0.09);
font-size: 12px;
font-weight: 850;
}
.readout-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 10px;
}
.readout {
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(0, 0, 0, 0.12);
}
.readout .label {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.readout .value {
color: #f5f8ff;
font-size: 14px;
font-weight: 850;
}
.pair-list {
display: grid;
gap: 5px;
}
.pair-row {
display: flex;
justify-content: space-between;
gap: 10px;
padding: 6px 8px;
border-radius: 7px;
background: rgba(255, 255, 255, 0.026);
color: var(--muted);
font-size: 11px;
}
.pair-row strong {
color: #e9f1ff;
font-variant-numeric: tabular-nums;
}
.arm-tabs {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-bottom: 12px;
}
.arm-button {
padding: 8px 6px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.025);
color: var(--muted);
cursor: pointer;
font-size: 11px;
font-weight: 800;
}
.arm-button.active {
border-color: rgba(255, 153, 77, 0.62);
background: rgba(255, 153, 77, 0.12);
color: #ffe1c5;
}
.slider-row {
display: grid;
grid-template-columns: 1fr 64px;
align-items: center;
gap: 10px;
}
input[type="range"] {
width: 100%;
accent-color: var(--orange);
cursor: pointer;
}
.torsion-value {
padding: 7px 6px;
border: 1px solid rgba(255, 153, 77, 0.25);
border-radius: 8px;
background: rgba(255, 153, 77, 0.08);
color: #ffe0c1;
text-align: center;
font-size: 12px;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
.button-row {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 10px;
}
.button {
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.035);
color: #dce8f8;
cursor: pointer;
font-size: 10px;
font-weight: 800;
transition: background 150ms ease, border-color 150ms ease;
}
.button:hover {
border-color: rgba(161, 190, 226, 0.38);
background: rgba(255, 255, 255, 0.075);
}
.button.primary {
border-color: rgba(255, 153, 77, 0.42);
background: rgba(255, 153, 77, 0.14);
color: #ffe2c8;
}
.button.primary.active {
background: rgba(255, 153, 77, 0.25);
}
.check-row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 11px;
color: var(--muted);
font-size: 11px;
cursor: pointer;
}
.check-row input {
accent-color: var(--cyan);
}
.invariant {
padding: 11px;
border: 1px solid rgba(56, 214, 198, 0.22);
border-radius: 10px;
background: rgba(56, 214, 198, 0.055);
color: #a7c7ca;
font-size: 10px;
line-height: 1.5;
}
.invariant strong {
display: block;
margin-bottom: 4px;
color: #baf8ef;
font-size: 11px;
}
.invariant code {
color: #e8f8ff;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
}
.legend {
position: fixed;
z-index: 3;
left: 20px;
bottom: 20px;
display: flex;
flex-wrap: wrap;
gap: 12px;
max-width: calc(100vw - 420px);
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(9, 19, 34, 0.75);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 10px;
white-space: nowrap;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 2px;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.22);
}
.status {
position: fixed;
z-index: 3;
left: 50%;
bottom: 22px;
display: flex;
align-items: center;
gap: 8px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(9, 19, 34, 0.78);
color: var(--muted);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
transform: translateX(-50%);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.05em;
pointer-events: none;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(56, 214, 198, 0.7);
}
.status.internal .status-dot {
background: var(--orange);
box-shadow: 0 0 12px rgba(255, 153, 77, 0.7);
}
@media (max-width: 920px) {
.topbar {
flex-wrap: wrap;
}
.mode-switch {
margin-left: auto;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 46vh;
}
.legend {
display: none;
}
.status {
top: 132px;
bottom: auto;
}
}
@media (max-width: 620px) {
.topbar {
top: 10px;
left: 12px;
right: 12px;
gap: 10px;
}
.brand {
width: 100%;
}
.subtitle {
display: none;
}
.mode-switch {
width: 100%;
}
.mode-button {
flex: 1;
min-width: 0;
}
.status {
top: 96px;
}
.panel {
max-height: 52vh;
padding: 13px;
}
.template {
grid-template-columns: 57px 1fr auto;
}
.template svg {
width: 57px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional voxel molecule"></canvas>
<div id="labels" aria-hidden="true">
<div id="angleTag" hidden></div>
</div>
<header class="topbar">
<div class="brand">
<div class="eyebrow">Voxel molecular mechanics</div>
<h1>Bond Angle Lab</h1>
<p class="subtitle">
Orbit the model to inspect it, or twist one ligand around a selected bond.
Connectivity and atom count remain fixed.
</p>
</div>
<div class="mode-switch" role="group" aria-label="Interaction mode">
<button
id="cameraMode"
class="mode-button camera active"
type="button"
aria-pressed="true"
>
Camera orbit
</button>
<button
id="internalMode"
class="mode-button internal"
type="button"
aria-pressed="false"
>
Internal twist
</button>
</div>
</header>
<aside class="panel" aria-label="Bond angle controls">
<section class="section">
<div class="section-heading">
<h2>Interaction</h2>
<small>Separate controls</small>
</div>
<div id="modeNote" class="mode-note">
<strong id="modeTitle">Camera orbit</strong>
<p id="modeDescription">
Drag the canvas to rotate the view. Scroll to zoom.
Geometry and internal torsions remain unchanged.
</p>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2>Compare geometries</h2>
<small>AX₃ templates</small>
</div>
<div class="template-list">
<button class="template active" type="button" data-geometry="planar">
<svg viewBox="0 0 80 58" aria-hidden="true">
<line class="line" x1="40" y1="29" x2="14" y2="43"></line>
<line class="line" x1="40" y1="29" x2="66" y2="43"></line>
<line class="line" x1="40" y1="29" x2="40" y2="6"></line>
<circle class="node" cx="40" cy="29" r="5"></circle>
<circle cx="14" cy="43" r="4"></circle>
<circle cx="66" cy="43" r="4"></circle>
<circle cx="40" cy="6" r="4"></circle>
</svg>
<span>
<span class="template-name">Trigonal planar</span>
<span class="template-detail">Three coplanar bonds around X</span>
</span>
<span class="angle-pill">120°</span>
</button>
<button class="template" type="button" data-geometry="tetrahedral">
<svg viewBox="0 0 80 58" aria-hidden="true">
<line class="line" x1="40" y1="29" x2="40" y2="5"></line>
<line class="line" x1="40" y1="29" x2="12" y2="48"></line>
<line class="line" x1="40" y1="29" x2="68" y2="48"></line>
<circle class="node" cx="40" cy="29" r="5"></circle>
<circle cx="40" cy="5" r="4"></circle>
<circle cx="12" cy="48" r="4"></circle>
<circle cx="68" cy="48" r="4"></circle>
</svg>
<span>
<span class="template-name">Tetrahedral</span>
<span class="template-detail">Three equal AX₃ bond angles</span>
</span>
<span class="angle-pill">109.5°</span>
</button>
<button class="template" type="button" data-geometry="pyramidal">
<svg viewBox="0 0 80 58" aria-hidden="true">
<line class="line" x1="40" y1="10" x2="14" y2="47"></line>
<line class="line" x1="40" y1="10" x2="40" y2="54"></line>
<line class="line" x1="40" y1="10" x2="66" y2="47"></line>
<circle class="node" cx="40" cy="10" r="5"></circle>
<circle cx="14" cy="47" r="4"></circle>
<circle cx="40" cy="54" r="4"></circle>
<circle cx="66" cy="47" r="4"></circle>
</svg>
<span>
<span class="template-name">Trigonal pyramidal</span>
<span class="template-detail">Compressed AX₃ angle</span>
</span>
<span class="angle-pill">107.3°</span>
</button>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2>Central angles</h2>
<small id="geometryState">Exact template</small>
</div>
<div class="readout-grid">
<div class="readout">
<span class="label">Active geometry</span>
<span id="activeGeometry" class="value">Trigonal planar</span>
</div>
<div class="readout">
<span class="label">Ideal angle</span>
<span id="idealAngle" class="value">120.0°</span>
</div>
</div>
<div class="pair-list">
<div class="pair-row">
<span>∠ A₁–X–A₂</span>
<strong id="pair01">120.0°</strong>
</div>
<div class="pair-row">
<span>∠ A₂–X–A₃</span>
<strong id="pair12">120.0°</strong>
</div>
<div class="pair-row">
<span>∠ A₃–X–A₁</span>
<strong id="pair20">120.0°</strong>
</div>
</div>
<label class="check-row">
<input id="showGuides" type="checkbox" checked />
Show angle and torsion guides
</label>
</section>
<section class="section">
<div class="section-heading">
<h2>Internal bond rotation</h2>
<small>Distal B atom only</small>
</div>
<div class="arm-tabs" role="group" aria-label="Selected ligand arm">
<button class="arm-button active" type="button" data-arm="0">Arm A₁</button>
<button class="arm-button" type="button" data-arm="1">Arm A₂</button>
<button class="arm-button" type="button" data-arm="2">Arm A₃</button>
</div>
<div class="slider-row">
<input
id="torsionSlider"
type="range"
min="0"
max="360"
step="1"
value="0"
aria-label="Selected bond torsion"
/>
<output id="torsionValue" class="torsion-value">000°</output>
</div>
<div class="button-row">
<button id="playTorsion" class="button primary" type="button">
Animate twist
</button>
<button id="minusTorsion" class="button" type="button">−15°</button>
<button id="plusTorsion" class="button" type="button">+15°</button>
<button id="resetTorsions" class="button" type="button">Zero twists</button>
</div>
</section>
<section class="section">
<div class="button-row" style="margin-top: 0">
<button id="resetCamera" class="button" type="button">Reset camera</button>
<button id="resetLab" class="button" type="button">Reset experiment</button>
</div>
</section>
<section class="section">
<div class="invariant">
<strong>Connectivity invariant</strong>
The graph always contains 7 atoms and 6 bonds:
<code>X–A₁–B₁</code>, <code>X–A₂–B₂</code>, and
<code>X–A₃–B₃</code>.
Camera orbit and bond torsion never add, remove, or reconnect atoms.
</div>
</section>
</aside>
<div class="legend" aria-label="Atom legend">
<div class="legend-item">
<span class="swatch" style="background: #8a74ff"></span>
X · central atom × 1
</div>
<div class="legend-item">
<span class="swatch" style="background: #38d6c6"></span>
A · proximal atoms × 3
</div>
<div class="legend-item">
<span class="swatch" style="background: #ffc857"></span>
B · distal atoms × 3
</div>
</div>
<div id="status" class="status">
<span class="status-dot"></span>
<span id="statusText">VIEW ROTATION · GEOMETRY LOCKED</span>
</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 canvas = $("scene");
const labelsLayer = $("labels");
const angleTag = $("angleTag");
// ---------------------------------------------------------------------
// Renderer, scene, and camera
// ---------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.FogExp2(0x07111f, 0.026);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const orbit = {
radius: 10.4,
theta: 0.82,
phi: 1.02,
target: new THREE.Vector3(0, 2.25, 0)
};
const defaultOrbit = {
radius: 10.4,
theta: 0.82,
phi: 1.02
};
function applyCamera() {
orbit.phi = THREE.MathUtils.clamp(orbit.phi, 0.32, Math.PI - 0.32);
orbit.radius = THREE.MathUtils.clamp(orbit.radius, 5.8, 16);
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();
// ---------------------------------------------------------------------
// Lighting and voxel environment
// ---------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xbfdcff, 0x162033, 1.8));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(5, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -5;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 25;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x486cff, 28, 18, 2);
rimLight.position.set(-5, 4.5, -4);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffa14a, 18, 14, 2);
warmLight.position.set(4, 2.5, 4);
scene.add(warmLight);
const floorMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.88,
metalness: 0.05
});
const tileCount = 17;
const tileSpacing = 0.72;
const floorTiles = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.68, 0.08, 0.68),
floorMaterial,
tileCount * tileCount
);
floorTiles.receiveShadow = true;
const dummy = new THREE.Object3D();
const floorColor = new THREE.Color();
let tileIndex = 0;
for (let x = 0; x < tileCount; x++) {
for (let z = 0; z < tileCount; z++) {
const px = (x - (tileCount - 1) / 2) * tileSpacing;
const pz = (z - (tileCount - 1) / 2) * tileSpacing;
dummy.position.set(px, -0.16, pz);
dummy.updateMatrix();
floorTiles.setMatrixAt(tileIndex, dummy.matrix);
const checker = (x + z) % 2;
floorColor.setHex(checker ? 0x101d2d : 0x0d1928);
floorTiles.setColorAt(tileIndex, floorColor);
tileIndex++;
}
}
floorTiles.instanceMatrix.needsUpdate = true;
if (floorTiles.instanceColor) floorTiles.instanceColor.needsUpdate = true;
scene.add(floorTiles);
const pedestal = new THREE.Mesh(
new THREE.BoxGeometry(2.3, 0.16, 2.3),
new THREE.MeshStandardMaterial({
color: 0x16263a,
roughness: 0.7,
metalness: 0.18
})
);
pedestal.position.set(0, -0.04, 0);
pedestal.receiveShadow = true;
scene.add(pedestal);
// ---------------------------------------------------------------------
// Molecular model and geometry templates
// ---------------------------------------------------------------------
const CENTER = new THREE.Vector3(0, 2.8, 0);
const CENTER_BOND_LENGTH = 2.15;
const DISTAL_BOND_LENGTH = 1.45;
const PROXIMAL_BEND = THREE.MathUtils.degToRad(109.5);
const pyramidalAngle = THREE.MathUtils.degToRad(107.3);
const pyramidY = -Math.sqrt(
(1 + 2 * Math.cos(pyramidalAngle)) / 3
);
const pyramidRadius = Math.sqrt(1 - pyramidY * pyramidY);
function planarDirections() {
return [0, (2 * Math.PI) / 3, (4 * Math.PI) / 3].map((a) =>
new THREE.Vector3(Math.cos(a), 0, Math.sin(a)).normalize()
);
}
function pyramidalDirections() {
return [0, (2 * Math.PI) / 3, (4 * Math.PI) / 3].map((a) =>
new THREE.Vector3(
pyramidRadius * Math.cos(a),
pyramidY,
pyramidRadius * Math.sin(a)
).normalize()
);
}
const presets = {
planar: {
name: "Trigonal planar",
ideal: 120,
description: "Three equal bonds in one plane.",
directions: planarDirections()
},
tetrahedral: {
name: "Tetrahedral",
ideal: 109.5,
description: "Three equal AX₃ bonds in tetrahedral directions.",
directions: [
new THREE.Vector3(1, 1, 1),
new THREE.Vector3(-1, -1, 1),
new THREE.Vector3(1, -1, -1)
].map((v) => v.normalize())
},
pyramidal: {
name: "Trigonal pyramidal",
ideal: 107.3,
description: "Three bonds compressed to 107.3°.",
directions: pyramidalDirections()
}
};
let activeGeometry = "planar";
let currentDirections = presets.planar.directions.map((v) => v.clone());
let transition = null;
const torsions = [0, 0, 0];
let selectedArm = 0;
let interactionMode = "camera";
let playingTorsion = false;
const proximalPositions = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()];
const distalPositions = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()];
const atomMeshes = [];
const labelEntries = [];
function makeAtom(color, size, role, arm = -1) {
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.33,
metalness: 0.18,
emissive: 0x000000,
emissiveIntensity: 0
});
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size, size, size),
material
);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData = { role, arm };
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.25
})
);
mesh.add(edges);
mesh.userData.edges = edges;
scene.add(mesh);
atomMeshes.push(mesh);
return mesh;
}
function addLabel(text, mesh, className) {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.textContent = text;
labelsLayer.appendChild(element);
const entry = { element, mesh };
labelEntries.push(entry);
return entry;
}
const centerAtom = makeAtom(0x8a74ff, 0.72, "center");
centerAtom.position.copy(CENTER);
addLabel("X", centerAtom, "center");
const proximalAtoms = [];
const distalAtoms = [];
const proximalLabels = [];
const distalLabels = [];
for (let i = 0; i < 3; i++) {
const proximal = makeAtom(0x38d6c6, 0.52, "proximal", i);
const distal = makeAtom(0xffc857, 0.48, "distal", i);
proximalAtoms.push(proximal);
distalAtoms.push(distal);
const proximalLabel = addLabel(
`A${["₁", "₂", "₃"][i]}`,
proximal,
"proximal"
);
const distalLabel = addLabel(
`B${["₁", "₂", "₃"][i]}`,
distal,
"distal"
);
proximalLabels.push(proximalLabel);
distalLabels.push(distalLabel);
}
function makeBondSet(count, material) {
const group = [];
for (let i = 0; i < count; i++) {
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.235, 0.235, 0.235),
material
);
cube.castShadow = true;
cube.receiveShadow = true;
scene.add(cube);
group.push(cube);
}
return group;
}
const centralBondMaterials = [];
const distalBondMaterials = [];
const centralBondSets = [];
const distalBondSets = [];
for (let i = 0; i < 3; i++) {
const centralMaterial = new THREE.MeshStandardMaterial({
color: 0x52647f,
roughness: 0.5,
metalness: 0.18
});
const distalMaterial = new THREE.MeshStandardMaterial({
color: 0x69748b,
roughness: 0.5,
metalness: 0.16
});
centralBondMaterials.push(centralMaterial);
distalBondMaterials.push(distalMaterial);
centralBondSets.push(makeBondSet(12, centralMaterial));
distalBondSets.push(makeBondSet(8, distalMaterial));
}
const angleArc = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: 0xff994d,
transparent: true,
opacity: 0.95
})
);
scene.add(angleArc);
const twistRing = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: 0xffb15f,
transparent: true,
opacity: 0.75,
dashSize: 0.14,
gapSize: 0.09
})
);
scene.add(twistRing);
// ---------------------------------------------------------------------
// Molecular geometry and guide updates
// ---------------------------------------------------------------------
const up = new THREE.Vector3(0, 1, 0);
const fallbackAxis = new THREE.Vector3(0, 0, 1);
const bondQuaternion = new THREE.Quaternion();
const zAxis = new THREE.Vector3(0, 0, 1);
function updateBondSet(set, from, to) {
const direction = new THREE.Vector3().subVectors(to, from);
const length = direction.length();
direction.normalize();
bondQuaternion.setFromUnitVectors(zAxis, direction);
for (let i = 0; i < set.length; i++) {
const t = i / (set.length - 1);
set[i].position.lerpVectors(from, to, t);
set[i].quaternion.copy(bondQuaternion);
}
}
function getArmBasis(axis) {
const radial = new THREE.Vector3().crossVectors(axis, up);
if (radial.lengthSq() < 0.0001) {
radial.crossVectors(axis, fallbackAxis);
}
radial.normalize();
const normal = new THREE.Vector3()
.crossVectors(axis, radial)
.normalize();
return { radial, normal };
}
function updateMolecule() {
for (let i = 0; i < 3; i++) {
const axis = currentDirections[i].clone().normalize();
proximalPositions[i]
.copy(CENTER)
.addScaledVector(axis, CENTER_BOND_LENGTH);
const { radial, normal } = getArmBasis(axis);
const torsion = THREE.MathUtils.degToRad(torsions[i]);
const rotatingRadial = radial
.clone()
.multiplyScalar(Math.cos(torsion))
.addScaledVector(normal, Math.sin(torsion));
const distalDirection = rotatingRadial
.multiplyScalar(Math.sin(PROXIMAL_BEND))
.addScaledVector(axis, -Math.cos(PROXIMAL_BEND))
.normalize();
distalPositions[i]
.copy(proximalPositions[i])
.addScaledVector(distalDirection, DISTAL_BOND_LENGTH);
proximalAtoms[i].position.copy(proximalPositions[i]);
distalAtoms[i].position.copy(distalPositions[i]);
updateBondSet(
centralBondSets[i],
CENTER,
proximalPositions[i]
);
updateBondSet(
distalBondSets[i],
proximalPositions[i],
distalPositions[i]
);
}
updateHighlights();
updateAngleArc();
updateTwistRing();
updateReadouts();
}
function updateHighlights() {
for (let i = 0; i < 3; i++) {
const selected = i === selectedArm;
proximalAtoms[i].scale.setScalar(selected ? 1.14 : 1);
distalAtoms[i].scale.setScalar(selected ? 1.18 : 1);
proximalAtoms[i].material.emissive.setHex(
selected ? 0x8a3b12 : 0x000000
);
proximalAtoms[i].material.emissiveIntensity = selected ? 0.32 : 0;
distalAtoms[i].material.emissive.setHex(
selected ? 0x9a4d0c : 0x000000
);
distalAtoms[i].material.emissiveIntensity = selected ? 0.4 : 0;
proximalAtoms[i].userData.edges.material.opacity = selected ? 0.55 : 0.25;
distalAtoms[i].userData.edges.material.opacity = selected ? 0.62 : 0.25;
centralBondMaterials[i].color.setHex(
selected ? 0xff994d : 0x52647f
);
distalBondMaterials[i].color.setHex(
selected ? 0xffc857 : 0x69748b
);
proximalLabels[i].element.classList.toggle("selected", selected);
distalLabels[i].element.classList.toggle("selected", selected);
}
}
function angleBetween(a, b) {
const dot = THREE.MathUtils.clamp(a.dot(b), -1, 1);
return THREE.MathUtils.radToDeg(Math.acos(dot));
}
function updateAngleArc() {
const showGuides = $("showGuides").checked;
angleArc.visible = showGuides;
const a = currentDirections[selectedArm];
const b = currentDirections[(selectedArm + 1) % 3];
const angle = THREE.MathUtils.degToRad(angleBetween(a, b));
const points = [];
for (let i = 0; i <= 48; i++) {
const t = i / 48;
const direction = a
.clone()
.multiplyScalar(Math.sin((1 - t) * angle) / Math.sin(angle))
.addScaledVector(
b,
Math.sin(t * angle) / Math.sin(angle)
)
.normalize();
points.push(
CENTER.clone().addScaledVector(direction, 0.78)
);
}
angleArc.geometry.setFromPoints(points);
angleArc.geometry.computeBoundingSphere();
const midpoint = a.clone().add(b).normalize();
const labelPosition = CENTER.clone().addScaledVector(midpoint, 1.05);
angleTag.hidden = !showGuides;
angleTag.textContent = `∠ A${["₁", "₂", "₃"][selectedArm]}–X–A${
["₁", "₂", "₃"][(selectedArm + 1) % 3]
} ${angleBetween(a, b).toFixed(1)}°`;
angleTag.dataset.worldX = labelPosition.x;
angleTag.dataset.worldY = labelPosition.y;
angleTag.dataset.worldZ = labelPosition.z;
}
function updateTwistRing() {
const visible = interactionMode === "internal" && $("showGuides").checked;
twistRing.visible = visible;
if (!visible) return;
const axis = currentDirections[selectedArm].clone().normalize();
const { radial, normal } = getArmBasis(axis);
const radius = DISTAL_BOND_LENGTH * Math.sin(PROXIMAL_BEND);
const points = [];
for (let i = 0; i <= 64; i++) {
const t = (i / 64) * Math.PI * 2;
const point = proximalPositions[selectedArm]
.clone()
.addScaledVector(radial, Math.cos(t) * radius)
.addScaledVector(normal, Math.sin(t) * radius);
points.push(point);
}
twistRing.geometry.setFromPoints(points);
twistRing.computeLineDistances();
twistRing.geometry.computeBoundingSphere();
}
function updateReadouts() {
const values = [
angleBetween(currentDirections[0], currentDirections[1]),
angleBetween(currentDirections[1], currentDirections[2]),
angleBetween(currentDirections[2], currentDirections[0])
];
$("pair01").textContent = `${values[0].toFixed(1)}°`;
$("pair12").textContent = `${values[1].toFixed(1)}°`;
$("pair20").textContent = `${values[2].toFixed(1)}°`;
$("activeGeometry").textContent = presets[activeGeometry].name;
$("idealAngle").textContent = `${presets[activeGeometry].ideal.toFixed(1)}°`;
$("geometryState").textContent = transition
? "Transitioning…"
: "Exact template";
const torsion = Math.round(torsions[selectedArm]) % 360;
$("torsionSlider").value = torsion;
$("torsionValue").textContent = `${String(torsion).padStart(3, "0")}°`;
if (interactionMode === "camera") {
$("statusText").textContent =
"VIEW ROTATION · GEOMETRY AND TORSION LOCKED";
} else {
$("statusText").textContent =
`INTERNAL TORSION · ARM A${["₁", "₂", "₃"][selectedArm]} · ${String(
torsion
).padStart(3, "0")}°`;
}
}
// ---------------------------------------------------------------------
// Interface behavior
// ---------------------------------------------------------------------
function setMode(mode) {
interactionMode = mode;
const cameraActive = mode === "camera";
$("cameraMode").classList.toggle("active", cameraActive);
$("internalMode").classList.toggle("active", !cameraActive);
$("cameraMode").setAttribute("aria-pressed", String(cameraActive));
$("internalMode").setAttribute("aria-pressed", String(!cameraActive));
$("modeNote").classList.toggle("internal", !cameraActive);
$("modeTitle").textContent = cameraActive
? "Camera orbit"
: "Internal twist";
$("modeDescription").textContent = cameraActive
? "Drag the canvas to rotate the view. Scroll to zoom. Geometry and internal torsions remain unchanged."
: "Drag a yellow B atom sideways, or use the torsion slider. The camera and three central bond angles stay fixed.";
canvas.classList.toggle("internal-mode", !cameraActive);
canvas.classList.remove("camera-dragging");
$("status").classList.toggle("internal", !cameraActive);
updateReadouts();
updateTwistRing();
}
function selectArm(index) {
selectedArm = index;
document.querySelectorAll(".arm-button").forEach((button) => {
button.classList.toggle(
"active",
Number(button.dataset.arm) === selectedArm
);
});
updateHighlights();
updateAngleArc();
updateTwistRing();
updateReadouts();
}
function selectGeometry(key) {
if (!presets[key]) return;
activeGeometry = key;
transition = {
from: currentDirections.map((v) => v.clone()),
to: presets[key].directions.map((v) => v.clone()),
elapsed: 0,
duration: 0.7
};
document.querySelectorAll(".template").forEach((button) => {
button.classList.toggle(
"active",
button.dataset.geometry === key
);
});
updateReadouts();
}
function setTorsion(value) {
torsions[selectedArm] = ((value % 360) + 360) % 360;
updateMolecule();
}
$("cameraMode").addEventListener("click", () => setMode("camera"));
$("internalMode").addEventListener("click", () => setMode("internal"));
document.querySelectorAll(".template").forEach((button) => {
button.addEventListener("click", () => {
selectGeometry(button.dataset.geometry);
});
});
document.querySelectorAll(".arm-button").forEach((button) => {
button.addEventListener("click", () => {
selectArm(Number(button.dataset.arm));
});
});
$("torsionSlider").addEventListener("input", (event) => {
setTorsion(Number(event.target.value));
});
$("minusTorsion").addEventListener("click", () => {
setTorsion(torsions[selectedArm] - 15);
});
$("plusTorsion").addEventListener("click", () => {
setTorsion(torsions[selectedArm] + 15);
});
$("resetTorsions").addEventListener("click", () => {
torsions.fill(0);
playingTorsion = false;
$("playTorsion").classList.remove("active");
$("playTorsion").textContent = "Animate twist";
updateMolecule();
});
$("playTorsion").addEventListener("click", () => {
playingTorsion = !playingTorsion;
$("playTorsion").classList.toggle("active", playingTorsion);
$("playTorsion").textContent = playingTorsion
? "Pause twist"
: "Animate twist";
});
$("resetCamera").addEventListener("click", () => {
orbit.radius = defaultOrbit.radius;
orbit.theta = defaultOrbit.theta;
orbit.phi = defaultOrbit.phi;
applyCamera();
});
$("resetLab").addEventListener("click", () => {
torsions.fill(0);
playingTorsion = false;
$("playTorsion").classList.remove("active");
$("playTorsion").textContent = "Animate twist";
orbit.radius = defaultOrbit.radius;
orbit.theta = defaultOrbit.theta;
orbit.phi = defaultOrbit.phi;
applyCamera();
selectGeometry("planar");
selectArm(0);
setMode("camera");
});
$("showGuides").addEventListener("change", () => {
updateAngleArc();
updateTwistRing();
});
// ---------------------------------------------------------------------
// Direct pointer controls: camera orbit vs. internal torsion
// ---------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let drag = null;
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;
}
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", (event) => {
event.preventDefault();
canvas.setPointerCapture(event.pointerId);
const useCamera =
interactionMode === "camera" || event.button === 2 || event.button === 1;
if (useCamera) {
drag = {
type: "camera",
x: event.clientX,
y: event.clientY,
theta: orbit.theta,
phi: orbit.phi
};
canvas.classList.add("camera-dragging");
return;
}
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(atomMeshes, false)[0];
if (!hit) return;
const { role, arm } = hit.object.userData;
if (role === "proximal" || role === "distal") {
selectArm(arm);
if (role === "distal") {
drag = {
type: "torsion",
arm,
lastX: event.clientX
};
}
}
});
canvas.addEventListener("pointermove", (event) => {
if (!drag) return;
if (drag.type === "camera") {
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
orbit.theta = drag.theta - dx * 0.006;
orbit.phi = drag.phi - dy * 0.006;
applyCamera();
} else if (drag.type === "torsion") {
const dx = event.clientX - drag.lastX;
drag.lastX = event.clientX;
torsions[drag.arm] =
((torsions[drag.arm] + dx * 0.75) % 360 + 360) % 360;
updateMolecule();
}
});
function endDrag(event) {
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
drag = null;
canvas.classList.remove("camera-dragging");
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius += event.deltaY * 0.006;
applyCamera();
},
{ passive: false }
);
// ---------------------------------------------------------------------
// Screen-space labels
// ---------------------------------------------------------------------
const projected = new THREE.Vector3();
function positionLabel(element, worldPosition, visible = true) {
projected.copy(worldPosition).project(camera);
const inFront = projected.z > -1 && projected.z < 1;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
element.style.opacity = visible && inFront ? "1" : "0";
}
function updateLabels() {
for (const entry of labelEntries) {
const world = entry.mesh.getWorldPosition(new THREE.Vector3());
world.y += entry.mesh.userData.role === "center" ? 0.55 : 0.43;
positionLabel(entry.element, world);
}
if (!angleTag.hidden) {
const world = new THREE.Vector3(
Number(angleTag.dataset.worldX),
Number(angleTag.dataset.worldY),
Number(angleTag.dataset.worldZ)
);
world.y += 0.08;
positionLabel(angleTag, world);
}
}
// ---------------------------------------------------------------------
// Resize and animation loop
// ---------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (transition) {
transition.elapsed += dt;
const t = Math.min(transition.elapsed / transition.duration, 1);
const eased = t * t * (3 - 2 * t);
for (let i = 0; i < 3; i++) {
currentDirections[i]
.lerpVectors(transition.from[i], transition.to[i], eased)
.normalize();
}
if (t >= 1) transition = null;
}
if (playingTorsion && interactionMode === "internal") {
torsions[selectedArm] =
((torsions[selectedArm] + dt * 26) % 360 + 360) % 360;
}
updateMolecule();
updateLabels();
renderer.render(scene, camera);
}
updateMolecule();
updateLabels();
animate();
</script>
</body>
</html>
```