Prompt specification
Build or customize the Three.js 3D scene "Grain discharge through a gate" 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: Grain discharge through a gate
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/grain-discharge-through-a-gate-x1066
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows grain storage. Animate a prescribed particle flow from the hopper into a bag; particles leave only through the open outlet and a count tracks remaining stored units. Voxel style.
Working Three.js Starter (grain-discharge-through-a-gate-x1066):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Grain Storage</title>
<style>
:root {
--ink: #173036;
--muted: #617579;
--panel: rgba(248, 249, 244, 0.92);
--line: rgba(23, 48, 54, 0.16);
--gold: #e7a63b;
--gold-dark: #b97922;
--green: #4f7770;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #d8e1dd;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
cursor: grab;
touch-action: none;
}
#viewport canvas:active {
cursor: grabbing;
}
.hud {
position: fixed;
z-index: 10;
pointer-events: none;
}
.panel {
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.72);
box-shadow:
0 16px 40px rgba(30, 53, 56, 0.13),
inset 0 0 0 1px var(--line);
backdrop-filter: blur(12px);
}
.stats {
top: 24px;
left: 24px;
width: 300px;
padding: 20px;
border-radius: 18px;
pointer-events: auto;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--gold);
box-shadow: 0 0 0 4px rgba(231, 166, 59, 0.15);
animation: pulse 1.5s ease-in-out infinite;
}
@keyframes pulse {
50% {
box-shadow: 0 0 0 7px rgba(231, 166, 59, 0);
}
}
h1 {
margin: 0;
font-size: 27px;
line-height: 1.05;
letter-spacing: -0.045em;
}
.subtitle {
margin: 7px 0 18px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.counter-wrap {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
padding: 15px 0 12px;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
#remaining {
display: block;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 45px;
font-weight: 800;
line-height: 0.95;
letter-spacing: -0.07em;
}
.counter-label {
max-width: 110px;
padding-bottom: 3px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
line-height: 1.35;
letter-spacing: 0.1em;
text-align: right;
text-transform: uppercase;
}
.bar {
height: 7px;
margin: 14px 0 10px;
overflow: hidden;
border-radius: 99px;
background: rgba(23, 48, 54, 0.1);
}
#remainingBar {
display: block;
width: 100%;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--gold-dark), var(--gold));
transition: width 180ms ease-out;
}
.metrics {
display: flex;
justify-content: space-between;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.metrics strong {
color: var(--ink);
font-family: "SFMono-Regular", Consolas, monospace;
}
.actions {
display: flex;
gap: 8px;
margin-top: 17px;
}
.actions button {
min-height: 38px;
padding: 0 13px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.68);
color: var(--ink);
cursor: pointer;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.04em;
transition: transform 120ms ease, background 120ms ease;
}
.actions button:hover {
transform: translateY(-1px);
background: white;
}
.actions button.primary {
border-color: var(--ink);
background: var(--ink);
color: white;
}
.flow-status {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 13px;
color: var(--muted);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 9px;
letter-spacing: 0.05em;
}
#flowState {
color: var(--green);
text-align: right;
}
.help {
top: 24px;
right: 24px;
padding: 11px 14px;
border-radius: 12px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
}
.route {
right: 24px;
bottom: 24px;
display: flex;
align-items: stretch;
overflow: hidden;
border-radius: 14px;
}
.route-step {
position: relative;
min-width: 94px;
padding: 12px 15px 11px;
border-left: 1px solid var(--line);
}
.route-step:first-child {
border-left: 0;
}
.route-step span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 9px;
}
.route-step strong {
font-size: 10px;
letter-spacing: 0.08em;
}
.route-step.active {
background: rgba(231, 166, 59, 0.13);
}
.route-step.active strong {
color: var(--gold-dark);
}
#worldLabels {
position: fixed;
z-index: 5;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
padding: 7px 10px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 8px;
background: rgba(23, 48, 54, 0.88);
box-shadow: 0 8px 20px rgba(23, 48, 54, 0.16);
color: white;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
white-space: nowrap;
transform: translate(-50%, -50%);
transition: opacity 120ms ease;
}
.world-label::before {
content: "";
display: inline-block;
width: 6px;
height: 6px;
margin-right: 7px;
border-radius: 2px;
background: var(--gold);
vertical-align: 1px;
}
@media (max-width: 720px) {
.stats {
top: 12px;
left: 12px;
width: min(270px, calc(100vw - 24px));
padding: 16px;
}
h1 {
font-size: 23px;
}
.subtitle,
.help {
display: none;
}
.route {
right: 12px;
bottom: 12px;
left: 12px;
}
.route-step {
min-width: 0;
flex: 1;
padding: 10px 8px;
}
.world-label {
font-size: 8px;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div id="worldLabels">
<div id="outletLabel" class="world-label">OPEN OUTLET</div>
<div id="bagLabel" class="world-label">COLLECTION BAG</div>
</div>
<section class="hud stats panel">
<div class="eyebrow">
<span class="live-dot"></span>
Material flow / unit 07
</div>
<h1>Grain hopper</h1>
<p class="subtitle">
A prescribed voxel discharge sequence. Every unit travels through the
single open outlet before entering the bag.
</p>
<div class="counter-wrap">
<span id="remaining">180</span>
<span class="counter-label">Units remaining in hopper</span>
</div>
<div class="bar"><i id="remainingBar"></i></div>
<div class="metrics">
<span>In bag <strong id="transferred">000</strong></span>
<span>Total <strong id="total">180</strong></span>
</div>
<div class="actions">
<button id="pauseButton" class="primary" type="button">Pause flow</button>
<button id="resetButton" type="button">Refill hopper</button>
</div>
<div class="flow-status">
<span>OUTLET GATE</span>
<span id="flowState">OPEN · SEQUENCE ARMED</span>
</div>
</section>
<div class="hud help panel">Drag to orbit · Wheel to zoom · Double-click to reset</div>
<nav class="hud route panel" aria-label="Transfer stages">
<div id="stepStore" class="route-step active">
<span>01</span><strong>STORED</strong>
</div>
<div id="stepFunnel" class="route-step">
<span>02</span><strong>FUNNEL</strong>
</div>
<div id="stepOutlet" class="route-step">
<span>03</span><strong>OUTLET</strong>
</div>
<div id="stepBag" class="route-step">
<span>04</span><strong>BAG</strong>
</div>
</nav>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const viewport = document.getElementById("viewport");
const renderer = new THREE.WebGLRenderer({
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.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xd8e1dd);
scene.fog = new THREE.Fog(0xd8e1dd, 16, 30);
const camera = new THREE.OrthographicCamera(-8, 8, 5.25, -5.25, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 3.55, 0);
const desiredView = {
theta: 0.58,
phi: 1.06,
radius: 12.5,
zoom: 1
};
const currentView = {
theta: desiredView.theta,
phi: desiredView.phi,
radius: desiredView.radius,
zoom: desiredView.zoom
};
const hemisphere = new THREE.HemisphereLight(0xf7fbf7, 0x536565, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff3d6, 3.3);
sun.position.set(7, 11, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -7;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0xaac8d0, 1.2);
rimLight.position.set(-7, 5, -6);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Materials and voxel construction helpers
// -------------------------------------------------------------------------
const materials = {
steel: new THREE.MeshStandardMaterial({
color: 0x52757a,
roughness: 0.72,
metalness: 0.18,
flatShading: true
}),
steelLight: new THREE.MeshStandardMaterial({
color: 0x789397,
roughness: 0.68,
metalness: 0.16,
flatShading: true
}),
steelDark: new THREE.MeshStandardMaterial({
color: 0x304b50,
roughness: 0.7,
metalness: 0.24,
flatShading: true
}),
accent: new THREE.MeshStandardMaterial({
color: 0xe3a13a,
roughness: 0.7,
metalness: 0.08,
flatShading: true
}),
bag: new THREE.MeshStandardMaterial({
color: 0xb8894e,
roughness: 0.96,
metalness: 0,
flatShading: true
}),
bagDark: new THREE.MeshStandardMaterial({
color: 0x8d6338,
roughness: 1,
metalness: 0,
flatShading: true
}),
ghost: new THREE.MeshStandardMaterial({
color: 0xa9c5c6,
roughness: 0.6,
metalness: 0.05,
transparent: true,
opacity: 0.16,
depthWrite: false,
flatShading: true
}),
bagGhost: new THREE.MeshStandardMaterial({
color: 0xd0a468,
roughness: 1,
metalness: 0,
transparent: true,
opacity: 0.27,
depthWrite: false,
flatShading: true
}),
ground: new THREE.MeshStandardMaterial({
color: 0x71817f,
roughness: 1,
flatShading: true
})
};
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function addBox(
width,
height,
depth,
x,
y,
z,
material,
castShadow = true,
receiveShadow = true
) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(width, height, depth);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = receiveShadow;
scene.add(mesh);
return mesh;
}
function addBeam(start, end, width, depth, material) {
const a = new THREE.Vector3(...start);
const b = new THREE.Vector3(...end);
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const mesh = new THREE.Mesh(unitBox, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.scale.set(width, length, depth);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Voxel floor
// -------------------------------------------------------------------------
addBox(16, 0.22, 12, 0, -0.16, 0, materials.ground, false, true);
const tileGeometry = new THREE.BoxGeometry(0.92, 0.06, 0.92);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.94,
flatShading: true
});
const tileColumns = 16;
const tileRows = 12;
const tiles = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
tileColumns * tileRows
);
const tileDummy = new THREE.Object3D();
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let row = 0; row < tileRows; row++) {
for (let column = 0; column < tileColumns; column++) {
tileDummy.position.set(
-7.5 + column,
-0.055,
-5.5 + row
);
tileDummy.updateMatrix();
tiles.setMatrixAt(tileIndex, tileDummy.matrix);
if ((row + column) % 2 === 0) {
tileColor.set(0xb9c5c0);
} else {
tileColor.set(0xcbd3ce);
}
// A small voxel safety pattern beneath the machine.
if (
(column >= 5 && column <= 10 && row >= 4 && row <= 7) &&
(column + row) % 3 === 0
) {
tileColor.set(0xd7a74d);
}
tiles.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
tiles.receiveShadow = true;
scene.add(tiles);
// -------------------------------------------------------------------------
// Hopper frame
// -------------------------------------------------------------------------
const legPositions = [
[-2.72, -1.78],
[2.72, -1.78],
[-2.72, 1.78],
[2.72, 1.78]
];
for (const [x, z] of legPositions) {
addBox(0.24, 4.0, 0.24, x, 2.0, z, materials.steelDark);
addBox(0.48, 0.16, 0.48, x, 0.08, z, materials.steelDark);
addBox(0.29, 0.22, 0.29, x, 3.86, z, materials.accent);
}
// Rear diagonal braces.
addBeam(
[-2.66, 0.35, -1.82],
[2.66, 3.72, -1.82],
0.13,
0.13,
materials.steelDark
);
addBeam(
[2.66, 0.35, -1.82],
[-2.66, 3.72, -1.82],
0.13,
0.13,
materials.steelDark
);
// Side braces.
addBeam(
[-2.76, 0.35, -1.7],
[-2.76, 3.65, 1.7],
0.11,
0.11,
materials.steelDark
);
addBeam(
[2.76, 0.35, -1.7],
[2.76, 3.65, 1.7],
0.11,
0.11,
materials.steelDark
);
// -------------------------------------------------------------------------
// Upper hopper: intentionally cut away at the front for visibility
// -------------------------------------------------------------------------
addBox(5.0, 3.16, 0.18, 0, 5.57, -1.42, materials.steel);
addBox(0.18, 3.16, 2.9, -2.45, 5.57, 0, materials.steel);
addBox(0.18, 3.16, 2.9, 2.45, 5.57, 0, materials.steel);
// Transparent front cutaway.
addBox(
5.0,
3.16,
0.07,
0,
5.57,
1.42,
materials.ghost,
false,
false
);
// Top open rim.
addBox(5.25, 0.18, 0.25, 0, 7.17, -1.43, materials.steelLight);
addBox(5.25, 0.18, 0.25, 0, 7.17, 1.43, materials.steelLight);
addBox(0.25, 0.18, 3.05, -2.5, 7.17, 0, materials.steelLight);
addBox(0.25, 0.18, 3.05, 2.5, 7.17, 0, materials.steelLight);
// Horizontal ribs and vertical seams on the rear wall.
for (const y of [4.25, 5.12, 5.99, 6.86]) {
addBox(4.82, 0.075, 0.08, 0, y, -1.535, materials.steelLight);
}
for (const x of [-1.75, -0.88, 0, 0.88, 1.75]) {
addBox(0.075, 2.95, 0.08, x, 5.56, -1.535, materials.steelLight);
}
// Corner caps.
for (const x of [-2.45, 2.45]) {
for (const z of [-1.42, 1.42]) {
addBox(0.28, 3.18, 0.28, x, 5.57, z, materials.steelDark);
}
}
// -------------------------------------------------------------------------
// Stepped funnel and the one permitted exit
// -------------------------------------------------------------------------
const funnelLevels = [
{ y: 3.79, half: 2.25, material: materials.steelLight },
{ y: 3.39, half: 1.80, material: materials.steel },
{ y: 2.99, half: 1.35, material: materials.steelLight },
{ y: 2.59, half: 0.90, material: materials.steel },
{ y: 2.27, half: 0.46, material: materials.steelLight }
];
for (const level of funnelLevels) {
const h = level.half;
const wallHeight = 0.43;
addBox(
0.18,
wallHeight,
2 * h + 0.18,
-h - 0.08,
level.y,
0,
level.material
);
addBox(
0.18,
wallHeight,
2 * h + 0.18,
h + 0.08,
level.y,
0,
level.material
);
addBox(
2 * h + 0.36,
wallHeight,
0.18,
0,
level.y,
-h - 0.08,
level.material
);
// The front is a ghost cutaway, not an opening used by particles.
addBox(
2 * h + 0.36,
wallHeight,
0.09,
0,
level.y,
h + 0.08,
materials.ghost,
false,
false
);
}
// Short open outlet tube centered directly over the bag.
addBox(0.14, 0.36, 0.82, -0.39, 2.20, 0, materials.steelDark);
addBox(0.14, 0.36, 0.82, 0.39, 2.20, 0, materials.steelDark);
addBox(0.82, 0.36, 0.14, 0, 2.20, -0.39, materials.steelDark);
addBox(
0.82,
0.36,
0.07,
0,
2.20,
0.39,
materials.ghost,
false,
false
);
// Bright voxel lip emphasizes the open exit.
addBox(0.13, 0.12, 0.80, -0.43, 2.04, 0, materials.accent);
addBox(0.13, 0.12, 0.80, 0.43, 2.04, 0, materials.accent);
addBox(0.80, 0.12, 0.13, 0, 2.04, -0.43, materials.accent);
addBox(0.80, 0.12, 0.13, 0, 2.04, 0.43, materials.accent);
// -------------------------------------------------------------------------
// Voxel collection bag
// -------------------------------------------------------------------------
const bagLevels = [
{ y: 0.14, w: 1.05, d: 0.76 },
{ y: 0.28, w: 1.25, d: 0.92 },
{ y: 0.42, w: 1.42, d: 1.04 },
{ y: 0.56, w: 1.56, d: 1.13 },
{ y: 0.70, w: 1.64, d: 1.19 },
{ y: 0.84, w: 1.68, d: 1.22 },
{ y: 0.98, w: 1.62, d: 1.18 },
{ y: 1.10, w: 1.50, d: 1.10 }
];
for (const level of bagLevels) {
const h = 0.17;
addBox(
0.15,
h,
level.d,
-level.w / 2,
level.y,
0,
materials.bag
);
addBox(
0.15,
h,
level.d,
level.w / 2,
level.y,
0,
materials.bag
);
addBox(
level.w,
h,
0.15,
0,
level.y,
-level.d / 2,
materials.bagDark
);
addBox(
level.w,
h,
0.08,
0,
level.y,
level.d / 2,
materials.bagGhost,
false,
false
);
}
// Dark bottom and a slightly lighter rolled rim.
addBox(1.12, 0.10, 0.84, 0, 0.05, 0, materials.bagDark);
addBox(1.58, 0.10, 0.16, 0, 1.16, -0.56, materials.bagDark);
addBox(1.58, 0.10, 0.16, 0, 1.16, 0.56, materials.bagDark);
addBox(0.16, 0.10, 1.18, -0.75, 1.16, 0, materials.bagDark);
addBox(0.16, 0.10, 1.18, 0.75, 1.16, 0, materials.bagDark);
// Small voxel control cabinet.
addBox(0.72, 1.10, 0.54, 3.20, 2.55, -0.86, materials.steelDark);
addBox(0.48, 0.40, 0.04, 3.20, 2.78, -0.575, materials.steelLight);
addBox(0.13, 0.13, 0.06, 3.05, 2.35, -0.56, materials.accent);
addBox(0.13, 0.13, 0.06, 3.34, 2.35, -0.56, materials.steelLight);
// -------------------------------------------------------------------------
// Grain particles
// -------------------------------------------------------------------------
const TOTAL = 180;
const grainGeometry = new THREE.BoxGeometry(0.13, 0.13, 0.13);
const grainMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.86,
metalness: 0,
flatShading: true
});
const grainMesh = new THREE.InstancedMesh(
grainGeometry,
grainMaterial,
TOTAL
);
grainMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
grainMesh.castShadow = true;
grainMesh.receiveShadow = true;
grainMesh.frustumCulled = false;
scene.add(grainMesh);
const particles = [];
const grainDummy = new THREE.Object3D();
const grainColor = new THREE.Color();
function hash(n) {
const value = Math.sin(n * 127.1 + 311.7) * 43758.5453123;
return value - Math.floor(value);
}
let particleIndex = 0;
// Three orderly layers of 60 grains inside the hopper.
for (let layer = 0; layer < 3; layer++) {
for (let row = 0; row < 6; row++) {
for (let column = 0; column < 10; column++) {
const index = particleIndex++;
const start = {
x: (column - 4.5) * 0.43,
y: 4.47 + layer * 0.64,
z: (row - 2.5) * 0.43
};
// Each grain receives a unique, stable target slot in the bag.
const bagLayer = Math.floor(index / 60);
const bagIndex = index % 60;
const bagRow = Math.floor(bagIndex / 10);
const bagColumn = bagIndex % 10;
const target = {
x: (bagColumn - 4.5) * 0.14,
y: 0.22 + bagLayer * 0.15,
z: (bagRow - 2.5) * 0.18
};
particles.push({
index,
start,
target,
entry: {
x: start.x * 0.42,
y: 3.93,
z: start.z * 0.43
},
throat: {
x: (hash(index + 2) - 0.5) * 0.05,
y: 2.58,
z: (hash(index + 7) - 0.5) * 0.05
},
outlet: {
x: (hash(index + 11) - 0.5) * 0.035,
y: 2.20,
z: (hash(index + 19) - 0.5) * 0.035
},
bagMouth: {
x: (hash(index + 23) - 0.5) * 0.26,
y: 1.17,
z: (hash(index + 31) - 0.5) * 0.20
},
birth: 0.25 + index * 0.025,
rotationX: hash(index + 41) * Math.PI,
rotationY: hash(index + 43) * Math.PI,
rotationZ: hash(index + 47) * Math.PI,
exited: false
});
grainColor.setHSL(
0.105 + hash(index + 53) * 0.025,
0.68 + hash(index + 59) * 0.16,
0.48 + hash(index + 61) * 0.15
);
grainMesh.setColorAt(index, grainColor);
}
}
}
grainMesh.instanceColor.needsUpdate = true;
// -------------------------------------------------------------------------
// Deterministic animation
// -------------------------------------------------------------------------
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
function smooth01(value) {
const t = clamp(value, 0, 1);
return t * t * (3 - 2 * t);
}
function particlePosition(particle, time) {
const p = particle;
if (time < 0) {
return { ...p.start };
}
// Stage 1: move from the stored voxel lattice into the upper funnel.
if (time < 0.75) {
const t = smooth01(time / 0.75);
return {
x: lerp(p.start.x, p.entry.x, t),
y: lerp(p.start.y, p.entry.y, t),
z: lerp(p.start.z, p.entry.z, t)
};
}
// Stage 2: contract through the stepped funnel.
if (time < 1.45) {
const t = smooth01((time - 0.75) / 0.70);
return {
x: lerp(p.entry.x, p.throat.x, t),
y: lerp(p.entry.y, p.throat.y, t),
z: lerp(p.entry.z, p.throat.z, t)
};
}
// Stage 3: the only exit. The center path passes through the open tube.
if (time < 1.60) {
const t = smooth01((time - 1.45) / 0.15);
return {
x: lerp(p.throat.x, p.outlet.x, t),
y: lerp(p.throat.y, p.outlet.y, t),
z: lerp(p.throat.z, p.outlet.z, t)
};
}
// Stage 4: gravity-like descent into the bag mouth.
if (time < 2.15) {
const t = (time - 1.60) / 0.55;
const fall = t * t;
return {
x: lerp(p.outlet.x, p.bagMouth.x, t),
y: lerp(p.outlet.y, p.bagMouth.y, fall),
z: lerp(p.outlet.z, p.bagMouth.z, t)
};
}
// Stage 5: settle into the assigned voxel pile.
if (time < 2.60) {
const t = smooth01((time - 2.15) / 0.45);
return {
x: lerp(p.bagMouth.x, p.target.x, t),
y: lerp(p.bagMouth.y, p.target.y, t),
z: lerp(p.bagMouth.z, p.target.z, t)
};
}
return { ...p.target };
}
let simTime = 0;
let paused = false;
let remaining = TOTAL;
let transferred = 0;
const remainingElement = document.getElementById("remaining");
const transferredElement = document.getElementById("transferred");
const totalElement = document.getElementById("total");
const remainingBar = document.getElementById("remainingBar");
const flowState = document.getElementById("flowState");
const pauseButton = document.getElementById("pauseButton");
const resetButton = document.getElementById("resetButton");
const stepStore = document.getElementById("stepStore");
const stepFunnel = document.getElementById("stepFunnel");
const stepOutlet = document.getElementById("stepOutlet");
const stepBag = document.getElementById("stepBag");
totalElement.textContent = TOTAL;
function syncStats() {
remainingElement.textContent = String(remaining).padStart(3, "0");
transferredElement.textContent = String(transferred).padStart(3, "0");
remainingBar.style.width = `${(remaining / TOTAL) * 100}%`;
if (paused) {
flowState.textContent = "PAUSED · OUTLET STILL OPEN";
} else if (remaining === 0) {
flowState.textContent = "COMPLETE · ALL UNITS IN BAG";
} else if (transferred === 0) {
flowState.textContent = "OPEN · PRESCRIBED FLOW ARMED";
} else {
flowState.textContent = "DISCHARGING · OUTLET OPEN";
}
stepStore.classList.toggle("active", transferred === 0);
stepFunnel.classList.toggle("active", transferred > 0 && remaining > 0);
stepOutlet.classList.toggle("active", transferred > 0 && remaining > 0);
stepBag.classList.toggle("active", remaining === 0);
}
function updateGrains() {
for (let index = 0; index < particles.length; index++) {
const particle = particles[index];
const localTime = simTime - particle.birth;
const position = particlePosition(particle, localTime);
// Units are counted out only after crossing the lower outlet plane.
if (!particle.exited && position.y <= 2.201) {
particle.exited = true;
remaining--;
transferred++;
syncStats();
}
grainDummy.position.set(position.x, position.y, position.z);
if (localTime >= 1.40 && localTime < 2.20) {
grainDummy.rotation.set(
particle.rotationX + localTime * 2.2,
particle.rotationY + localTime * 1.7,
particle.rotationZ + localTime * 1.1
);
} else {
grainDummy.rotation.set(
particle.rotationX,
particle.rotationY,
particle.rotationZ
);
}
grainDummy.updateMatrix();
grainMesh.setMatrixAt(index, grainDummy.matrix);
}
grainMesh.instanceMatrix.needsUpdate = true;
}
function resetSimulation() {
simTime = 0;
remaining = TOTAL;
transferred = 0;
paused = false;
for (const particle of particles) {
particle.exited = false;
}
pauseButton.textContent = "Pause flow";
syncStats();
}
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume flow" : "Pause flow";
syncStats();
});
resetButton.addEventListener("click", resetSimulation);
// -------------------------------------------------------------------------
// Direct camera controls: orbit, zoom, and reset
// -------------------------------------------------------------------------
let dragging = false;
let previousX = 0;
let previousY = 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;
desiredView.theta -= deltaX * 0.006;
desiredView.phi = clamp(desiredView.phi + deltaY * 0.005, 0.55, 1.42);
});
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();
desiredView.radius = clamp(
desiredView.radius + event.deltaY * 0.012,
8.5,
18
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
desiredView.theta = 0.58;
desiredView.phi = 1.06;
desiredView.radius = 12.5;
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
function updateCamera(delta) {
const easing = 1 - Math.pow(0.0008, delta);
currentView.theta +=
(desiredView.theta - currentView.theta) * easing;
currentView.phi +=
(desiredView.phi - currentView.phi) * easing;
currentView.radius +=
(desiredView.radius - currentView.radius) * easing;
const desiredZoom = 12.5 / desiredView.radius;
currentView.zoom +=
(desiredZoom - currentView.zoom) * easing;
const horizontalRadius =
currentView.radius * Math.sin(currentView.phi);
camera.position.set(
cameraTarget.x +
horizontalRadius * Math.sin(currentView.theta),
cameraTarget.y +
currentView.radius * Math.cos(currentView.phi),
cameraTarget.z +
horizontalRadius * Math.cos(currentView.theta)
);
camera.zoom = currentView.zoom;
camera.updateProjectionMatrix();
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
// -------------------------------------------------------------------------
// Projected world labels
// -------------------------------------------------------------------------
const outletLabel = document.getElementById("outletLabel");
const bagLabel = document.getElementById("bagLabel");
const outletAnchor = new THREE.Vector3(0.45, 2.18, 0.12);
const bagAnchor = new THREE.Vector3(0.94, 0.80, 0.68);
function placeLabel(element, anchor, offsetX, offsetY) {
const projected = anchor.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.opacity = visible ? "1" : "0";
element.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth + offsetX}px`;
element.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight + offsetY}px`;
}
function updateLabels() {
placeLabel(outletLabel, outletAnchor, -48, -25);
placeLabel(bagLabel, bagAnchor, 45, 12);
}
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const viewHeight = Math.max(10.5, 7.4 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
resize();
syncStats();
updateGrains();
updateCamera(1);
let lastTime = performance.now();
function animate(now) {
const delta = Math.min((now - lastTime) / 1000, 0.05);
lastTime = now;
if (!paused) {
simTime += delta;
}
updateGrains();
updateCamera(delta);
updateLabels();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```