Prompt specification
Build or customize the Three.js 3D scene "Profile Edit Changes the Finished Part" 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: Profile Edit Changes the Finished Part
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/profile-edit-changes-the-finished-part-x2068
Scene Description Prompt:
Make a low-poly Three.js scene in a self-contained HTML file using cdnjs: profile edit changes the finished part. Create a parametric turning studio with bounded profile points. Regenerate the revolved geometry, reject self-intersecting profiles, and show which dimensions changed.
Working Three.js Starter (profile-edit-changes-the-finished-part-x2068):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parametric Turning Studio</title>
<style>
:root {
color-scheme: dark;
--bg: #0a1018;
--panel: #111a25;
--panel-2: #172230;
--line: #263547;
--text: #edf3f8;
--muted: #91a3b5;
--accent: #f0a45b;
--accent-2: #73b8ff;
--good: #65d6a0;
--bad: #ff727d;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
body {
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;
}
button {
color: inherit;
}
.app {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
}
header {
z-index: 5;
display: flex;
align-items: center;
justify-content: space-between;
min-height: 76px;
padding: 14px 22px;
border-bottom: 1px solid var(--line);
background: rgba(12, 18, 27, 0.95);
}
.brand {
display: flex;
align-items: center;
gap: 14px;
}
.brand-mark {
display: grid;
place-items: center;
width: 42px;
height: 42px;
border: 1px solid #705138;
border-radius: 12px;
color: var(--accent);
background: #211a17;
font-weight: 800;
letter-spacing: -0.08em;
}
h1 {
margin: 0;
font-size: 19px;
line-height: 1.1;
letter-spacing: 0.01em;
}
.subtitle {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
}
.header-badge {
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 999px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
letter-spacing: 0.08em;
}
main {
display: grid;
grid-template-columns: 410px minmax(0, 1fr);
flex: 1;
min-height: 0;
}
aside {
z-index: 3;
overflow: auto;
padding: 18px;
border-right: 1px solid var(--line);
background: var(--panel);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.section-heading h2 {
margin: 0;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 0.12em;
}
.section-heading span {
color: var(--muted);
font-size: 11px;
}
.limits {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 10px;
}
.limit {
padding: 5px 8px;
border: 1px solid var(--line);
border-radius: 6px;
color: #b9c7d4;
background: #0d151f;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
}
#profileCanvas {
display: block;
width: 100%;
height: 260px;
border: 1px solid var(--line);
border-radius: 10px;
background: #0b121b;
cursor: crosshair;
touch-action: none;
}
.editor-help {
display: flex;
justify-content: space-between;
gap: 12px;
margin: 8px 2px 14px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.table-wrap {
overflow: hidden;
border: 1px solid var(--line);
border-radius: 9px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
th {
padding: 9px 8px;
color: var(--muted);
background: #0d151f;
text-align: left;
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
td {
padding: 7px 8px;
border-top: 1px solid var(--line);
}
td:first-child {
width: 46px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
input[type="number"] {
width: 100%;
min-width: 0;
padding: 7px 6px;
border: 1px solid #304155;
border-radius: 5px;
outline: none;
color: var(--text);
background: #0b131d;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
}
input[type="number"]:focus {
border-color: var(--accent-2);
box-shadow: 0 0 0 2px rgba(115, 184, 255, 0.12);
}
.delete-point {
width: 25px;
height: 25px;
padding: 0;
border: 1px solid transparent;
border-radius: 5px;
color: var(--muted);
background: transparent;
cursor: pointer;
}
.delete-point:hover:not(:disabled) {
border-color: #67343a;
color: var(--bad);
background: #28171b;
}
.delete-point:disabled {
opacity: 0.25;
cursor: not-allowed;
}
.button-row {
display: flex;
gap: 8px;
margin-top: 12px;
}
button.control {
min-height: 36px;
padding: 8px 12px;
border: 1px solid var(--line);
border-radius: 7px;
background: var(--panel-2);
cursor: pointer;
font-size: 12px;
font-weight: 650;
}
button.control:hover {
border-color: #425772;
background: #1c2a3a;
}
button.primary {
flex: 1;
border-color: #b7773e;
color: #17100b;
background: var(--accent);
}
button.primary:hover {
background: #ffb96e;
}
.validation {
margin-top: 12px;
padding: 11px 12px;
border: 1px solid var(--line);
border-radius: 8px;
background: #0d151f;
}
.validation.ok {
border-color: rgba(101, 214, 160, 0.36);
background: rgba(101, 214, 160, 0.07);
}
.validation.bad {
border-color: rgba(255, 114, 125, 0.5);
background: rgba(255, 114, 125, 0.08);
}
.validation strong {
display: block;
margin-bottom: 4px;
font-size: 12px;
}
.validation.ok strong {
color: var(--good);
}
.validation.bad strong {
color: var(--bad);
}
.validation span {
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: var(--bg);
}
.scene-canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.overlay-card {
position: absolute;
z-index: 2;
border: 1px solid rgba(75, 96, 119, 0.55);
border-radius: 10px;
background: rgba(13, 20, 30, 0.88);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(10px);
pointer-events: none;
}
.metrics {
top: 18px;
right: 18px;
width: 230px;
padding: 14px;
}
.card-title {
margin-bottom: 10px;
color: #dbe6ef;
font-size: 10px;
font-weight: 750;
text-transform: uppercase;
letter-spacing: 0.13em;
}
.metric {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
padding: 6px 0;
border-top: 1px solid rgba(72, 91, 113, 0.35);
}
.metric:first-of-type {
border-top: 0;
}
.metric span {
color: var(--muted);
font-size: 11px;
}
.metric strong {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
}
.changes {
bottom: 18px;
left: 18px;
width: min(430px, calc(100% - 36px));
max-height: 40%;
overflow: hidden;
padding: 14px;
}
.changes p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.change-list {
margin: 0;
padding: 0;
list-style: none;
}
.change-list li {
padding: 7px 0;
border-top: 1px solid rgba(72, 91, 113, 0.35);
color: #c5d1dc;
font-size: 11px;
line-height: 1.5;
}
.change-list li:first-child {
border-top: 0;
}
.change-list b {
color: #f2f6fa;
}
.point-tag {
display: inline-block;
min-width: 31px;
margin-right: 5px;
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-weight: 700;
}
.delta {
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.view-help {
position: absolute;
right: 18px;
bottom: 18px;
z-index: 2;
padding: 8px 10px;
border: 1px solid rgba(75, 96, 119, 0.4);
border-radius: 7px;
color: var(--muted);
background: rgba(13, 20, 30, 0.78);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
pointer-events: none;
}
@media (max-width: 900px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100%;
}
header {
align-items: flex-start;
}
.header-badge {
display: none;
}
main {
grid-template-columns: 1fr;
}
aside {
overflow: visible;
border-right: 0;
border-bottom: 1px solid var(--line);
}
.stage {
height: 65vh;
min-height: 480px;
}
.metrics {
top: 12px;
right: 12px;
width: 205px;
}
.changes {
bottom: 12px;
left: 12px;
width: calc(100% - 24px);
}
.view-help {
display: none;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark">◉</div>
<div>
<h1>Parametric Turning Studio</h1>
<p class="subtitle">Edit a bounded turning profile and revolve it into a low-poly finished part.</p>
</div>
</div>
<div class="header-badge">THREE.JS / 36-SIDED LATHE</div>
</header>
<main>
<aside>
<div class="section-heading">
<h2>Profile Editor</h2>
<span>Radius / axial position</span>
</div>
<div class="limits">
<span class="limit">RADIUS 4–42 mm</span>
<span class="limit">AXIAL −60–60 mm</span>
<span class="limit">3–12 POINTS</span>
</div>
<canvas id="profileCanvas" aria-label="Interactive turning profile editor"></canvas>
<div class="editor-help">
<span>Drag points to edit. Click empty space to append.</span>
<span>Right-click a point to remove.</span>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Point</th>
<th>Radius mm</th>
<th>Axial Z mm</th>
<th></th>
</tr>
</thead>
<tbody id="pointRows"></tbody>
</table>
</div>
<div class="button-row">
<button class="control" id="addPoint">+ Add point</button>
<button class="control" id="resetProfile">Reset</button>
</div>
<div class="button-row">
<button class="control primary" id="regenerate">Regenerate finished part</button>
</div>
<div class="validation" id="validation" role="status" aria-live="polite">
<strong id="validationTitle">Checking profile</strong>
<span id="validationMessage"></span>
</div>
</aside>
<section class="stage" id="viewport">
<div class="overlay-card metrics">
<div class="card-title">Finished Part</div>
<div class="metric">
<span>Overall length</span>
<strong id="metricLength">—</strong>
</div>
<div class="metric">
<span>Maximum Ø</span>
<strong id="metricDiameter">—</strong>
</div>
<div class="metric">
<span>Axial range</span>
<strong id="metricRange">—</strong>
</div>
<div class="metric">
<span>Profile points</span>
<strong id="metricPoints">—</strong>
</div>
<div class="overlay-card changes" id="changes">
<div class="card-title">Changed Dimensions</div>
<p>Accepted profile changes are listed here. Invalid profiles never replace the finished part.</p>
</div>
<div class="view-help">DRAG ORBIT · WHEEL ZOOM · SHIFT-DRAG PAN</div>
</section>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Profile model and bounds
// ------------------------------------------------------------
const MIN_POINTS = 3;
const MAX_POINTS = 12;
const R_MIN = 4;
const R_MAX = 42;
const Z_MIN = -60;
const Z_MAX = 60;
const VIEW_Z = 66;
const VIEW_R = 46;
const DEFAULT_PROFILE = [
{ id: "P1", r: 10, z: -52 },
{ id: "P2", r: 18, z: -44 },
{ id: "P3", r: 30, z: -30 },
{ id: "P4", r: 24, z: -9 },
{ id: "P5", r: 39, z: 8 },
{ id: "P6", r: 31, z: 25 },
{ id: "P7", r: 15, z: 37 },
{ id: "P8", r: 8, z: 52 }
];
const cloneProfile = (points) => points.map((p) => ({ ...p }));
let profile = cloneProfile(DEFAULT_PROFILE);
let lastAcceptedProfile = null;
let nextPointNumber = 9;
let dragIndex = null;
const $ = (id) => document.getElementById(id);
const profileCanvas = $("profileCanvas");
const profileContext = profileCanvas.getContext("2d");
const pointRows = $("pointRows");
const validation = $("validation");
const validationTitle = $("validationTitle");
const validationMessage = $("validationMessage");
const changesPanel = $("changes");
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
const snap = (value) => Math.round(value * 2) / 2;
const nearlyEqual = (a, b, epsilon = 1e-7) => Math.abs(a - b) <= epsilon;
function escapeHTML(value) {
return String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
// ------------------------------------------------------------
// Profile validation
// ------------------------------------------------------------
function cross(a, b, c) {
return (
(b.r - a.r) * (c.z - a.z) -
(b.z - a.z) * (c.r - a.r)
);
}
function onSegment(a, b, p) {
return (
p.r >= Math.min(a.r, b.r) - 1e-7 &&
p.r <= Math.max(a.r, b.r) + 1e-7 &&
p.z >= Math.min(a.z, b.z) - 1e-7 &&
p.z <= Math.max(a.z, b.z) + 1e-7
);
}
function segmentsIntersect(a, b, c, d) {
const o1 = cross(a, b, c);
const o2 = cross(a, b, d);
const o3 = cross(c, d, a);
const o4 = cross(c, d, b);
const properIntersection =
((o1 > 1e-7 && o2 < -1e-7) || (o1 < -1e-7 && o2 > 1e-7)) &&
((o3 > 1e-7 && o4 < -1e-7) || (o3 < -1e-7 && o4 > 1e-7));
if (properIntersection) return true;
if (nearlyEqual(o1, 0) && onSegment(a, b, c)) return true;
if (nearlyEqual(o2, 0) && onSegment(a, b, d)) return true;
if (nearlyEqual(o3, 0) && onSegment(c, d, a)) return true;
if (nearlyEqual(o4, 0) && onSegment(c, d, b)) return true;
return false;
}
function validateProfile(points) {
if (points.length < MIN_POINTS) {
return {
ok: false,
title: "Profile rejected",
message: `At least ${MIN_POINTS} points are required. The previous valid part was kept.`
};
}
if (points.length > MAX_POINTS) {
return {
ok: false,
title: "Profile rejected",
message: `A maximum of ${MAX_POINTS} points is allowed.`
};
}
for (const point of points) {
if (!Number.isFinite(point.r) || !Number.isFinite(point.z)) {
return {
ok: false,
title: "Profile rejected",
message: "Every radius and axial coordinate must be a finite number."
};
}
if (point.r < R_MIN || point.r > R_MAX) {
return {
ok: false,
title: "Profile rejected",
message: `${point.id} radius must remain between ${R_MIN} and ${R_MAX} mm.`
};
}
if (point.z < Z_MIN || point.z > Z_MAX) {
return {
ok: false,
title: "Profile rejected",
message: `${point.id} axial position must remain between ${Z_MIN} and ${Z_MAX} mm.`
};
}
}
for (let i = 0; i < points.length - 1; i++) {
if (
nearlyEqual(points[i].r, points[i + 1].r) &&
nearlyEqual(points[i].z, points[i + 1].z)
) {
return {
ok: false,
title: "Profile rejected",
message: `Points ${points[i].id} and ${points[i + 1].id} overlap.`
};
}
}
// Adjacent segments may share their endpoint, but they may not
// double back and overlap over the same radial/axial interval.
for (let i = 0; i < points.length - 2; i++) {
const a = points[i];
const b = points[i + 1];
const c = points[i + 2];
if (nearlyEqual(cross(a, b, c), 0)) {
const ab = { r: a.r - b.r, z: a.z - b.z };
const cb = { r: c.r - b.r, z: c.z - b.z };
const dot = ab.r * cb.r + ab.z * cb.z;
if (dot > 1e-7) {
return {
ok: false,
title: "Self-intersection rejected",
message: `Profile segments ${i + 1} and ${i + 2} overlap near ${b.id}.`
};
}
}
}
// Non-adjacent segment intersections are genuine self-intersections.
for (let i = 0; i < points.length - 1; i++) {
for (let j = i + 2; j < points.length - 1; j++) {
if (
segmentsIntersect(
points[i],
points[i + 1],
points[j],
points[j + 1]
)
) {
return {
ok: false,
title: "Self-intersection rejected",
message:
`Profile segments ${i + 1} and ${j + 1} intersect. ` +
"The previous valid geometry was kept."
};
}
}
}
return {
ok: true,
title: "Profile is valid",
message: "The profile is bounded and contains no self-intersections."
};
}
function refreshValidation() {
const result = validateProfile(profile);
validation.className = `validation ${result.ok ? "ok" : "bad"}`;
validationTitle.textContent = result.title;
validationMessage.textContent = result.message;
drawProfile(result);
return result;
}
function showTemporaryError(message) {
validation.className = "validation bad";
validationTitle.textContent = "Profile rejected";
validationMessage.textContent = message;
}
// ------------------------------------------------------------
// Profile canvas
// ------------------------------------------------------------
let canvasSize = {
width: 500,
height: 260,
dpr: 1
};
function resizeProfileCanvas() {
const rect = profileCanvas.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2);
canvasSize = {
width: Math.max(280, rect.width),
height: 260,
dpr
};
profileCanvas.width = Math.round(canvasSize.width * dpr);
profileCanvas.height = Math.round(canvasSize.height * dpr);
drawProfile(validateProfile(profile));
}
function profileMap() {
const margin = {
left: 46,
right: 18,
top: 18,
bottom: 39
};
return {
margin,
plotWidth: canvasSize.width - margin.left - margin.right,
plotHeight: canvasSize.height - margin.top - margin.bottom
};
}
function mapX(z) {
const m = profileMap();
return m.margin.left + ((z + VIEW_Z) / (VIEW_Z * 2)) * m.plotWidth;
}
function mapY(r) {
const m = profileMap();
return m.margin.top + ((VIEW_R - r) / VIEW_R) * m.plotHeight;
}
function canvasPoint(event) {
const rect = profileCanvas.getBoundingClientRect();
const px = event.clientX - rect.left;
const py = event.clientY - rect.top;
const m = profileMap();
const z = ((px - m.margin.left) / m.plotWidth) * VIEW_Z * 2 - VIEW_Z;
const r = VIEW_R - ((py - m.margin.top) / m.plotHeight) * VIEW_R;
return { x: px, y: py, r, z };
}
function safePoint(point) {
return {
r: Number.isFinite(point.r) ? point.r : R_MIN,
z: Number.isFinite(point.z) ? point.z : 0
};
}
function drawProfile(validationResult = validateProfile(profile)) {
const ctx = profileContext;
const { width, height, dpr } = canvasSize;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "#0b121b";
ctx.fillRect(0, 0, width, height);
const m = profileMap();
// Bounded profile region.
ctx.fillStyle = "rgba(115, 184, 255, 0.025)";
ctx.fillRect(
mapX(Z_MIN),
mapY(R_MAX),
mapX(Z_MAX) - mapX(Z_MIN),
mapY(R_MIN) - mapY(R_MAX)
);
ctx.strokeStyle = "rgba(79, 101, 124, 0.28)";
ctx.lineWidth = 1;
ctx.font = "9px ui-monospace, monospace";
ctx.textAlign = "center";
for (let z = -60; z <= 60; z += 20) {
const x = mapX(z);
ctx.beginPath();
ctx.moveTo(x, m.margin.top);
ctx.lineTo(x, height - m.margin.bottom);
ctx.stroke();
ctx.fillStyle = "#718397";
ctx.fillText(String(z), x, height - 12);
}
ctx.textAlign = "right";
for (let r = 0; r <= 40; r += 10) {
const y = mapY(r);
ctx.beginPath();
ctx.moveTo(m.margin.left, y);
ctx.lineTo(width - m.margin.right, y);
ctx.stroke();
ctx.fillStyle = "#718397";
ctx.fillText(String(r), m.margin.left - 8, y + 3);
}
// Axis and allowed bounds.
ctx.save();
ctx.setLineDash([4, 4]);
ctx.strokeStyle = "rgba(230, 238, 245, 0.2)";
ctx.beginPath();
ctx.moveTo(mapX(0), m.margin.top);
ctx.lineTo(mapX(0), height - m.margin.bottom);
ctx.stroke();
ctx.restore();
ctx.strokeStyle = "rgba(115, 184, 255, 0.32)";
ctx.strokeRect(
mapX(Z_MIN),
mapY(R_MAX),
mapX(Z_MAX) - mapX(Z_MIN),
mapY(R_MIN) - mapY(R_MAX)
);
const color = validationResult.ok ? "#f0a45b" : "#ff727d";
if (profile.length) {
// Filled body of the revolved profile.
ctx.beginPath();
const first = safePoint(profile[0]);
ctx.moveTo(mapX(first.z), mapY(0));
ctx.lineTo(mapX(first.z), mapY(first.r));
for (const point of profile) {
const p = safePoint(point);
ctx.lineTo(mapX(p.z), mapY(p.r));
}
const last = safePoint(profile[profile.length - 1]);
ctx.lineTo(mapX(last.z), mapY(0));
ctx.closePath();
ctx.fillStyle = validationResult.ok
? "rgba(240, 164, 91, 0.11)"
: "rgba(255, 114, 125, 0.1)";
ctx.fill();
ctx.beginPath();
profile.forEach((point, index) => {
const p = safePoint(point);
const x = mapX(p.z);
const y = mapY(p.r);
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.stroke();
profile.forEach((point, index) => {
const p = safePoint(point);
const x = mapX(p.z);
const y = mapY(p.r);
ctx.beginPath();
ctx.arc(x, y, index === dragIndex ? 6 : 4.5, 0, Math.PI * 2);
ctx.fillStyle = index === dragIndex ? "#ffffff" : color;
ctx.fill();
ctx.strokeStyle = "#111a25";
ctx.lineWidth = 2;
ctx.stroke();
ctx.fillStyle = "#aebdca";
ctx.font = "9px ui-monospace, monospace";
ctx.textAlign = "left";
ctx.fillText(point.id, x + 7, y - 6);
});
}
ctx.fillStyle = "#8194a7";
ctx.font = "9px ui-monospace, monospace";
ctx.textAlign = "center";
ctx.fillText("AXIAL Z (mm)", m.margin.left + m.plotWidth / 2, height - 1);
}
function hitTest(event) {
const p = canvasPoint(event);
let closest = -1;
let closestDistance = 13;
profile.forEach((point, index) => {
const safe = safePoint(point);
const dx = p.x - mapX(safe.z);
const dy = p.y - mapY(safe.r);
const distance = Math.hypot(dx, dy);
if (distance < closestDistance) {
closest = index;
closestDistance = distance;
}
});
return closest;
}
function updateTableValues(id) {
const point = profile.find((p) => p.id === id);
if (!point) return;
const row = pointRows.querySelector(`tr[data-id="${id}"]`);
if (!row) return;
row.querySelector('input[data-field="r"]').value =
Number.isFinite(point.r) ? point.r : "";
row.querySelector('input[data-field="z"]').value =
Number.isFinite(point.z) ? point.z : "";
}
// ------------------------------------------------------------
// Profile table
// ------------------------------------------------------------
function renderTable() {
pointRows.innerHTML = profile
.map(
(point) => `
<tr data-id="${escapeHTML(point.id)}">
<td>${escapeHTML(point.id)}</td>
<td>
<input
type="number"
data-field="r"
min="${R_MIN}"
max="${R_MAX}"
step="0.5"
value="${Number.isFinite(point.r) ? point.r : ""}"
aria-label="${escapeHTML(point.id)} radius in millimeters"
>
</td>
<td>
<input
type="number"
data-field="z"
min="${Z_MIN}"
max="${Z_MAX}"
step="0.5"
value="${Number.isFinite(point.z) ? point.z : ""}"
aria-label="${escapeHTML(point.id)} axial position in millimeters"
>
</td>
<td>
<button
class="delete-point"
data-delete
${profile.length <= MIN_POINTS ? "disabled" : ""}
aria-label="Delete ${escapeHTML(point.id)}"
title="Delete point"
>×</button>
</td>
</tr>
`
)
.join("");
}
pointRows.addEventListener("input", (event) => {
const input = event.target.closest("input[data-field]");
if (!input) return;
const row = input.closest("tr");
const point = profile.find((p) => p.id === row.dataset.id);
if (!point) return;
const value = input.valueAsNumber;
point[input.dataset.field] = Number.isFinite(value) ? value : NaN;
refreshValidation();
});
pointRows.addEventListener("change", () => {
regenerate();
});
pointRows.addEventListener("click", (event) => {
const button = event.target.closest("button[data-delete]");
if (!button) return;
const row = button.closest("tr");
removePointById(row.dataset.id);
});
// ------------------------------------------------------------
// Three.js scene
// ------------------------------------------------------------
const viewport = $("viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a1018);
scene.fog = new THREE.Fog(0x0a1018, 22, 45);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.domElement.className = "scene-canvas";
renderer.domElement.setAttribute("aria-label", "Interactive 3D turning studio");
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
viewport.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xa9d6ff, 0x21170f, 2.2);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffe2bd, 4.2);
keyLight.position.set(8, 15, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 13;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x65aaff, 2.8);
rimLight.position.set(-10, 7, -9);
scene.add(rimLight);
const fillLight = new THREE.PointLight(0xff9d55, 25, 18, 2);
fillLight.position.set(1, 4, 7);
scene.add(fillLight);
const materials = {
floor: new THREE.MeshStandardMaterial({
color: 0x111a24,
roughness: 0.94,
metalness: 0.04
}),
wall: new THREE.MeshStandardMaterial({
color: 0x0d1620,
roughness: 1
}),
bed: new THREE.MeshStandardMaterial({
color: 0x233342,
roughness: 0.58,
metalness: 0.55,
flatShading: true
}),
bedDark: new THREE.MeshStandardMaterial({
color: 0x172331,
roughness: 0.66,
metalness: 0.52,
flatShading: true
}),
headstock: new THREE.MeshStandardMaterial({
color: 0x34566a,
roughness: 0.47,
metalness: 0.45,
flatShading: true
}),
steel: new THREE.MeshStandardMaterial({
color: 0x80919f,
roughness: 0.3,
metalness: 0.82,
flatShading: true
}),
darkSteel: new THREE.MeshStandardMaterial({
color: 0x293a49,
roughness: 0.4,
metalness: 0.7,
flatShading: true
}),
orange: new THREE.MeshStandardMaterial({
color: 0xc76c34,
roughness: 0.48,
metalness: 0.45,
flatShading: true
})
};
const partMaterial = new THREE.MeshStandardMaterial({
color: 0xe39a50,
roughness: 0.48,
metalness: 0.28,
flatShading: true
});
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x5e351f,
transparent: true,
opacity: 0.58
});
const AXIS_Y = 2.8;
function addBox(width, height, depth, material, x, y, z) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
function addCylinderX(radius, length, material, x, y, z, segments = 16) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, length, segments),
material
);
mesh.rotation.z = Math.PI / 2;
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
// Floor and wall.
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
materials.floor
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -2.3;
floor.receiveShadow = true;
scene.add(floor);
const wall = new THREE.Mesh(
new THREE.PlaneGeometry(50, 22),
materials.wall
);
wall.position.set(0, 7, -10);
wall.receiveShadow = true;
scene.add(wall);
const grid = new THREE.GridHelper(38, 38, 0x385065, 0x1d2b39);
grid.position.y = -2.285;
grid.material.transparent = true;
grid.material.opacity = 0.46;
scene.add(grid);
// Lathe bed.
addBox(18, 0.85, 5.7, materials.bedDark, 0, -1.78, 0);
addBox(17.4, 0.3, 0.55, materials.steel, 0, -1.25, -2.18);
addBox(17.4, 0.3, 0.55, materials.steel, 0, -1.25, 2.18);
// Headstock and tailstock.
addBox(2.8, 6.1, 4.5, materials.headstock, -7.25, 0.78, 0);
addBox(3.15, 0.45, 4.8, materials.bed, -7.25, -1.18, 0);
addBox(2.2, 4.7, 3.5, materials.headstock, 7.15, 0.75, 0);
addBox(2.7, 0.42, 4.2, materials.bed, 7.15, -1.2, 0);
// Spindle and animated low-poly chuck.
addCylinderX(0.85, 1.65, materials.darkSteel, -5.78, AXIS_Y, 0, 16);
const chuckSpin = new THREE.Group();
chuckSpin.position.set(-5.02, AXIS_Y, 0);
scene.add(chuckSpin);
const chuckBody = new THREE.Mesh(
new THREE.CylinderGeometry(1.58, 1.58, 0.72, 12),
materials.steel
);
chuckBody.rotation.z = Math.PI / 2;
chuckBody.castShadow = true;
chuckSpin.add(chuckBody);
for (let i = 0; i < 3; i++) {
const angle = (i / 3) * Math.PI * 2;
const jaw = new THREE.Mesh(
new THREE.BoxGeometry(0.62, 0.34, 0.72),
materials.darkSteel
);
jaw.position.set(
0,
Math.cos(angle) * 1.22,
Math.sin(angle) * 1.22
);
jaw.rotation.x = angle;
jaw.castShadow = true;
chuckSpin.add(jaw);
}
// Tailstock quill.
addCylinderX(0.42, 2.2, materials.steel, 6.25, AXIS_Y, 0, 12);
addCylinderX(0.73, 0.75, materials.darkSteel, 7.05, AXIS_Y, 0, 12);
// Stylized tool post and cutting tool.
addBox(1.5, 0.55, 4.2, materials.bedDark, 0.8, -0.8, 0);
addBox(1.0, 2.0, 1.0, materials.headstock, 0.8, -0.05, 2.35);
addBox(1.55, 0.35, 0.45, materials.steel, 0.8, 0.82, 1.65);
addBox(0.55, 0.28, 0.28, materials.orange, 0.8, 0.67, 1.25);
// The finished part lives in a group whose local X axis is the spindle axis.
const partSpin = new THREE.Group();
partSpin.position.set(0, AXIS_Y, 0);
scene.add(partSpin);
let currentPartContent = null;
function buildFinishedPart(points) {
const vectors = points.map(
(point) => new THREE.Vector2(point.r / 10, point.z / 10)
);
const latheGeometry = new THREE.LatheGeometry(
vectors,
36,
0,
Math.PI * 2
);
const geometry = latheGeometry.toNonIndexed();
latheGeometry.dispose();
geometry.computeVertexNormals();
const content = new THREE.Group();
const mesh = new THREE.Mesh(geometry, partMaterial);
mesh.castShadow = true;
mesh.receiveShadow = true;
content.add(mesh);
const edgeGeometry = new THREE.EdgesGeometry(geometry, 20);
const edges = new THREE.LineSegments(edgeGeometry, edgeMaterial);
content.add(edges);
if (currentPartContent) {
partSpin.remove(currentPartContent);
currentPartContent.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
}
currentPartContent = content;
partSpin.add(content);
}
// ------------------------------------------------------------
// Dimensions and change reporting
// ------------------------------------------------------------
function getDimensions(points) {
const radii = points.map((p) => p.r);
const positions = points.map((p) => p.z);
const minZ = Math.min(...positions);
const maxZ = Math.max(...positions);
const maxR = Math.max(...radii);
return {
minZ,
maxZ,
maxR,
length: maxZ - minZ,
diameter: maxR * 2
};
}
function signed(value) {
const rounded = Math.round(value * 10) / 10;
return rounded > 0 ? `+${rounded.toFixed(1)}` : rounded.toFixed(1);
}
function renderMetrics(points) {
const d = getDimensions(points);
$("metricLength").textContent = `${d.length.toFixed(1)} mm`;
$("metricDiameter").textContent = `${d.diameter.toFixed(1)} mm`;
$("metricRange").textContent = `${d.minZ.toFixed(0)} … ${d.maxZ.toFixed(0)}`;
$("metricPoints").textContent = String(points.length);
}
function renderChanges(oldPoints, newPoints) {
if (!oldPoints) {
changesPanel.innerHTML = `
<div class="card-title">Accepted Baseline</div>
<p>
The initial bounded profile was accepted. Edit the points and
regenerate to see individual dimension changes here.
</p>
`;
return;
}
const oldDimensions = getDimensions(oldPoints);
const newDimensions = getDimensions(newPoints);
const rows = [];
const summaryComparisons = [
["Overall length", oldDimensions.length, newDimensions.length],
["Maximum diameter", oldDimensions.diameter, newDimensions.diameter],
["Axial start", oldDimensions.minZ, newDimensions.minZ],
["Axial end", oldDimensions.maxZ, newDimensions.maxZ],
["Maximum radius", oldDimensions.maxR, newDimensions.maxR]
];
for (const [label, oldValue, newValue] of summaryComparisons) {
if (nearlyEqual(oldValue, newValue, 0.05)) continue;
rows.push(`
<li>
<b>${escapeHTML(label)}</b>:
${oldValue.toFixed(1)} → ${newValue.toFixed(1)} mm
<span class="delta">(${signed(newValue - oldValue)})</span>
</li>
`);
}
const oldMap = new Map(oldPoints.map((p) => [p.id, p]));
for (const point of newPoints) {
const oldPoint = oldMap.get(point.id);
if (!oldPoint) {
rows.push(`
<li>
<span class="point-tag">${escapeHTML(point.id)}</span>
<b>Added</b>: radius ${point.r.toFixed(1)} mm,
axial ${point.z.toFixed(1)} mm
</li>
`);
continue;
}
const changes = [];
if (!nearlyEqual(oldPoint.r, point.r, 0.05)) {
changes.push(
`radius ${oldPoint.r.toFixed(1)} → ${point.r.toFixed(1)} mm ` +
`<span class="delta">(${signed(point.r - oldPoint.r)})</span>`
);
}
if (!nearlyEqual(oldPoint.z, point.z, 0.05)) {
changes.push(
`axial ${oldPoint.z.toFixed(1)} → ${point.z.toFixed(1)} mm ` +
`<span class="delta">(${signed(point.z - oldPoint.z)})</span>`
);
}
if (changes.length) {
rows.push(`
<li>
<span class="point-tag">${escapeHTML(point.id)}</span>
${changes.join("; ")}
</li>
`);
}
}
const newMap = new Set(newPoints.map((p) => p.id));
for (const oldPoint of oldPoints) {
if (!newMap.has(oldPoint.id)) {
rows.push(`
<li>
<span class="point-tag">${escapeHTML(oldPoint.id)}</span>
<b>Removed</b> from the profile
</li>
`);
}
}
if (!rows.length) {
changesPanel.innerHTML = `
<div class="card-title">Changed Dimensions</div>
<p>No dimensional changes. The accepted profile is unchanged.</p>
`;
return;
}
changesPanel.innerHTML = `
<div class="card-title">Changed Dimensions</div>
<ul class="change-list">
${rows.join("")}
</ul>
`;
}
function regenerate() {
const result = refreshValidation();
if (!result.ok) {
if (lastAcceptedProfile) renderMetrics(lastAcceptedProfile);
return false;
}
const previous = lastAcceptedProfile
? cloneProfile(lastAcceptedProfile)
: null;
try {
buildFinishedPart(profile);
lastAcceptedProfile = cloneProfile(profile);
validation.className = "validation ok";
validationTitle.textContent = "Profile accepted";
validationMessage.textContent =
`${profile.length} points revolved into a 36-sided low-poly part.`;
renderMetrics(lastAcceptedProfile);
renderChanges(previous, lastAcceptedProfile);
return true;
} catch (error) {
showTemporaryError(
`Geometry generation failed: ${error.message}. Previous geometry was kept.`
);
return false;
}
}
// ------------------------------------------------------------
// Profile editing actions
// ------------------------------------------------------------
function addPoint(radius, z) {
if (profile.length >= MAX_POINTS) {
showTemporaryError(`A maximum of ${MAX_POINTS} profile points is allowed.`);
return;
}
profile.push({
id: `P${nextPointNumber++}`,
r: clamp(snap(radius), R_MIN, R_MAX),
z: clamp(snap(z), Z_MIN, Z_MAX)
});
renderTable();
regenerate();
}
function removePointById(id) {
if (profile.length <= MIN_POINTS) {
showTemporaryError(`At least ${MIN_POINTS} profile points are required.`);
return;
}
const index = profile.findIndex((p) => p.id === id);
if (index < 0) return;
profile.splice(index, 1);
renderTable();
regenerate();
}
$("addPoint").addEventListener("click", () => {
const last = profile[profile.length - 1];
let z = last.z + 10;
if (z > Z_MAX) z = last.z - 10;
addPoint(last.r, z);
});
$("resetProfile").addEventListener("click", () => {
profile = cloneProfile(DEFAULT_PROFILE);
nextPointNumber = 9;
renderTable();
regenerate();
});
$("regenerate").addEventListener("click", regenerate);
profileCanvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
profileCanvas.addEventListener("pointerdown", (event) => {
if (event.button === 2) {
const index = hitTest(event);
if (index >= 0) {
event.preventDefault();
removePointById(profile[index].id);
}
return;
}
if (event.button !== 0) return;
const hit = hitTest(event);
if (hit >= 0) {
dragIndex = hit;
profileCanvas.setPointerCapture(event.pointerId);
drawProfile(validateProfile(profile));
} else {
const p = canvasPoint(event);
addPoint(p.r, p.z);
}
});
profileCanvas.addEventListener("pointermove", (event) => {
if (dragIndex === null) return;
const p = canvasPoint(event);
const point = profile[dragIndex];
point.r = clamp(snap(p.r), R_MIN, R_MAX);
point.z = clamp(snap(p.z), Z_MIN, Z_MAX);
updateTableValues(point.id);
refreshValidation();
});
function finishDrag() {
if (dragIndex === null) return;
dragIndex = null;
regenerate();
}
profileCanvas.addEventListener("pointerup", finishDrag);
profileCanvas.addEventListener("pointercancel", finishDrag);
// ------------------------------------------------------------
// Direct camera controls: orbit, pan and zoom
// ------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 1.0, 0),
radius: 25,
theta: 0.78,
phi: 1.07
};
function updateCamera() {
const { target, radius, theta, phi } = 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);
}
function resetCamera() {
cameraState.target.set(0, 1.0, 0);
cameraState.radius = 25;
cameraState.theta = 0.78;
cameraState.phi = 1.07;
updateCamera();
}
let gesture = null;
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
gesture = {
mode: event.button === 2 || event.shiftKey ? "pan" : "orbit",
x: event.clientX,
y: event.clientY
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!gesture) return;
const dx = event.clientX - gesture.x;
const dy = event.clientY - gesture.y;
gesture.x = event.clientX;
gesture.y = event.clientY;
if (gesture.mode === "orbit") {
cameraState.theta -= dx * 0.006;
cameraState.phi = clamp(cameraState.phi - dy * 0.006, 0.25, 1.46);
} else {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, new THREE.Vector3(0, 1, 0))
.normalize();
cameraState.target.addScaledVector(
right,
-dx * cameraState.radius * 0.0015
);
cameraState.target.y += dy * cameraState.radius * 0.0015;
}
updateCamera();
});
function endGesture() {
gesture = null;
}
renderer.domElement.addEventListener("pointerup", endGesture);
renderer.domElement.addEventListener("pointercancel", endGesture);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11,
43
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// ------------------------------------------------------------
// Resize and render loop
// ------------------------------------------------------------
function resizeScene() {
const rect = viewport.getBoundingClientRect();
const width = Math.max(1, rect.width);
const height = Math.max(1, rect.height);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const sceneResizeObserver = new ResizeObserver(resizeScene);
sceneResizeObserver.observe(viewport);
const profileResizeObserver = new ResizeObserver(resizeProfileCanvas);
profileResizeObserver.observe(profileCanvas.parentElement);
window.addEventListener("keydown", (event) => {
if (event.key === "Enter" && event.target.tagName !== "INPUT") {
regenerate();
}
});
let previousTime = performance.now();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
partSpin.rotation.x += delta * 1.05;
chuckSpin.rotation.x = partSpin.rotation.x;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
renderTable();
resizeProfileCanvas();
resizeScene();
resetCamera();
regenerate();
requestAnimationFrame(animate);
</script>
</body>
</html>
```