Prompt specification
Build or customize the Three.js 3D scene "Rotate Gravity in One Chamber" 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: Rotate Gravity in One Chamber
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/rotate-gravity-in-one-chamber-x3454
Scene Description Prompt:
I'd like to see this as a voxel Three.js scene: rotate gravity in one chamber. Create a bounded chamber where a ball settles on different walls after a button changes gravity. Use stable collision handling and clearly show the active acceleration direction. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (rotate-gravity-in-one-chamber-x3454):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Gravity Chamber</title>
<style>
:root {
color-scheme: dark;
--bg: #07111d;
--panel: rgba(8, 24, 37, 0.78);
--border: rgba(126, 213, 255, 0.18);
--text: #e8f7ff;
--muted: #85a9bb;
--cyan: #65dcff;
--amber: #ffd166;
--orange: #ff8a3d;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
background:
radial-gradient(circle at 50% 42%, #102c40 0%, #07111d 52%, #030a12 100%);
}
canvas {
position: fixed;
inset: 0;
display: block;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
}
.panel {
background: var(--panel);
border: 1px solid var(--border);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.brand {
position: absolute;
top: 24px;
left: 24px;
width: min(370px, calc(100vw - 48px));
padding: 18px 20px;
border-radius: 16px;
}
.brand-row {
display: flex;
align-items: center;
gap: 13px;
}
.brand-icon {
position: relative;
width: 36px;
height: 36px;
flex: 0 0 auto;
border: 2px solid var(--cyan);
border-radius: 9px;
transform: rotate(30deg) skewY(-8deg);
box-shadow: inset 0 0 20px rgba(101, 220, 255, 0.12);
}
.brand-icon::before,
.brand-icon::after {
content: "";
position: absolute;
background: var(--cyan);
opacity: 0.75;
}
.brand-icon::before {
width: 2px;
height: 100%;
left: 16px;
top: 0;
}
.brand-icon::after {
width: 100%;
height: 2px;
left: 0;
top: 16px;
}
h1 {
margin: 0;
font-size: 17px;
line-height: 1.15;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.subtitle {
margin: 7px 0 0;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.telemetry {
position: absolute;
top: 24px;
right: 24px;
width: 236px;
padding: 16px;
border-radius: 16px;
}
.eyebrow {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.gravity-main {
display: flex;
align-items: center;
gap: 14px;
margin-top: 9px;
}
#gravityGlyph {
width: 54px;
color: var(--amber);
font-size: 48px;
font-weight: 800;
line-height: 1;
text-align: center;
text-shadow: 0 0 24px rgba(255, 209, 102, 0.28);
}
#gravityName {
font-size: 16px;
font-weight: 800;
letter-spacing: 0.08em;
}
#gravityVector {
margin-top: 5px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
}
.stages {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 7px;
margin-top: 14px;
}
.stage {
display: grid;
place-items: center;
height: 29px;
border: 1px solid rgba(126, 213, 255, 0.12);
border-radius: 7px;
color: #5f8192;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 17px;
transition: 160ms ease;
}
.stage.active {
border-color: rgba(255, 209, 102, 0.72);
background: rgba(255, 209, 102, 0.12);
color: var(--amber);
box-shadow: 0 0 18px rgba(255, 209, 102, 0.1);
}
.status {
display: flex;
align-items: center;
gap: 8px;
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid rgba(126, 213, 255, 0.1);
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--orange);
box-shadow: 0 0 12px var(--orange);
}
.status.settled .status-dot {
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
.controls {
position: absolute;
left: 50%;
bottom: 25px;
display: flex;
align-items: center;
gap: 10px;
padding: 10px;
border-radius: 17px;
pointer-events: auto;
transform: translateX(-50%);
}
button {
border: 0;
font: inherit;
cursor: pointer;
}
#rotateButton {
display: flex;
align-items: center;
gap: 11px;
min-width: 224px;
justify-content: center;
padding: 14px 19px;
border-radius: 11px;
background: linear-gradient(135deg, #ffd978, #ffad43);
color: #231500;
font-size: 13px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
box-shadow: 0 8px 24px rgba(255, 170, 61, 0.2);
transition: transform 140ms ease, filter 140ms ease, box-shadow 140ms ease;
}
#rotateButton:hover {
filter: brightness(1.08);
transform: translateY(-2px);
box-shadow: 0 12px 30px rgba(255, 170, 61, 0.3);
}
#rotateButton:active {
transform: translateY(0) scale(0.98);
}
#rotateButton:focus-visible,
#resetButton:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 3px;
}
.rotate-icon {
font-size: 21px;
line-height: 1;
}
.keycap {
margin-left: 3px;
padding: 3px 6px;
border: 1px solid rgba(35, 21, 0, 0.24);
border-radius: 5px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
#resetButton {
width: 46px;
height: 46px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(101, 220, 255, 0.06);
color: var(--cyan);
font-size: 20px;
transition: background 140ms ease, transform 140ms ease;
}
#resetButton:hover {
background: rgba(101, 220, 255, 0.13);
transform: translateY(-1px);
}
.help {
position: absolute;
left: 24px;
bottom: 27px;
color: rgba(167, 203, 220, 0.68);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
letter-spacing: 0.05em;
line-height: 1.7;
}
.help strong {
color: var(--cyan);
font-weight: 700;
}
.corner-note {
position: absolute;
right: 26px;
bottom: 27px;
color: rgba(167, 203, 220, 0.5);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.09em;
text-align: right;
text-transform: uppercase;
}
@media (max-width: 760px) {
.brand {
top: 12px;
left: 12px;
padding: 13px 15px;
}
.brand-icon {
width: 29px;
height: 29px;
}
.brand-icon::before {
left: 12px;
}
.brand-icon::after {
top: 12px;
}
h1 {
font-size: 13px;
}
.subtitle {
font-size: 9px;
}
.telemetry {
top: auto;
right: 12px;
bottom: 88px;
width: 185px;
padding: 12px;
}
#gravityGlyph {
width: 39px;
font-size: 36px;
}
#gravityName {
font-size: 12px;
}
.status {
font-size: 8px;
}
.controls {
bottom: 14px;
}
#rotateButton {
min-width: 190px;
padding: 13px 15px;
font-size: 11px;
}
.keycap,
.help,
.corner-note {
display: none;
}
}
</style>
</head>
<body>
<div class="hud">
<section class="brand panel">
<div class="brand-row">
<div class="brand-icon" aria-hidden="true"></div>
<div>
<h1>Gravity Chamber</h1>
<p class="subtitle">Voxel dynamics / four-wall rotation</p>
</div>
</div>
</section>
<section class="telemetry panel" aria-live="polite">
<div class="eyebrow">Active acceleration</div>
<div class="gravity-main">
<div id="gravityGlyph">↓</div>
<div>
<div id="gravityName">FLOOR WALL</div>
<div id="gravityVector">(0, −20, 0) m/s²</div>
</div>
</div>
<div class="stages" aria-label="Gravity direction">
<div class="stage active" data-stage="0">↓</div>
<div class="stage" data-stage="1">→</div>
<div class="stage" data-stage="2">↑</div>
<div class="stage" data-stage="3">←</div>
</div>
<div id="status" class="status">
<span class="status-dot"></span>
<span id="statusText">Settling on floor wall</span>
</div>
</section>
<section class="controls panel">
<button id="rotateButton" type="button">
<span class="rotate-icon">↻</span>
<span>Rotate gravity 90°</span>
<span class="keycap">SPACE</span>
</button>
<button id="resetButton" type="button" title="Reset chamber" aria-label="Reset chamber">↺</button>
</section>
<div class="help">
<strong>DRAG</strong> to orbit · <strong>SCROLL</strong> to zoom<br>
Fixed-step collision · Damping · Sleep threshold
</div>
<div class="corner-note">Single bounded voxel test cell<br>Acceleration magnitude locked at 20 m/s²</div>
</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, camera
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111d);
scene.fog = new THREE.FogExp2(0x07111d, 0.022);
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.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xbdeeff, 0x132331, 1.8);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff1d6, 3.2);
keyLight.position.set(-8, 12, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x38caff, 35, 30, 2);
rimLight.position.set(9, 2, -3);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Chamber dimensions. Physics boundaries correspond to the inner tile faces.
// -------------------------------------------------------------------------
const bounds = {
min: new THREE.Vector3(-7, -5, -3.8),
max: new THREE.Vector3(7, 5, 3.8)
};
const width = bounds.max.x - bounds.min.x;
const height = bounds.max.y - bounds.min.y;
const depth = bounds.max.z - bounds.min.z;
const center = new THREE.Vector3(0, 0, 0);
const unitCube = new THREE.BoxGeometry(1, 1, 1);
function seededRandom(seed) {
const value = Math.sin(seed * 12.9898 + 78.233) * 43758.5453;
return value - Math.floor(value);
}
function createVoxelSurface(entries, material, baseHex, seedOffset) {
const mesh = new THREE.InstancedMesh(unitCube, material, entries.length);
const matrix = new THREE.Matrix4();
const quaternion = new THREE.Quaternion();
const scale = new THREE.Vector3();
const color = new THREE.Color();
entries.forEach((entry, index) => {
matrix.compose(entry.position, quaternion, entry.scale);
mesh.setMatrixAt(index, matrix);
const variation = seededRandom(index + seedOffset);
color.setHex(baseHex);
color.offsetHSL(
(variation - 0.5) * 0.018,
(variation - 0.5) * 0.08,
(variation - 0.5) * 0.14
);
mesh.setColorAt(index, color);
});
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.receiveShadow = !material.transparent;
scene.add(mesh);
return mesh;
}
function makeGridEntries(axis, side) {
const entries = [];
const thickness = 0.32;
const nx = 28;
const ny = 20;
const nz = 15;
const sx = width / nx;
const sy = height / ny;
const sz = depth / nz;
if (axis === "x") {
for (let y = 0; y < ny; y++) {
for (let z = 0; z < nz; z++) {
entries.push({
position: new THREE.Vector3(
side < 0 ? bounds.min.x - thickness * 0.5 : bounds.max.x + thickness * 0.5,
bounds.min.y + (y + 0.5) * sy,
bounds.min.z + (z + 0.5) * sz
),
scale: new THREE.Vector3(thickness, sy * 0.9, sz * 0.9)
});
}
}
} else if (axis === "y") {
for (let x = 0; x < nx; x++) {
for (let z = 0; z < nz; z++) {
entries.push({
position: new THREE.Vector3(
bounds.min.x + (x + 0.5) * sx,
side < 0 ? bounds.min.y - thickness * 0.5 : bounds.max.y + thickness * 0.5,
bounds.min.z + (z + 0.5) * sz
),
scale: new THREE.Vector3(sx * 0.9, thickness, sz * 0.9)
});
}
}
} else {
for (let x = 0; x < nx; x++) {
for (let y = 0; y < ny; y++) {
entries.push({
position: new THREE.Vector3(
bounds.min.x + (x + 0.5) * sx,
bounds.min.y + (y + 0.5) * sy,
side < 0 ? bounds.min.z - thickness * 0.5 : bounds.max.z + thickness * 0.5
),
scale: new THREE.Vector3(sx * 0.9, sy * 0.9, thickness)
});
}
}
}
return entries;
}
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.8,
metalness: 0.12
});
const ceilingMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.72,
metalness: 0.08,
transparent: true,
opacity: 0.15,
depthWrite: false
});
const backMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.75,
metalness: 0.08,
transparent: true,
opacity: 0.38,
depthWrite: false
});
const sideMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.68,
metalness: 0.08,
transparent: true,
opacity: 0.2,
depthWrite: false
});
const frontMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.65,
metalness: 0.05,
transparent: true,
opacity: 0.055,
depthWrite: false
});
createVoxelSurface(makeGridEntries("y", -1), floorMaterial, 0x245968, 10);
createVoxelSurface(makeGridEntries("y", 1), ceilingMaterial, 0x4a8ca3, 100);
createVoxelSurface(makeGridEntries("z", -1), backMaterial, 0x24536d, 200);
createVoxelSurface(makeGridEntries("z", 1), frontMaterial, 0x4b91aa, 300);
createVoxelSurface(makeGridEntries("x", -1), sideMaterial, 0x2e7188, 400);
createVoxelSurface(makeGridEntries("x", 1), sideMaterial, 0x2e7188, 500);
// Structural frame around the voxel cell.
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x2c7085,
emissive: 0x082a35,
emissiveIntensity: 0.55,
roughness: 0.48,
metalness: 0.34
});
function addFrameBeam(position, scale) {
const beam = new THREE.Mesh(unitCube, frameMaterial);
beam.position.copy(position);
beam.scale.copy(scale);
beam.castShadow = true;
beam.receiveShadow = true;
scene.add(beam);
}
const postX = bounds.max.x + 0.18;
const postZ = bounds.max.z + 0.18;
for (const x of [bounds.min.x - 0.18, postX]) {
for (const z of [bounds.min.z - 0.18, postZ]) {
addFrameBeam(new THREE.Vector3(x, 0, z), new THREE.Vector3(0.48, height + 0.75, 0.48));
}
}
for (const y of [bounds.min.y - 0.18, bounds.max.y + 0.18]) {
for (const z of [bounds.min.z - 0.18, postZ]) {
addFrameBeam(new THREE.Vector3(0, y, z), new THREE.Vector3(width + 0.75, 0.48, 0.48));
}
for (const x of [bounds.min.x - 0.18, postX]) {
addFrameBeam(new THREE.Vector3(x, y, 0), new THREE.Vector3(0.48, 0.48, depth + 0.75));
}
}
// -------------------------------------------------------------------------
// Active wall highlights
// -------------------------------------------------------------------------
const wallGlows = [];
function addWallGlow(geometry, position, rotation, wallIndex) {
const material = new THREE.MeshBasicMaterial({
color: 0x65dcff,
transparent: true,
opacity: 0.025,
depthWrite: false,
side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(position);
mesh.rotation.set(rotation.x, rotation.y, rotation.z);
mesh.renderOrder = 2;
scene.add(mesh);
wallGlows[wallIndex] = mesh;
}
addWallGlow(
new THREE.PlaneGeometry(width, depth),
new THREE.Vector3(0, bounds.min.y + 0.012, 0),
new THREE.Euler(-Math.PI / 2, 0, 0),
0
);
addWallGlow(
new THREE.PlaneGeometry(depth, height),
new THREE.Vector3(bounds.max.x - 0.012, 0, 0),
new THREE.Euler(0, -Math.PI / 2, 0),
1
);
addWallGlow(
new THREE.PlaneGeometry(width, depth),
new THREE.Vector3(0, bounds.max.y - 0.012, 0),
new THREE.Euler(Math.PI / 2, 0, 0),
2
);
addWallGlow(
new THREE.PlaneGeometry(depth, height),
new THREE.Vector3(bounds.min.x + 0.012, 0, 0),
new THREE.Euler(0, Math.PI / 2, 0),
3
);
// -------------------------------------------------------------------------
// Voxel ball
// -------------------------------------------------------------------------
const ballRoot = new THREE.Group();
const ballVisual = new THREE.Group();
ballRoot.add(ballVisual);
scene.add(ballRoot);
const voxelStep = 0.18;
const voxelSize = 0.166;
const ballPositions = [];
for (let x = -3; x <= 3; x++) {
for (let y = -3; y <= 3; y++) {
for (let z = -3; z <= 3; z++) {
const point = new THREE.Vector3(x * voxelStep, y * voxelStep, z * voxelStep);
if (point.length() <= 0.50) ballPositions.push(point);
}
}
}
const ballMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
emissive: 0x6b1d05,
emissiveIntensity: 0.3,
roughness: 0.36,
metalness: 0.04
});
const ballMesh = new THREE.InstancedMesh(unitCube, ballMaterial, ballPositions.length);
const ballMatrix = new THREE.Matrix4();
const identity = new THREE.Quaternion();
const ballScale = new THREE.Vector3();
const ballColor = new THREE.Color();
ballPositions.forEach((position, index) => {
ballMatrix.compose(position, identity, ballScale.setScalar(voxelSize));
ballMesh.setMatrixAt(index, ballMatrix);
const variation = seededRandom(index + 900);
ballColor.setHex(0xff8a3d);
ballColor.offsetHSL(0, (variation - 0.5) * 0.06, (variation - 0.5) * 0.13);
ballMesh.setColorAt(index, ballColor);
});
ballMesh.instanceMatrix.needsUpdate = true;
if (ballMesh.instanceColor) ballMesh.instanceColor.needsUpdate = true;
ballMesh.castShadow = true;
ballMesh.receiveShadow = true;
ballVisual.add(ballMesh);
const ballLight = new THREE.PointLight(0xff8438, 12, 5, 2);
scene.add(ballLight);
// Small voxel trail.
const trailCount = 22;
const trailMesh = new THREE.InstancedMesh(
unitCube,
new THREE.MeshBasicMaterial({
color: 0xffb35f,
transparent: true,
opacity: 0.38,
depthWrite: false
}),
trailCount
);
trailMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
trailMesh.frustumCulled = false;
scene.add(trailMesh);
const trailHistory = [];
const trailMatrix = new THREE.Matrix4();
const trailScale = new THREE.Vector3();
// -------------------------------------------------------------------------
// Gravity arrow and label
// -------------------------------------------------------------------------
const arrowGroup = new THREE.Group();
const arrowMaterial = new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0xff8c19,
emissiveIntensity: 1.05,
roughness: 0.34,
metalness: 0.16
});
const arrowShaft = new THREE.Mesh(
new THREE.CylinderGeometry(0.095, 0.095, 2.25, 8),
arrowMaterial
);
arrowShaft.position.y = 1.125;
arrowShaft.castShadow = true;
arrowGroup.add(arrowShaft);
const arrowHead = new THREE.Mesh(
new THREE.ConeGeometry(0.36, 0.82, 8),
arrowMaterial
);
arrowHead.position.y = 2.65;
arrowHead.castShadow = true;
arrowGroup.add(arrowHead);
const arrowTail = new THREE.Mesh(
new THREE.SphereGeometry(0.14, 8, 6),
arrowMaterial
);
arrowTail.position.y = 0;
arrowGroup.add(arrowTail);
scene.add(arrowGroup);
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const labelContext = labelCanvas.getContext("2d");
const labelTexture = new THREE.CanvasTexture(labelCanvas);
labelTexture.colorSpace = THREE.SRGBColorSpace;
const labelSprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: labelTexture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
labelSprite.scale.set(3.35, 0.84, 1);
labelSprite.renderOrder = 10;
scene.add(labelSprite);
function roundedRect(context, x, y, width, height, radius) {
const r = Math.min(radius, width * 0.5, height * 0.5);
context.beginPath();
context.moveTo(x + r, y);
context.arcTo(x + width, y, x + width, y + height, r);
context.arcTo(x + width, y + height, x, y + height, r);
context.arcTo(x, y + height, x, y, r);
context.arcTo(x, y, x + width, y, r);
context.closePath();
}
function updateArrowLabel(glyph, wallName) {
labelContext.clearRect(0, 0, labelCanvas.width, labelCanvas.height);
roundedRect(labelContext, 8, 8, 496, 112, 24);
labelContext.fillStyle = "rgba(8, 24, 37, 0.88)";
labelContext.fill();
labelContext.strokeStyle = "rgba(255, 209, 102, 0.55)";
labelContext.lineWidth = 3;
labelContext.stroke();
labelContext.textAlign = "center";
labelContext.textBaseline = "middle";
labelContext.fillStyle = "#ffd166";
labelContext.font = "800 42px ui-monospace, monospace";
labelContext.fillText(`${glyph} g = 20 m/s²`, 256, 62);
labelContext.fillStyle = "#8fb5c7";
labelContext.font = "700 17px ui-monospace, monospace";
labelContext.fillText(wallName, 256, 98);
labelTexture.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Stable fixed-step sphere/AABB chamber physics
// -------------------------------------------------------------------------
const directions = [
{
vector: new THREE.Vector3(0, -1, 0),
glyph: "↓",
name: "FLOOR WALL",
vectorText: "(0, −20, 0) m/s²"
},
{
vector: new THREE.Vector3(1, 0, 0),
glyph: "→",
name: "RIGHT WALL",
vectorText: "(20, 0, 0) m/s²"
},
{
vector: new THREE.Vector3(0, 1, 0),
glyph: "↑",
name: "CEILING WALL",
vectorText: "(0, 20, 0) m/s²"
},
{
vector: new THREE.Vector3(-1, 0, 0),
glyph: "←",
name: "LEFT WALL",
vectorText: "(−20, 0, 0) m/s²"
}
];
const GRAVITY_MAGNITUDE = 20;
const BALL_RADIUS = 0.52;
const FIXED_STEP = 1 / 120;
const RESTITUTION = 0.08;
const FRICTION = 9;
const MAX_SPEED = 24;
const physicsPosition = new THREE.Vector3(0, bounds.min.y + BALL_RADIUS + 0.002, 0);
const physicsVelocity = new THREE.Vector3();
const gravityVector = directions[0].vector.clone();
const displayDirection = gravityVector.clone();
const upVector = new THREE.Vector3(0, 1, 0);
let gravityIndex = 0;
let accumulator = 0;
let sleepTimer = 0;
let sleeping = false;
let trailClock = 0;
function resolveAxis(axis, minimum, maximum) {
let touched = false;
if (physicsPosition[axis] - BALL_RADIUS < minimum) {
physicsPosition[axis] = minimum + BALL_RADIUS;
if (physicsVelocity[axis] < 0) {
const impactSpeed = -physicsVelocity[axis];
physicsVelocity[axis] = impactSpeed > 0.75 ? impactSpeed * RESTITUTION : 0;
}
touched = true;
} else if (physicsPosition[axis] + BALL_RADIUS > maximum) {
physicsPosition[axis] = maximum - BALL_RADIUS;
if (physicsVelocity[axis] > 0) {
const impactSpeed = physicsVelocity[axis];
physicsVelocity[axis] = impactSpeed > 0.75 ? -impactSpeed * RESTITUTION : 0;
}
touched = true;
}
return touched;
}
function stepPhysics(dt) {
if (sleeping) return;
physicsVelocity.addScaledVector(gravityVector, GRAVITY_MAGNITUDE * dt);
physicsVelocity.multiplyScalar(Math.exp(-0.015 * dt));
const speed = physicsVelocity.length();
if (speed > MAX_SPEED) {
physicsVelocity.multiplyScalar(MAX_SPEED / speed);
}
physicsPosition.addScaledVector(physicsVelocity, dt);
// Axis-separated resolution prevents tunneling and keeps corner contacts stable.
const touchedX = resolveAxis("x", bounds.min.x, bounds.max.x);
const touchedY = resolveAxis("y", bounds.min.y, bounds.max.y);
const touchedZ = resolveAxis("z", bounds.min.z, bounds.max.z);
const touchingWall = touchedX || touchedY || touchedZ;
// Tangential friction is applied only while in contact with the chamber.
if (touchingWall) {
const damping = Math.exp(-FRICTION * dt);
if (touchedY) {
physicsVelocity.x *= damping;
physicsVelocity.z *= damping;
}
if (touchedX) {
physicsVelocity.y *= damping;
physicsVelocity.z *= damping;
}
if (touchedZ) {
physicsVelocity.x *= damping;
physicsVelocity.y *= damping;
}
}
const remainingSpeed = physicsVelocity.length();
if (touchingWall && remainingSpeed < 0.18) {
sleepTimer += dt;
if (sleepTimer > 0.65) {
sleeping = true;
physicsVelocity.set(0, 0, 0);
}
} else {
sleepTimer = 0;
}
}
// -------------------------------------------------------------------------
// UI and gravity changes
// -------------------------------------------------------------------------
const gravityGlyph = document.getElementById("gravityGlyph");
const gravityName = document.getElementById("gravityName");
const gravityVectorText = document.getElementById("gravityVector");
const statusElement = document.getElementById("status");
const statusText = document.getElementById("statusText");
const stageElements = [...document.querySelectorAll(".stage")];
function updateGravityUI() {
const direction = directions[gravityIndex];
gravityGlyph.textContent = direction.glyph;
gravityName.textContent = direction.name;
gravityVectorText.textContent = direction.vectorText;
stageElements.forEach((element, index) => {
element.classList.toggle("active", index === gravityIndex);
});
updateArrowLabel(direction.glyph, direction.name);
}
function rotateGravity() {
gravityIndex = (gravityIndex + 1) % directions.length;
gravityVector.copy(directions[gravityIndex].vector);
// A small orbital kick gives the rotating gravity field a readable arc
// toward the center of the newly selected wall.
const tangent = new THREE.Vector3(
-gravityVector.y,
gravityVector.x,
0
).normalize();
const tangentCoordinate = physicsPosition.dot(tangent);
if (Math.abs(tangentCoordinate) > 0.05) {
physicsVelocity.addScaledVector(tangent, -Math.sign(tangentCoordinate) * 5.8);
}
sleeping = false;
sleepTimer = 0;
updateGravityUI();
}
function resetSimulation() {
gravityIndex = 0;
gravityVector.copy(directions[0].vector);
displayDirection.copy(gravityVector);
physicsPosition.set(0, bounds.min.y + BALL_RADIUS + 0.002, 0);
physicsVelocity.set(0, 0, 0);
sleeping = false;
sleepTimer = 0;
trailHistory.length = 0;
updateGravityUI();
}
document.getElementById("rotateButton").addEventListener("click", rotateGravity);
document.getElementById("resetButton").addEventListener("click", resetSimulation);
window.addEventListener("keydown", (event) => {
if (event.code === "Space" && event.target.tagName !== "BUTTON") {
event.preventDefault();
rotateGravity();
}
});
// -------------------------------------------------------------------------
// Custom camera controls — no external controls addon
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, -0.1, 0),
radius: 23.5,
azimuth: 0.62,
elevation: 0.31
};
function updateCamera() {
const horizontal = Math.cos(cameraState.elevation) * cameraState.radius;
camera.position.set(
cameraState.target.x + Math.sin(cameraState.azimuth) * horizontal,
cameraState.target.y + Math.sin(cameraState.elevation) * cameraState.radius,
cameraState.target.z + Math.cos(cameraState.azimuth) * horizontal
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.radius = 23.5;
cameraState.azimuth = 0.62;
cameraState.elevation = 0.31;
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.azimuth -= dx * 0.006;
cameraState.elevation = THREE.MathUtils.clamp(
cameraState.elevation + dy * 0.005,
-0.12,
1.15
);
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();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
15,
38
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
const rotationAxis = new THREE.Vector3();
const rotationQuaternion = new THREE.Quaternion();
let elapsed = 0;
updateGravityUI();
updateCamera();
function animate() {
requestAnimationFrame(animate);
const frameDelta = Math.min(clock.getDelta(), 0.05);
elapsed += frameDelta;
accumulator += frameDelta;
while (accumulator >= FIXED_STEP) {
stepPhysics(FIXED_STEP);
accumulator -= FIXED_STEP;
}
ballRoot.position.copy(physicsPosition);
ballLight.position.copy(physicsPosition);
// Rotate the voxel ball in the direction of travel.
const planarSpeed = Math.hypot(
physicsVelocity.x,
physicsVelocity.y
);
if (planarSpeed > 0.01) {
rotationAxis.set(
-physicsVelocity.y,
physicsVelocity.x,
0
).normalize();
rotationQuaternion.setFromAxisAngle(
rotationAxis,
planarSpeed * frameDelta / BALL_RADIUS
);
ballVisual.quaternion.premultiply(rotationQuaternion);
}
const pulse = sleeping ? 1 + Math.sin(elapsed * 2.2) * 0.012 : 1;
ballRoot.scale.setScalar(pulse);
// Smooth the visual arrow while the physical acceleration changes instantly.
displayDirection.lerp(
gravityVector,
1 - Math.exp(-frameDelta * 7)
).normalize();
arrowGroup.quaternion.setFromUnitVectors(upVector, displayDirection);
arrowGroup.position.copy(center)
.addScaledVector(displayDirection, -1.25)
.add(new THREE.Vector3(0, 0, 2.15));
labelSprite.position.copy(center)
.addScaledVector(displayDirection, -2.0)
.add(new THREE.Vector3(0, 0, 2.22));
const glowPulse = 0.13 + Math.sin(elapsed * 2.4) * 0.025;
wallGlows.forEach((wall, index) => {
wall.material.opacity = index === gravityIndex ? glowPulse : 0.018;
});
// Record the moving ball's path as shrinking voxel particles.
trailClock += frameDelta;
if (planarSpeed > 0.8 && trailClock > 0.035) {
trailClock = 0;
trailHistory.unshift({
position: physicsPosition.clone(),
born: elapsed
});
if (trailHistory.length > trailCount) trailHistory.pop();
}
for (let i = 0; i < trailCount; i++) {
const particle = trailHistory[i];
if (particle) {
const age = elapsed - particle.born;
const life = Math.max(0, 1 - age / 0.55);
trailMatrix.compose(
particle.position,
identity,
trailScale.setScalar(0.15 * life)
);
} else {
trailMatrix.compose(
center,
identity,
trailScale.setScalar(0)
);
}
trailMesh.setMatrixAt(i, trailMatrix);
}
trailMesh.instanceMatrix.needsUpdate = true;
if (sleeping) {
statusElement.classList.add("settled");
statusText.textContent = `Settled on ${directions[gravityIndex].name.toLowerCase()}`;
} else {
statusElement.classList.remove("settled");
statusText.textContent = `Ball moving toward ${directions[gravityIndex].name.toLowerCase()}`;
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```