Prompt specification
Build or customize the Three.js 3D scene "Pick and Place With Occupancy Checks" 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: Pick and Place With Occupancy Checks
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/pick-and-place-with-occupancy-checks-x2062
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring a robot workcell with fixtures and occupancy rules. Animate one object transferred between fixtures only when the destination is empty. Preserve attachment during motion and update station occupancy at actual contact events. Voxel style.
Working Three.js Starter (pick-and-place-with-occupancy-checks-x2062):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Robot Workcell</title>
<style>
:root {
color-scheme: dark;
--bg: #081019;
--panel: rgba(12, 21, 32, 0.93);
--line: #26394b;
--text: #d9e7f2;
--muted: #8297aa;
--green: #59f2a3;
--red: #ff647c;
--amber: #ffc85a;
--blue: #55c8ff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
color: var(--text);
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
pointer-events: auto;
position: absolute;
top: 18px;
left: 18px;
width: min(350px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
overflow: auto;
padding: 18px;
background: var(--panel);
border: 1px solid var(--line);
border-top: 3px solid var(--amber);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(12px);
}
h1 {
margin: 0 0 4px;
font-size: 19px;
letter-spacing: 0.08em;
}
.subtitle {
margin: 0 0 15px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.status {
min-height: 44px;
padding: 10px 12px;
margin-bottom: 14px;
background: #111f2c;
border-left: 4px solid var(--blue);
font-size: 12px;
line-height: 1.45;
}
.status.success {
border-color: var(--green);
}
.status.danger {
border-color: var(--red);
}
.status.warning {
border-color: var(--amber);
}
.section-title {
margin: 16px 0 8px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.fixture-row,
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
min-height: 32px;
font-size: 12px;
}
.occupancy {
display: inline-block;
min-width: 72px;
padding: 4px 7px;
text-align: center;
border: 1px solid;
font-size: 10px;
letter-spacing: 0.08em;
}
.occupancy.occupied {
color: var(--green);
border-color: rgba(89, 242, 163, 0.55);
background: rgba(89, 242, 163, 0.08);
}
.occupancy.empty {
color: var(--red);
border-color: rgba(255, 100, 124, 0.45);
background: rgba(255, 100, 124, 0.06);
}
select,
button {
font: inherit;
color: var(--text);
background: #152534;
border: 1px solid #334b60;
border-radius: 0;
padding: 9px 10px;
cursor: pointer;
}
select {
width: 150px;
}
button {
min-height: 38px;
font-size: 11px;
letter-spacing: 0.05em;
text-transform: uppercase;
}
button:hover:not(:disabled) {
border-color: var(--amber);
color: var(--amber);
}
button.primary {
background: var(--amber);
border-color: var(--amber);
color: #17120a;
font-weight: 800;
}
button.primary:hover:not(:disabled) {
color: #17120a;
filter: brightness(1.08);
}
button:disabled,
select:disabled {
opacity: 0.38;
cursor: not-allowed;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
.buttons .wide {
grid-column: 1 / -1;
}
.progress-track {
height: 8px;
margin-top: 13px;
overflow: hidden;
background: #071018;
border: 1px solid #223747;
}
#progress {
width: 0;
height: 100%;
background: var(--amber);
transition: width 0.08s linear;
}
#phase {
margin-top: 7px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#log {
display: flex;
flex-direction: column;
gap: 7px;
max-height: 150px;
overflow: auto;
padding: 10px;
background: #070e15;
border: 1px solid #1d2e3e;
color: #a9bdcd;
font-size: 10px;
line-height: 1.4;
}
.log-time {
color: #587184;
margin-right: 6px;
}
#hint {
position: absolute;
right: 18px;
bottom: 18px;
padding: 10px 13px;
color: #a9bdcd;
background: rgba(8, 16, 25, 0.82);
border: 1px solid var(--line);
font-size: 10px;
letter-spacing: 0.04em;
pointer-events: none;
}
@media (max-width: 700px) {
.panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
max-height: 54vh;
padding: 13px;
}
#hint {
right: 10px;
bottom: 10px;
}
}
</style>
</head>
<body>
<div id="ui">
<section class="panel">
<h1>VOXEL WORKCELL</h1>
<p class="subtitle">
Pick-and-place transfer controller<br>
Fixture A → selected destination
</p>
<div id="status" class="status">
Ready. Fixture A is occupied; the selected destination is empty.
</div>
<div class="section-title">Fixture occupancy</div>
<div class="fixture-row">
<span>A · Load</span>
<span id="occ-A" class="occupancy occupied">OCCUPIED</span>
</div>
<div class="fixture-row">
<span>B · Inspect</span>
<span id="occ-B" class="occupancy empty">EMPTY</span>
</div>
<div class="fixture-row">
<span>C · Pack</span>
<span id="occ-C" class="occupancy empty">EMPTY</span>
</div>
<div class="section-title">Transfer destination</div>
<div class="control-row">
<label for="targetSelect">Target fixture</label>
<select id="targetSelect">
<option value="B">B · Inspect</option>
<option value="C">C · Pack</option>
</select>
</div>
<div class="buttons">
<button id="runBtn" class="primary wide">Run transfer</button>
<button id="toggleBtn">Toggle target occupancy</button>
<button id="resetBtn">Reset workcell</button>
</div>
<div class="progress-track"><div id="progress"></div></div>
<div id="phase">Idle</div>
<div class="section-title">Contact events</div>
<div id="log"></div>
</section>
<div id="hint">
DRAG TO ORBIT · WHEEL / PINCH TO ZOOM · CLICK FIXTURE TO SELECT
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const statusEl = $("status");
const logEl = $("log");
const phaseEl = $("phase");
const progressEl = $("progress");
const runBtn = $("runBtn");
const toggleBtn = $("toggleBtn");
const resetBtn = $("resetBtn");
const targetSelect = $("targetSelect");
// ---------------------------------------------------------------------
// Renderer and scene
// ---------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.domElement.setAttribute("aria-label", "Interactive voxel robot workcell");
document.body.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x081019);
scene.fog = new THREE.Fog(0x081019, 15, 30);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const hemisphere = new THREE.HemisphereLight(0xb9dcff, 0x263224, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff1cf, 3.2);
keyLight.position.set(5, 12, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -11;
keyLight.shadow.camera.right = 11;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x55aaff, 1.7);
rimLight.position.set(-8, 6, -7);
scene.add(rimLight);
function material(color, extra = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.08,
flatShading: true,
...extra
});
}
function addBox(parent, size, position, mat, castShadow = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), mat);
mesh.position.set(...position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const floorMaterial = material(0x15212b);
const floor = addBox(
scene,
[18, 0.3, 14],
[0, -0.15, 0.5],
floorMaterial,
false
);
const grid = new THREE.GridHelper(18, 36, 0x365166, 0x223542);
grid.position.y = 0.012;
grid.material.transparent = true;
grid.material.opacity = 0.6;
scene.add(grid);
// Low safety fence built entirely from box geometry.
const safetyYellow = material(0xe9ad36);
const safetyDark = material(0x202a32);
function safetyPost(x, z) {
addBox(scene, [0.18, 1.25, 0.18], [x, 0.625, z], safetyYellow);
addBox(scene, [0.25, 0.12, 0.25], [x, 0.06, z], safetyDark);
}
function safetyRail(x, y, z, width, depth = 0.12) {
addBox(scene, [width, 0.13, depth], [x, y, z], safetyYellow);
}
[
[-6.7, -3.0],
[-3.4, -3.0],
[0, -3.0],
[3.4, -3.0],
[6.7, -3.0],
[-6.7, 4.6],
[-3.4, 4.6],
[0, 4.6],
[3.4, 4.6],
[6.7, 4.6]
].forEach(([x, z]) => safetyPost(x, z));
for (const y of [0.35, 1.0]) {
safetyRail(-5.05, y, -3, 3.3);
safetyRail(-1.7, y, -3, 3.3);
safetyRail(1.7, y, -3, 3.3);
safetyRail(5.05, y, -3, 3.3);
safetyRail(-6.7, y, 0.8, 7.4, 0.12);
safetyRail(6.7, y, 0.8, 7.4, 0.12);
}
// ---------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------
const SUPPORT_TOP = 0.76;
const PAYLOAD_SIZE = 0.9;
const PAYLOAD_HALF = PAYLOAD_SIZE / 2;
const GRIPPER_DROP = 0.95;
const CONTACT_EPSILON = 0.012;
const SEPARATION_EPSILON = 0.018;
const pickMeshes = [];
function makeLabel(text, accent = "#ffc85a") {
const canvas = document.createElement("canvas");
canvas.width = 320;
canvas.height = 72;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(8,16,25,0.92)";
ctx.fillRect(0, 0, 320, 72);
ctx.fillStyle = accent;
ctx.fillRect(0, 0, 8, 72);
ctx.strokeStyle = "#365064";
ctx.strokeRect(1, 1, 318, 70);
ctx.fillStyle = "#e4f1fa";
ctx.font = "bold 27px monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 164, 37);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false
})
);
sprite.scale.set(1.85, 0.42, 1);
sprite.renderOrder = 20;
return sprite;
}
function buildStation(id, name, x, z, accentColor, occupied) {
const group = new THREE.Group();
group.position.set(x, 0, z);
scene.add(group);
const bodyMat = material(0x344858);
const deckMat = material(0x50697b);
const accentMat = material(accentColor);
const darkMat = material(0x17232d);
const base = addBox(group, [2.0, 0.35, 1.8], [0, 0.175, 0], bodyMat);
const pedestal = addBox(group, [1.25, 0.23, 1.12], [0, 0.465, 0], deckMat);
const leftRail = addBox(
group,
[0.18, 0.18, 0.95],
[-0.36, 0.67, 0],
accentMat
);
const rightRail = addBox(
group,
[0.18, 0.18, 0.95],
[0.36, 0.67, 0],
accentMat
);
[base, pedestal, leftRail, rightRail].forEach((mesh) => {
mesh.userData.stationId = id;
pickMeshes.push(mesh);
});
// Four voxel locating pegs.
for (const px of [-0.82, 0.82]) {
for (const pz of [-0.68, 0.68]) {
addBox(
group,
[0.15, 0.19, 0.15],
[px, 0.445, pz],
accentMat
);
}
}
// Occupancy beacon.
addBox(group, [0.15, 1.35, 0.15], [0, 0.675, 0.76], darkMat);
addBox(group, [0.65, 0.26, 0.34], [0, 1.39, 0.76], darkMat);
const lampMat = material(
occupied ? 0x59f2a3 : 0xff647c,
{
emissive: occupied ? 0x59f2a3 : 0xff647c,
emissiveIntensity: 1.25
}
);
const lamp = addBox(
group,
[0.48, 0.15, 0.25],
[0, 1.39, 0.82],
lampMat,
false
);
const label = makeLabel(`${id} · ${name}`, accentColor);
label.position.set(0, 0.36, 1.15);
group.add(label);
const center = new THREE.Vector3(
x,
SUPPORT_TOP + PAYLOAD_HALF,
z
);
return {
id,
name,
group,
lamp,
center,
graspWrist: center.clone().add(new THREE.Vector3(0, GRIPPER_DROP, 0)),
aboveWrist: center.clone().add(new THREE.Vector3(0, 2.1, 0)),
occupied
};
}
const stations = {
A: buildStation("A", "LOAD", -4.2, -1.1, 0xffad42, true),
B: buildStation("B", "INSPECT", 0, -1.1, 0x45bfff, false),
C: buildStation("C", "PACK", 4.2, -1.1, 0xa679ff, false)
};
const source = stations.A;
// ---------------------------------------------------------------------
// Cargo objects
// ---------------------------------------------------------------------
function makeCargo(mainColor, panelColor) {
const group = new THREE.Group();
const bodyMat = material(mainColor);
const panelMat = material(panelColor);
addBox(
group,
[PAYLOAD_SIZE, PAYLOAD_SIZE, PAYLOAD_SIZE],
[0, 0, 0],
bodyMat
);
// Recessed-looking voxel panels, without changing the contact footprint.
addBox(
group,
[0.62, 0.48, 0.035],
[0, 0, PAYLOAD_HALF + 0.018],
panelMat
);
addBox(
group,
[0.62, 0.48, 0.035],
[0, 0, -PAYLOAD_HALF - 0.018],
panelMat
);
addBox(
group,
[0.035, 0.48, 0.62],
[PAYLOAD_HALF + 0.018, 0, 0],
panelMat
);
return group;
}
const payload = makeCargo(0xffa23a, 0x5b3017);
payload.position.copy(source.center);
scene.add(payload);
const blockers = new Map();
// ---------------------------------------------------------------------
// Voxel robot arm
// ---------------------------------------------------------------------
const robotRoot = new THREE.Group();
robotRoot.position.set(0, 0, 2.3);
scene.add(robotRoot);
const robotBaseMat = material(0x263746);
const robotDarkMat = material(0x17232e);
const robotArmMat = material(0xf4b63f);
const robotJointMat = material(0x4d6476);
addBox(robotRoot, [1.65, 0.32, 1.65], [0, 0.16, 0], robotDarkMat);
addBox(robotRoot, [1.12, 0.68, 1.12], [0, 0.66, 0], robotBaseMat);
addBox(robotRoot, [1.28, 0.15, 1.28], [0, 1.05, 0], robotJointMat);
const L1 = 4.4;
const L2 = 3.8;
const SHOULDER_Y = 1.15;
const yawGroup = new THREE.Group();
yawGroup.position.y = SHOULDER_Y;
robotRoot.add(yawGroup);
const shoulderHousing = addBox(
yawGroup,
[0.82, 0.82, 0.82],
[0, 0, 0],
robotJointMat
);
const shoulderGroup = new THREE.Group();
yawGroup.add(shoulderGroup);
addBox(
shoulderGroup,
[L1, 0.48, 0.48],
[L1 / 2, 0, 0],
robotArmMat
);
addBox(
shoulderGroup,
[0.58, 0.66, 0.66],
[0.38, 0, 0],
robotDarkMat
);
const elbowGroup = new THREE.Group();
elbowGroup.position.x = L1;
shoulderGroup.add(elbowGroup);
addBox(elbowGroup, [0.78, 0.78, 0.78], [0, 0, 0], robotJointMat);
addBox(
elbowGroup,
[L2, 0.39, 0.39],
[L2 / 2, 0, 0],
robotArmMat
);
const wristGroup = new THREE.Group();
wristGroup.position.x = L2;
elbowGroup.add(wristGroup);
addBox(wristGroup, [0.68, 0.62, 0.62], [0, 0, 0], robotJointMat);
addBox(wristGroup, [1.18, 0.25, 0.48], [0, -0.24, 0], robotDarkMat);
const leftFinger = addBox(
wristGroup,
[0.16, 0.78, 0.30],
[-0.66, -0.67, 0],
robotJointMat
);
const rightFinger = addBox(
wristGroup,
[0.16, 0.78, 0.30],
[0.66, -0.67, 0],
robotJointMat
);
// A small illuminated status block on the shoulder.
const servoLightMat = material(0x59f2a3, {
emissive: 0x59f2a3,
emissiveIntensity: 1.4
});
addBox(
shoulderHousing,
[0.28, 0.12, 0.86],
[0, 0.42, 0],
servoLightMat,
false
);
const homeWrist = new THREE.Vector3(-1.8, 3.8, 1.0);
const currentWrist = homeWrist.clone();
function solveIK(target) {
const dx = target.x - robotRoot.position.x;
const dz = target.z - robotRoot.position.z;
const radial = Math.max(0.001, Math.hypot(dx, dz));
const dy = target.y - SHOULDER_Y;
const rawCos =
(radial * radial + dy * dy - L1 * L1 - L2 * L2) /
(2 * L1 * L2);
const elbowCos = THREE.MathUtils.clamp(rawCos, -1, 1);
const elbowAngle = Math.acos(elbowCos);
const shoulderAngle =
Math.atan2(dy, radial) -
Math.atan2(
L2 * Math.sin(elbowAngle),
L1 + L2 * Math.cos(elbowAngle)
);
yawGroup.rotation.y = Math.atan2(-dz, dx);
shoulderGroup.rotation.z = shoulderAngle;
elbowGroup.rotation.z = elbowAngle;
// Counter-rotate the wrist so the gripper remains vertical.
wristGroup.rotation.z = -(shoulderAngle + elbowAngle);
}
solveIK(currentWrist);
// ---------------------------------------------------------------------
// Occupancy and UI
// ---------------------------------------------------------------------
function setStationOccupied(station, occupied) {
station.occupied = occupied;
const color = occupied ? 0x59f2a3 : 0xff647c;
station.lamp.material.color.setHex(color);
station.lamp.material.emissive.setHex(color);
const badge = $(`occ-${station.id}`);
badge.textContent = occupied ? "OCCUPIED" : "EMPTY";
badge.className = `occupancy ${occupied ? "occupied" : "empty"}`;
}
function refreshOccupancy() {
Object.values(stations).forEach((station) => {
setStationOccupied(station, station.occupied);
});
}
function setStatus(message, type = "info") {
statusEl.textContent = message;
statusEl.className = `status ${type}`;
}
function log(message) {
const row = document.createElement("div");
const time = document.createElement("span");
const text = document.createElement("span");
time.className = "log-time";
time.textContent = new Date().toLocaleTimeString([], {
hour12: false,
minute: "2-digit",
second: "2-digit"
});
text.textContent = message;
row.append(time, text);
logEl.prepend(row);
while (logEl.children.length > 8) {
logEl.lastElementChild.remove();
}
}
function getTargetStation() {
return stations[targetSelect.value];
}
function isTransferActive() {
return !["idle", "done"].includes(phase.name);
}
function updateButtons() {
const active = isTransferActive();
runBtn.disabled = active || hasTransferred;
toggleBtn.disabled = active || hasTransferred;
targetSelect.disabled = active;
}
refreshOccupancy();
// ---------------------------------------------------------------------
// Transfer state machine
// ---------------------------------------------------------------------
const phaseMessages = {
idle: "Idle",
approach: "Approaching source fixture",
"lower-source": "Lowering to source contact",
lift: "Lifting; source releases at contact loss",
transfer: "Transferring with payload attached",
"lower-destination": "Descending toward the empty destination",
retract: "Payload released; retracting gripper",
done: "Transfer complete",
blocked: "Transfer blocked"
};
let phase = {
name: "idle",
elapsed: 0,
duration: 1,
from: currentWrist.clone(),
to: currentWrist.clone(),
arc: 0
};
let hasTransferred = false;
const flashes = [];
function beginPhase(name, to, duration, arc = 0) {
phase = {
name,
elapsed: 0,
duration,
from: currentWrist.clone(),
to: to.clone(),
arc
};
if (name !== "done") {
setStatus(phaseMessages[name] || name, "info");
}
}
function flashStation(station, color) {
const group = new THREE.Group();
group.position.set(
station.center.x,
station.supportTop ?? SUPPORT_TOP,
station.center.z
);
const flashMat = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.95,
depthWrite: false
});
for (const x of [-0.62, 0.62]) {
for (const z of [-0.62, 0.62]) {
addBox(group, [0.22, 0.055, 0.22], [x, 0.02, z], flashMat, false);
}
}
scene.add(group);
flashes.push({ group, mat: flashMat, life: 1 });
}
function updateFlashes(dt) {
for (let i = flashes.length - 1; i >= 0; i--) {
const flash = flashes[i];
flash.life -= dt * 1.4;
if (flash.life <= 0) {
scene.remove(flash.group);
flashes.splice(i, 1);
continue;
}
flash.mat.opacity = flash.life;
const scale = 1 + (1 - flash.life) * 0.55;
flash.group.scale.setScalar(scale);
}
}
function updateGripperAperture() {
const closed = [
"lower-source",
"lift",
"transfer",
"lower-destination"
].includes(phase.name);
const offset = closed ? 0.54 : 0.66;
leftFinger.position.x = -offset;
rightFinger.position.x = offset;
}
function checkSourceSeparation() {
if (!source.occupied) return;
const bounds = new THREE.Box3().setFromObject(payload);
if (bounds.min.y > SUPPORT_TOP + SEPARATION_EPSILON) {
// Actual geometric separation, not a precomputed animation timestamp.
setStationOccupied(source, false);
flashStation(source, 0xffc85a);
log("CONTACT LOSS at A: payload cleared the support plane; A is empty.");
}
}
function checkDestinationContact() {
const target = getTargetStation();
const bounds = new THREE.Box3().setFromObject(payload);
const worldCenter = payload.getWorldPosition(new THREE.Vector3());
const aligned =
Math.abs(worldCenter.x - target.center.x) < 0.38 &&
Math.abs(worldCenter.z - target.center.z) < 0.38;
const touching =
bounds.min.y <= SUPPORT_TOP + CONTACT_EPSILON &&
bounds.min.y >= SUPPORT_TOP - 0.2;
if (!aligned || !touching) return false;
// Preserve the world transform at the moment of contact, then detach.
scene.attach(payload);
// Remove the tiny contact tolerance so the payload rests exactly on
// the fixture support plane.
payload.position.y += SUPPORT_TOP - bounds.min.y;
// Occupancy changes only after actual support contact.
setStationOccupied(target, true);
flashStation(target, 0x59f2a3);
log(`CONTACT at ${target.id}: payload touched the support; ${target.id} is occupied.`);
log("Payload detached at contact using a preserved world transform.");
hasTransferred = true;
beginPhase("retract", target.aboveWrist, 1.05);
setStatus(
`Released at ${target.id}. The gripper is retracting without the payload.`,
"success"
);
updateButtons();
return true;
}
function completePhase(completedName) {
const target = getTargetStation();
switch (completedName) {
case "approach":
beginPhase("lower-source", source.graspWrist, 1.15);
break;
case "lower-source":
// Object3D.attach preserves the payload's world transform.
wristGroup.updateWorldMatrix(true, false);
wristGroup.attach(payload);
log("GRASP: payload parented to the wrist; world transform preserved.");
beginPhase("lift", source.aboveWrist, 1.45);
break;
case "lift":
// Recheck immediately before transit. The transfer cannot begin
// unless the destination is still empty.
if (target.occupied) {
phase = {
name: "blocked",
elapsed: 0,
duration: 1,
from: currentWrist.clone(),
to: currentWrist.clone(),
arc: 0
};
setStatus(
`Transfer blocked: ${target.id} became occupied before transit. Reset the workcell.`,
"danger"
);
log(`RULE CHECK FAILED: ${target.id} is occupied. Transit was not started.`);
updateButtons();
break;
}
log(`RULE CHECK PASSED: ${target.id} is empty.`);
log("TRANSIT: payload remains attached to the moving wrist.");
beginPhase("transfer", target.aboveWrist, 2.45, 0.48);
break;
case "transfer":
beginPhase("lower-destination", target.graspWrist, 1.25);
break;
case "lower-destination":
// Normally contact handling has already changed the phase.
if (phase.name === "lower-destination") {
if (!checkDestinationContact()) {
phase = {
name: "blocked",
elapsed: 0,
duration: 1,
from: currentWrist.clone(),
to: currentWrist.clone(),
arc: 0
};
setStatus("Placement contact was not detected; transfer stopped safely.", "danger");
log("ERROR: destination contact was not detected.");
}
}
break;
case "retract":
phase = {
name: "done",
elapsed: 1,
duration: 1,
from: currentWrist.clone(),
to: currentWrist.clone(),
arc: 0
};
setStatus(
`Transfer complete. ${target.id} is occupied and fixture A is empty.`,
"success"
);
log(`TRANSFER COMPLETE: A → ${target.id}.`);
updateButtons();
break;
}
}
function updateTransfer(dt) {
if (!isTransferActive()) return;
const activePhase = phase;
activePhase.elapsed = Math.min(
activePhase.duration,
activePhase.elapsed + dt
);
const u = activePhase.elapsed / activePhase.duration;
const eased = u * u * (3 - 2 * u);
currentWrist.lerpVectors(activePhase.from, activePhase.to, eased);
if (activePhase.arc) {
currentWrist.y += Math.sin(Math.PI * u) * activePhase.arc;
}
solveIK(currentWrist);
scene.updateMatrixWorld(true);
if (activePhase.name === "lift") {
checkSourceSeparation();
}
if (activePhase.name === "lower-destination") {
if (checkDestinationContact()) return;
}
if (u >= 1 && phase === activePhase) {
completePhase(activePhase.name);
}
}
function runTransfer() {
if (isTransferActive() || hasTransferred) return;
const target = getTargetStation();
if (!source.occupied) {
setStatus("Transfer blocked: source fixture A is empty.", "danger");
log("RULE CHECK FAILED: source A is empty.");
return;
}
if (target.occupied) {
setStatus(
`Transfer blocked: destination ${target.id} is occupied.`,
"danger"
);
log(`RULE CHECK FAILED: destination ${target.id} is occupied.`);
flashStation(target, 0xff647c);
return;
}
log(`RULE CHECK PASSED: destination ${target.id} is empty.`);
beginPhase("approach", source.aboveWrist, 1.45);
updateButtons();
}
function toggleTargetOccupancy() {
if (isTransferActive() || hasTransferred) return;
const target = getTargetStation();
if (target.occupied) {
const blocker = blockers.get(target.id);
if (blocker) {
scene.remove(blocker);
blockers.delete(target.id);
}
setStationOccupied(target, false);
setStatus(`${target.id} cleared. The destination is empty and eligible.`, "success");
log(`MANUAL EVENT: ${target.id} occupancy cleared.`);
} else {
const blocker = makeCargo(0x426a9e, 0x223c61);
blocker.position.copy(target.center);
scene.add(blocker);
blockers.set(target.id, blocker);
setStationOccupied(target, true);
setStatus(`${target.id} is occupied. Any transfer to it will be rejected.`, "warning");
log(`MANUAL EVENT: ${target.id} occupied by an external cargo block.`);
}
}
function resetWorkcell() {
for (const blocker of blockers.values()) {
scene.remove(blocker);
}
blockers.clear();
if (payload.parent !== scene) {
scene.attach(payload);
}
payload.position.copy(source.center);
payload.quaternion.identity();
payload.scale.set(1, 1, 1);
setStationOccupied(source, true);
setStationOccupied(stations.B, false);
setStationOccupied(stations.C, false);
currentWrist.copy(homeWrist);
solveIK(currentWrist);
phase = {
name: "idle",
elapsed: 0,
duration: 1,
from: currentWrist.clone(),
to: currentWrist.clone(),
arc: 0
};
hasTransferred = false;
setStatus("Workcell reset. Fixture A is occupied; the selected destination is empty.", "info");
log("RESET: payload returned to A and all occupancy states were restored.");
updateButtons();
}
runBtn.addEventListener("click", runTransfer);
toggleBtn.addEventListener("click", toggleTargetOccupancy);
resetBtn.addEventListener("click", resetWorkcell);
targetSelect.addEventListener("change", () => {
const target = getTargetStation();
setStatus(
target.occupied
? `${target.id} is occupied and cannot accept the payload.`
: `${target.id} is empty and ready for transfer.`,
target.occupied ? "warning" : "info"
);
});
// ---------------------------------------------------------------------
// Custom camera controls: drag orbit, wheel zoom, pinch zoom.
// ---------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 1.0, -0.35),
radius: 13.8,
theta: 0.32,
phi: 1.03
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
updateCamera();
const pointers = new Map();
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
let dragTravel = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
dragTravel = 0;
});
renderer.domElement.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
previous.x = event.clientX;
previous.y = event.clientY;
dragTravel += Math.hypot(dx, dy);
if (pointers.size === 1) {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.005,
0.32,
1.43
);
} else if (pointers.size === 2) {
const values = [...pointers.values()];
const oldDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
const newDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (oldDistance > 0 && newDistance > 0) {
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * (oldDistance / newDistance),
7.0,
24.0
);
}
}
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
pointers.delete(event.pointerId);
if (dragTravel < 6) {
const rect = renderer.domElement.getBoundingClientRect();
pointerNDC.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const hit = raycaster.intersectObjects(pickMeshes, false)[0];
if (hit) {
const selectedId = hit.object.userData.stationId;
if (selectedId === "B" || selectedId === "C") {
targetSelect.value = selectedId;
targetSelect.dispatchEvent(new Event("change"));
}
}
}
});
renderer.domElement.addEventListener("pointercancel", (event) => {
pointers.delete(event.pointerId);
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7.0,
24.0
);
updateCamera();
},
{ passive: false }
);
// ---------------------------------------------------------------------
// Animation loop
// ---------------------------------------------------------------------
function updateHUD() {
let progress = 0;
if (phase.name === "done") {
progress = 1;
} else if (isTransferActive()) {
progress = phase.elapsed / phase.duration;
}
progressEl.style.width = `${THREE.MathUtils.clamp(progress, 0, 1) * 100}%`;
phaseEl.textContent = phaseMessages[phase.name] || phase.name;
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
updateTransfer(dt);
updateGripperAperture();
updateFlashes(dt);
updateHUD();
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
updateButtons();
log("SYSTEM READY: source A occupied; destinations B and C empty.");
animate();
</script>
</body>
</html>
```