Prompt specification
Build or customize the Three.js 3D scene "Metal lattice and electron-gas schematic" 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: Metal lattice and electron-gas schematic
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/metal-lattice-and-electron-gas-schematic-x1957
Scene Description Prompt:
Make a cutaway Three.js scene in a self-contained HTML file using cdnjs: metal lattice and electron-gas schematic. Build a regular array of ion-core proxies with a translucent delocalized-electron region; label the representation conceptual and avoid depicting electrons as stationary particles owned by one atom.
Working Three.js Starter (metal-lattice-and-electron-gas-schematic-x1957):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Metal Lattice and Delocalized Electron Density</title>
<style>
:root {
color-scheme: dark;
--bg: #06101b;
--panel: rgba(8, 20, 33, 0.76);
--line: rgba(160, 212, 235, 0.18);
--text: #e8f4fb;
--muted: #9db2c1;
--cyan: #66e6f2;
--blue: #6487ff;
--gold: #f4b65f;
--orange: #ff9a68;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 52% 42%, #10283a 0%, #081521 42%, #040b13 100%);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
color: var(--text);
}
canvas {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
#leaders {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
z-index: 3;
overflow: visible;
pointer-events: none;
}
#leaders line {
stroke: rgba(183, 225, 240, 0.58);
stroke-width: 1;
stroke-dasharray: 3 4;
}
#leaders circle {
fill: #dffbff;
stroke: rgba(89, 221, 235, 0.6);
stroke-width: 5;
paint-order: stroke;
}
.masthead {
position: fixed;
z-index: 5;
top: 24px;
left: 28px;
width: min(450px, calc(100vw - 56px));
pointer-events: none;
}
.eyebrow {
margin-bottom: 9px;
color: var(--cyan);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(24px, 3vw, 39px);
font-weight: 620;
line-height: 1.06;
letter-spacing: -0.035em;
text-wrap: balance;
}
.subtitle {
max-width: 410px;
margin: 12px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.status {
position: fixed;
z-index: 6;
top: 25px;
right: 27px;
display: flex;
align-items: center;
gap: 9px;
padding: 9px 12px;
border: 1px solid rgba(108, 222, 237, 0.25);
border-radius: 999px;
background: rgba(5, 16, 28, 0.68);
color: #b8d8e5;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.14em;
text-transform: uppercase;
backdrop-filter: blur(10px);
pointer-events: none;
}
.status::before {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
content: "";
}
.callout {
position: fixed;
z-index: 4;
top: 0;
left: 0;
width: 220px;
padding: 11px 12px 12px;
border: 1px solid rgba(175, 218, 237, 0.19);
border-radius: 9px;
background: rgba(5, 16, 28, 0.82);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(12px);
pointer-events: none;
will-change: transform;
}
.callout-head {
display: flex;
align-items: center;
gap: 8px;
color: #e9f8ff;
font-size: 11px;
font-weight: 700;
line-height: 1.25;
}
.callout-head .index {
display: grid;
flex: 0 0 22px;
width: 22px;
height: 22px;
place-items: center;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 50%;
color: var(--cyan);
font-size: 9px;
font-variant-numeric: tabular-nums;
}
.callout p {
margin: 8px 0 0 30px;
color: #9fb5c4;
font-size: 10px;
line-height: 1.48;
}
#label-ion .index {
color: var(--gold);
}
#label-cut .index {
color: var(--orange);
}
.legend {
position: fixed;
z-index: 5;
top: 83px;
right: 27px;
width: 286px;
padding: 17px;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--panel);
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(14px);
pointer-events: none;
}
.legend-title {
margin-bottom: 13px;
color: #d9eaf3;
font-size: 10px;
font-weight: 760;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.legend-row {
display: grid;
grid-template-columns: 30px 1fr;
gap: 10px;
align-items: center;
margin: 11px 0;
}
.legend-symbol {
position: relative;
display: grid;
width: 30px;
height: 30px;
place-items: center;
}
.ion-symbol {
width: 13px;
height: 13px;
border-radius: 50%;
background: radial-gradient(circle at 35% 30%, #fff0bd, #e8a64f 50%, #7b451c);
box-shadow: 0 0 13px rgba(244, 182, 95, 0.35);
}
.density-symbol {
width: 25px;
height: 25px;
border-radius: 50%;
background:
radial-gradient(circle at 38% 38%, rgba(153, 255, 246, 0.8), transparent 38%),
radial-gradient(circle, rgba(75, 143, 255, 0.65), rgba(40, 200, 224, 0.08) 68%);
box-shadow: inset 0 0 10px rgba(112, 227, 255, 0.4);
}
.cut-symbol {
width: 25px;
height: 18px;
border: 1px solid rgba(255, 154, 104, 0.8);
background: rgba(255, 154, 104, 0.13);
transform: skewY(-12deg);
}
.legend-row b {
display: block;
margin-bottom: 3px;
color: #dbeaf2;
font-size: 11px;
font-weight: 650;
}
.legend-row small {
display: block;
color: #8fa7b8;
font-size: 9px;
line-height: 1.4;
}
.notice {
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid rgba(169, 211, 230, 0.13);
color: #9db3c2;
font-size: 10px;
line-height: 1.52;
}
.notice strong {
color: #d7e9f2;
font-weight: 650;
}
.controls {
position: fixed;
z-index: 7;
right: 27px;
bottom: 22px;
display: flex;
align-items: center;
gap: 13px;
color: #829baa;
font-size: 10px;
pointer-events: none;
}
.controls kbd {
padding: 3px 5px;
border: 1px solid rgba(164, 206, 225, 0.18);
border-radius: 4px;
background: rgba(10, 24, 37, 0.68);
color: #b6cad6;
font: inherit;
}
#reset {
padding: 8px 12px;
border: 1px solid rgba(113, 218, 233, 0.24);
border-radius: 7px;
background: rgba(7, 20, 32, 0.82);
color: #c8eaf1;
font: inherit;
font-weight: 650;
cursor: pointer;
pointer-events: auto;
}
#reset:hover {
border-color: rgba(113, 218, 233, 0.55);
background: rgba(12, 34, 48, 0.94);
}
@media (max-width: 800px) {
.masthead {
top: 18px;
left: 18px;
width: calc(100vw - 36px);
}
.subtitle {
max-width: 330px;
font-size: 11px;
}
.status {
top: auto;
right: 18px;
bottom: 20px;
}
.legend {
top: auto;
right: 18px;
bottom: 66px;
width: min(310px, calc(100vw - 36px));
padding: 12px 14px;
}
.legend-row {
display: none;
}
.legend-title {
margin-bottom: 7px;
}
.notice {
margin-top: 0;
padding-top: 0;
border-top: 0;
font-size: 9px;
}
.controls {
display: none;
}
.callout {
width: 190px;
}
.callout p {
display: none;
}
}
@media (max-width: 520px) {
h1 {
max-width: 330px;
font-size: 25px;
}
.subtitle {
display: none;
}
.callout {
width: 165px;
padding: 8px 9px;
}
.callout-head {
font-size: 9px;
}
.callout-head .index {
flex-basis: 18px;
width: 18px;
height: 18px;
}
}
</style>
</head>
<body>
<canvas
id="scene"
aria-label="Interactive conceptual cutaway of a metallic lattice surrounded by a continuous delocalized electron-density field."
></canvas>
<svg id="leaders" aria-hidden="true">
<g>
<line id="line-density"></line>
<circle id="dot-density" r="3"></circle>
</g>
<g>
<line id="line-ion"></line>
<circle id="dot-ion" r="3"></circle>
</g>
<g>
<line id="line-cut"></line>
<circle id="dot-cut" r="3"></circle>
</g>
</svg>
<header class="masthead">
<div class="eyebrow">Conceptual materials model / 01</div>
<h1>Metal lattice &<br>delocalized electron density</h1>
<p class="subtitle">
A cutaway schematic of a metallic solid. The continuous teal field represents
electron density extending through the lattice—not a collection of point
electrons assigned to individual atoms.
</p>
</header>
<div class="status">Conceptual · Not to scale</div>
<div id="label-density" class="callout">
<div class="callout-head">
<span class="index">01</span>
<span>Delocalized electron density</span>
</div>
<p>
A continuous electron-gas field fills the occupied region of the lattice.
Its texture is illustrative, not a trajectory map.
</p>
</div>
<div id="label-ion" class="callout">
<div class="callout-head">
<span class="index">02</span>
<span>Positive ion-core proxies</span>
</div>
<p>
The regular spheres represent positively charged lattice centers. Their
size and metallic appearance are symbolic.
</p>
</div>
<div id="label-cut" class="callout">
<div class="callout-head">
<span class="index">03</span>
<span>Cutaway section</span>
</div>
<p>
One corner is removed to expose the interior arrangement and the
spatial relationship between ion cores and the density field.
</p>
</div>
<aside class="legend">
<div class="legend-title">Reading the representation</div>
<div class="legend-row">
<div class="legend-symbol"><span class="ion-symbol"></span></div>
<div>
<b>Ion-core proxy</b>
<small>Positive lattice centers; size is not physical.</small>
</div>
</div>
<div class="legend-row">
<div class="legend-symbol"><span class="density-symbol"></span></div>
<div>
<b>Electron-gas schematic</b>
<small>Continuous density spread across the occupied region.</small>
</div>
</div>
<div class="legend-row">
<div class="legend-symbol"><span class="cut-symbol"></span></div>
<div>
<b>Section surface</b>
<small>A visual aid for revealing the interior.</small>
</div>
</div>
<div class="notice">
<strong>Interpretive note:</strong> no electron dots, atom-owned electron
shells, or literal electron paths are shown. The rods clarify lattice
positions only. Slow animation indicates a continuous density texture,
not the motion of discrete particles.
</div>
</aside>
<div class="controls">
<span><kbd>Drag</kbd> orbit</span>
<span><kbd>Shift / right-drag</kbd> pan</span>
<span><kbd>Scroll / pinch</kbd> zoom</span>
<button id="reset" type="button">Reset view</button>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x06101b);
scene.fog = new THREE.FogExp2(0x06101b, 0.022);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
80
);
// Custom camera controls: spherical orbit, target pan, and dolly zoom.
const defaultTarget = new THREE.Vector3(0, -0.15, 0);
const defaultSpherical = new THREE.Spherical(13.8, 1.02, 0.72);
const goalTarget = defaultTarget.clone();
const goalSpherical = defaultSpherical.clone();
const currentTarget = defaultTarget.clone();
const currentSpherical = defaultSpherical.clone();
camera.position.setFromSpherical(currentSpherical).add(currentTarget);
camera.lookAt(currentTarget);
camera.updateMatrixWorld();
// Lighting.
scene.add(new THREE.HemisphereLight(0xb8e9ff, 0x08111a, 1.45));
const keyLight = new THREE.DirectionalLight(0xfff2dc, 3.2);
keyLight.position.set(7, 11, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x42dce9, 22, 18, 2);
cyanLight.position.set(-5, 2, 4);
scene.add(cyanLight);
const warmLight = new THREE.PointLight(0xffad58, 16, 14, 2);
warmLight.position.set(5, 1, -3);
scene.add(warmLight);
// Ground and measurement-like grid.
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(44, 44),
new THREE.MeshStandardMaterial({
color: 0x07121c,
roughness: 0.92,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -3.42;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(30, 30, 0x2d6572, 0x17313f);
grid.position.y = -3.4;
grid.material.transparent = true;
grid.material.opacity = 0.28;
scene.add(grid);
// A low plinth gives the specimen a visual base.
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(8.75, 0.16, 6.75),
new THREE.MeshStandardMaterial({
color: 0x0b1c28,
metalness: 0.45,
roughness: 0.56
})
);
plinth.position.y = -3.22;
plinth.receiveShadow = true;
plinth.castShadow = true;
scene.add(plinth);
const plinthEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(plinth.geometry),
new THREE.LineBasicMaterial({
color: 0x315563,
transparent: true,
opacity: 0.5
})
);
plinthEdges.position.copy(plinth.position);
scene.add(plinthEdges);
// Regular lattice positions.
const xs = [-3, -1.5, 0, 1.5, 3];
const ys = [-2.25, -0.75, 0.75, 2.25];
const zs = [-2.25, -0.75, 0.75, 2.25];
const lattice = new Map();
const nodeList = [];
for (let ix = 0; ix < xs.length; ix++) {
for (let iy = 0; iy < ys.length; iy++) {
for (let iz = 0; iz < zs.length; iz++) {
// Remove a near upper-right corner to form the cutaway.
const removedCorner =
ix >= 3 && iy >= 2 && iz >= 2;
if (removedCorner) continue;
const key = `${ix},${iy},${iz}`;
const node = {
key,
ix,
iy,
iz,
position: new THREE.Vector3(xs[ix], ys[iy], zs[iz])
};
lattice.set(key, node);
nodeList.push(node);
}
}
}
// Ion-core proxies: equal-sized spheres in a regular array.
const ionGeometry = new THREE.SphereGeometry(0.245, 22, 16);
const ionMaterial = new THREE.MeshPhysicalMaterial({
color: 0xf2b35f,
emissive: 0x321404,
emissiveIntensity: 0.28,
metalness: 0.72,
roughness: 0.25,
clearcoat: 0.55,
clearcoatRoughness: 0.24
});
const ions = new THREE.InstancedMesh(
ionGeometry,
ionMaterial,
nodeList.length
);
ions.castShadow = true;
ions.receiveShadow = true;
const matrix = new THREE.Matrix4();
nodeList.forEach((node, index) => {
matrix.makeTranslation(
node.position.x,
node.position.y,
node.position.z
);
ions.setMatrixAt(index, matrix);
});
scene.add(ions);
// Thin rods show the lattice geometry only. They are not electron paths.
const edges = [];
const directions = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
];
for (const node of nodeList) {
for (const [dx, dy, dz] of directions) {
const neighborKey = `${node.ix + dx},${node.iy + dy},${node.iz + dz}`;
const neighbor = lattice.get(neighborKey);
if (!neighbor) continue;
edges.push([
node.position.clone(),
neighbor.position.clone()
]);
}
}
const rodGeometry = new THREE.CylinderGeometry(0.021, 0.021, 1, 7);
const rodMaterial = new THREE.MeshStandardMaterial({
color: 0x56788a,
metalness: 0.82,
roughness: 0.34
});
const rods = new THREE.InstancedMesh(
rodGeometry,
rodMaterial,
edges.length
);
rods.castShadow = true;
const up = new THREE.Vector3(0, 1, 0);
const midpoint = new THREE.Vector3();
const direction = new THREE.Vector3();
const quaternion = new THREE.Quaternion();
edges.forEach(([a, b], index) => {
direction.subVectors(b, a);
const length = direction.length();
midpoint.addVectors(a, b).multiplyScalar(0.5);
quaternion.setFromUnitVectors(up, direction.normalize());
matrix.compose(
midpoint,
quaternion,
new THREE.Vector3(1, length, 1)
);
rods.setMatrixAt(index, matrix);
});
scene.add(rods);
// Transparent section planes emphasize the removed corner.
const sectionMaterial = new THREE.MeshBasicMaterial({
color: 0xff9563,
transparent: true,
opacity: 0.075,
side: THREE.DoubleSide,
depthWrite: false,
blending: THREE.AdditiveBlending
});
const sectionEdgeMaterial = new THREE.LineBasicMaterial({
color: 0xff9d70,
transparent: true,
opacity: 0.5
});
function addSectionPlane(width, height, position, rotation) {
const geometry = new THREE.PlaneGeometry(width, height);
const plane = new THREE.Mesh(geometry, sectionMaterial);
plane.position.copy(position);
plane.rotation.set(...rotation);
plane.renderOrder = 2;
scene.add(plane);
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
sectionEdgeMaterial
);
outline.position.copy(position);
outline.rotation.copy(plane.rotation);
outline.renderOrder = 4;
scene.add(outline);
}
addSectionPlane(
2.75,
2.75,
new THREE.Vector3(0.75, 1.375, 1.375),
[0, Math.PI / 2, 0]
);
addSectionPlane(
3.0,
2.75,
new THREE.Vector3(2.25, 0, 1.375),
[-Math.PI / 2, 0, 0]
);
addSectionPlane(
3.0,
2.75,
new THREE.Vector3(2.25, 1.375, 0),
[0, 0, 0]
);
// Continuous electron-density volume.
// This ray-marched shader contains no point-electron representation.
const volumeBounds = new THREE.Vector3(4.15, 3.15, 3.15);
const cutOrigin = new THREE.Vector3(0.75, 0, 0);
const densityMaterial = new THREE.ShaderMaterial({
uniforms: {
uTime: { value: 0 },
uBounds: { value: volumeBounds },
uCutOrigin: { value: cutOrigin },
uColorLow: { value: new THREE.Color(0x36d7e7) },
uColorHigh: { value: new THREE.Color(0x6478ff) }
},
vertexShader: `
varying vec3 vWorldPosition;
void main() {
vec4 worldPosition = modelMatrix * vec4(position, 1.0);
vWorldPosition = worldPosition.xyz;
gl_Position = projectionMatrix * viewMatrix * worldPosition;
}
`,
fragmentShader: `
precision highp float;
uniform float uTime;
uniform vec3 uBounds;
uniform vec3 uCutOrigin;
uniform vec3 uColorLow;
uniform vec3 uColorHigh;
varying vec3 vWorldPosition;
vec2 intersectBox(vec3 rayOrigin, vec3 rayDirection, vec3 bounds) {
vec3 inverseDirection = 1.0 / rayDirection;
vec3 t0 = (-bounds - rayOrigin) * inverseDirection;
vec3 t1 = ( bounds - rayOrigin) * inverseDirection;
vec3 tSmall = min(t0, t1);
vec3 tBig = max(t0, t1);
float nearT = max(max(tSmall.x, tSmall.y), tSmall.z);
float farT = min(min(tBig.x, tBig.y), tBig.z);
return vec2(nearT, farT);
}
void main() {
vec3 rayOrigin = cameraPosition;
vec3 rayDirection = normalize(vWorldPosition - rayOrigin);
vec2 hit = intersectBox(rayOrigin, rayDirection, uBounds);
float entryT = max(hit.x, 0.0);
float exitT = hit.y;
if (exitT <= entryT) discard;
float stepLength = (exitT - entryT) / 32.0;
vec4 accumulated = vec4(0.0);
vec3 sampledColor = vec3(0.0);
for (int i = 0; i < 32; i++) {
float t = entryT + (float(i) + 0.5) * stepLength;
vec3 p = rayOrigin + rayDirection * t;
// Match the visual cutaway: omit density from the removed octant.
float cutMask =
step(uCutOrigin.x, p.x) *
step(uCutOrigin.y, p.y) *
step(uCutOrigin.z, p.z);
vec3 flow = p;
flow.x += 0.13 * sin(p.y * 1.15 + uTime * 0.18);
flow.z += 0.10 * sin(p.x * 1.4 - uTime * 0.15);
float broad =
sin(flow.x * 1.55 + uTime * 0.19) *
sin(flow.y * 1.85 - uTime * 0.14) *
sin(flow.z * 1.65 + uTime * 0.12);
float detail =
sin((flow.x + flow.z) * 3.15 - uTime * 0.22) *
sin(flow.y * 3.45 + uTime * 0.17);
float density = 0.49 + broad * 0.34 + detail * 0.17;
density = smoothstep(0.08, 0.92, density);
density *= 1.0 - cutMask;
vec3 normalizedPosition = abs(p) / uBounds;
float edgeDistance = max(
max(normalizedPosition.x, normalizedPosition.y),
normalizedPosition.z
);
float edgeFade = 1.0 - smoothstep(0.72, 1.0, edgeDistance);
density *= edgeFade;
float colorMix = clamp(
0.5 + 0.5 * sin(flow.y * 0.8 + flow.x * 0.18),
0.0,
1.0
);
vec3 localColor = mix(uColorLow, uColorHigh, colorMix);
float sampleAlpha = 1.0 - exp(-density * stepLength * 1.35);
accumulated.rgb +=
(1.0 - accumulated.a) * localColor * sampleAlpha;
accumulated.a +=
(1.0 - accumulated.a) * sampleAlpha;
}
vec3 finalColor = accumulated.rgb / max(accumulated.a, 0.001);
float finalAlpha = accumulated.a * 0.40;
gl_FragColor = vec4(finalColor, finalAlpha);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}
`,
transparent: true,
depthWrite: false,
depthTest: false,
side: THREE.BackSide,
blending: THREE.NormalBlending
});
const densityVolume = new THREE.Mesh(
new THREE.BoxGeometry(
volumeBounds.x * 2,
volumeBounds.y * 2,
volumeBounds.z * 2
),
densityMaterial
);
densityVolume.renderOrder = 5;
scene.add(densityVolume);
// A faint dashed envelope makes the conceptual occupied region legible.
const envelopeGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(
volumeBounds.x * 2,
volumeBounds.y * 2,
volumeBounds.z * 2
)
);
const envelope = new THREE.LineSegments(
envelopeGeometry,
new THREE.LineDashedMaterial({
color: 0x67c9d8,
transparent: true,
opacity: 0.19,
dashSize: 0.16,
gapSize: 0.13,
depthWrite: false
})
);
envelope.computeLineDistances();
envelope.renderOrder = 6;
scene.add(envelope);
// HTML annotations anchored to 3D positions.
const annotationDefinitions = [
{
element: document.querySelector("#label-density"),
line: document.querySelector("#line-density"),
dot: document.querySelector("#dot-density"),
anchor: new THREE.Vector3(-0.1, 2.65, -1.85),
offset: [-70, -112]
},
{
element: document.querySelector("#label-ion"),
line: document.querySelector("#line-ion"),
dot: document.querySelector("#dot-ion"),
anchor: new THREE.Vector3(-2.0, 0.75, 2.15),
offset: [-75, 58]
},
{
element: document.querySelector("#label-cut"),
line: document.querySelector("#line-cut"),
dot: document.querySelector("#dot-cut"),
anchor: new THREE.Vector3(0.82, 0.02, 1.25),
offset: [78, 44]
}
];
const projected = new THREE.Vector3();
function updateAnnotations() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const item of annotationDefinitions) {
projected.copy(item.anchor).project(camera);
const anchorX = (projected.x * 0.5 + 0.5) * width;
const anchorY = (-projected.y * 0.5 + 0.5) * height;
const visible =
projected.z > -1 &&
projected.z < 1 &&
anchorX > -60 &&
anchorX < width + 60 &&
anchorY > -60 &&
anchorY < height + 60;
item.element.style.visibility = visible ? "visible" : "hidden";
item.line.style.visibility = visible ? "visible" : "hidden";
item.dot.style.visibility = visible ? "visible" : "hidden";
if (!visible) continue;
const rect = item.element.getBoundingClientRect();
const left = THREE.MathUtils.clamp(
anchorX + item.offset[0],
12,
Math.max(12, width - rect.width - 12)
);
const top = THREE.MathUtils.clamp(
anchorY + item.offset[1],
12,
Math.max(12, height - rect.height - 12)
);
item.element.style.transform =
`translate(${left.toFixed(1)}px, ${top.toFixed(1)}px)`;
const lineEndX =
left > anchorX ? left : left + rect.width;
const lineEndY = top + rect.height * 0.5;
item.line.setAttribute("x1", anchorX.toFixed(1));
item.line.setAttribute("y1", anchorY.toFixed(1));
item.line.setAttribute("x2", lineEndX.toFixed(1));
item.line.setAttribute("y2", lineEndY.toFixed(1));
item.dot.setAttribute("cx", anchorX.toFixed(1));
item.dot.setAttribute("cy", anchorY.toFixed(1));
}
}
// Mouse and touch camera controls implemented directly.
const pointers = new Map();
let primaryPointerId = null;
let primaryMode = "orbit";
let previousPinchDistance = 0;
const cameraRight = new THREE.Vector3();
const cameraUp = new THREE.Vector3();
function pointerDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
function panCamera(deltaX, deltaY) {
camera.updateMatrixWorld();
cameraRight.setFromMatrixColumn(camera.matrixWorld, 0);
cameraUp.setFromMatrixColumn(camera.matrixWorld, 1);
const scale = goalSpherical.radius * 0.00125;
goalTarget.addScaledVector(
cameraRight,
-deltaX * scale
);
goalTarget.addScaledVector(
cameraUp,
deltaY * scale
);
}
canvas.addEventListener("contextmenu", event => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
primaryPointerId = event.pointerId;
primaryMode =
event.button === 2 || event.shiftKey ? "pan" : "orbit";
} else if (pointers.size === 2) {
previousPinchDistance = pointerDistance();
}
});
canvas.addEventListener("pointermove", event => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const deltaX = event.clientX - previous.x;
const deltaY = event.clientY - previous.y;
previous.x = event.clientX;
previous.y = event.clientY;
if (pointers.size === 1 && event.pointerId === primaryPointerId) {
if (primaryMode === "pan") {
panCamera(deltaX, deltaY);
} else {
goalSpherical.theta -= deltaX * 0.005;
goalSpherical.phi = THREE.MathUtils.clamp(
goalSpherical.phi + deltaY * 0.005,
0.22,
Math.PI - 0.22
);
}
} else if (pointers.size === 2) {
const distance = pointerDistance();
if (previousPinchDistance > 0 && distance > 0) {
goalSpherical.radius = THREE.MathUtils.clamp(
goalSpherical.radius *
(previousPinchDistance / distance),
7.2,
24
);
}
previousPinchDistance = distance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (event.pointerId === primaryPointerId) {
primaryPointerId = null;
}
if (pointers.size === 2) {
previousPinchDistance = pointerDistance();
} else {
previousPinchDistance = 0;
}
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener(
"wheel",
event => {
event.preventDefault();
goalSpherical.radius = THREE.MathUtils.clamp(
goalSpherical.radius * Math.exp(event.deltaY * 0.001),
7.2,
24
);
},
{ passive: false }
);
function resetView() {
goalTarget.copy(defaultTarget);
goalSpherical.copy(defaultSpherical);
}
canvas.addEventListener("dblclick", resetView);
document.querySelector("#reset").addEventListener("click", resetView);
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 elapsed = clock.getElapsedTime();
densityMaterial.uniforms.uTime.value = elapsed;
// Gentle damping for the direct camera controls.
currentTarget.lerp(goalTarget, 0.11);
currentSpherical.radius = THREE.MathUtils.lerp(
currentSpherical.radius,
goalSpherical.radius,
0.11
);
currentSpherical.theta = THREE.MathUtils.lerp(
currentSpherical.theta,
goalSpherical.theta,
0.11
);
currentSpherical.phi = THREE.MathUtils.lerp(
currentSpherical.phi,
goalSpherical.phi,
0.11
);
camera.position.setFromSpherical(currentSpherical).add(currentTarget);
camera.lookAt(currentTarget);
camera.updateMatrixWorld();
updateAnnotations();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```