Prompt specification
Build or customize the Three.js 3D scene "Rolling Ball Through a Transformed Door" 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: Rolling Ball Through a Transformed Door
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/rolling-ball-through-a-transformed-door-x3482
Scene Description Prompt:
Animate a low-poly ball crossing fictional portals under a stated position-and-velocity transform. Use Three.js from cdnjs in one HTML file.
Working Three.js Starter (rolling-ball-through-a-transformed-door-x3482):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Transit Protocol — Three.js Portals</title>
<style>
:root {
color-scheme: dark;
--cyan: #78e7ff;
--violet: #b487ff;
--amber: #ffbd66;
--panel: rgba(7, 13, 28, 0.72);
--border: rgba(150, 205, 255, 0.18);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #050814;
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body {
color: #edf7ff;
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 2;
}
.panel {
position: absolute;
border: 1px solid var(--border);
background:
linear-gradient(135deg, rgba(255, 255, 255, 0.045), transparent),
var(--panel);
box-shadow:
0 20px 60px rgba(0, 0, 0, 0.25),
inset 0 1px rgba(255, 255, 255, 0.04);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
#title-panel {
top: 22px;
left: 22px;
width: min(360px, calc(100vw - 44px));
padding: 20px 22px;
border-radius: 18px;
}
.eyebrow {
color: var(--cyan);
font: 700 11px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 9px 0 7px;
font-size: clamp(25px, 4vw, 36px);
line-height: 1;
letter-spacing: -0.04em;
}
.subtitle {
margin: 0;
color: #a6b8ca;
font-size: 13px;
line-height: 1.55;
}
.status-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-top: 17px;
padding-top: 14px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
font: 700 11px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status-dot {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 8px;
border-radius: 50%;
background: #62ffb0;
box-shadow: 0 0 14px #62ffb0;
}
#transform-panel {
top: 22px;
right: 22px;
width: min(390px, calc(100vw - 44px));
padding: 18px 20px;
border-radius: 18px;
}
.equation {
margin: 10px 0;
color: #f5f9ff;
font: 600 14px/1.65 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.equation .accent {
color: var(--cyan);
}
.explanation {
margin: 8px 0 0;
color: #92a6ba;
font-size: 12px;
line-height: 1.55;
}
.readout {
display: grid;
grid-template-columns: 78px 1fr;
gap: 6px 12px;
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
font: 11px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.readout dt {
color: #698096;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.readout dd {
margin: 0;
color: #cfe8f8;
overflow-wrap: anywhere;
}
#route-panel {
left: 22px;
bottom: 22px;
width: min(300px, calc(100vw - 44px));
padding: 15px 17px;
border-radius: 16px;
}
.route-items {
display: flex;
gap: 8px;
margin-top: 12px;
}
.route-item {
flex: 1;
padding: 9px 8px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 9px;
color: #65798e;
background: rgba(255, 255, 255, 0.02);
font: 700 10px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: center;
text-transform: uppercase;
transition: 180ms ease;
}
.route-item.active {
color: white;
border-color: currentColor;
background: rgba(120, 231, 255, 0.08);
box-shadow: 0 0 22px rgba(120, 231, 255, 0.08);
}
#controls {
right: 22px;
bottom: 22px;
padding: 11px 15px;
border-radius: 999px;
color: #91a7ba;
font: 11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.03em;
}
kbd {
display: inline-block;
min-width: 23px;
padding: 3px 6px;
margin: 0 2px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 5px;
color: #e9f6ff;
background: rgba(255, 255, 255, 0.055);
text-align: center;
font: inherit;
}
#flash {
position: fixed;
inset: 0;
z-index: 3;
pointer-events: none;
opacity: 0;
background:
radial-gradient(circle at center, rgba(220, 245, 255, 0.18), transparent 48%),
linear-gradient(90deg, rgba(120, 231, 255, 0.05), transparent);
}
#flash.on {
animation: teleport-flash 460ms ease-out;
}
@keyframes teleport-flash {
0% {
opacity: 0;
transform: scale(1.08);
}
20% {
opacity: 1;
}
100% {
opacity: 0;
transform: scale(1);
}
}
@media (max-width: 760px) {
#title-panel {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 15px 17px;
}
#transform-panel {
top: auto;
right: 12px;
bottom: 58px;
width: calc(100vw - 24px);
padding: 13px 15px;
}
#transform-panel .explanation,
.readout {
display: none;
}
.equation {
margin: 7px 0 0;
font-size: 11px;
}
#route-panel {
display: none;
}
#controls {
right: 12px;
bottom: 12px;
left: 12px;
border-radius: 12px;
text-align: center;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div class="hud">
<section id="title-panel" class="panel">
<div class="eyebrow">Fictional Transit Laboratory</div>
<h1>Transit Protocol</h1>
<p class="subtitle">
A faceted probe is crossing three linked apertures. At each crossing,
both position and velocity are transformed.
</p>
<div class="status-row">
<span><i class="status-dot"></i><span id="run-state">Autopilot active</span></span>
<span id="cross-count">0 crossings</span>
</div>
</section>
<section id="transform-panel" class="panel">
<div class="eyebrow">Position + Velocity Transform</div>
<div class="equation">
<span class="accent">p′</span> = c<sub>B</sub> +
R<sub>B←A</sub>(p − c<sub>A</sub>)
</div>
<div class="equation">
<span class="accent">v′</span> = R<sub>B←A</sub>v
</div>
<div class="equation">
R<sub>B←A</sub> = q<sub>B</sub> · q<sub>A</sub><sup>−1</sup>
</div>
<p class="explanation">
The quaternion maps the source portal frame into the destination frame.
Rotation preserves speed exactly. For a reverse crossing, A and B are swapped.
</p>
<dl class="readout">
<dt>Last pair</dt>
<dd id="pair-value">Awaiting first crossing</dd>
<dt>Rotation</dt>
<dd id="rotation-value">—</dd>
<dt>Centers</dt>
<dd id="centers-value">—</dd>
<dt>Speed</dt>
<dd id="speed-value">0.00 u/s</dd>
</dl>
</section>
<section id="route-panel" class="panel">
<div class="eyebrow">Current Relay</div>
<div class="route-items" id="route-items"></div>
</section>
<section id="controls" class="panel">
<kbd>Drag</kbd> orbit <kbd>Wheel</kbd> zoom
<kbd>Space</kbd> pause <kbd>R</kbd> reset <kbd>C</kbd> camera
</section>
</div>
<div id="flash"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer, scene, and camera
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
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.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x050814);
scene.fog = new THREE.FogExp2(0x050814, 0.025);
const camera = new THREE.PerspectiveCamera(
52,
window.innerWidth / window.innerHeight,
0.1,
150
);
const cameraTarget = new THREE.Vector3(0, 1.25, 0);
let cameraYaw = 0.55;
let cameraPitch = 1.13;
let cameraRadius = 24;
function updateCamera() {
const sinPhi = Math.sin(cameraPitch);
const cosPhi = Math.cos(cameraPitch);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraYaw),
cameraTarget.y + cameraRadius * cosPhi,
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
updateCamera();
// -------------------------------------------------------------------------
// Lighting and environment
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0x8ccfff, 0x11101d, 1.55));
const keyLight = new THREE.DirectionalLight(0xd9efff, 2.2);
keyLight.position.set(8, 15, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -18;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 18;
keyLight.shadow.camera.bottom = -18;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 45;
scene.add(keyLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({
color: 0x070c17,
roughness: 0.82,
metalness: 0.18
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.055;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(52, 52, 0x315273, 0x14243c);
grid.position.y = -0.035;
grid.material.transparent = true;
grid.material.opacity = 0.34;
scene.add(grid);
// A sparse procedural star field.
{
const count = 850;
const positions = new Float32Array(count * 3);
for (let i = 0; i < count; i++) {
const radius = 32 + Math.random() * 22;
const theta = Math.random() * Math.PI * 2;
const y = 2 + Math.random() * 32;
positions[i * 3] = radius * Math.cos(theta);
positions[i * 3 + 1] = y;
positions[i * 3 + 2] = radius * Math.sin(theta);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
const stars = new THREE.Points(
geometry,
new THREE.PointsMaterial({
color: 0x8dbdff,
size: 0.075,
transparent: true,
opacity: 0.72,
sizeAttenuation: true,
depthWrite: false
})
);
scene.add(stars);
}
// -------------------------------------------------------------------------
// Portal construction
// -------------------------------------------------------------------------
const portalVertexShader = `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const portalFragmentShader = `
uniform float uTime;
uniform vec3 uColor;
varying vec2 vUv;
void main() {
vec2 p = (vUv - 0.5) * 2.0;
float r = length(p);
float angle = atan(p.y, p.x);
float spiral = sin(r * 25.0 - uTime * 4.0 + angle * 3.0);
float bands = 0.5 + 0.5 * spiral;
float innerGlow = smoothstep(0.92, 0.1, r);
float rim = smoothstep(0.72, 0.98, r);
vec3 color = uColor * (0.35 + bands * 1.25 + rim * 1.8);
float alpha = (0.07 + bands * 0.12 + rim * 0.65) * innerGlow;
gl_FragColor = vec4(color, alpha);
}
`;
function roundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
function makeLabel(text, subtext, color) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
const cssColor = `#${new THREE.Color(color).getHexString()}`;
roundedRect(ctx, 6, 6, 500, 116, 20);
ctx.fillStyle = "rgba(5, 10, 23, 0.78)";
ctx.fill();
ctx.strokeStyle = cssColor;
ctx.globalAlpha = 0.55;
ctx.lineWidth = 3;
ctx.stroke();
ctx.globalAlpha = 1;
ctx.textAlign = "center";
ctx.fillStyle = cssColor;
ctx.font = "700 35px ui-monospace, monospace";
ctx.fillText(text, 256, 57);
ctx.fillStyle = "#dcefff";
ctx.font = "600 17px ui-monospace, monospace";
ctx.fillText(subtext, 256, 91);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(3.5, 0.875, 1);
return sprite;
}
const portalDefinitions = [
{
name: "VIOLET",
side: "A",
color: 0xa979ff,
position: [-6, 1.65, -8],
yaw: 0,
linkIndex: 1
},
{
name: "VIOLET",
side: "B",
color: 0xa979ff,
position: [6, 1.65, 5],
yaw: -0.14,
linkIndex: 0
},
{
name: "AZURE",
side: "A",
color: 0x55d9ff,
position: [6, 1.65, -6],
yaw: 0,
linkIndex: 3
},
{
name: "AZURE",
side: "B",
color: 0x55d9ff,
position: [-7, 1.65, -1],
yaw: Math.PI,
linkIndex: 2
},
{
name: "EMBER",
side: "A",
color: 0xffa858,
position: [-7, 1.65, 9],
yaw: Math.PI,
linkIndex: 5
},
{
name: "EMBER",
side: "B",
color: 0xffa858,
position: [6, 1.65, 8],
yaw: Math.PI,
linkIndex: 4
}
];
const portals = [];
for (const definition of portalDefinitions) {
const group = new THREE.Group();
group.position.fromArray(definition.position);
group.quaternion.setFromEuler(
new THREE.Euler(0, definition.yaw, 0, "YXZ")
);
const color = new THREE.Color(definition.color);
const surfaceMaterial = new THREE.ShaderMaterial({
uniforms: {
uTime: { value: 0 },
uColor: { value: color.clone() }
},
vertexShader: portalVertexShader,
fragmentShader: portalFragmentShader,
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
side: THREE.DoubleSide
});
const surface = new THREE.Mesh(
new THREE.CircleGeometry(1.14, 48),
surfaceMaterial
);
group.add(surface);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(1.25, 0.105, 8, 40),
new THREE.MeshStandardMaterial({
color: definition.color,
emissive: definition.color,
emissiveIntensity: 2.5,
roughness: 0.28,
metalness: 0.52
})
);
group.add(ring);
const outerRing = new THREE.Mesh(
new THREE.TorusGeometry(1.43, 0.027, 6, 56),
new THREE.MeshBasicMaterial({
color: definition.color,
transparent: true,
opacity: 0.68
})
);
group.add(outerRing);
const tickGroup = new THREE.Group();
for (let i = 0; i < 12; i++) {
const angle = (i / 12) * Math.PI * 2;
const tick = new THREE.Mesh(
new THREE.BoxGeometry(0.055, 0.22, 0.045),
new THREE.MeshBasicMaterial({
color: definition.color,
transparent: true,
opacity: 0.78
})
);
tick.position.set(
Math.cos(angle) * 1.43,
Math.sin(angle) * 1.43,
0
);
tick.rotation.z = angle - Math.PI / 2;
tickGroup.add(tick);
}
group.add(tickGroup);
scene.add(group);
const label = makeLabel(
definition.name,
`${definition.side} / ${definition.side === "A" ? "SOURCE" : "DESTINATION"}`,
definition.color
);
label.position.set(
definition.position[0],
definition.position[1] + 1.78,
definition.position[2]
);
scene.add(label);
const portal = {
name: definition.name,
side: definition.side,
color: definition.color,
position: group.position.clone(),
quaternion: group.quaternion.clone(),
normal: new THREE.Vector3(0, 0, 1).applyQuaternion(group.quaternion),
group,
ring,
tickGroup,
surfaceMaterial,
link: null
};
portals.push(portal);
}
for (let i = 0; i < portals.length; i++) {
portals[i].link = portals[portalDefinitions[i].linkIndex];
}
// Source portals are visited in relay order.
const route = [portals[0], portals[2], portals[4]];
let routeIndex = 0;
const routeItems = document.querySelector("#route-items");
routeItems.innerHTML = route
.map(
(portal, index) =>
`<div class="route-item" id="route-${index}">${portal.name} ${index + 1}</div>`
)
.join("");
function updateRouteUI() {
route.forEach((portal, index) => {
const item = document.querySelector(`#route-${index}`);
item.classList.toggle("active", index === routeIndex);
item.style.color = index === routeIndex
? `#${new THREE.Color(portal.color).getHexString()}`
: "";
});
}
updateRouteUI();
// -------------------------------------------------------------------------
// Low-poly ball
// -------------------------------------------------------------------------
let ballGeometry = new THREE.IcosahedronGeometry(0.42, 1);
if (ballGeometry.index) {
const indexedGeometry = ballGeometry;
ballGeometry = indexedGeometry.toNonIndexed();
indexedGeometry.dispose();
}
const ballPalette = [
new THREE.Color(0x8cecff),
new THREE.Color(0x6d8dff),
new THREE.Color(0xb780ff),
new THREE.Color(0xffffff),
new THREE.Color(0x55d9c3)
];
const vertexCount = ballGeometry.attributes.position.count;
const ballColors = new Float32Array(vertexCount * 3);
for (let i = 0; i < vertexCount; i += 3) {
const color = ballPalette[(i / 3) % ballPalette.length];
for (let j = 0; j < 3; j++) {
const index = (i + j) * 3;
ballColors[index] = color.r;
ballColors[index + 1] = color.g;
ballColors[index + 2] = color.b;
}
}
ballGeometry.setAttribute(
"color",
new THREE.BufferAttribute(ballColors, 3)
);
const ballMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 0.34,
metalness: 0.22,
emissive: 0x0b1830,
emissiveIntensity: 0.6
});
const ball = new THREE.Mesh(ballGeometry, ballMaterial);
ball.castShadow = true;
ball.receiveShadow = true;
scene.add(ball);
const ballEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(ballGeometry, 18),
new THREE.LineBasicMaterial({
color: 0xd8f8ff,
transparent: true,
opacity: 0.3
})
);
ball.add(ballEdges);
const ballLight = new THREE.PointLight(0x8cecff, 7, 6, 2);
ball.add(ballLight);
const shadow = new THREE.Mesh(
new THREE.CircleGeometry(0.48, 32),
new THREE.MeshBasicMaterial({
color: 0x000000,
transparent: true,
opacity: 0.3,
depthWrite: false
})
);
shadow.rotation.x = -Math.PI / 2;
shadow.position.y = -0.025;
scene.add(shadow);
const velocity = new THREE.Vector3(0, 0, -5.2);
const previousPosition = new THREE.Vector3();
const desiredDirection = new THREE.Vector3();
const desiredVelocity = new THREE.Vector3();
// -------------------------------------------------------------------------
// Trail and autopilot guide
// -------------------------------------------------------------------------
const maxTrailPoints = 170;
const trailPositions = new Float32Array(maxTrailPoints * 3);
const trailGeometry = new THREE.BufferGeometry();
const trailAttribute = new THREE.BufferAttribute(trailPositions, 3);
trailAttribute.setUsage(THREE.DynamicDrawUsage);
trailGeometry.setAttribute("position", trailAttribute);
trailGeometry.setDrawRange(0, 0);
const trail = new THREE.Line(
trailGeometry,
new THREE.LineBasicMaterial({
color: 0x8cecff,
transparent: true,
opacity: 0.65,
blending: THREE.AdditiveBlending,
depthWrite: false
})
);
trail.frustumCulled = false;
scene.add(trail);
let trailCount = 0;
function clearTrail() {
trailCount = 0;
trailGeometry.setDrawRange(0, 0);
}
function addTrailPoint(position) {
if (trailCount === maxTrailPoints) {
trailPositions.copyWithin(
0,
3,
maxTrailPoints * 3
);
trailCount--;
}
const offset = trailCount * 3;
trailPositions[offset] = position.x;
trailPositions[offset + 1] = position.y;
trailPositions[offset + 2] = position.z;
trailCount++;
trailAttribute.needsUpdate = true;
trailGeometry.setDrawRange(0, trailCount);
}
const guideGeometry = new THREE.BufferGeometry();
guideGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(6), 3)
);
const guideMaterial = new THREE.LineBasicMaterial({
color: 0x78e7ff,
transparent: true,
opacity: 0.13,
depthWrite: false
});
const guide = new THREE.Line(guideGeometry, guideMaterial);
guide.frustumCulled = false;
scene.add(guide);
function updateGuide() {
const target = route[routeIndex];
const attribute = guideGeometry.attributes.position;
attribute.setXYZ(0, ball.position.x, ball.position.y, ball.position.z);
attribute.setXYZ(1, target.position.x, target.position.y, target.position.z);
attribute.needsUpdate = true;
guideMaterial.color.setHex(target.color);
}
// -------------------------------------------------------------------------
// Portal crossing transform
// -------------------------------------------------------------------------
const pairValue = document.querySelector("#pair-value");
const rotationValue = document.querySelector("#rotation-value");
const centersValue = document.querySelector("#centers-value");
const speedValue = document.querySelector("#speed-value");
const crossCountValue = document.querySelector("#cross-count");
const flash = document.querySelector("#flash");
let crossingCount = 0;
let teleportCooldown = 0;
function formatVector(vector) {
return `(${vector.x.toFixed(1)}, ${vector.y.toFixed(1)}, ${vector.z.toFixed(1)})`;
}
function signedDistance(portal, position) {
return (
(position.x - portal.position.x) * portal.normal.x +
(position.y - portal.position.y) * portal.normal.y +
(position.z - portal.position.z) * portal.normal.z
);
}
function applyPortalTransform(source, destination) {
/*
Position:
p' = cB + R(p - cA)
Velocity:
v' = Rv
Rotation:
R = qB * qA^(-1)
Quaternion multiplication order matches Three.js:
destinationQuaternion * inverse(sourceQuaternion)
*/
const inverseSourceQuaternion = source.quaternion.clone().invert();
const rotation = destination.quaternion
.clone()
.multiply(inverseSourceQuaternion);
const relativePosition = ball.position
.clone()
.sub(source.position)
.applyQuaternion(rotation);
ball.position.copy(destination.position).add(relativePosition);
velocity.applyQuaternion(rotation);
crossingCount++;
teleportCooldown = 0.22;
clearTrail();
addTrailPoint(ball.position);
pairValue.textContent =
`${source.name} ${source.side} → ${destination.name} ${destination.side}`;
rotationValue.textContent =
`q = (${rotation.x.toFixed(3)}, ${rotation.y.toFixed(3)}, ` +
`${rotation.z.toFixed(3)}, ${rotation.w.toFixed(3)})`;
centersValue.textContent =
`cA ${formatVector(source.position)} · ` +
`cB ${formatVector(destination.position)}`;
crossCountValue.textContent =
`${crossingCount} crossing${crossingCount === 1 ? "" : "s"}`;
flash.classList.remove("on");
void flash.offsetWidth;
flash.classList.add("on");
}
function detectPortalCrossing() {
if (teleportCooldown > 0) return;
for (const source of portals) {
const previousDistance = signedDistance(source, previousPosition);
const currentDistance = signedDistance(source, ball.position);
const crossedPlane =
(previousDistance > 0 && currentDistance <= 0) ||
(previousDistance < 0 && currentDistance >= 0);
if (!crossedPlane) continue;
// Find the actual plane intersection.
const denominator = previousDistance - currentDistance;
const fraction = Math.abs(denominator) > 1e-6
? previousDistance / denominator
: 0;
const intersection = previousPosition
.clone()
.lerp(ball.position, THREE.MathUtils.clamp(fraction, 0, 1));
const offsetFromCenter = intersection.clone().sub(source.position);
// Only the finite aperture triggers a crossing.
offsetFromCenter.addScaledVector(
source.normal,
-offsetFromCenter.dot(source.normal)
);
if (offsetFromCenter.length() > 1.42) continue;
const sourceWasTarget = source === route[routeIndex];
applyPortalTransform(source, source.link);
if (sourceWasTarget) {
routeIndex = (routeIndex + 1) % route.length;
updateRouteUI();
}
break;
}
}
// -------------------------------------------------------------------------
// Controls
// -------------------------------------------------------------------------
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
cameraYaw -= deltaX * 0.006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + deltaY * 0.005,
0.35,
1.42
);
previousPointerX = event.clientX;
previousPointerY = event.clientY;
});
canvas.addEventListener("pointerup", (event) => {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
11,
39
);
},
{ passive: false }
);
const runState = document.querySelector("#run-state");
let paused = false;
function resetSimulation() {
ball.position.set(-6, 1.65, -1.5);
velocity.set(0, 0, -5.2);
previousPosition.copy(ball.position);
routeIndex = 0;
crossingCount = 0;
teleportCooldown = 0.3;
clearTrail();
addTrailPoint(ball.position);
pairValue.textContent = "Awaiting first crossing";
rotationValue.textContent = "—";
centersValue.textContent = "—";
crossCountValue.textContent = "0 crossings";
updateRouteUI();
}
function resetCamera() {
cameraYaw = 0.55;
cameraPitch = 1.13;
cameraRadius = 24;
}
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
if (event.repeat) return;
paused = !paused;
runState.textContent = paused ? "Simulation paused" : "Autopilot active";
}
if (event.code === "KeyR") {
resetSimulation();
}
if (event.code === "KeyC") {
resetCamera();
}
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let elapsed = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.04);
if (!paused) {
elapsed += delta;
teleportCooldown = Math.max(0, teleportCooldown - delta);
const target = route[routeIndex];
// Gentle steering keeps the relay moving toward the active aperture.
desiredDirection.subVectors(target.position, ball.position);
desiredDirection.normalize();
desiredVelocity
.copy(desiredDirection)
.multiplyScalar(5.2);
const steering = 1 - Math.exp(-2.6 * delta);
velocity.lerp(desiredVelocity, steering);
previousPosition.copy(ball.position);
ball.position.addScaledVector(velocity, delta);
detectPortalCrossing();
// Visual spin of the faceted probe.
ball.rotation.x += velocity.z * delta / 0.42;
ball.rotation.z -= velocity.x * delta / 0.42;
const lastTrailPoint = new THREE.Vector3(
trailPositions[Math.max(0, trailCount - 1) * 3],
trailPositions[Math.max(0, trailCount - 1) * 3 + 1],
trailPositions[Math.max(0, trailCount - 1) * 3 + 2]
);
if (ball.position.distanceTo(lastTrailPoint) > 0.075) {
addTrailPoint(ball.position);
}
speedValue.textContent = `${velocity.length().toFixed(2)} u/s`;
}
for (let i = 0; i < portals.length; i++) {
const portal = portals[i];
portal.surfaceMaterial.uniforms.uTime.value = elapsed;
portal.tickGroup.rotation.z =
elapsed * (i % 2 === 0 ? 0.11 : -0.11);
const isActive = portal === route[routeIndex];
const pulse = isActive
? 1 + Math.sin(elapsed * 4.5) * 0.035
: 1;
portal.ring.scale.setScalar(pulse);
}
shadow.position.x = ball.position.x;
shadow.position.z = ball.position.z;
shadow.material.opacity = 0.3;
updateGuide();
updateCamera();
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
resetSimulation();
animate();
</script>
</body>
</html>
```