Prompt specification
Build or customize the Three.js 3D scene "Tool Diameter Counterfactual Pocket" 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: Tool Diameter Counterfactual Pocket
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/tool-diameter-counterfactual-pocket-x2080
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows milling toolpaths and material removal. Compare the same desired pocket under two cutter diameters in a geometric model. Show inaccessible corners and required clearance without generating real manufacturing control code. Voxel style.
Working Three.js Starter (tool-diameter-counterfactual-pocket-x2080):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Milling Toolpath Geometry Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #070d17;
--panel: rgba(13, 22, 37, 0.9);
--border: rgba(148, 163, 184, 0.2);
--text: #e5edf7;
--muted: #94a3b8;
--cyan: #22d3ee;
--pink: #e879f9;
--orange: #fb923c;
--red: #fb7185;
--amber: #f59e0b;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
display: flex;
flex-direction: column;
}
header {
z-index: 10;
padding: 14px 18px 10px;
background: linear-gradient(180deg, #0c1422 0%, #09111d 100%);
border-bottom: 1px solid var(--border);
}
.header-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
h1 {
margin: 0;
font-size: clamp(18px, 2.1vw, 27px);
letter-spacing: -0.025em;
}
.subtitle {
margin-top: 4px;
color: var(--muted);
font-size: 13px;
}
.badges {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.badge {
padding: 6px 9px;
border: 1px solid var(--border);
border-radius: 999px;
color: #cbd5e1;
background: rgba(255,255,255,0.035);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
white-space: nowrap;
}
.badge.safe {
color: #86efac;
border-color: rgba(134, 239, 172, 0.28);
}
.toolbar {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
margin-top: 13px;
}
.control {
display: flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 12px;
font-weight: 650;
}
button, select {
border: 1px solid rgba(148, 163, 184, 0.25);
border-radius: 8px;
background: #172338;
color: var(--text);
padding: 8px 11px;
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
button:hover, select:hover {
background: #20314b;
}
button.primary {
color: #06202a;
background: #67e8f9;
border-color: #67e8f9;
}
input[type="range"] {
width: 135px;
accent-color: #22d3ee;
}
input[type="range"].time-range {
width: min(260px, 32vw);
}
input[type="checkbox"] {
width: 15px;
height: 15px;
accent-color: #22d3ee;
}
.toggle {
display: inline-flex;
align-items: center;
gap: 7px;
color: #cbd5e1;
font-size: 12px;
font-weight: 650;
cursor: pointer;
}
.legend {
display: flex;
gap: 13px;
flex-wrap: wrap;
margin-top: 11px;
color: #aebed0;
font-size: 11px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 2px;
box-shadow: 0 0 10px currentColor;
}
#stage {
position: relative;
flex: 1;
min-height: 390px;
overflow: hidden;
background: #09111d;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active { cursor: grabbing; }
#separator {
position: absolute;
z-index: 5;
pointer-events: none;
background: rgba(148, 163, 184, 0.3);
box-shadow: 0 0 18px rgba(34, 211, 238, 0.12);
}
.hud {
position: absolute;
z-index: 6;
pointer-events: none;
min-width: 225px;
max-width: min(310px, calc(100% - 24px));
padding: 12px 13px;
border: 1px solid rgba(148, 163, 184, 0.2);
border-radius: 12px;
background: rgba(8, 15, 27, 0.79);
backdrop-filter: blur(10px);
box-shadow: 0 10px 35px rgba(0, 0, 0, 0.25);
}
.hud-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 9px;
}
.hud-title {
font-size: 15px;
font-weight: 850;
letter-spacing: -0.015em;
}
.hud-tag {
padding: 4px 7px;
border-radius: 999px;
background: rgba(34, 211, 238, 0.12);
color: #67e8f9;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric {
display: flex;
justify-content: space-between;
gap: 15px;
padding: 4px 0;
border-top: 1px solid rgba(148, 163, 184, 0.09);
color: #94a3b8;
font-size: 11px;
}
.metric:first-of-type { border-top: 0; }
.metric b {
color: #e5edf7;
font-variant-numeric: tabular-nums;
text-align: right;
}
.metric b.good { color: #86efac; }
.metric b.warn { color: #fbbf24; }
.metric b.bad { color: #fb7185; }
#camera-hint {
position: absolute;
z-index: 6;
left: 50%;
bottom: 12px;
transform: translateX(-50%);
padding: 6px 10px;
border-radius: 999px;
background: rgba(8, 15, 27, 0.72);
border: 1px solid rgba(148, 163, 184, 0.16);
color: #94a3b8;
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
#loading {
position: absolute;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
color: #94a3b8;
background: #09111d;
font-size: 13px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
footer {
z-index: 10;
padding: 8px 18px;
border-top: 1px solid var(--border);
color: #8291a6;
background: #09111d;
font-size: 10px;
text-align: center;
}
@media (max-width: 820px) {
header { padding: 11px 12px 9px; }
.toolbar { gap: 10px 13px; }
.control { font-size: 11px; }
input[type="range"].time-range { width: 180px; }
.hud {
min-width: 205px;
padding: 9px 10px;
}
.hud-title { font-size: 13px; }
.metric { padding: 3px 0; font-size: 10px; }
.legend { gap: 9px; font-size: 10px; }
}
</style>
</head>
<body>
<header>
<div class="header-row">
<div>
<h1>Milling Toolpath Geometry Lab</h1>
<div class="subtitle">
Same stepped pocket, two cutter diameters, voxel material-removal preview
</div>
</div>
<div class="badges">
<span class="badge safe">Geometric preview only</span>
<span class="badge">No NC / machine-control output</span>
</div>
</div>
<div class="toolbar">
<button id="play" class="primary">Pause</button>
<button id="restart">Restart</button>
<label class="control">
Scrub
<input id="time" class="time-range" type="range" min="0" max="1000" value="0" />
</label>
<label class="control">
Speed
<select id="speed">
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="1.5">1.5×</option>
<option value="2">2×</option>
</select>
</label>
<label class="control">
Required wall gap
<input id="clearance" type="range" min="0" max="4" step="0.5" value="1" />
<output id="clearance-value">1.0 mm</output>
</label>
<label class="toggle">
<input id="show-paths" type="checkbox" checked />
Tool centerlines
</label>
<label class="toggle">
<input id="show-removal" type="checkbox" checked />
Removal volume
</label>
<label class="toggle">
<input id="show-clearance" type="checkbox" checked />
Clearance dimensions
</label>
</div>
<div class="legend">
<span><i class="swatch" style="background:#22d3ee;color:#22d3ee"></i>Desired pocket edge</span>
<span><i class="swatch" style="background:#fbbf24;color:#fbbf24"></i>Offset contour</span>
<span><i class="swatch" style="background:#e879f9;color:#e879f9"></i>Raster center path</span>
<span><i class="swatch" style="background:#fb7185;color:#fb7185"></i>Unreachable corner</span>
<span><i class="swatch" style="background:#f59e0b;color:#f59e0b"></i>Clearance reserve</span>
<span><i class="swatch" style="background:#fb923c;color:#fb923c"></i>Removed-volume ghost</span>
</div>
</header>
<section id="stage">
<div id="loading">Loading Three.js geometry…</div>
<div id="separator"></div>
<div class="hud" id="hud0">
<div class="hud-head">
<div class="hud-title">Cutter Ø 12 mm</div>
<div class="hud-tag">Small radius</div>
</div>
<div class="metric"><span>Corner residual</span><b id="corner0">—</b></div>
<div class="metric"><span>Clearance reserve</span><b id="reserve0">—</b></div>
<div class="metric"><span>Upper leg</span><b id="leg0">—</b></div>
<div class="metric"><span>Center wall offset</span><b id="offset0">—</b></div>
</div>
<div class="hud" id="hud1">
<div class="hud-head">
<div class="hud-title">Cutter Ø 20 mm</div>
<div class="hud-tag">Large radius</div>
</div>
<div class="metric"><span>Corner residual</span><b id="corner1">—</b></div>
<div class="metric"><span>Clearance reserve</span><b id="reserve1">—</b></div>
<div class="metric"><span>Upper leg</span><b id="leg1">—</b></div>
<div class="metric"><span>Center wall offset</span><b id="offset1">—</b></div>
</div>
<div id="camera-hint">Drag to orbit · wheel to zoom · double-click to reset</div>
</section>
<footer>
Visual swept-volume and clearance study only. The displayed paths are illustrative geometric centerlines;
no manufacturing control instructions are generated.
</footer>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
const CELL = 2; // mm
const STOCK_X = 88; // mm
const STOCK_Z = 96; // mm
const STOCK_HEIGHT = 16; // mm
const POCKET_DEPTH = 10; // mm
const POCKET = [
new THREE.Vector2(-34, -40),
new THREE.Vector2( 34, -40),
new THREE.Vector2( 34, 0),
new THREE.Vector2( 4, 0),
new THREE.Vector2( 4, 40),
new THREE.Vector2(-34, 40)
];
const CUTTERS = [
{ diameter: 12, radius: 6 },
{ diameter: 20, radius: 10 }
];
const state = {
time: 0,
playing: true,
speed: 1,
clearance: 1,
showPaths: true,
showRemoval: true,
showClearance: true
};
const stage = document.getElementById("stage");
const separator = document.getElementById("separator");
const timeInput = document.getElementById("time");
const clearanceInput = document.getElementById("clearance");
const clearanceValue = document.getElementById("clearance-value");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.6));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.setClearColor(0x09111d, 1);
stage.prepend(renderer.domElement);
const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 400);
const cameraTarget = new THREE.Vector3(0, 6, 0);
const orbit = {
theta: 0.68,
phi: 0.72,
radius: 130,
dragging: false,
lastX: 0,
lastY: 0
};
// -------------------------------------------------------------------------
// Small geometric helpers
// -------------------------------------------------------------------------
function clamp(v, a, b) {
return Math.max(a, Math.min(b, v));
}
function smoothstep(v) {
v = clamp(v, 0, 1);
return v * v * (3 - 2 * v);
}
function pointInPolygon(x, z, polygon = POCKET) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const zi = polygon[i].y;
const zj = polygon[j].y;
const xi = polygon[i].x;
const xj = polygon[j].x;
if (
((zi > z) !== (zj > z)) &&
x < ((xj - xi) * (z - zi)) / (zj - zi) + xi
) {
inside = !inside;
}
}
return inside;
}
function distanceToSegment(x, z, a, b) {
const dx = b.x - a.x;
const dz = b.y - a.y;
const lengthSquared = dx * dx + dz * dz;
if (lengthSquared < 1e-12) {
return Math.hypot(x - a.x, z - a.y);
}
const t = clamp(
((x - a.x) * dx + (z - a.y) * dz) / lengthSquared,
0,
1
);
return Math.hypot(
x - (a.x + t * dx),
z - (a.y + t * dz)
);
}
function distanceToBoundary(x, z) {
let distance = Infinity;
for (let i = 0; i < POCKET.length; i++) {
const a = POCKET[i];
const b = POCKET[(i + 1) % POCKET.length];
distance = Math.min(distance, distanceToSegment(x, z, a, b));
}
return distance;
}
function distanceToNearestVertex(x, z) {
let distance = Infinity;
for (const vertex of POCKET) {
distance = Math.min(distance, Math.hypot(x - vertex.x, z - vertex.y));
}
return distance;
}
function pushUnique(points, point) {
const previous = points[points.length - 1];
if (!previous || previous.distanceTo(point) > 0.015) {
points.push(point.clone());
}
}
function appendLine(points, from, to, step = 3) {
const distance = from.distanceTo(to);
const count = Math.max(1, Math.ceil(distance / step));
for (let i = 0; i <= count; i++) {
const t = i / count;
points.push(new THREE.Vector2(
THREE.MathUtils.lerp(from.x, to.x, t),
THREE.MathUtils.lerp(from.y, to.y, t)
));
}
}
// Inward polygon offset: mitered convex corners and a rounded re-entrant corner.
function buildOffsetContour(radius) {
const count = POCKET.length;
const edges = [];
const normals = [];
const convex = [];
for (let i = 0; i < count; i++) {
const a = POCKET[i];
const b = POCKET[(i + 1) % count];
const direction = b.clone().sub(a).normalize();
const inward = new THREE.Vector2(-direction.y, direction.x);
edges.push({ a, b, direction });
normals.push(inward);
}
for (let i = 0; i < count; i++) {
const previous = edges[(i - 1 + count) % count].direction;
const next = edges[i].direction;
const cross = previous.x * next.y - previous.y * next.x;
convex.push(cross > 0);
}
const incoming = new Array(count);
const outgoing = new Array(count);
const arcDirections = new Array(count).fill(1);
for (let i = 0; i < count; i++) {
const vertex = POCKET[i];
const previousNormal = normals[(i - 1 + count) % count];
const nextNormal = normals[i];
if (convex[i]) {
const miter = previousNormal.clone().add(nextNormal).normalize();
const distance = radius / Math.max(0.2, miter.dot(previousNormal));
const point = vertex.clone().addScaledVector(miter, distance);
incoming[i] = point.clone();
outgoing[i] = point.clone();
} else {
incoming[i] = vertex.clone().addScaledVector(previousNormal, radius);
outgoing[i] = vertex.clone().addScaledVector(nextNormal, radius);
arcDirections[i] = -1;
}
}
const points = [];
for (let i = 0; i < count; i++) {
const nextIndex = (i + 1) % count;
appendLine(
points,
outgoing[i],
incoming[nextIndex],
Math.max(2, CELL * 1.4)
);
if (!convex[nextIndex]) {
const vertex = POCKET[nextIndex];
const startAngle = Math.atan2(
incoming[nextIndex].y - vertex.y,
incoming[nextIndex].x - vertex.x
);
const endAngle = Math.atan2(
outgoing[nextIndex].y - vertex.y,
outgoing[nextIndex].x - vertex.x
);
let delta = endAngle - startAngle;
delta = Math.atan2(Math.sin(delta), Math.cos(delta));
if (arcDirections[nextIndex] < 0 && delta > 0) {
delta -= Math.PI * 2;
}
const arcSteps = Math.max(8, Math.ceil(Math.abs(delta) / 0.12));
for (let step = 1; step <= arcSteps; step++) {
const angle = startAngle + delta * (step / arcSteps);
points.push(new THREE.Vector2(
vertex.x + Math.cos(angle) * radius,
vertex.y + Math.sin(angle) * radius
));
}
}
}
return points;
}
function safeToolCenter(x, z, radius) {
if (!pointInPolygon(x, z)) return false;
return distanceToBoundary(x, z) >= radius - 0.045;
}
// Raster lanes are connected only through tool-center locations that remain
// inside the required-clearance region.
function buildRasterPath(radius, actualRadius) {
const minX = Math.min(...POCKET.map(p => p.x));
const maxX = Math.max(...POCKET.map(p => p.x));
const minZ = Math.min(...POCKET.map(p => p.y));
const maxZ = Math.max(...POCKET.map(p => p.y));
const rowStep = Math.max(4, actualRadius * 0.7);
const xStep = Math.max(2.5, CELL * 1.25);
const rows = [];
for (let z = minZ + radius; z <= maxZ - radius + 0.01; z += rowStep) {
const intervals = [];
let intervalStart = null;
let previousX = null;
for (
let x = minX + radius - 0.2;
x <= maxX - radius + 0.21;
x += xStep
) {
const safe = safeToolCenter(x, z, radius);
if (safe && intervalStart === null) {
intervalStart = x;
}
if (!safe && intervalStart !== null) {
intervals.push({
left: intervalStart,
right: previousX ?? intervalStart,
z
});
intervalStart = null;
}
previousX = x;
}
if (intervalStart !== null) {
intervals.push({
left: intervalStart,
right: previousX ?? intervalStart,
z
});
}
if (intervals.length) {
intervals.sort((a, b) => (b.right - b.left) - (a.right - a.left));
rows.push(intervals[0]);
}
}
const points = [];
let previous = null;
for (const row of rows) {
if (!previous) {
appendLine(
points,
new THREE.Vector2(row.left, row.z),
new THREE.Vector2(row.right, row.z),
xStep
);
} else {
const overlapLeft = Math.max(previous.left, row.left);
const overlapRight = Math.min(previous.right, row.right);
let join;
if (overlapLeft <= overlapRight) {
join = (overlapLeft + overlapRight) * 0.5;
} else if (Math.abs(previous.left - row.left) < 6) {
join = (previous.left + row.left) * 0.5;
} else {
join = row.left;
}
points.push(new THREE.Vector2(join, previous.z));
points.push(new THREE.Vector2(join, row.z));
appendLine(
points,
new THREE.Vector2(row.left, row.z),
new THREE.Vector2(join, row.z),
xStep
);
appendLine(
points,
new THREE.Vector2(join, row.z),
new THREE.Vector2(row.right, row.z),
xStep
);
}
previous = row;
}
return points;
}
function makeSegments(points) {
const raw = [];
let cumulative = 0;
for (let i = 1; i < points.length; i++) {
const a = points[i - 1];
const b = points[i];
const dx = b.x - a.x;
const dz = b.y - a.y;
const length = Math.hypot(dx, dz);
if (length < 1e-6) continue;
raw.push({
ax: a.x, az: a.y,
bx: b.x, bz: b.y,
dx, dz,
length,
lengthSquared: length * length,
startDistance: cumulative
});
cumulative += length;
}
for (const segment of raw) {
segment.t0 = segment.startDistance / cumulative;
segment.t1 = (segment.startDistance + segment.length) / cumulative;
}
return { segments: raw, totalLength: cumulative };
}
function nearestSegment(x, z, segments) {
let bestDistance = Infinity;
let bestTime = 0;
for (const segment of segments) {
const projection = clamp(
((x - segment.ax) * segment.dx + (z - segment.az) * segment.dz) /
segment.lengthSquared,
0,
1
);
const px = segment.ax + projection * segment.dx;
const pz = segment.az + projection * segment.dz;
const distance = Math.hypot(x - px, z - pz);
if (distance < bestDistance) {
bestDistance = distance;
bestTime = THREE.MathUtils.lerp(segment.t0, segment.t1, projection);
}
}
return { distance: bestDistance, time: bestTime };
}
function samplePath(time, segments, totalLength) {
if (!segments.length) return { x: 0, z: 0 };
const targetDistance = clamp(time, 0, 1) * totalLength;
let segment = segments[segments.length - 1];
for (const candidate of segments) {
if (targetDistance <= candidate.startDistance + candidate.length) {
segment = candidate;
break;
}
}
const local = clamp(
(targetDistance - segment.startDistance) / segment.length,
0,
1
);
return {
x: THREE.MathUtils.lerp(segment.ax, segment.bx, local),
z: THREE.MathUtils.lerp(segment.az, segment.bz, local)
};
}
// -------------------------------------------------------------------------
// Scene construction
// -------------------------------------------------------------------------
function createScene() {
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x09111d);
scene.fog = new THREE.Fog(0x09111d, 150, 270);
scene.add(new THREE.HemisphereLight(0xbfe8ff, 0x172033, 1.65));
const key = new THREE.DirectionalLight(0xffffff, 2.1);
key.position.set(45, 85, 55);
scene.add(key);
const rim = new THREE.DirectionalLight(0x38bdf8, 1.0);
rim.position.set(-55, 35, -45);
scene.add(rim);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(240, 240),
new THREE.MeshStandardMaterial({
color: 0x0b1422,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.08;
scene.add(ground);
const grid = new THREE.GridHelper(180, 90, 0x23364b, 0x152235);
grid.position.y = -0.03;
grid.material.transparent = true;
grid.material.opacity = 0.45;
scene.add(grid);
return scene;
}
function createTextSprite(text, color = "#fbbf24") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 112;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(7, 13, 23, 0.88)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = color;
context.lineWidth = 4;
context.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
context.fillStyle = color;
context.font = "700 34px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
}));
sprite.scale.set(27, 5.9, 1);
sprite.renderOrder = 20;
return sprite;
}
function disposeGroup(group) {
const geometries = new Set();
const materials = new Set();
const textures = new Set();
group.traverse(object => {
if (object.geometry) geometries.add(object.geometry);
if (object.material) {
const list = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of list) {
materials.add(material);
if (material.map) textures.add(material.map);
}
}
});
geometries.forEach(geometry => geometry.dispose());
materials.forEach(material => material.dispose());
textures.forEach(texture => texture.dispose());
}
class PocketModel {
constructor(cutter, scene) {
this.cutter = cutter;
this.scene = scene;
this.group = new THREE.Group();
this.scene.add(this.group);
this.rebuild(state.clearance);
}
rebuild(clearance) {
this.scene.remove(this.group);
disposeGroup(this.group);
this.group = new THREE.Group();
this.scene.add(this.group);
this.pathGroup = new THREE.Group();
this.annotationGroup = new THREE.Group();
this.clearanceGroup = new THREE.Group();
this.group.add(
this.pathGroup,
this.annotationGroup,
this.clearanceGroup
);
const actualRadius = this.cutter.radius;
const effectiveRadius = actualRadius + clearance;
const contour = buildOffsetContour(effectiveRadius);
const raster = buildRasterPath(effectiveRadius, actualRadius);
const allPoints = contour.concat(raster);
const pathData = makeSegments(allPoints);
this.segments = pathData.segments;
this.totalLength = pathData.totalLength;
this.buildFloorGuide();
this.buildToolpaths(contour, raster);
this.buildCornerMarkers();
this.buildClearanceDimension(effectiveRadius, clearance);
this.buildStock(effectiveRadius);
this.setOptions(
state.showPaths,
state.showRemoval,
state.showClearance
);
}
buildFloorGuide() {
const shape = new THREE.Shape();
shape.moveTo(POCKET[0].x, -POCKET[0].y);
for (let i = 1; i < POCKET.length; i++) {
shape.lineTo(POCKET[i].x, -POCKET[i].y);
}
shape.closePath();
const geometry = new THREE.ShapeGeometry(shape);
geometry.rotateX(-Math.PI / 2);
const floor = new THREE.Mesh(
geometry,
new THREE.MeshBasicMaterial({
color: 0x22d3ee,
transparent: true,
opacity: 0.09,
side: THREE.DoubleSide,
depthWrite: false
})
);
floor.position.y = STOCK_HEIGHT - POCKET_DEPTH + 0.025;
this.group.add(floor);
const edgePoints = POCKET.map(
point => new THREE.Vector3(point.x, STOCK_HEIGHT + 0.25, point.y)
);
edgePoints.push(edgePoints[0].clone());
const edge = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(edgePoints),
new THREE.LineDashedMaterial({
color: 0x22d3ee,
dashSize: 4,
gapSize: 2.2,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
edge.computeLineDistances();
edge.renderOrder = 15;
this.annotationGroup.add(edge);
}
lineFromPoints(points, y, color, opacity = 1) {
const geometryPoints = points.map(
point => new THREE.Vector3(point.x, y, point.y)
);
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(geometryPoints),
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity,
depthTest: false,
depthWrite: false
})
);
line.renderOrder = 13;
return line;
}
buildToolpaths(contour, raster) {
const topY = STOCK_HEIGHT + 0.35;
const floorY = STOCK_HEIGHT - POCKET_DEPTH + 0.13;
this.pathGroup.add(
this.lineFromPoints(contour, topY, 0xfbbf24, 0.95),
this.lineFromPoints(raster, topY, 0xe879f9, 0.90),
this.lineFromPoints(contour, floorY, 0xfbbf24, 0.36),
this.lineFromPoints(raster, floorY, 0xe879f9, 0.32)
);
}
buildCornerMarkers() {
const geometry = new THREE.OctahedronGeometry(2.2);
for (let i = 0; i < POCKET.length; i++) {
const vertex = POCKET[i];
const marker = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: i === 3 ? 0xfbbf24 : 0xfb7185,
emissive: i === 3 ? 0x7c2d12 : 0x7f1d1d,
emissiveIntensity: 0.5,
roughness: 0.55
})
);
marker.position.set(vertex.x, STOCK_HEIGHT + 1.4, vertex.y);
marker.scale.setScalar(i === 3 ? 1.35 : 1);
this.annotationGroup.add(marker);
}
}
buildClearanceDimension(effectiveRadius, clearance) {
const y = STOCK_HEIGHT + 2.2;
const corner = POCKET[0];
const bottomOffset = new THREE.Vector2(corner.x, corner.y + effectiveRadius);
const leftOffset = new THREE.Vector2(corner.x + effectiveRadius, corner.y);
const points = [
new THREE.Vector3(corner.x, y, corner.y),
new THREE.Vector3(bottomOffset.x, y, bottomOffset.y),
new THREE.Vector3(corner.x, y, corner.y),
new THREE.Vector3(leftOffset.x, y, leftOffset.y)
];
const lines = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(points),
new THREE.LineBasicMaterial({
color: 0xfacc15,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
lines.renderOrder = 18;
this.clearanceGroup.add(lines);
const label = createTextSprite(
`center offset ${effectiveRadius.toFixed(1)} mm`,
"#facc15"
);
label.position.set(
corner.x + effectiveRadius * 0.52,
y + 4.2,
corner.y + effectiveRadius * 0.52
);
this.clearanceGroup.add(label);
if (clearance > 0) {
const gapLabel = createTextSprite(
`required gap ${clearance.toFixed(1)} mm`,
"#f59e0b"
);
gapLabel.position.set(
corner.x + effectiveRadius * 0.6,
y - 1.5,
corner.y + effectiveRadius * 0.6
);
this.clearanceGroup.add(gapLabel);
}
}
buildStock(effectiveRadius) {
const box = new THREE.BoxGeometry(CELL * 0.92, CELL * 0.92, CELL * 0.92);
const solidMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.88,
metalness: 0.04,
flatShading: true
});
const staticCells = [];
const dynamicCells = [];
const nx = Math.round(STOCK_X / CELL);
const nz = Math.round(STOCK_Z / CELL);
const ny = Math.round(STOCK_HEIGHT / CELL);
const cavityLayers = Math.round(POCKET_DEPTH / CELL);
const stockColor = new THREE.Color();
const floorColor = new THREE.Color(0xc7b99b);
const cuttableColor = new THREE.Color();
const cornerColor = new THREE.Color(0xfb7185);
const reserveColor = new THREE.Color(0xf59e0b);
for (let ix = 0; ix < nx; ix++) {
const x = -STOCK_X / 2 + (ix + 0.5) * CELL;
for (let iz = 0; iz < nz; iz++) {
const z = -STOCK_Z / 2 + (iz + 0.5) * CELL;
const inside = pointInPolygon(x, z);
if (inside) {
const nearest = nearestSegment(x, z, this.segments);
const boundaryDistance = distanceToBoundary(x, z);
const vertexDistance = distanceToNearestVertex(x, z);
const reachable = nearest.distance <= this.cutter.radius + 0.08;
const column = {
x,
z,
reachable,
cutTime: nearest.time,
boundaryDistance,
vertexDistance,
isCorner: !reachable &&
vertexDistance <= this.cutter.radius + 7
};
for (let iy = 0; iy < ny; iy++) {
const y = (iy + 0.5) * CELL;
if (iy < ny - cavityLayers) {
staticCells.push({
x, y, z,
color: floorColor
});
} else {
if (reachable) {
cuttableColor.setHSL(
0.56,
0.16,
0.29 + (iy / ny) * 0.08
);
} else if (column.isCorner) {
cuttableColor.copy(cornerColor);
} else {
cuttableColor.copy(reserveColor);
}
dynamicCells.push({
x, y, z,
column,
cutGlobalTime: reachable
? 0.12 + 0.88 * nearest.time
: Infinity,
stage: -1
});
}
}
} else {
for (let iy = 0; iy < ny; iy++) {
const y = (iy + 0.5) * CELL;
stockColor.setHSL(
0.585,
0.17,
0.19 + (iy / ny) * 0.075
);
staticCells.push({
x, y, z,
color: stockColor.clone()
});
}
}
}
}
this.staticMesh = new THREE.InstancedMesh(
box,
solidMaterial,
staticCells.length
);
const matrix = new THREE.Matrix4();
const position = new THREE.Vector3();
const quaternion = new THREE.Quaternion();
const scale = new THREE.Vector3(1, 1, 1);
staticCells.forEach((cell, index) => {
position.set(cell.x, cell.y, cell.z);
matrix.compose(position, quaternion, scale);
this.staticMesh.setMatrixAt(index, matrix);
this.staticMesh.setColorAt(index, cell.color);
});
this.staticMesh.instanceMatrix.needsUpdate = true;
this.staticMesh.instanceColor.needsUpdate = true;
this.group.add(this.staticMesh);
this.dynamicMesh = new THREE.InstancedMesh(
box,
solidMaterial.clone(),
dynamicCells.length
);
this.ghostMesh = new THREE.InstancedMesh(
box,
new THREE.MeshBasicMaterial({
color: 0xff7a1a,
transparent: true,
opacity: 0.19,
depthWrite: false
}),
dynamicCells.length
);
this.dynamicMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
this.ghostMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
this.cells = [];
dynamicCells.forEach((cell, index) => {
position.set(cell.x, cell.y, cell.z);
matrix.compose(position, quaternion, scale);
this.dynamicMesh.setMatrixAt(index, matrix);
this.dynamicMesh.setColorAt(index, cell.column.reachable
? cuttableColor
: (cell.column.isCorner ? cornerColor : reserveColor)
);
scale.set(0.001, 0.001, 0.001);
matrix.compose(position, quaternion, scale);
this.ghostMesh.setMatrixAt(index, matrix);
this.cells.push({
...cell,
stockIndex: index,
ghostIndex: index,
position: position.clone()
});
});
this.dynamicMesh.instanceMatrix.needsUpdate = true;
this.dynamicMesh.instanceColor.needsUpdate = true;
this.ghostMesh.instanceMatrix.needsUpdate = true;
this.group.add(this.dynamicMesh, this.ghostMesh);
this.buildCutter();
this.computeMetrics();
}
buildCutter() {
this.cutterGroup = new THREE.Group();
const endMill = new THREE.Mesh(
new THREE.CylinderGeometry(
this.cutter.radius,
this.cutter.radius,
12,
24,
1,
false
),
new THREE.MeshStandardMaterial({
color: 0xcbd5e1,
metalness: 0.72,
roughness: 0.26,
flatShading: true
})
);
endMill.position.y = 6;
this.cutterGroup.add(endMill);
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(3.2, 3.2, 19, 20),
new THREE.MeshStandardMaterial({
color: 0x64748b,
metalness: 0.8,
roughness: 0.3
})
);
shaft.position.y = 20;
this.cutterGroup.add(shaft);
const edge = new THREE.Mesh(
new THREE.TorusGeometry(this.cutter.radius, 0.45, 6, 32),
new THREE.MeshStandardMaterial({
color: 0xfb923c,
emissive: 0x9a3412,
emissiveIntensity: 1.1,
metalness: 0.25,
roughness: 0.45
})
);
edge.rotation.x = Math.PI / 2;
edge.position.y = 0.25;
this.cutterGroup.add(edge);
const light = new THREE.PointLight(0xfb923c, 1.4, 24, 2);
light.position.y = 1;
this.cutterGroup.add(light);
this.group.add(this.cutterGroup);
}
computeMetrics() {
let cornerCount = 0;
let reserveCount = 0;
let unreachableCount = 0;
let upperReached = false;
for (const cell of this.cells) {
const column = cell.column;
if (column.reachable) {
if (column.z > 2) upperReached = true;
continue;
}
unreachableCount++;
if (column.isCorner) {
cornerCount++;
} else {
reserveCount++;
}
}
// Counts are voxel columns, not individual depth layers.
const squareMillimeters = CELL * CELL;
this.metrics = {
cornerArea: cornerCount * squareMillimeters / 100,
reserveArea: reserveCount * squareMillimeters / 100,
unreachableArea: unreachableCount * squareMillimeters / 100,
upperReached
};
}
setOptions(showPaths, showRemoval, showClearance) {
if (this.pathGroup) this.pathGroup.visible = showPaths;
if (this.ghostMesh) this.ghostMesh.visible = showRemoval;
if (this.clearanceGroup) this.clearanceGroup.visible = showClearance;
}
update(time) {
const plungeEnd = 0.12;
const floorY = STOCK_HEIGHT - POCKET_DEPTH + 0.16;
let traversal = 0;
let tipY;
if (time < plungeEnd) {
const p = smoothstep(time / plungeEnd);
tipY = THREE.MathUtils.lerp(STOCK_HEIGHT + 0.45, floorY, p);
} else {
traversal = clamp((time - plungeEnd) / (1 - plungeEnd), 0, 1);
tipY = floorY;
}
const toolPosition = samplePath(
traversal,
this.segments,
this.totalLength
);
this.cutterGroup.position.set(
toolPosition.x,
tipY,
toolPosition.z
);
const matrix = new THREE.Matrix4();
const quaternion = new THREE.Quaternion();
const position = new THREE.Vector3();
const scale = new THREE.Vector3();
for (const cell of this.cells) {
if (time < cell.cutGlobalTime) {
if (cell.stage !== -1) {
cell.stage = -1;
scale.set(1, 1, 1);
matrix.compose(cell.position, quaternion, scale);
this.dynamicMesh.setMatrixAt(cell.stockIndex, matrix);
scale.set(0.001, 0.001, 0.001);
matrix.compose(cell.position, quaternion, scale);
this.ghostMesh.setMatrixAt(cell.ghostIndex, matrix);
}
continue;
}
if (cell.stage === -1) {
cell.stage = 0;
}
if (cell.stage === 0) {
const age = time - cell.cutGlobalTime;
const p = smoothstep(age / 0.055);
scale.setScalar(Math.max(0.012, 1 - p));
matrix.compose(cell.position, quaternion, scale);
this.dynamicMesh.setMatrixAt(cell.stockIndex, matrix);
scale.setScalar(0.68 * p);
matrix.compose(cell.position, quaternion, scale);
this.ghostMesh.setMatrixAt(cell.ghostIndex, matrix);
if (p >= 1) {
cell.stage = 1;
scale.set(0.012, 0.012, 0.012);
matrix.compose(cell.position, quaternion, scale);
this.dynamicMesh.setMatrixAt(cell.stockIndex, matrix);
scale.set(0.68, 0.68, 0.68);
matrix.compose(cell.position, quaternion, scale);
this.ghostMesh.setMatrixAt(cell.ghostIndex, matrix);
}
}
}
this.dynamicMesh.instanceMatrix.needsUpdate = true;
this.ghostMesh.instanceMatrix.needsUpdate = true;
}
}
const scenes = CUTTERS.map(() => createScene());
const models = CUTTERS.map((cutter, index) =>
new PocketModel(cutter, scenes[index])
);
// -------------------------------------------------------------------------
// HUD metrics
// -------------------------------------------------------------------------
function updateHUD(index) {
const model = models[index];
const metrics = model.metrics;
document.getElementById(`corner${index}`).textContent =
`${metrics.cornerArea.toFixed(1)} cm²`;
document.getElementById(`reserve${index}`).textContent =
`${metrics.reserveArea.toFixed(1)} cm²`;
const leg = document.getElementById(`leg${index}`);
leg.textContent = metrics.upperReached ? "Reached" : "Restricted";
leg.className = metrics.upperReached ? "good" : "warn";
document.getElementById(`offset${index}`).textContent =
`${(model.cutter.radius + state.clearance).toFixed(1)} mm`;
}
function updateAllHUD() {
updateHUD(0);
updateHUD(1);
}
updateAllHUD();
// -------------------------------------------------------------------------
// Layout and custom camera controls
// -------------------------------------------------------------------------
let viewportWidth = 1;
let viewportHeight = 1;
let mobileLayout = false;
function updateCamera() {
const panelWidth = mobileLayout ? viewportWidth : viewportWidth / 2;
const panelHeight = mobileLayout ? viewportHeight / 2 : viewportHeight;
const aspect = panelWidth / Math.max(1, panelHeight);
const halfHeight = 59;
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
camera.position.set(
cameraTarget.x + orbit.radius * Math.sin(orbit.phi) * Math.cos(orbit.theta),
cameraTarget.y + orbit.radius * Math.cos(orbit.phi),
cameraTarget.z + orbit.radius * Math.sin(orbit.phi) * Math.sin(orbit.theta)
);
camera.lookAt(cameraTarget);
}
function resize() {
const rect = stage.getBoundingClientRect();
viewportWidth = Math.max(1, Math.floor(rect.width));
viewportHeight = Math.max(1, Math.floor(rect.height));
mobileLayout = viewportWidth < 820;
renderer.setSize(viewportWidth, viewportHeight, false);
updateCamera();
const hud0 = document.getElementById("hud0");
const hud1 = document.getElementById("hud1");
if (mobileLayout) {
separator.style.left = "0";
separator.style.top = `${viewportHeight / 2}px`;
separator.style.width = "100%";
separator.style.height = "1px";
hud0.style.left = "12px";
hud0.style.top = "12px";
hud1.style.left = "12px";
hud1.style.top = `${viewportHeight / 2 + 12}px`;
} else {
separator.style.left = `${viewportWidth / 2}px`;
separator.style.top = "0";
separator.style.width = "1px";
separator.style.height = "100%";
hud0.style.left = "14px";
hud0.style.top = "14px";
hud1.style.left = `${viewportWidth / 2 + 14}px`;
hud1.style.top = "14px";
}
}
new ResizeObserver(resize).observe(stage);
resize();
function resetCamera() {
orbit.theta = 0.68;
orbit.phi = 0.72;
camera.zoom = 1;
camera.updateProjectionMatrix();
updateCamera();
}
const canvas = renderer.domElement;
canvas.addEventListener("pointerdown", event => {
orbit.dragging = true;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!orbit.dragging) return;
const dx = event.clientX - orbit.lastX;
const dy = event.clientY - orbit.lastY;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
orbit.theta -= dx * 0.007;
orbit.phi = clamp(orbit.phi - dy * 0.006, 0.24, 1.35);
updateCamera();
});
function endPointer(event) {
orbit.dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("wheel", event => {
event.preventDefault();
camera.zoom = clamp(
camera.zoom * Math.exp(-event.deltaY * 0.001),
0.58,
2.8
);
camera.updateProjectionMatrix();
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Controls
// -------------------------------------------------------------------------
const playButton = document.getElementById("play");
playButton.addEventListener("click", () => {
if (state.time >= 1) state.time = 0;
state.playing = !state.playing;
playButton.textContent = state.playing ? "Pause" : "Play";
});
document.getElementById("restart").addEventListener("click", () => {
state.time = 0;
state.playing = true;
playButton.textContent = "Pause";
timeInput.value = "0";
});
timeInput.addEventListener("input", () => {
state.time = Number(timeInput.value) / 1000;
state.playing = false;
playButton.textContent = "Play";
});
document.getElementById("speed").addEventListener("change", event => {
state.speed = Number(event.target.value);
});
let rebuildQueued = false;
clearanceInput.addEventListener("input", () => {
state.clearance = Number(clearanceInput.value);
clearanceValue.textContent = `${state.clearance.toFixed(1)} mm`;
if (!rebuildQueued) {
rebuildQueued = true;
requestAnimationFrame(() => {
rebuildQueued = false;
for (const model of models) {
model.rebuild(state.clearance);
}
updateAllHUD();
});
}
});
document.getElementById("show-paths").addEventListener("change", event => {
state.showPaths = event.target.checked;
for (const model of models) {
model.setOptions(
state.showPaths,
state.showRemoval,
state.showClearance
);
}
});
document.getElementById("show-removal").addEventListener("change", event => {
state.showRemoval = event.target.checked;
for (const model of models) {
model.setOptions(
state.showPaths,
state.showRemoval,
state.showClearance
);
}
});
document.getElementById("show-clearance").addEventListener("change", event => {
state.showClearance = event.target.checked;
for (const model of models) {
model.setOptions(
state.showPaths,
state.showRemoval,
state.showClearance
);
}
});
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
function renderViews() {
renderer.setScissorTest(true);
if (mobileLayout) {
const halfHeight = Math.floor(viewportHeight / 2);
renderer.setViewport(0, halfHeight, viewportWidth, viewportHeight - halfHeight);
renderer.setScissor(0, halfHeight, viewportWidth, viewportHeight - halfHeight);
renderer.render(scenes[0], camera);
renderer.setViewport(0, 0, viewportWidth, halfHeight);
renderer.setScissor(0, 0, viewportWidth, halfHeight);
renderer.render(scenes[1], camera);
} else {
const halfWidth = Math.floor(viewportWidth / 2);
renderer.setViewport(0, 0, halfWidth, viewportHeight);
renderer.setScissor(0, 0, halfWidth, viewportHeight);
renderer.render(scenes[0], camera);
renderer.setViewport(halfWidth, 0, viewportWidth - halfWidth, viewportHeight);
renderer.setScissor(halfWidth, 0, viewportWidth - halfWidth, viewportHeight);
renderer.render(scenes[1], camera);
}
}
let previousTime = performance.now();
function animate(now) {
const delta = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
if (state.playing) {
state.time += delta * 0.075 * state.speed;
if (state.time >= 1) {
state.time = 1;
state.playing = false;
playButton.textContent = "Replay";
}
}
timeInput.value = String(Math.round(state.time * 1000));
models[0].update(state.time);
models[1].update(state.time);
renderViews();
requestAnimationFrame(animate);
}
document.getElementById("loading").style.display = "none";
requestAnimationFrame(animate);
</script>
</body>
</html>
```