Prompt specification
Build or customize the Three.js 3D scene "Fixture Design for Two Part Shapes" 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: Fixture Design for Two Part Shapes
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/fixture-design-for-two-part-shapes-x2040
Scene Description Prompt:
Please make a voxel Three.js scene in one standalone HTML file using cdnjs. Create a bounded fixture puzzle with interchangeable stops and two workpiece geometries. Validate contact and tool clearance rather than assuming more clamps always improve the design.
Working Three.js Starter (fixture-design-for-two-part-shapes-x2040):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Voxel Fixture Lab</title>
<style>
:root {
--bg: #071019;
--panel: rgba(10, 23, 32, 0.92);
--panel-border: rgba(139, 220, 231, 0.18);
--text: #e9f6f7;
--muted: #8ba6ad;
--cyan: #62e3df;
--green: #72e39a;
--amber: #ffc46b;
--red: #ff6f78;
--steel: #9eb3bd;
}
* { 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;
}
button, input { font: inherit; }
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.panel {
position: absolute;
z-index: 10;
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: 14px;
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(14px);
}
#controls {
top: 16px;
left: 16px;
width: 310px;
max-height: calc(100vh - 32px);
overflow: auto;
padding: 16px;
scrollbar-width: thin;
}
#validation {
top: 16px;
right: 16px;
width: 315px;
max-height: calc(100vh - 32px);
overflow: auto;
padding: 16px;
scrollbar-width: thin;
}
h1 {
margin: 0;
font-size: 18px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.subtitle {
margin: 5px 0 15px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.section {
margin-top: 15px;
padding-top: 14px;
border-top: 1px solid rgba(139, 220, 231, 0.12);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
color: #c9dfe3;
font-size: 11px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.tiny {
color: var(--muted);
font-size: 10px;
font-weight: 500;
letter-spacing: 0.04em;
text-transform: none;
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.segmented button,
.palette button {
min-height: 39px;
color: #dcebed;
background: #142a34;
border: 1px solid #284550;
border-radius: 8px;
cursor: pointer;
transition: 120ms ease;
}
.segmented button:hover,
.palette button:hover {
border-color: #5a8d96;
transform: translateY(-1px);
}
.segmented button.active,
.palette button.active {
color: #041417;
background: var(--cyan);
border-color: var(--cyan);
font-weight: 800;
}
.palette {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.palette button {
min-height: 57px;
padding: 7px 4px;
font-size: 11px;
line-height: 1.25;
}
.swatch {
display: block;
width: 22px;
height: 8px;
margin: 0 auto 6px;
border-radius: 2px;
box-shadow: inset 0 0 0 1px rgba(255,255,255,.18);
}
.swatch.hard { background: linear-gradient(90deg, #758a94 50%, #ffc46b 50%); }
.swatch.bumper { background: linear-gradient(90deg, #ff8c54 50%, #ffc46b 50%); }
.swatch.pin { background: linear-gradient(90deg, #62e3df 50%, #365e64 50%); }
.slot-list {
display: grid;
gap: 6px;
}
.slot-row {
display: grid;
grid-template-columns: 1fr auto auto;
align-items: center;
gap: 6px;
min-height: 31px;
padding: 4px 5px 4px 8px;
background: rgba(255,255,255,.025);
border: 1px solid rgba(255,255,255,.055);
border-radius: 7px;
}
.slot-main {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
padding: 0;
color: #c7dde1;
background: none;
border: 0;
text-align: left;
cursor: pointer;
}
.slot-main strong {
font-size: 11px;
}
.slot-main span {
overflow: hidden;
color: var(--muted);
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
.badge {
padding: 3px 6px;
color: #91a6ac;
background: #182c34;
border-radius: 999px;
font-size: 9px;
font-weight: 800;
letter-spacing: .04em;
text-transform: uppercase;
}
.badge.contact {
color: #071b12;
background: var(--green);
}
.remove {
width: 23px;
height: 23px;
padding: 0;
color: #9bb1b7;
background: transparent;
border: 1px solid #304851;
border-radius: 6px;
cursor: pointer;
}
.remove:hover {
color: #fff;
background: #74333c;
border-color: #a84a56;
}
.toggle {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 8px 0;
padding: 8px 9px;
background: rgba(255,255,255,.025);
border: 1px solid rgba(255,255,255,.06);
border-radius: 7px;
cursor: pointer;
}
.toggle strong {
display: block;
font-size: 12px;
}
.toggle small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.toggle input {
width: 17px;
height: 17px;
accent-color: var(--cyan);
}
.range-row {
margin: 9px 0;
}
.range-label {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
color: #bcd2d6;
font-size: 11px;
}
.range-label output {
color: var(--cyan);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.button-row button {
min-height: 36px;
color: #cfe4e7;
background: #142a34;
border: 1px solid #284550;
border-radius: 7px;
cursor: pointer;
}
.button-row button:hover {
border-color: var(--cyan);
}
.overall {
padding: 12px;
background: #142a34;
border: 1px solid #284550;
border-radius: 10px;
}
.overall.good {
background: rgba(64, 163, 100, .14);
border-color: rgba(114, 227, 154, .48);
}
.overall.warn {
background: rgba(206, 139, 47, .13);
border-color: rgba(255, 196, 107, .42);
}
.overall.bad {
background: rgba(189, 58, 71, .14);
border-color: rgba(255, 111, 120, .46);
}
#overallTitle {
font-size: 16px;
font-weight: 900;
letter-spacing: .08em;
}
#overallSub {
margin-top: 4px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.check {
display: grid;
grid-template-columns: 8px 1fr;
gap: 9px;
margin-top: 11px;
}
.dot {
width: 8px;
height: 8px;
margin-top: 4px;
border-radius: 50%;
background: var(--muted);
}
.dot.good { background: var(--green); box-shadow: 0 0 10px rgba(114,227,154,.45); }
.dot.warn { background: var(--amber); box-shadow: 0 0 10px rgba(255,196,107,.4); }
.dot.bad { background: var(--red); box-shadow: 0 0 10px rgba(255,111,120,.4); }
.check strong {
display: block;
font-size: 11px;
letter-spacing: .04em;
text-transform: uppercase;
}
.check p {
margin: 3px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.notes {
margin: 13px 0 0;
padding: 0;
list-style: none;
}
.notes li {
position: relative;
margin: 7px 0;
padding-left: 13px;
color: #9eb7bd;
font-size: 11px;
line-height: 1.45;
}
.notes li::before {
content: "›";
position: absolute;
left: 0;
color: var(--cyan);
font-weight: 900;
}
.notes li.error { color: #ffabb1; }
.notes li.warning { color: #ffd39a; }
.principle {
margin-top: 14px;
padding: 10px;
color: #94afb5;
background: rgba(98, 227, 223, .045);
border-left: 3px solid var(--cyan);
font-size: 10px;
line-height: 1.5;
}
#sceneTag {
position: absolute;
z-index: 5;
top: 18px;
left: 50%;
padding: 8px 12px;
transform: translateX(-50%);
color: #89a8ae;
background: rgba(7,16,25,.68);
border: 1px solid rgba(139,220,231,.13);
border-radius: 999px;
font-size: 10px;
font-weight: 750;
letter-spacing: .12em;
white-space: nowrap;
}
#hint {
position: absolute;
z-index: 5;
bottom: 16px;
left: 50%;
max-width: min(620px, calc(100vw - 32px));
padding: 9px 14px;
transform: translateX(-50%);
color: #9bb5bb;
background: rgba(7,16,25,.78);
border: 1px solid rgba(139,220,231,.13);
border-radius: 999px;
font-size: 11px;
text-align: center;
white-space: nowrap;
}
@media (max-width: 850px) {
#controls, #validation {
width: min(285px, calc(50vw - 20px));
font-size: 11px;
}
#sceneTag { display: none; }
#hint {
white-space: normal;
border-radius: 10px;
}
}
@media (max-width: 580px) {
#controls {
left: 8px;
top: 8px;
width: calc(50vw - 12px);
max-height: calc(100vh - 16px);
padding: 11px;
}
#validation {
right: 8px;
top: 8px;
width: calc(50vw - 12px);
max-height: calc(100vh - 16px);
padding: 11px;
}
.palette { grid-template-columns: 1fr; }
.slot-main span { display: none; }
.toggle small { display: none; }
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div id="sceneTag">BOUNDED CELL // VOXEL LOCATOR PUZZLE</div>
<section class="panel" id="controls">
<h1>Voxel Fixture Lab</h1>
<p class="subtitle">
Interchangeable stops, two workpieces, and a real contact/clearance check.
Click a socket to place the selected module.
</p>
<div class="section-title">Workpiece <span class="tiny">switch resets tool target</span></div>
<div class="segmented" id="geometryButtons">
<button data-part="A" class="active">L Bracket</button>
<button data-part="B">Stepped Block</button>
</div>
<div class="section">
<div class="section-title">Stop module <span class="tiny">click socket to place</span></div>
<div class="palette" id="palette">
<button data-type="hard" class="active">
<span class="swatch hard"></span>Hard steel
</button>
<button data-type="bumper">
<span class="swatch bumper"></span>Compliant
</button>
<button data-type="pin">
<span class="swatch pin"></span>Pin stop
</button>
</div>
</div>
<div class="section">
<div class="section-title">Occupied sockets <span class="tiny" id="stopCount"></span></div>
<div class="slot-list" id="slotList"></div>
</div>
<div class="section">
<div class="section-title">Clamps <span class="tiny">holding ≠ locating</span></div>
<label class="toggle">
<span>
<strong>West clamp</strong>
<small>Useful on both workpieces</small>
</span>
<input id="clampA" type="checkbox" checked>
</label>
<label class="toggle">
<span>
<strong>East clamp</strong>
<small>Does not touch the L bracket</small>
</span>
<input id="clampB" type="checkbox">
</label>
</div>
<div class="section">
<div class="section-title">Virtual cutter <span class="tiny">test envelope</span></div>
<div class="range-row">
<div class="range-label"><span>Tool X</span><output id="toolXValue"></output></div>
<input id="toolX" type="range" min="-7.25" max="7.25" step="0.25" value="0">
</div>
<div class="range-row">
<div class="range-label"><span>Tool Z</span><output id="toolZValue"></output></div>
<input id="toolZ" type="range" min="-4.75" max="4.75" step="0.25" value="-1.75">
</div>
<div class="range-row">
<div class="range-label"><span>Tool tip height</span><output id="toolYValue"></output></div>
<input id="toolY" type="range" min="0.25" max="6.25" step="0.05" value="4.05">
</div>
<div class="button-row">
<button id="targetButton">Move to target</button>
<button id="clearStops">Clear stops</button>
</div>
</div>
<div class="section">
<div class="button-row">
<button id="resetCamera">Reset camera</button>
<button id="presetA">Safe preset</button>
</div>
</div>
</section>
<section class="panel" id="validation">
<div class="overall" id="overall">
<div id="overallTitle">VALIDATING</div>
<div id="overallSub"></div>
</div>
<div class="section">
<div class="section-title">Validation</div>
<div id="checks"></div>
</div>
<div class="section">
<div class="section-title">Findings</div>
<ul class="notes" id="notes"></ul>
</div>
<div class="principle">
A rigid part is located by a small, non-opposed set of datums. Clamps hold;
they do not automatically improve location. Excess hard contacts can
overconstrain the part, and every clamp consumes tool-access space.
</div>
</section>
<div id="hint">
Drag to orbit · Wheel to zoom · Click socket to place · Right-click socket to remove
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const $$ = (selector) => [...document.querySelectorAll(selector)];
const canvas = $("#scene");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071019);
scene.fog = new THREE.Fog(0x071019, 27, 53);
const camera = new THREE.PerspectiveCamera(42, innerWidth / innerHeight, 0.1, 100);
scene.add(new THREE.HemisphereLight(0xbdefff, 0x26302d, 2.0));
const keyLight = new THREE.DirectionalLight(0xfff1d6, 3.2);
keyLight.position.set(9, 16, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
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.DirectionalLight(0x62e3df, 1.4);
rimLight.position.set(-10, 8, -9);
scene.add(rimLight);
const world = new THREE.Group();
scene.add(world);
function standardMaterial(color, extra = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.18,
...extra
});
}
function addBox(parent, size, position, color, options = {}) {
const geometry = new THREE.BoxGeometry(...size);
const material = options.material || standardMaterial(color, options);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(...position);
mesh.castShadow = options.castShadow !== false;
mesh.receiveShadow = options.receiveShadow !== false;
parent.add(mesh);
return mesh;
}
function disposeChildren(group) {
for (const child of [...group.children]) {
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach((material) => material.dispose());
}
});
group.remove(child);
}
}
function setCollisionGlow(group, active) {
group.traverse((object) => {
if (!object.isMesh || !object.material) return;
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach((material) => {
if (material.emissive) {
material.emissive.setHex(active ? 0x7b101a : 0x000000);
material.emissiveIntensity = active ? 1.3 : 0;
}
});
});
}
// ---------------------------------------------------------------------------
// Bounded voxel fixture bed
// ---------------------------------------------------------------------------
addBox(world, [18, 0.35, 12], [0, -0.68, 0], 0x111c22);
addBox(world, [16.6, 0.5, 10.6], [0, -0.25, 0], 0x263941, {
metalness: 0.36,
roughness: 0.48
});
addBox(world, [16.1, 0.08, 10.1], [0, 0.04, 0], 0x304950, {
metalness: 0.42,
roughness: 0.46
});
// Recessed voxel grid lines.
const grid = new THREE.GridHelper(16, 32, 0x43606a, 0x30474e);
grid.position.y = 0.085;
grid.scale.z = 0.625;
grid.material.transparent = true;
grid.material.opacity = 0.35;
world.add(grid);
const floor = addBox(world, [70, 0.2, 70], [0, -0.88, 0], 0x081116, {
castShadow: false
});
floor.receiveShadow = true;
// Low alternating safety boundary.
const railObstacles = [];
function addRailSegment(x, z, sx, sz, color) {
const rail = addBox(world, [sx, 0.42, sz], [x, 0.28, z], color, {
metalness: 0.25
});
railObstacles.push({
minX: x - sx / 2, maxX: x + sx / 2,
minY: 0.07, maxY: 0.49,
minZ: z - sz / 2, maxZ: z + sz / 2
});
}
for (let x = -7.5; x <= 7.5; x += 1.5) {
const c = Math.round((x + 7.5) / 1.5) % 2 ? 0xf3ad42 : 0x27383d;
addRailSegment(x, -5.25, 1.25, 0.28, c);
addRailSegment(x, 5.25, 1.25, 0.28, c);
}
for (let z = -3.75; z <= 3.75; z += 1.5) {
const c = Math.round((z + 3.75) / 1.5) % 2 ? 0xf3ad42 : 0x27383d;
addRailSegment(-8.25, z, 0.28, 1.25, c);
addRailSegment(8.25, z, 0.28, 1.25, c);
}
// ---------------------------------------------------------------------------
// Workpieces and interchangeable stops
// ---------------------------------------------------------------------------
const SLOT_DEFS = [
{ id: "S1", x: -4.00, z: 0.00, label: "West lower" },
{ id: "S2", x: 1.50, z: -2.50, label: "North middle" },
{ id: "S3", x: 4.00, z: 0.00, label: "East lower" },
{ id: "S4", x: 4.00, z: -1.75, label: "East upper" },
{ id: "S5", x: -1.50, z: 2.50, label: "South center" },
{ id: "S6", x: -2.50, z: 2.50, label: "South west" },
{ id: "S7", x: 0.00, z: -2.50, label: "North left" },
{ id: "S8", x: 2.50, z: 2.50, label: "South east" }
];
const config = {
part: "A",
selectedType: "hard",
stops: {
S1: "hard",
S2: "bumper"
},
clamps: { A: true, B: false },
tool: { x: 0, z: -1.75, tipY: 4.05 }
};
const slotMeshes = [];
const slotById = Object.fromEntries(SLOT_DEFS.map((slot) => [slot.id, slot]));
for (const slot of SLOT_DEFS) {
const pad = addBox(
world,
[1.22, 0.08, 1.22],
[slot.x, 0.11, slot.z],
0x1a3038,
{
transparent: true,
opacity: 0.42,
depthWrite: false,
castShadow: false
}
);
pad.userData.slotId = slot.id;
slotMeshes.push(pad);
}
const workpieceGroup = new THREE.Group();
const stopGroup = new THREE.Group();
const clampGroup = new THREE.Group();
const contactMarkerGroup = new THREE.Group();
const toolGroup = new THREE.Group();
world.add(workpieceGroup, stopGroup, clampGroup, contactMarkerGroup, toolGroup);
const PART_DEFS = {
A: {
name: "L bracket",
boxes: [
{ minX: -3.5, maxX: 0.5, minY: 0, maxY: 1, minZ: -2, maxZ: 2 },
{ minX: -3.5, maxX: 3.5, minY: 0, maxY: 4, minZ: -2, maxZ: -1.5 }
],
target: {
minX: -1.5, maxX: 1.5,
minZ: -1.92, maxZ: -1.58,
surfaceY: 4,
x: 0,
z: -1.75
},
color: 0xe7ae49
},
B: {
name: "Stepped block",
boxes: [
{ minX: -3, maxX: 3, minY: 0, maxY: 1, minZ: -2, maxZ: 2 },
{ minX: 0, maxX: 3, minY: 1, maxY: 3, minZ: -1.5, maxZ: 1.5 }
],
target: {
minX: 1.0, maxX: 2.5,
minZ: -0.6, maxZ: 0.6,
surfaceY: 3,
x: 1.75,
z: 0
},
color: 0x4ec9bf
}
};
let partBoxes = [];
let targetDefinition = PART_DEFS.A.target;
let workpieceMaterial = null;
function buildWorkpiece() {
disposeChildren(workpieceGroup);
partBoxes = PART_DEFS[config.part].boxes;
targetDefinition = PART_DEFS[config.part].target;
const cell = 0.5;
const cells = new Map();
function addCells(box) {
const x0 = Math.round(box.minX / cell);
const x1 = Math.round(box.maxX / cell);
const y0 = Math.round(box.minY / cell);
const y1 = Math.round(box.maxY / cell);
const z0 = Math.round(box.minZ / cell);
const z1 = Math.round(box.maxZ / cell);
for (let x = x0; x < x1; x++) {
for (let y = y0; y < y1; y++) {
for (let z = z0; z < z1; z++) {
cells.set(`${x},${y},${z}`, { x, y, z });
}
}
}
}
partBoxes.forEach(addCells);
const geometry = new THREE.BoxGeometry(0.47, 0.47, 0.47);
workpieceMaterial = standardMaterial(0xffffff, {
roughness: 0.64,
metalness: 0.16
});
const mesh = new THREE.InstancedMesh(
geometry,
workpieceMaterial,
cells.size
);
mesh.castShadow = true;
mesh.receiveShadow = true;
const matrix = new THREE.Matrix4();
const baseColor = new THREE.Color(PART_DEFS[config.part].color);
const color = new THREE.Color();
let index = 0;
for (const voxel of cells.values()) {
const x = (voxel.x + 0.5) * cell;
const y = (voxel.y + 0.5) * cell;
const z = (voxel.z + 0.5) * cell;
matrix.makeTranslation(x, y, z);
mesh.setMatrixAt(index, matrix);
const variation = ((voxel.x * 17 + voxel.y * 31 + voxel.z * 13) % 9) - 4;
color.copy(baseColor).offsetHSL(0, 0, variation * 0.012);
mesh.setColorAt(index, color);
index++;
}
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
workpieceGroup.add(mesh);
// Magenta machining target pad.
const targetWidth = targetDefinition.maxX - targetDefinition.minX;
const targetDepth = targetDefinition.maxZ - targetDefinition.minZ;
const targetPad = addBox(
workpieceGroup,
[targetWidth, 0.055, targetDepth],
[
(targetDefinition.minX + targetDefinition.maxX) / 2,
targetDefinition.surfaceY + 0.035,
(targetDefinition.minZ + targetDefinition.maxZ) / 2
],
0xf36adf,
{
transparent: true,
opacity: 0.82,
depthWrite: false,
emissive: 0x441039,
emissiveIntensity: 0.8,
castShadow: false
}
);
const edgeGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(targetWidth + 0.08, 0.07, targetDepth + 0.08)
);
const edges = new THREE.LineSegments(
edgeGeometry,
new THREE.LineBasicMaterial({ color: 0xffb2ed })
);
edges.position.copy(targetPad.position);
workpieceGroup.add(edges);
}
function makeStopVisual(type) {
const group = new THREE.Group();
if (type === "hard") {
addBox(group, [1.0, 0.16, 1.0], [0, 0.16, 0], 0x26383f);
addBox(group, [0.96, 0.94, 0.96], [0, 0.72, 0], 0x91a4ac, {
metalness: 0.48,
roughness: 0.4
});
addBox(group, [1.0, 0.18, 1.0], [0, 1.26, 0], 0xf3ad42);
addBox(group, [0.18, 0.54, 0.18], [0, 0.58, 0.49], 0x4c646e);
} else if (type === "bumper") {
addBox(group, [1.0, 0.15, 1.0], [0, 0.15, 0], 0x26383f);
addBox(group, [0.72, 0.68, 0.72], [0, 0.53, 0], 0x80949d, {
metalness: 0.45
});
addBox(group, [0.98, 0.44, 0.98], [0, 1.04, 0], 0xff8c54, {
roughness: 0.85,
metalness: 0.02
});
addBox(group, [1.02, 0.10, 1.02], [0, 1.30, 0], 0xffc46b);
} else {
addBox(group, [1.0, 0.20, 1.0], [0, 0.18, 0], 0x294148);
addBox(group, [0.96, 0.38, 0.96], [0, 0.46, 0], 0x6e858e, {
metalness: 0.48
});
addBox(group, [0.38, 1.02, 0.38], [0, 1.03, 0], 0x62e3df, {
metalness: 0.65,
roughness: 0.28
});
addBox(group, [0.62, 0.16, 0.62], [0, 1.60, 0], 0xb4fff7, {
metalness: 0.7,
roughness: 0.22
});
}
return group;
}
function buildStops() {
disposeChildren(stopGroup);
for (const [slotId, type] of Object.entries(config.stops)) {
const slot = slotById[slotId];
const visual = makeStopVisual(type);
visual.position.set(slot.x, 0, slot.z);
visual.userData.slotId = slotId;
stopGroup.add(visual);
}
updateSlotVisuals();
}
function updateSlotVisuals() {
for (const pad of slotMeshes) {
const occupied = Boolean(config.stops[pad.userData.slotId]);
const hovered = pad.userData.slotId === hoveredSlotId;
pad.material.color.setHex(
hovered ? 0x62e3df : occupied ? 0x31545c : 0x1b343d
);
pad.material.opacity = hovered ? 0.65 : occupied ? 0.3 : 0.18;
}
}
// ---------------------------------------------------------------------------
// Clamps and virtual voxel cutter
// ---------------------------------------------------------------------------
const clampVisuals = {};
function buildClamps() {
disposeChildren(clampGroup);
clampVisuals.A = null;
clampVisuals.B = null;
function makeClamp(id, x) {
const group = new THREE.Group();
group.position.x = x;
addBox(group, [1.2, 0.55, 0.85], [0, 0.34, 3.55], 0x304b57, {
metalness: 0.45
});
addBox(group, [0.48, 1.25, 0.48], [0, 1.03, 3.47], 0xa6bbc2, {
metalness: 0.62,
roughness: 0.35
});
addBox(group, [1.02, 0.26, 1.55], [0, 1.47, 2.72], 0x62a9b5, {
metalness: 0.48
});
addBox(group, [0.84, 0.30, 0.42], [0, 1.15, 1.96], 0xffb44d, {
metalness: 0.22,
roughness: 0.56
});
group.userData.clampId = id;
clampGroup.add(group);
clampVisuals[id] = group;
}
makeClamp("A", -1.5);
makeClamp("B", 1.5);
updateClampVisibility();
}
function updateClampVisibility() {
if (clampVisuals.A) clampVisuals.A.visible = config.clamps.A;
if (clampVisuals.B) clampVisuals.B.visible = config.clamps.B;
}
const toolMaterials = [];
function buildTool() {
disposeChildren(toolGroup);
toolMaterials.length = 0;
const bitMaterial = standardMaterial(0xff6f78, {
emissive: 0x401015,
emissiveIntensity: 0.5,
metalness: 0.4
});
const collarMaterial = standardMaterial(0xe9b35b, {
metalness: 0.65,
roughness: 0.28
});
const bodyMaterial = standardMaterial(0x70d7dc, {
metalness: 0.45,
roughness: 0.34
});
const darkMaterial = standardMaterial(0x334951, {
metalness: 0.55
});
toolMaterials.push(bitMaterial, collarMaterial, bodyMaterial, darkMaterial);
addBox(toolGroup, [0.40, 0.70, 0.40], [0, -0.10, 0], 0xffffff, {
material: bitMaterial
});
addBox(toolGroup, [0.86, 0.25, 0.86], [0, 0.36, 0], 0xffffff, {
material: collarMaterial
});
addBox(toolGroup, [0.88, 1.34, 0.88], [0, 1.16, 0], 0xffffff, {
material: bodyMaterial
});
addBox(toolGroup, [1.22, 0.22, 0.70], [0, 1.94, 0], 0xffffff, {
material: darkMaterial
});
addBox(toolGroup, [0.44, 1.12, 0.44], [0, 2.54, 0], 0xffffff, {
material: bodyMaterial
});
addBox(toolGroup, [2.6, 0.25, 0.52], [0, 3.10, 0], 0xffffff, {
material: darkMaterial
});
updateToolTransform();
}
function updateToolTransform() {
toolGroup.position.set(config.tool.x, config.tool.tipY, config.tool.z);
}
// ---------------------------------------------------------------------------
// Contact analysis
// ---------------------------------------------------------------------------
function computeContacts() {
const contacts = [];
const seen = new Set();
for (const [slotId, type] of Object.entries(config.stops)) {
const slot = slotById[slotId];
const stop = {
minX: slot.x - 0.5,
maxX: slot.x + 0.5,
minY: 0,
maxY: type === "pin" ? 1.68 : type === "bumper" ? 1.35 : 1.35,
minZ: slot.z - 0.5,
maxZ: slot.z + 0.5
};
partBoxes.forEach((part, partIndex) => {
const verticalOverlap =
stop.minY < part.maxY - 0.02 && stop.maxY > part.minY + 0.02;
if (verticalOverlap) {
const zOverlap =
stop.minZ < part.maxZ - 0.03 && stop.maxZ > part.minZ + 0.03;
const xOverlap =
stop.minX < part.maxX - 0.03 && stop.maxX > part.minX + 0.03;
const candidates = [];
if (zOverlap) {
candidates.push({
direction: "X-",
axis: "X",
gap: part.minX - stop.maxX
});
candidates.push({
direction: "X+",
axis: "X",
gap: stop.minX - part.maxX
});
}
if (xOverlap) {
candidates.push({
direction: "Z-",
axis: "Z",
gap: part.minZ - stop.maxZ
});
candidates.push({
direction: "Z+",
axis: "Z",
gap: stop.minZ - part.maxZ
});
}
for (const candidate of candidates) {
if (Math.abs(candidate.gap) <= 0.055) {
const key = `${slotId}:${candidate.direction}`;
if (!seen.has(key)) {
seen.add(key);
contacts.push({
slotId,
type,
partIndex,
direction: candidate.direction,
axis: candidate.axis,
gap: candidate.gap,
x: slot.x,
z: slot.z
});
}
}
}
}
});
}
return contacts;
}
function clampIsEffective(clampId) {
const x = clampId === "A" ? -1.5 : 1.5;
return partBoxes.some((part) =>
part.minX <= x && part.maxX >= x &&
part.maxZ >= 1.9 &&
part.maxY >= 0.9
);
}
function rebuildContactMarkers(contacts) {
disposeChildren(contactMarkerGroup);
for (const contact of contacts) {
const part = partBoxes[contact.partIndex];
let x = contact.x;
let z = contact.z;
if (contact.direction === "X-") x = part.minX;
if (contact.direction === "X+") x = part.maxX;
if (contact.direction === "Z-") z = part.minZ;
if (contact.direction === "Z+") z = part.maxZ;
const marker = addBox(
contactMarkerGroup,
[0.17, 0.17, 0.17],
[x, 0.55, z],
0x72e39a,
{
emissive: 0x1b7838,
emissiveIntensity: 1.2,
castShadow: false
}
);
marker.rotation.set(0.25, 0.5, 0.15);
}
}
// ---------------------------------------------------------------------------
// Tool clearance analysis
// ---------------------------------------------------------------------------
function targetContains(x, z) {
return x >= targetDefinition.minX && x <= targetDefinition.maxX &&
z >= targetDefinition.minZ && z <= targetDefinition.maxZ;
}
function circleIntersectsBox(x, z, radius, box) {
const closestX = Math.max(box.minX, Math.min(x, box.maxX));
const closestZ = Math.max(box.minZ, Math.min(z, box.maxZ));
const dx = x - closestX;
const dz = z - closestZ;
return dx * dx + dz * dz < radius * radius;
}
function boxesOverlap(a, b) {
return (
a.minX < b.maxX && a.maxX > b.minX &&
a.minY < b.maxY && a.maxY > b.minY &&
a.minZ < b.maxZ && a.maxZ > b.minZ
);
}
function analyzeTool(contacts) {
const segments = [
{
name: "bit",
minX: config.tool.x - 0.20, maxX: config.tool.x + 0.20,
minY: config.tool.tipY - 0.45, maxY: config.tool.tipY + 0.25,
minZ: config.tool.z - 0.20, maxZ: config.tool.z + 0.20,
radius: 0.20
},
{
name: "collar",
minX: config.tool.x - 0.43, maxX: config.tool.x + 0.43,
minY: config.tool.tipY + 0.25, maxY: config.tool.tipY + 0.50,
minZ: config.tool.z - 0.43, maxZ: config.tool.z + 0.43,
radius: 0.43
},
{
name: "body",
minX: config.tool.x - 0.44, maxX: config.tool.x + 0.44,
minY: config.tool.tipY + 0.50, maxY: config.tool.tipY + 1.84,
minZ: config.tool.z - 0.44, maxZ: config.tool.z + 0.44,
radius: 0.44
},
{
name: "mast",
minX: config.tool.x - 0.22, maxX: config.tool.x + 0.22,
minY: config.tool.tipY + 1.84, maxY: config.tool.tipY + 3.10,
minZ: config.tool.z - 0.22, maxZ: config.tool.z + 0.22,
radius: 0.22
}
];
const obstacles = [];
const hitStopIds = new Set();
const hitClampIds = new Set();
for (const [slotId, type] of Object.entries(config.stops)) {
const slot = slotById[slotId];
obstacles.push({
minX: slot.x - 0.5, maxX: slot.x + 0.5,
minY: 0, maxY: type === "pin" ? 1.68 : 1.35,
minZ: slot.z - 0.5, maxZ: slot.z + 0.5,
stopId: slotId
});
}
if (config.clamps.A) {
obstacles.push({
minX: -2.10, maxX: -0.90,
minY: 0, maxY: 1.72,
minZ: 1.76, maxZ: 3.98,
clampId: "A"
});
}
if (config.clamps.B) {
obstacles.push({
minX: 0.90, maxX: 2.10,
minY: 0, maxY: 1.72,
minZ: 1.76, maxZ: 3.98,
clampId: "B"
});
}
obstacles.push(...railObstacles);
for (const slot of SLOT_DEFS) {
obstacles.push({
minX: slot.x - 0.61, maxX: slot.x + 0.61,
minY: 0.07, maxY: 0.15,
minZ: slot.z - 0.61, maxZ: slot.z + 0.61
});
}
const engaged =
targetContains(config.tool.x, config.tool.z) &&
config.tool.tipY <= targetDefinition.surfaceY + 0.20 &&
config.tool.tipY >= targetDefinition.surfaceY - 0.65;
let stockHit = false;
let fixtureHit = false;
for (const segment of segments) {
for (const obstacle of obstacles) {
const yOverlap =
segment.minY < obstacle.maxY && segment.maxY > obstacle.minY;
if (yOverlap && circleIntersectsBox(
config.tool.x,
config.tool.z,
segment.radius,
obstacle
)) {
fixtureHit = true;
if (obstacle.stopId) hitStopIds.add(obstacle.stopId);
if (obstacle.clampId) hitClampIds.add(obstacle.clampId);
}
}
for (const part of partBoxes) {
if (!boxesOverlap(segment, part)) continue;
const allowedIntentionalCut =
segment.name === "bit" && engaged && targetContains(config.tool.x, config.tool.z);
if (!allowedIntentionalCut) {
stockHit = true;
}
}
}
return {
segments,
obstacles,
engaged,
stockHit,
fixtureHit,
hitStopIds,
hitClampIds
};
}
// ---------------------------------------------------------------------------
// Validation presentation
// ---------------------------------------------------------------------------
function statusIcon(status) {
return status === "good" ? "✓" : status === "bad" ? "×" : "!";
}
function renderChecks(checks) {
$("#checks").innerHTML = checks.map((check) => `
<div class="check">
<span class="dot ${check.status}"></span>
<div>
<strong>${check.title}</strong>
<p>${check.detail}</p>
</div>
</div>
`).join("");
}
function renderNotes(notes) {
$("#notes").innerHTML = notes.map((note) => `
<li class="${note.status || ""}">${note.text}</li>
`).join("");
}
function renderSlotList(contacts) {
const list = $("#slotList");
list.innerHTML = "";
$("#stopCount").textContent = `${Object.keys(config.stops).length} placed`;
for (const slot of SLOT_DEFS) {
const type = config.stops[slot.id];
const contactCount = contacts.filter((contact) => contact.slotId === slot.id).length;
const row = document.createElement("div");
row.className = "slot-row";
row.innerHTML = `
<button class="slot-main" title="Place or replace the selected module">
<strong>${slot.id}</strong>
<span>${type ? slot.label : "Empty socket"}</span>
</button>
<span class="badge ${contactCount ? "contact" : ""}">
${type ? (contactCount ? "contact" : "clear") : "empty"}
</span>
<button class="remove" title="Remove module">×</button>
`;
row.querySelector(".slot-main").addEventListener("click", () => {
config.stops[slot.id] = config.selectedType;
buildStops();
updateAll();
});
row.querySelector(".remove").addEventListener("click", () => {
delete config.stops[slot.id];
buildStops();
updateAll();
});
list.appendChild(row);
}
}
function updateAll() {
const contacts = computeContacts();
const hardContacts = contacts.filter((contact) => contact.type === "hard");
const axes = new Set(contacts.map((contact) => contact.axis));
const hardDirections = new Set(hardContacts.map((contact) => contact.direction));
const opposedX = hardDirections.has("X-") && hardDirections.has("X+");
const opposedZ = hardDirections.has("Z-") && hardDirections.has("Z+");
const opposed = opposedX || opposedZ;
const penetration = contacts.find((contact) => contact.gap < -0.08);
const stable = contacts.length >= 2 && axes.size >= 2;
const overconstrained = hardContacts.length > 3 || opposed;
const effectiveA = config.clamps.A && clampIsEffective("A");
const effectiveB = config.clamps.B && clampIsEffective("B");
const effectiveClamps = Number(effectiveA) + Number(effectiveB);
const activeClamps = Number(config.clamps.A) + Number(config.clamps.B);
const tool = analyzeTool(contacts);
const toolClear = !tool.stockHit && !tool.fixtureHit;
const toolReady = toolClear && tool.engaged;
// Reset and apply collision highlighting.
stopGroup.children.forEach((group) => setCollisionGlow(group, false));
clampGroup.children.forEach((group) => setCollisionGlow(group, false));
toolMaterials.forEach((material) => {
material.emissive.setHex(tool.fixtureHit || tool.stockHit ? 0x7a101a : 0x000000);
material.emissiveIntensity = tool.fixtureHit || tool.stockHit ? 1.2 : 0;
});
if (workpieceMaterial) {
workpieceMaterial.emissive.setHex(tool.stockHit ? 0x6c1019 : 0x000000);
workpieceMaterial.emissiveIntensity = tool.stockHit ? 0.8 : 0;
}
tool.hitStopIds.forEach((id) => {
const group = stopGroup.children.find((child) => child.userData.slotId === id);
if (group) setCollisionGlow(group, true);
});
tool.hitClampIds.forEach((id) => {
const group = clampGroup.children.find((child) => child.userData.clampId === id);
if (group) setCollisionGlow(group, true);
});
const checks = [];
const notes = [];
let locatorStatus = "good";
let locatorDetail = `${contacts.length} contact${contacts.length === 1 ? "" : "s"} across ${axes.size} locating axis${axes.size === 1 ? "" : "es"}.`;
if (!stable) {
locatorStatus = "bad";
locatorDetail = "Use contacting stops on at least two orthogonal axes.";
notes.push({
status: "error",
text: "The workpiece is not fully located. One contact or one-axis location can still translate or rotate."
});
} else if (overconstrained) {
locatorStatus = "bad";
locatorDetail = opposed
? "Opposed hard datums can overconstrain the rigid workpiece."
: `${hardContacts.length} hard contacts exceed the three-point locator limit.`;
notes.push({
status: "error",
text: opposed
? "Opposed hard stops are fighting each other. Relieve one opposed datum or replace it with a compliant stop."
: "More than three hard contacts can lock the manufacturing tolerances. Remove redundant hard stops."
});
} else {
notes.push({
text: "The active contacts form a stable locator. Hard stops are being used as location datums, while compliant contacts can absorb assembly variation."
});
}
if (penetration) {
locatorStatus = "bad";
notes.push({
status: "error",
text: `${penetration.slotId} overlaps the workpiece instead of touching its datum.`
});
}
const duplicateDirections = [...hardDirections].filter((direction) =>
hardContacts.filter((contact) => contact.direction === direction).length > 1
);
if (duplicateDirections.length) {
notes.push({
status: "warning",
text: "Duplicate hard locators in the same direction are redundant. One normally provides the same direction constraint with less overconstraint risk."
});
}
checks.push({
status: locatorStatus,
title: "Location and contact",
detail: locatorDetail
});
let clampStatus = "good";
let clampDetail = `${effectiveClamps} effective clamp${effectiveClamps === 1 ? "" : "s"}; ${activeClamps} active.`;
if (activeClamps === 0) {
clampStatus = "bad";
clampDetail = "No clamp is holding the part.";
notes.push({
status: "error",
text: "Add at least one clamp that actually bears on this workpiece."
});
} else if (!stable) {
clampStatus = "bad";
clampDetail = "A clamp is active before the part is located.";
notes.push({
status: "error",
text: "Do not clamp an unlocated rigid part; the clamp force can move it off its datums."
});
} else if (effectiveClamps === 0) {
clampStatus = "bad";
clampDetail = "No active clamp touches this workpiece.";
notes.push({
status: "error",
text: "The active clamps do not bear on the selected workpiece."
});
} else {
notes.push({
text: "The active clamp adds holding force without adding a locator constraint."
});
}
if (effectiveA && !effectiveB && config.clamps.B) {
notes.push({
status: "warning",
text: "The east clamp does not touch the L bracket. It adds no constraint here and only consumes potential access space."
});
} else if (effectiveA && effectiveB) {
notes.push({
status: "warning",
text: "Two clamps are not automatically better. Check that the second clamp does not distort the part or obstruct the cutter."
});
}
checks.push({
status: clampStatus,
title: "Clamp effectiveness",
detail: clampDetail
});
let toolStatus = "good";
let toolDetail = "The cutter is at the target and clear of stock and fixture hardware.";
if (tool.fixtureHit) {
toolStatus = "bad";
toolDetail = "The cutter envelope intersects a stop, clamp, socket, or boundary rail.";
notes.push({
status: "error",
text: "Tool clearance failure: the highlighted fixture hardware intersects the cutter envelope."
});
} else if (tool.stockHit) {
toolStatus = "bad";
toolDetail = "The cutter intersects workpiece stock outside the permitted target cut.";
notes.push({
status: "error",
text: "The cutter would strike unpermitted stock. Move it to the magenta target or change its height."
});
} else if (!tool.engaged) {
toolStatus = "warn";
toolDetail = "The cutter is clear, but it is not engaged with the magenta target.";
notes.push({
status: "warning",
text: "The tool is physically clear but off target. Use “Move to target” to place it over the machining window."
});
} else {
notes.push({
text: "The cutter is allowed to remove material only at the magenta target. All other stock and fixture hardware remains protected."
});
}
checks.push({
status: toolStatus,
title: "Tool clearance",
detail: toolDetail
});
const ready =
stable &&
!overconstrained &&
!penetration &&
activeClamps > 0 &&
effectiveClamps > 0 &&
toolReady;
const overall = $("#overall");
overall.className = `overall ${ready ? "good" : toolStatus === "bad" || locatorStatus === "bad" || clampStatus === "bad" ? "bad" : "warn"}`;
$("#overallTitle").textContent = ready ? "READY TO MACHINE" : "DESIGN NEEDS ATTENTION";
$("#overallSub").textContent = ready
? `${contacts.length} locating contacts, ${effectiveClamps} effective clamp, and a clear engaged cutter.`
: "Resolve the failed checks below. Extra modules are only useful when they improve location or holding without reducing access.";
renderChecks(checks);
renderNotes(notes);
renderSlotList(contacts);
rebuildContactMarkers(contacts);
}
// ---------------------------------------------------------------------------
// Interaction
// ---------------------------------------------------------------------------
function placeStop(slotId) {
config.stops[slotId] = config.selectedType;
buildStops();
updateAll();
}
function removeStop(slotId) {
delete config.stops[slotId];
buildStops();
updateAll();
}
$$("#geometryButtons button").forEach((button) => {
button.addEventListener("click", () => {
config.part = button.dataset.part;
$$("#geometryButtons button").forEach((item) => item.classList.toggle("active", item === button));
buildWorkpiece();
config.tool.x = targetDefinition.x;
config.tool.z = targetDefinition.z;
config.tool.tipY = targetDefinition.surfaceY + 0.05;
$("#toolX").value = config.tool.x;
$("#toolZ").value = config.tool.z;
$("#toolY").value = config.tool.tipY;
updateToolTransform();
updateAll();
});
});
$$("#palette button").forEach((button) => {
button.addEventListener("click", () => {
config.selectedType = button.dataset.type;
$$("#palette button").forEach((item) => item.classList.toggle("active", item === button));
});
});
$("#clampA").addEventListener("change", (event) => {
config.clamps.A = event.target.checked;
updateClampVisibility();
updateAll();
});
$("#clampB").addEventListener("change", (event) => {
config.clamps.B = event.target.checked;
updateClampVisibility();
updateAll();
});
$("#toolX").addEventListener("input", (event) => {
config.tool.x = Number(event.target.value);
updateToolTransform();
updateAll();
});
$("#toolZ").addEventListener("input", (event) => {
config.tool.z = Number(event.target.value);
updateToolTransform();
updateAll();
});
$("#toolY").addEventListener("input", (event) => {
config.tool.tipY = Number(event.target.value);
updateToolTransform();
updateAll();
});
$("#targetButton").addEventListener("click", () => {
config.tool.x = targetDefinition.x;
config.tool.z = targetDefinition.z;
config.tool.tipY = targetDefinition.surfaceY + 0.05;
$("#toolX").value = config.tool.x;
$("#toolZ").value = config.tool.z;
$("#toolY").value = config.tool.tipY;
updateToolTransform();
updateAll();
});
$("#clearStops").addEventListener("click", () => {
config.stops = {};
buildStops();
updateAll();
});
$("#presetA").addEventListener("click", () => {
config.part = "A";
config.stops = { S1: "hard", S2: "bumper" };
config.clamps = { A: true, B: false };
config.tool = { x: 0, z: -1.75, tipY: 4.05 };
$$("#geometryButtons button").forEach((item) =>
item.classList.toggle("active", item.dataset.part === "A")
);
$("#clampA").checked = true;
$("#clampB").checked = false;
$("#toolX").value = config.tool.x;
$("#toolZ").value = config.tool.z;
$("#toolY").value = config.tool.tipY;
buildWorkpiece();
buildStops();
updateClampVisibility();
updateToolTransform();
updateAll();
});
// ---------------------------------------------------------------------------
// Direct camera controls and socket picking
// ---------------------------------------------------------------------------
const cameraState = {
theta: 0.68,
phi: 0.92,
radius: 25,
target: new THREE.Vector3(0, 1.1, 0)
};
function updateCamera() {
const { theta, phi, radius, target } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
}
$("#resetCamera").addEventListener("click", () => {
cameraState.theta = 0.68;
cameraState.phi = 0.92;
cameraState.radius = 25;
cameraState.target.set(0, 1.1, 0);
updateCamera();
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let hoveredSlotId = null;
let pointerDown = null;
function pickSlot(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(slotMeshes, false);
return hits.length ? hits[0].object.userData.slotId : null;
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
pointerDown = {
x: event.clientX,
y: event.clientY,
moved: false
};
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - pointerDown.x;
const dy = event.clientY - pointerDown.y;
if (Math.hypot(dx, dy) > 4) pointerDown.moved = true;
if (pointerDown.moved) {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.42,
1.36
);
updateCamera();
}
return;
}
const nextHover = pickSlot(event);
if (nextHover !== hoveredSlotId) {
hoveredSlotId = nextHover;
updateSlotVisuals();
canvas.style.cursor = hoveredSlotId ? "pointer" : "grab";
}
});
canvas.addEventListener("pointerup", (event) => {
if (!pointerDown) return;
const wasClick = !pointerDown.moved && event.button === 0;
pointerDown = null;
if (wasClick) {
const slotId = pickSlot(event);
if (slotId) placeStop(slotId);
}
});
canvas.addEventListener("pointercancel", () => {
pointerDown = null;
});
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
const slotId = pickSlot(event);
if (slotId) removeStop(slotId);
});
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.018,
14,
38
);
updateCamera();
}, { passive: false });
// ---------------------------------------------------------------------------
// Initialization and animation
// ---------------------------------------------------------------------------
function resize() {
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
function animate() {
requestAnimationFrame(animate);
$("#toolXValue").textContent = config.tool.x.toFixed(2);
$("#toolZValue").textContent = config.tool.z.toFixed(2);
$("#toolYValue").textContent = config.tool.tipY.toFixed(2);
renderer.render(scene, camera);
}
buildWorkpiece();
buildStops();
buildClamps();
buildTool();
updateCamera();
updateAll();
animate();
</script>
</body>
</html>
```