Prompt specification
Build or customize the Three.js 3D scene "Folded-box surface path demonstration" 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: Folded-box surface path demonstration
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/folded-box-surface-path-demonstration-x1698
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring shortest paths constrained to surfaces. Show a path across adjacent box faces and an unfolded net revealing its straight-line construction; keep face correspondence and total path length consistent. Stylized solid forms.
Working Three.js Starter (folded-box-surface-path-demonstration-x1698):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Surface Shortest Path — Box Unfolding</title>
<style>
:root {
--ink: #17272d;
--muted: #64737a;
--paper: #f2efe7;
--panel: rgba(255, 255, 255, 0.88);
--line: rgba(23, 39, 45, 0.12);
--front: #78a9d4;
--top: #eda65e;
--path: #ffc83d;
--a: #e75687;
--b: #10aaa2;
--e: #765cff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
canvas {
position: fixed;
inset: 0;
display: block;
touch-action: none;
}
.hud {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
}
.topbar {
position: absolute;
top: 24px;
left: 28px;
right: 28px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
}
.eyebrow {
margin-bottom: 7px;
color: #6d777b;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(23px, 3vw, 40px);
font-weight: 760;
letter-spacing: -0.045em;
line-height: 1;
}
.subtitle {
margin-top: 9px;
color: var(--muted);
font-size: 13px;
}
.controls {
display: flex;
gap: 8px;
pointer-events: auto;
}
button {
min-height: 38px;
padding: 0 14px;
border: 1px solid rgba(23, 39, 45, 0.14);
border-radius: 12px;
background: rgba(255, 255, 255, 0.82);
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
box-shadow: 0 7px 22px rgba(28, 39, 42, 0.07);
backdrop-filter: blur(10px);
transition:
transform 150ms ease,
background 150ms ease;
}
button:hover {
transform: translateY(-1px);
background: #fff;
}
button:focus-visible {
outline: 3px solid rgba(118, 92, 255, 0.3);
outline-offset: 2px;
}
.legend {
position: absolute;
top: 128px;
left: 28px;
display: flex;
flex-wrap: wrap;
gap: 8px 15px;
max-width: 520px;
color: #536168;
font-size: 11px;
font-weight: 650;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 11px;
height: 11px;
border-radius: 4px;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.swatch.front {
background: var(--front);
}
.swatch.top {
background: var(--top);
}
.swatch.edge {
height: 3px;
border-radius: 3px;
background: var(--e);
}
.swatch.path {
height: 4px;
border-radius: 4px;
background: var(--path);
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
}
.dot.a {
background: var(--a);
}
.dot.b {
background: var(--b);
}
.dot.e {
background: var(--e);
}
.stats {
position: absolute;
left: 50%;
bottom: 22px;
width: min(930px, calc(100% - 32px));
transform: translateX(-50%);
padding: 14px 16px 12px;
border: 1px solid rgba(23, 39, 45, 0.11);
border-radius: 20px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(38, 46, 47, 0.13);
backdrop-filter: blur(18px);
}
.metrics {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
}
.metric {
min-width: 0;
padding: 4px 12px;
border-right: 1px solid var(--line);
}
.metric:last-child {
border-right: 0;
}
.metric-label {
display: block;
margin-bottom: 3px;
color: #718087;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.metric strong {
display: block;
font-size: clamp(18px, 2.2vw, 26px);
font-weight: 760;
letter-spacing: -0.04em;
white-space: nowrap;
}
.metric strong small {
margin-left: 3px;
color: #758289;
font-size: 10px;
font-weight: 700;
letter-spacing: 0;
}
.proof {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid var(--line);
color: #4f6067;
font-size: 11px;
}
.proof-title {
flex: 0 0 auto;
color: #202f35;
font-weight: 800;
}
.equation {
flex: 1;
text-align: center;
font-variant-numeric: tabular-nums;
}
.match {
flex: 0 0 auto;
padding: 5px 9px;
border-radius: 999px;
background: rgba(16, 170, 162, 0.12);
color: #087b75;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.hint {
position: absolute;
right: 28px;
bottom: 150px;
color: rgba(54, 70, 76, 0.72);
font-size: 10px;
font-weight: 650;
text-align: right;
}
@media (max-width: 760px) {
.topbar {
top: 17px;
left: 17px;
right: 17px;
}
.subtitle {
max-width: 230px;
font-size: 11px;
}
.controls {
flex-direction: column;
}
button {
min-height: 34px;
padding: 0 11px;
font-size: 10px;
}
.legend {
top: 113px;
left: 17px;
gap: 6px 11px;
font-size: 9px;
}
.stats {
bottom: 12px;
padding: 12px;
}
.metrics {
grid-template-columns: repeat(2, 1fr);
gap: 7px 0;
}
.metric:nth-child(2) {
border-right: 0;
}
.metric {
padding: 3px 9px;
}
.proof {
align-items: flex-start;
flex-wrap: wrap;
}
.equation {
order: 3;
flex-basis: 100%;
text-align: left;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div class="hud">
<header class="topbar">
<div>
<div class="eyebrow">Surface Geometry / 01</div>
<h1>Shortest path on a box</h1>
<div class="subtitle">
One route, two representations: folded across adjacent faces, straight on the net.
</div>
</div>
<div class="controls">
<button id="resetView" type="button">Reset view</button>
<button id="toggleMotion" type="button" aria-pressed="true">
Pause trace
</button>
</div>
</header>
<div class="legend" aria-label="Scene legend">
<span><i class="swatch front"></i>Front face</span>
<span><i class="swatch top"></i>Top face</span>
<span><i class="swatch edge"></i>Shared fold edge</span>
<span><i class="swatch path"></i>Surface path</span>
<span><i class="dot a"></i>A</span>
<span><i class="dot e"></i>E</span>
<span><i class="dot b"></i>B</span>
</div>
<section class="stats" aria-label="Path length measurements">
<div class="metrics">
<div class="metric">
<span class="metric-label">Folded surface route</span>
<strong><span id="foldedValue">0.000</span><small>units</small></strong>
</div>
<div class="metric">
<span class="metric-label">Front · |AE|</span>
<strong><span id="frontValue">0.000</span><small>units</small></strong>
</div>
<div class="metric">
<span class="metric-label">Top · |EB|</span>
<strong><span id="topValue">0.000</span><small>units</small></strong>
</div>
<div class="metric">
<span class="metric-label">Unfolded · |AB|</span>
<strong><span id="netValue">0.000</span><small>units</small></strong>
</div>
</div>
<div class="proof">
<span class="proof-title">Length-preserving unfolding</span>
<span class="equation" id="equation"></span>
<span class="match" id="matchStatus" aria-live="polite">Checking…</span>
</div>
</section>
<div class="hint">
Drag to orbit · Shift/right-drag to pan · Scroll to zoom<br />
The white tracer follows the same arc length in both views.
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Shared geometry. Both representations are derived from these definitions.
// -------------------------------------------------------------------------
const W = 4.2; // Box width: x
const H = 2.4; // Box height: y
const D = 3.0; // Box depth: z
const COLORS = {
front: 0x78a9d4,
top: 0xeda65e,
side: 0x88ae9f,
bottom: 0x9ba8b5,
back: 0xc58b78,
path: 0xffc83d,
a: 0xe75687,
e: 0x765cff,
b: 0x10aaa2,
edge: 0x765cff
};
// A is on the front face. B is on the top face.
const start = {
x: -1.45,
netV: 0.45
};
const end = {
x: 1.25,
z: 0.65
};
// Net coordinates:
// Front face: v = 0 ... H
// Top face: v = H ... H + D
const netA2 = new THREE.Vector2(start.x, start.netV);
const netB2 = new THREE.Vector2(
end.x,
H + (D / 2 - end.z)
);
// E is where the straight net segment crosses the shared fold edge.
const edgeT = (H - netA2.y) / (netB2.y - netA2.y);
const netE2 = netA2.clone().lerp(netB2, edgeT);
// Exact folded-box positions on the two surface planes.
const foldedA = new THREE.Vector3(
start.x,
start.netV - H / 2,
D / 2
);
const foldedE = new THREE.Vector3(
netE2.x,
H / 2,
D / 2
);
const foldedB = new THREE.Vector3(
end.x,
H / 2,
end.z
);
// Net positions use a tiny z offset only to prevent surface z-fighting.
const netA = new THREE.Vector3(netA2.x, netA2.y, 0.115);
const netE = new THREE.Vector3(netE2.x, netE2.y, 0.115);
const netB = new THREE.Vector3(netB2.x, netB2.y, 0.115);
const frontLength = foldedA.distanceTo(foldedE);
const topLength = foldedE.distanceTo(foldedB);
const foldedTotal = frontLength + topLength;
const netTotal = netA.distanceTo(netB);
const netFrontLength = netA.distanceTo(netE);
const netTopLength = netE.distanceTo(netB);
const lengthsMatch =
Math.abs(foldedTotal - netTotal) < 1e-10 &&
Math.abs(frontLength - netFrontLength) < 1e-10 &&
Math.abs(topLength - netTopLength) < 1e-10;
console.assert(lengthsMatch, "Folded and unfolded path lengths must agree.");
document.querySelector("#foldedValue").textContent = foldedTotal.toFixed(3);
document.querySelector("#frontValue").textContent = frontLength.toFixed(3);
document.querySelector("#topValue").textContent = topLength.toFixed(3);
document.querySelector("#netValue").textContent = netTotal.toFixed(3);
document.querySelector("#equation").textContent =
`|AE| + |EB| = ${frontLength.toFixed(3)} + ` +
`${topLength.toFixed(3)} = ${foldedTotal.toFixed(3)} = |AB|`;
const matchStatus = document.querySelector("#matchStatus");
if (lengthsMatch) {
matchStatus.textContent = "Length match ✓";
matchStatus.style.background = "rgba(16,170,162,.12)";
matchStatus.style.color = "#087b75";
} else {
matchStatus.textContent = "Mismatch";
matchStatus.style.background = "rgba(231,86,135,.12)";
matchStatus.style.color = "#a72e5c";
}
// -------------------------------------------------------------------------
// Renderer, camera, lighting.
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf2efe7);
scene.fog = new THREE.Fog(0xf2efe7, 20, 42);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D box and unfolded net showing an equal-length shortest surface path"
);
document.body.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(
0xffffff,
0xb8b3a8,
2.1
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-7, 12, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 15;
keyLight.shadow.camera.bottom = -15;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.00035;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xbcd9ff, 1.1);
fillLight.position.set(10, 4, -8);
scene.add(fillLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({
color: 0xe8e4da,
roughness: 0.95,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -1.42;
floor.receiveShadow = true;
scene.add(floor);
// -------------------------------------------------------------------------
// Reusable materials and geometry helpers.
// -------------------------------------------------------------------------
const standard = (color, extra = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0,
...extra
});
const pathMaterial = standard(COLORS.path, {
roughness: 0.42,
emissive: 0x5b3900,
emissiveIntensity: 0.2
});
const foldMaterial = standard(COLORS.edge, {
roughness: 0.4,
emissive: 0x28138a,
emissiveIntensity: 0.25
});
const markerMaterials = {
a: standard(COLORS.a, {
emissive: COLORS.a,
emissiveIntensity: 0.18
}),
e: standard(COLORS.e, {
emissive: COLORS.e,
emissiveIntensity: 0.2
}),
b: standard(COLORS.b, {
emissive: COLORS.b,
emissiveIntensity: 0.18
})
};
function cylinderBetween(a, b, radius, material, parent) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, length, 24),
material
);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeTextSprite(text, options = {}) {
const {
foreground = "#17272d",
background = "rgba(255,255,255,.90)",
width = 512,
height = 128,
fontSize = 42
} = options;
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, width, height);
if (background) {
ctx.fillStyle = background;
ctx.fillRect(8, 12, width - 16, height - 24);
}
ctx.fillStyle = foreground;
ctx.font = `800 ${fontSize}px system-ui, sans-serif`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, width / 2, height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
depthTest: options.depthTest ?? false
})
);
sprite.scale.set(
options.scaleX ?? 1.5,
options.scaleY ?? 0.375,
1
);
return sprite;
}
function makeMarker(parent, position, letter, color, labelOffset) {
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.095, 24, 16),
markerMaterials[letter.toLowerCase()]
);
marker.position.copy(position);
marker.castShadow = true;
parent.add(marker);
const label = makeTextSprite(letter, {
foreground: "#ffffff",
background: `#${color.toString(16).padStart(6, "0")}`,
width: 128,
height: 128,
fontSize: 66,
scaleX: 0.42,
scaleY: 0.42,
depthTest: false
});
label.position.copy(position).add(labelOffset);
label.renderOrder = 20;
parent.add(label);
return marker;
}
// -------------------------------------------------------------------------
// Folded solid box.
// -------------------------------------------------------------------------
const folded = new THREE.Group();
folded.position.set(-4.8, 0, 0);
folded.rotation.y = -0.13;
scene.add(folded);
const boxGeometry = new THREE.BoxGeometry(W, H, D);
const boxMaterials = [
standard(COLORS.side), // +x
standard(COLORS.side), // -x
standard(COLORS.top), // +y
standard(COLORS.bottom), // -y
standard(COLORS.front), // +z
standard(COLORS.back) // -z
];
const box = new THREE.Mesh(boxGeometry, boxMaterials);
box.castShadow = true;
box.receiveShadow = true;
folded.add(box);
const boxEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(boxGeometry, 18),
new THREE.LineBasicMaterial({
color: 0x344a52,
transparent: true,
opacity: 0.34
})
);
folded.add(boxEdges);
// Highlight the shared top/front fold edge.
cylinderBetween(
new THREE.Vector3(-W / 2, H / 2, D / 2),
new THREE.Vector3(W / 2, H / 2, D / 2),
0.027,
foldMaterial,
folded
);
// The two exact straight segments on the folded surfaces.
cylinderBetween(foldedA, foldedE, 0.034, pathMaterial, folded);
cylinderBetween(foldedE, foldedB, 0.034, pathMaterial, folded);
makeMarker(
folded,
foldedA,
"A",
COLORS.a,
new THREE.Vector3(-0.16, 0.34, 0.09)
);
makeMarker(
folded,
foldedE,
"E",
COLORS.e,
new THREE.Vector3(0.02, 0.38, 0.1)
);
makeMarker(
folded,
foldedB,
"B",
COLORS.b,
new THREE.Vector3(0.16, 0.35, 0.08)
);
const foldedFrontLabel = makeTextSprite("FRONT / F", {
foreground: "#315b78",
background: "rgba(255,255,255,.76)",
scaleX: 1.28,
scaleY: 0.32
});
foldedFrontLabel.position.set(-1.45, 0.15, D / 2 + 0.045);
folded.add(foldedFrontLabel);
const foldedTopLabel = makeTextSprite("TOP / T", {
foreground: "#8a521d",
background: "rgba(255,255,255,.76)",
scaleX: 1.28,
scaleY: 0.32
});
foldedTopLabel.position.set(-1.45, H / 2 + 0.05, -0.45);
folded.add(foldedTopLabel);
const foldedTitle = makeTextSprite("FOLDED BOX", {
foreground: "#24363d",
background: "rgba(255,255,255,.90)",
fontSize: 39,
scaleX: 2.0,
scaleY: 0.5
});
foldedTitle.position.set(0, H / 2 + 1.25, 0);
folded.add(foldedTitle);
const foldedPedestal = new THREE.Mesh(
new THREE.CylinderGeometry(2.65, 2.78, 0.16, 56),
standard(0xd2cec3)
);
foldedPedestal.position.set(0, -H / 2 - 0.08, 0);
foldedPedestal.castShadow = true;
foldedPedestal.receiveShadow = true;
folded.add(foldedPedestal);
// -------------------------------------------------------------------------
// Unfolded two-face net.
// -------------------------------------------------------------------------
const net = new THREE.Group();
net.position.set(4.7, -H / 2, 0);
net.rotation.y = 0.035;
scene.add(net);
const netFrontMaterial = standard(0xc5dcef);
const netTopMaterial = standard(0xf3d1aa);
const netFrontCard = new THREE.Mesh(
new THREE.BoxGeometry(W, H, 0.16),
netFrontMaterial
);
netFrontCard.position.set(0, H / 2, 0);
netFrontCard.castShadow = true;
netFrontCard.receiveShadow = true;
net.add(netFrontCard);
const netTopCard = new THREE.Mesh(
new THREE.BoxGeometry(W, D, 0.16),
netTopMaterial
);
netTopCard.position.set(0, H + D / 2, 0);
netTopCard.castShadow = true;
netTopCard.receiveShadow = true;
net.add(netTopCard);
function addNetEdges(mesh) {
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
new THREE.LineBasicMaterial({
color: 0x40545c,
transparent: true,
opacity: 0.3
})
);
edges.position.copy(mesh.position);
net.add(edges);
}
addNetEdges(netFrontCard);
addNetEdges(netTopCard);
// Highlight the same fold edge in the unfolded representation.
cylinderBetween(
new THREE.Vector3(-W / 2, H, 0.105),
new THREE.Vector3(W / 2, H, 0.105),
0.026,
foldMaterial,
net
);
// A single unbroken cylinder: the straight-line construction on the net.
cylinderBetween(netA, netB, 0.034, pathMaterial, net);
makeMarker(
net,
netA,
"A",
COLORS.a,
new THREE.Vector3(-0.16, 0.34, 0.07)
);
makeMarker(
net,
netE,
"E",
COLORS.e,
new THREE.Vector3(0.02, 0.38, 0.07)
);
makeMarker(
net,
netB,
"B",
COLORS.b,
new THREE.Vector3(0.16, 0.35, 0.07)
);
const netFrontLabel = makeTextSprite("FRONT / F", {
foreground: "#315b78",
background: "rgba(255,255,255,.72)",
scaleX: 1.28,
scaleY: 0.32
});
netFrontLabel.position.set(-1.45, 0.28, 0.095);
net.add(netFrontLabel);
const netTopLabel = makeTextSprite("TOP / T", {
foreground: "#8a521d",
background: "rgba(255,255,255,.72)",
scaleX: 1.28,
scaleY: 0.32
});
netTopLabel.position.set(-1.45, H + 0.3, 0.095);
net.add(netTopLabel);
const netTitle = makeTextSprite("UNFOLDED NET", {
foreground: "#24363d",
background: "rgba(255,255,255,.90)",
fontSize: 39,
scaleX: 2.25,
scaleY: 0.56
});
netTitle.position.set(0, H + D + 0.48, 0);
net.add(netTitle);
const netBase = new THREE.Mesh(
new THREE.BoxGeometry(W + 0.45, 0.16, 0.62),
standard(0xd2cec3)
);
netBase.position.set(0, -0.08, 0);
netBase.castShadow = true;
netBase.receiveShadow = true;
net.add(netBase);
// -------------------------------------------------------------------------
// Synchronized arclength tracer.
// -------------------------------------------------------------------------
const tracerMaterial = standard(0xffffff, {
emissive: 0x9feaff,
emissiveIntensity: 0.8,
roughness: 0.25
});
const foldedTracer = new THREE.Mesh(
new THREE.SphereGeometry(0.072, 20, 14),
tracerMaterial
);
folded.add(foldedTracer);
const netTracer = new THREE.Mesh(
new THREE.SphereGeometry(0.072, 20, 14),
tracerMaterial
);
net.add(netTracer);
function foldedPointAtDistance(distance) {
if (distance <= frontLength) {
return foldedA.clone().lerp(
foldedE,
distance / frontLength
);
}
return foldedE.clone().lerp(
foldedB,
(distance - frontLength) / topLength
);
}
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, and zoom.
// -------------------------------------------------------------------------
const initialTarget = new THREE.Vector3(0, 1.05, 0);
const initialCameraPosition = new THREE.Vector3(5.7, 7.4, 19.2);
const target = initialTarget.clone();
const spherical = new THREE.Spherical().setFromVector3(
initialCameraPosition.clone().sub(initialTarget)
);
function updateCamera() {
spherical.phi = THREE.MathUtils.clamp(
spherical.phi,
0.22,
Math.PI - 0.22
);
spherical.radius = THREE.MathUtils.clamp(
spherical.radius,
10,
34
);
camera.position.setFromSpherical(spherical).add(target);
camera.lookAt(target);
camera.updateMatrixWorld();
}
updateCamera();
let dragging = false;
let dragMode = "orbit";
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
dragMode =
event.button === 2 || event.shiftKey ? "pan" : "orbit";
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
if (dragMode === "orbit") {
spherical.theta -= dx * 0.0055;
spherical.phi -= dy * 0.0045;
} else {
const right = new THREE.Vector3().setFromMatrixColumn(
camera.matrix,
0
);
const up = new THREE.Vector3().setFromMatrixColumn(
camera.matrix,
1
);
const panScale = spherical.radius * 0.00115;
target
.addScaledVector(right, -dx * panScale)
.addScaledVector(up, dy * panScale);
}
updateCamera();
});
function endDrag(event) {
dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
spherical.radius *= Math.exp(event.deltaY * 0.001);
updateCamera();
},
{ passive: false }
);
function resetView() {
target.copy(initialTarget);
spherical.setFromVector3(
initialCameraPosition.clone().sub(initialTarget)
);
updateCamera();
}
document.querySelector("#resetView").addEventListener("click", resetView);
let motionEnabled = !matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
const motionButton = document.querySelector("#toggleMotion");
function updateMotionButton() {
motionButton.textContent = motionEnabled
? "Pause trace"
: "Resume trace";
motionButton.setAttribute(
"aria-pressed",
String(motionEnabled)
);
}
function toggleMotion() {
motionEnabled = !motionEnabled;
updateMotionButton();
}
motionButton.addEventListener("click", toggleMotion);
updateMotionButton();
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") resetView();
if (event.code === "Space") {
event.preventDefault();
toggleMotion();
}
});
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
// -------------------------------------------------------------------------
// Animation.
// -------------------------------------------------------------------------
const traceDuration = 6500;
let traceElapsed = 0;
let previousTime = performance.now();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (motionEnabled) {
traceElapsed =
(traceElapsed + delta * 1000) % traceDuration;
}
const progress = traceElapsed / traceDuration;
const distance = progress * foldedTotal;
// The net tracer is uniformly spaced along its straight segment.
netTracer.position.copy(netA).lerp(netB, progress);
// The folded tracer uses the same total arc length and the same E point.
foldedTracer.position.copy(
foldedPointAtDistance(distance)
);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```