Prompt specification
Build or customize the Three.js 3D scene "Cube-to-skewed-box deformation" 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: Cube-to-skewed-box deformation
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/cube-to-skewed-box-deformation-x1722
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows vertices, edges, and faces of connected polyhedra. Continuously deform a cube without changing connections or creating self-intersections; keep vertex, edge, and face counts constant while angles and lengths change. Stylized solid forms.
Working Three.js Starter (cube-to-skewed-box-deformation-x1722):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Topology — Morphing Cube</title>
<style>
:root {
--bg: #070b14;
--panel: rgba(13, 20, 34, 0.76);
--panel-border: rgba(150, 220, 255, 0.14);
--text: #edf8ff;
--muted: #8294aa;
--cyan: #71f3ff;
--pink: #ff6bb5;
--green: #7dffbd;
--violet: #8d7cff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 45%, #122039 0%, #080d18 45%, #05070d 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#stage {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--panel-border);
background: var(--panel);
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.28),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(18px) saturate(130%);
-webkit-backdrop-filter: blur(18px) saturate(130%);
}
.intro {
top: 26px;
left: 26px;
width: min(360px, calc(100vw - 52px));
padding: 20px 22px 18px;
border-radius: 18px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 10px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.eyebrow::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 14px var(--cyan);
content: "";
}
h1 {
margin: 0;
font-size: clamp(25px, 4vw, 39px);
font-weight: 750;
letter-spacing: -0.055em;
line-height: 0.98;
}
.subtitle {
margin: 11px 0 18px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.counts {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 7px;
}
.count {
min-width: 0;
padding: 9px 8px 8px;
border: 1px solid rgba(255, 255, 255, 0.065);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.count span {
display: block;
color: var(--muted);
font-size: 8px;
font-weight: 750;
letter-spacing: 0.15em;
}
.count strong {
display: block;
margin-top: 3px;
color: var(--text);
font-size: 18px;
font-variant-numeric: tabular-nums;
}
.connection {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 12px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.connection b {
color: var(--green);
font-weight: 750;
}
.controls {
right: 26px;
bottom: 26px;
width: min(330px, calc(100vw - 52px));
padding: 16px;
border-radius: 16px;
}
.control-title {
margin-bottom: 12px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.button-row {
display: flex;
gap: 8px;
margin-bottom: 13px;
}
button {
min-height: 36px;
padding: 0 13px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 10px;
background: rgba(255, 255, 255, 0.045);
color: var(--text);
cursor: pointer;
transition: 160ms ease;
}
button:hover {
border-color: rgba(113, 243, 255, 0.4);
background: rgba(113, 243, 255, 0.08);
}
button.active {
border-color: rgba(113, 243, 255, 0.48);
background: rgba(113, 243, 255, 0.11);
color: var(--cyan);
}
#pause {
flex: 1;
color: var(--cyan);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.range-row {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 10px;
margin-bottom: 14px;
color: var(--muted);
font-size: 10px;
}
#speed {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
#speedValue {
min-width: 38px;
color: var(--text);
text-align: right;
font-variant-numeric: tabular-nums;
}
.layers {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.layers button {
min-height: 32px;
padding: 0 7px;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.legend {
left: 26px;
bottom: 26px;
padding: 13px 15px;
border-radius: 14px;
}
.legend-row {
display: flex;
align-items: center;
gap: 15px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.dot.face {
border-radius: 2px;
background: var(--violet);
}
.dot.edge {
background: var(--cyan);
box-shadow: 0 0 8px rgba(113, 243, 255, 0.65);
}
.dot.vertex {
background: var(--pink);
box-shadow: 0 0 8px rgba(255, 107, 181, 0.65);
}
.metrics {
position: fixed;
z-index: 8;
top: 28px;
right: 28px;
width: 230px;
padding: 14px 16px;
border-right: 2px solid rgba(113, 243, 255, 0.65);
border-radius: 4px 14px 14px 4px;
background: rgba(8, 14, 25, 0.6);
backdrop-filter: blur(12px);
pointer-events: none;
}
.metric {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 15px;
margin: 5px 0;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metric b {
color: var(--text);
font-size: 10px;
font-variant-numeric: tabular-nums;
letter-spacing: 0;
}
.safe {
display: flex;
align-items: center;
gap: 7px;
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid rgba(255, 255, 255, 0.07);
color: var(--green);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.safe::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 10px var(--green);
content: "";
}
.help {
position: fixed;
z-index: 7;
right: 29px;
bottom: 225px;
color: rgba(190, 209, 229, 0.48);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
pointer-events: none;
}
@media (max-width: 760px) {
.intro {
top: 14px;
left: 14px;
width: calc(100vw - 28px);
padding: 15px 17px;
}
.subtitle {
margin-bottom: 12px;
}
.metrics {
top: auto;
right: 14px;
bottom: 174px;
width: 205px;
}
.controls {
right: 14px;
bottom: 14px;
width: calc(100vw - 28px);
}
.legend {
display: none;
}
.help {
display: none;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<section class="panel intro">
<div class="eyebrow">Topology / Live Study</div>
<h1>Connected Cube</h1>
<p class="subtitle">
A continuously morphing polyhedron. Connectivity is locked while edge
lengths and face angles change.
</p>
<div class="counts">
<div class="count"><span>VERTICES</span><strong>08</strong></div>
<div class="count"><span>EDGES</span><strong>12</strong></div>
<div class="count"><span>FACES</span><strong>06</strong></div>
<div class="count"><span>EULER χ</span><strong>02</strong></div>
</div>
<div class="connection">
<span>Connected components</span>
<b>1 · Manifold</b>
</div>
</section>
<aside class="metrics">
<div class="metric"><span>Edge length</span><b id="lengthMetric">—</b></div>
<div class="metric"><span>Face angle</span><b id="angleMetric">—</b></div>
<div class="metric"><span>Affine det.</span><b id="detMetric">—</b></div>
<div class="safe" id="safeStatus">Convex · Collision-free</div>
</aside>
<div class="help">Drag to orbit · Scroll to zoom</div>
<section class="panel legend">
<div class="legend-row">
<div class="legend-item"><i class="dot face"></i> Faces</div>
<div class="legend-item"><i class="dot edge"></i> Edges</div>
<div class="legend-item"><i class="dot vertex"></i> Vertices</div>
</div>
</section>
<section class="panel controls">
<div class="control-title">Deformation Controls</div>
<div class="button-row">
<button id="pause" type="button">Pause Motion</button>
<button id="resetCamera" type="button">Reset View</button>
</div>
<div class="range-row">
<label for="speed">Speed</label>
<input id="speed" type="range" min="0.15" max="2.2" step="0.05" value="1" />
<span id="speedValue">1.00×</span>
</div>
<div class="layers">
<button class="active" data-layer="faces" type="button">Faces</button>
<button class="active" data-layer="edges" type="button">Edges</button>
<button class="active" data-layer="vertices" type="button">Vertices</button>
</div>
</section>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.getElementById("stage");
// Scene ------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b14);
scene.fog = new THREE.Fog(0x070b14, 8, 18);
const camera = new THREE.PerspectiveCamera(
42,
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.18;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xbfeaff, 0x151125, 1.75);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xe9fbff, 3.2);
keyLight.position.set(4, 7, 5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -5;
keyLight.shadow.camera.right = 5;
keyLight.shadow.camera.top = 5;
keyLight.shadow.camera.bottom = -5;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 20;
keyLight.shadow.bias = -0.00035;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x44eaff, 35, 9, 2);
cyanLight.position.set(-4, 1.5, 3);
scene.add(cyanLight);
const pinkLight = new THREE.PointLight(0xff4ba8, 28, 9, 2);
pinkLight.position.set(4, -1, -3);
scene.add(pinkLight);
// Ground and graphic rings ------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({
color: 0x080d17,
roughness: 0.88,
metalness: 0.08
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -2.15;
ground.receiveShadow = true;
scene.add(ground);
for (const radius of [3.2, 4.25, 5.3]) {
const ring = new THREE.Mesh(
new THREE.RingGeometry(radius, radius + 0.012, 96),
new THREE.MeshBasicMaterial({
color: 0x4cc9df,
transparent: true,
opacity: radius === 3.2 ? 0.16 : 0.07,
side: THREE.DoubleSide,
depthWrite: false
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.y = -2.13;
scene.add(ring);
}
// Fixed cube topology -----------------------------------------------------
const VERTICES = [
[-1, -1, -1], // 0
[ 1, -1, -1], // 1
[ 1, 1, -1], // 2
[-1, 1, -1], // 3
[-1, -1, 1], // 4
[ 1, -1, 1], // 5
[ 1, 1, 1], // 6
[-1, 1, 1] // 7
].map((v) => new THREE.Vector3(...v));
const EDGES = [
[0, 1], [1, 2], [2, 3], [3, 0],
[4, 5], [5, 6], [6, 7], [7, 4],
[0, 4], [1, 5], [2, 6], [3, 7]
];
// Vertex order is counter-clockwise when viewed from outside.
const FACES = [
{ ids: [0, 3, 2, 1], color: 0x185875 },
{ ids: [4, 5, 6, 7], color: 0x1a777d },
{ ids: [0, 1, 5, 4], color: 0x2864a0 },
{ ids: [1, 2, 6, 5], color: 0x6753bd },
{ ids: [2, 3, 7, 6], color: 0x343f99 },
{ ids: [3, 0, 4, 7], color: 0x493a91 }
];
const cubeRoot = new THREE.Group();
cubeRoot.position.y = 0.08;
scene.add(cubeRoot);
const faceGroup = new THREE.Group();
const edgeGroup = new THREE.Group();
const vertexGroup = new THREE.Group();
cubeRoot.add(faceGroup, edgeGroup, vertexGroup);
const faceMeshes = [];
// Six independently colored, planar quad faces.
for (const definition of FACES) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(12), 3)
);
geometry.setAttribute(
"normal",
new THREE.BufferAttribute(new Float32Array(12), 3)
);
geometry.setIndex([0, 1, 2, 0, 2, 3]);
const material = new THREE.MeshPhysicalMaterial({
color: definition.color,
emissive: definition.color,
emissiveIntensity: 0.08,
metalness: 0.16,
roughness: 0.34,
clearcoat: 0.55,
clearcoatRoughness: 0.22,
side: THREE.DoubleSide,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
faceGroup.add(mesh);
faceMeshes.push({ mesh, ids: definition.ids });
}
// Edge rods ---------------------------------------------------------------
const edgeGeometry = new THREE.CylinderGeometry(0.032, 0.032, 1, 10, 1);
const edgeMaterial = new THREE.MeshStandardMaterial({
color: 0xa7fbff,
emissive: 0x24dce8,
emissiveIntensity: 1.65,
metalness: 0.5,
roughness: 0.22
});
const edgeMesh = new THREE.InstancedMesh(
edgeGeometry,
edgeMaterial,
EDGES.length
);
edgeMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
edgeMesh.frustumCulled = false;
edgeGroup.add(edgeMesh);
const glowGeometry = new THREE.CylinderGeometry(0.075, 0.075, 1, 10, 1);
const glowMaterial = new THREE.MeshBasicMaterial({
color: 0x43efff,
transparent: true,
opacity: 0.075,
blending: THREE.AdditiveBlending,
depthWrite: false
});
const glowMesh = new THREE.InstancedMesh(
glowGeometry,
glowMaterial,
EDGES.length
);
glowMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
glowMesh.frustumCulled = false;
edgeGroup.add(glowMesh);
// Vertex nodes ------------------------------------------------------------
const nodeGeometry = new THREE.IcosahedronGeometry(0.098, 2);
const nodeMaterial = new THREE.MeshStandardMaterial({
color: 0xffd8ef,
emissive: 0xff3d9c,
emissiveIntensity: 1.8,
roughness: 0.2,
metalness: 0.25
});
const nodeMesh = new THREE.InstancedMesh(
nodeGeometry,
nodeMaterial,
VERTICES.length
);
nodeMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
nodeMesh.frustumCulled = false;
vertexGroup.add(nodeMesh);
const haloGeometry = new THREE.BufferGeometry();
haloGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(VERTICES.length * 3), 3)
);
const haloMaterial = new THREE.PointsMaterial({
color: 0xff62b6,
size: 0.28,
transparent: true,
opacity: 0.38,
blending: THREE.AdditiveBlending,
depthWrite: false,
sizeAttenuation: true
});
const halos = new THREE.Points(haloGeometry, haloMaterial);
halos.frustumCulled = false;
vertexGroup.add(halos);
// Deformation --------------------------------------------------------------
/*
The cube is transformed by a continuously varying, invertible affine
matrix. An affine image of a cube remains a convex hexahedron, so the
topology cannot change and face/edge self-intersections cannot occur.
*/
const deformation = new THREE.Matrix4();
const transformed = VERTICES.map(() => new THREE.Vector3());
const dummy = new THREE.Object3D();
const up = new THREE.Vector3(0, 1, 0);
const direction = new THREE.Vector3();
const midpoint = new THREE.Vector3();
const normal = new THREE.Vector3();
const edgeA = new THREE.Vector3();
const edgeB = new THREE.Vector3();
const angleA = new THREE.Vector3();
const angleB = new THREE.Vector3();
function updateDeformation(time) {
const sx = 1.00 + 0.16 * Math.sin(time * 0.73);
const sy = 1.00 + 0.12 * Math.sin(time * 0.51 + 1.3);
const sz = 1.00 + 0.14 * Math.cos(time * 0.67 + 0.2);
const xy = 0.30 * Math.sin(time * 0.43);
const xz = 0.22 * Math.cos(time * 0.37 + 0.6);
const yx = 0.25 * Math.sin(time * 0.29 + 2.0);
const yz = 0.18 * Math.cos(time * 0.56);
const zx = 0.20 * Math.sin(time * 0.61 + 1.1);
const zy = 0.16 * Math.cos(time * 0.33 + 2.2);
deformation.set(
sx, xy, xz, 0,
yx, sy, yz, 0,
zx, zy, sz, 0,
0, 0, 0, 1
);
// Safety fallback: the selected ranges keep this determinant positive.
if (deformation.determinant() < 0.05) {
deformation.identity();
}
}
function updateCube() {
for (let i = 0; i < VERTICES.length; i++) {
transformed[i].copy(VERTICES[i]).applyMatrix4(deformation);
}
// Update each face and assign one flat normal to all four corners.
for (const face of faceMeshes) {
const positions = face.mesh.geometry.attributes.position;
const normals = face.mesh.geometry.attributes.normal;
edgeA.copy(transformed[face.ids[1]]).sub(transformed[face.ids[0]]);
edgeB.copy(transformed[face.ids[2]]).sub(transformed[face.ids[0]]);
normal.copy(edgeA).cross(edgeB).normalize();
for (let i = 0; i < 4; i++) {
const point = transformed[face.ids[i]];
positions.setXYZ(i, point.x, point.y, point.z);
normals.setXYZ(i, normal.x, normal.y, normal.z);
}
positions.needsUpdate = true;
normals.needsUpdate = true;
}
// Update edge rods.
for (let i = 0; i < EDGES.length; i++) {
const [aIndex, bIndex] = EDGES[i];
const a = transformed[aIndex];
const b = transformed[bIndex];
direction.copy(b).sub(a);
const length = direction.length();
direction.normalize();
midpoint.copy(a).add(b).multiplyScalar(0.5);
dummy.position.copy(midpoint);
dummy.quaternion.setFromUnitVectors(up, direction);
dummy.scale.set(1, length, 1);
dummy.updateMatrix();
edgeMesh.setMatrixAt(i, dummy.matrix);
glowMesh.setMatrixAt(i, dummy.matrix);
}
edgeMesh.instanceMatrix.needsUpdate = true;
glowMesh.instanceMatrix.needsUpdate = true;
// Update vertex nodes and their soft halos.
const haloPositions = haloGeometry.attributes.position;
for (let i = 0; i < transformed.length; i++) {
const point = transformed[i];
dummy.position.copy(point);
dummy.quaternion.identity();
dummy.scale.setScalar(1);
dummy.updateMatrix();
nodeMesh.setMatrixAt(i, dummy.matrix);
haloPositions.setXYZ(i, point.x, point.y, point.z);
}
nodeMesh.instanceMatrix.needsUpdate = true;
haloPositions.needsUpdate = true;
}
// Live measurements --------------------------------------------------------
const lengthMetric = document.getElementById("lengthMetric");
const angleMetric = document.getElementById("angleMetric");
const detMetric = document.getElementById("detMetric");
const safeStatus = document.getElementById("safeStatus");
function updateMetrics() {
let minLength = Infinity;
let maxLength = -Infinity;
let minAngle = Infinity;
let maxAngle = -Infinity;
let outward = true;
for (const [aIndex, bIndex] of EDGES) {
const length = transformed[aIndex].distanceTo(transformed[bIndex]);
minLength = Math.min(minLength, length);
maxLength = Math.max(maxLength, length);
}
for (const face of faceMeshes) {
const center = new THREE.Vector3();
for (const index of face.ids) center.add(transformed[index]);
center.multiplyScalar(0.25);
edgeA.copy(transformed[face.ids[1]]).sub(transformed[face.ids[0]]);
edgeB.copy(transformed[face.ids[2]]).sub(transformed[face.ids[0]]);
normal.copy(edgeA).cross(edgeB).normalize();
if (normal.dot(center) < -0.001) outward = false;
for (let i = 0; i < 4; i++) {
const current = face.ids[i];
const previous = face.ids[(i + 3) % 4];
const next = face.ids[(i + 1) % 4];
angleA.copy(transformed[previous]).sub(transformed[current]);
angleB.copy(transformed[next]).sub(transformed[current]);
const cosine = THREE.MathUtils.clamp(
angleA.dot(angleB) / (angleA.length() * angleB.length()),
-1,
1
);
const angle = Math.acos(cosine);
minAngle = Math.min(minAngle, angle);
maxAngle = Math.max(maxAngle, angle);
}
}
const determinant = deformation.determinant();
const isSafe = determinant > 0 && outward;
lengthMetric.textContent =
`${minLength.toFixed(2)}–${maxLength.toFixed(2)}`;
angleMetric.textContent =
`${THREE.MathUtils.radToDeg(minAngle).toFixed(0)}°–` +
`${THREE.MathUtils.radToDeg(maxAngle).toFixed(0)}°`;
detMetric.textContent = determinant.toFixed(3);
safeStatus.textContent = isSafe
? "Convex · Collision-free"
: "Checking geometry";
safeStatus.style.color = isSafe ? "var(--green)" : "var(--pink)";
}
// Camera controls, implemented without external addons ----------------------
let cameraTheta = 0.72;
let cameraPhi = 1.05;
let cameraRadius = 6.5;
let dragging = false;
let previousX = 0;
let previousY = 0;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraRadius * Math.cos(cameraPhi),
cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(0, 0.08, 0);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraTheta -= deltaX * 0.007;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - deltaY * 0.007,
0.28,
Math.PI - 0.28
);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (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();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.005,
4.1,
10
);
updateCamera();
},
{ passive: false }
);
// UI -----------------------------------------------------------------------
const pauseButton = document.getElementById("pause");
const speedInput = document.getElementById("speed");
const speedValue = document.getElementById("speedValue");
const resetButton = document.getElementById("resetCamera");
let paused = false;
let speed = 1;
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume Motion" : "Pause Motion";
pauseButton.classList.toggle("active", paused);
});
speedInput.addEventListener("input", () => {
speed = Number(speedInput.value);
speedValue.textContent = `${speed.toFixed(2)}×`;
});
resetButton.addEventListener("click", () => {
cameraTheta = 0.72;
cameraPhi = 1.05;
cameraRadius = 6.5;
updateCamera();
});
document.querySelectorAll("[data-layer]").forEach((button) => {
button.addEventListener("click", () => {
const layer = button.dataset.layer;
const group =
layer === "faces"
? faceGroup
: layer === "edges"
? edgeGroup
: vertexGroup;
group.visible = !group.visible;
button.classList.toggle("active", group.visible);
button.setAttribute("aria-pressed", String(group.visible));
});
});
// Resize -------------------------------------------------------------------
function onResize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
}
addEventListener("resize", onResize);
// Animation ----------------------------------------------------------------
let simulationTime = 1.6;
let previousTime = performance.now();
let metricTimer = 0;
updateDeformation(simulationTime);
updateCube();
updateMetrics();
updateCamera();
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (!paused) {
simulationTime += delta * speed;
}
updateDeformation(simulationTime);
updateCube();
// The rotation is presentation-only and does not affect topology.
cubeRoot.rotation.y = simulationTime * 0.16;
cubeRoot.rotation.x = Math.sin(simulationTime * 0.37) * 0.075;
metricTimer += delta;
if (metricTimer > 0.08) {
updateMetrics();
metricTimer = 0;
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```