Prompt specification
Build or customize the Three.js 3D scene "Design a Dwell in a Cam Sequence" 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: Design a Dwell in a Cam Sequence
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/design-a-dwell-in-a-cam-sequence-x2016
Scene Description Prompt:
Make a voxel Three.js scene in a self-contained HTML file using cdnjs: design a dwell in a cam sequence. Create a bounded cam-profile teaching tool with a deliberately simplified follower model. Compare motion and dwell intervals while rejecting discontinuous profiles that break contact assumptions.
Working Three.js Starter (design-a-dwell-in-a-cam-sequence-x2016):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dwell Lab — Voxel Cam Teaching Tool</title>
<style>
:root {
color-scheme: dark;
--bg: #07111c;
--panel: #0c1927;
--panel-2: #102131;
--line: #20364a;
--text: #e9f3fb;
--muted: #8da6b9;
--cyan: #36d8c4;
--orange: #ff8552;
--gold: #ffd166;
--purple: #b794ff;
--red: #ff526d;
--green: #65e6a7;
}
* { 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; }
button { color: inherit; }
.app {
height: 100dvh;
display: grid;
grid-template-rows: 64px minmax(0, 1fr);
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 0 20px;
border-bottom: 1px solid var(--line);
background: #091521;
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
width: 30px;
height: 30px;
border: 3px solid var(--cyan);
transform: rotate(45deg);
box-shadow: 7px 7px 0 -3px var(--orange);
}
.brand h1 {
margin: 0;
font-size: 17px;
letter-spacing: .13em;
white-space: nowrap;
}
.brand small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
letter-spacing: .18em;
text-transform: uppercase;
}
.top-actions {
display: flex;
align-items: center;
gap: 9px;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
min-height: 34px;
padding: 0 12px;
border: 1px solid #2c654f;
border-radius: 7px;
color: var(--green);
background: #102a22;
font-size: 11px;
font-weight: 800;
letter-spacing: .09em;
white-space: nowrap;
}
.status::before {
content: "";
width: 7px;
height: 7px;
border-radius: 2px;
background: currentColor;
box-shadow: 0 0 12px currentColor;
}
.status.invalid {
color: #ff8295;
border-color: #713141;
background: #311521;
}
.button {
min-height: 34px;
padding: 0 12px;
border: 1px solid var(--line);
border-radius: 7px;
background: #122334;
cursor: pointer;
font-size: 12px;
font-weight: 700;
transition: background .15s, border-color .15s, transform .15s;
}
.button:hover:not(:disabled) {
background: #193047;
border-color: #3b5e7d;
}
.button:active:not(:disabled) { transform: translateY(1px); }
.button:disabled { opacity: .4; cursor: not-allowed; }
.button.primary {
min-width: 112px;
color: #071711;
border-color: var(--cyan);
background: var(--cyan);
}
.workspace {
min-height: 0;
display: grid;
grid-template-columns: 340px minmax(0, 1fr);
}
.sidebar {
min-height: 0;
overflow: auto;
padding: 16px;
border-right: 1px solid var(--line);
background: linear-gradient(180deg, #0c1927 0%, #091521 100%);
scrollbar-width: thin;
scrollbar-color: #29435a transparent;
}
.section {
padding-bottom: 17px;
margin-bottom: 17px;
border-bottom: 1px solid var(--line);
}
.section:last-child { border-bottom: 0; }
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 13px;
}
.section-title h2 {
margin: 0;
font-size: 11px;
letter-spacing: .15em;
text-transform: uppercase;
color: #c8d9e8;
}
.section-title span {
color: var(--muted);
font-size: 10px;
letter-spacing: .08em;
}
.control { margin: 13px 0; }
.control-head {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 8px;
font-size: 12px;
}
.control output {
color: var(--cyan);
font-variant-numeric: tabular-nums;
font-weight: 800;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
appearance: none;
border-radius: 4px;
background: #253b50;
accent-color: var(--cyan);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
appearance: none;
width: 15px;
height: 15px;
border: 3px solid #0c1927;
border-radius: 3px;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan);
}
.bounds {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: #607b91;
font-size: 9px;
}
.sequence {
display: grid;
gap: 7px;
}
.interval {
display: grid;
grid-template-columns: 9px minmax(0, 1fr) 62px;
align-items: center;
gap: 9px;
min-height: 41px;
padding: 7px 8px;
border: 1px solid #1e3447;
border-radius: 7px;
background: #0e1e2d;
}
.interval-dot {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--dot);
box-shadow: 0 0 8px color-mix(in srgb, var(--dot), transparent 40%);
}
.interval-name {
min-width: 0;
font-size: 11px;
font-weight: 700;
}
.interval-name small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
font-weight: 500;
}
.angle-input {
display: flex;
align-items: center;
gap: 3px;
color: var(--muted);
font-size: 10px;
}
.angle-input input {
width: 48px;
height: 27px;
padding: 3px 5px;
border: 1px solid #314b63;
border-radius: 5px;
outline: none;
background: #081521;
color: var(--text);
text-align: right;
font-size: 11px;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.angle-input input:focus {
border-color: var(--cyan);
box-shadow: 0 0 0 2px #36d8c421;
}
.angle-total {
display: flex;
justify-content: space-between;
margin-top: 9px;
color: var(--muted);
font-size: 10px;
}
.angle-total strong {
color: var(--green);
font-variant-numeric: tabular-nums;
}
.angle-total strong.bad { color: var(--red); }
.text-button {
padding: 0;
border: 0;
color: var(--cyan);
background: transparent;
cursor: pointer;
font-size: 10px;
font-weight: 700;
}
.stress-row {
display: grid;
grid-template-columns: minmax(0, 1fr) 40px;
align-items: center;
gap: 10px;
margin-top: 11px;
padding: 10px;
border: 1px solid #493345;
border-radius: 7px;
background: #201723;
}
.stress-row strong {
display: block;
font-size: 11px;
color: #ffb1bd;
}
.stress-row small {
display: block;
margin-top: 3px;
color: #a98991;
font-size: 9px;
line-height: 1.4;
}
.switch {
position: relative;
width: 38px;
height: 21px;
}
.switch input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.switch span {
position: absolute;
inset: 0;
border: 1px solid #5a3a48;
border-radius: 20px;
background: #321d29;
cursor: pointer;
transition: .2s;
}
.switch span::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 13px;
height: 13px;
border-radius: 3px;
background: #9b7180;
transition: .2s;
}
.switch input:checked + span {
border-color: var(--red);
background: #5a2334;
}
.switch input:checked + span::after {
left: 20px;
background: var(--red);
}
.validation {
padding: 12px;
border: 1px solid #2d5949;
border-radius: 8px;
background: #0d251f;
}
.validation.invalid {
border-color: #6e3141;
background: #291622;
}
.validation-head {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: var(--green);
font-size: 11px;
font-weight: 900;
letter-spacing: .08em;
text-transform: uppercase;
}
.validation.invalid .validation-head { color: #ff8295; }
.validation-icon {
display: grid;
width: 18px;
height: 18px;
place-items: center;
border: 1px solid currentColor;
border-radius: 4px;
font-size: 11px;
}
.validation p,
.validation ul {
margin: 0;
color: #a9c3b9;
font-size: 10px;
line-height: 1.55;
}
.validation.invalid p,
.validation.invalid ul { color: #c5a1aa; }
.validation ul {
padding-left: 16px;
margin-top: 5px;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
padding: 11px;
border: 1px solid #20374b;
border-radius: 7px;
background: #0d1d2b;
}
.metric-label {
color: var(--muted);
font-size: 9px;
letter-spacing: .1em;
text-transform: uppercase;
}
.metric-value {
margin-top: 5px;
font-size: 21px;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
.metric-value small {
color: var(--muted);
font-size: 10px;
font-weight: 600;
}
.split-bar {
display: flex;
height: 7px;
margin: 11px 0 7px;
overflow: hidden;
border-radius: 5px;
background: #172a3c;
}
#motionBar { background: var(--orange); }
#dwellBar { background: var(--cyan); }
.split-labels {
display: flex;
justify-content: space-between;
color: var(--muted);
font-size: 9px;
}
table {
width: 100%;
margin-top: 11px;
border-collapse: collapse;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
th {
padding: 6px 3px;
color: #6f8a9f;
font-size: 8px;
font-weight: 700;
letter-spacing: .08em;
text-align: right;
text-transform: uppercase;
}
th:first-child, td:first-child { text-align: left; }
td {
padding: 7px 3px;
border-top: 1px solid #1a2e40;
color: #b8cad8;
text-align: right;
}
.notes {
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.notes strong { color: #c6d6e2; }
.notes code {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
}
.right-pane {
min-width: 0;
min-height: 0;
display: grid;
grid-template-rows: minmax(290px, 1fr) 282px;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 45%, #122b3c 0%, #091723 48%, #07111c 100%);
}
#stage {
position: absolute;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active { cursor: grabbing; }
.scene-hud {
position: absolute;
top: 16px;
left: 17px;
z-index: 2;
pointer-events: none;
}
.scene-kicker {
color: var(--cyan);
font-size: 9px;
font-weight: 900;
letter-spacing: .16em;
text-transform: uppercase;
}
.scene-hud h3 {
margin: 5px 0 3px;
font-size: 14px;
letter-spacing: .03em;
}
.scene-hud p {
margin: 0;
color: var(--muted);
font-size: 10px;
}
.angle-hud {
position: absolute;
top: 16px;
right: 17px;
z-index: 2;
min-width: 132px;
padding: 9px 11px;
border: 1px solid #294258;
border-radius: 7px;
background: #07131ecc;
text-align: right;
pointer-events: none;
backdrop-filter: blur(7px);
}
.angle-hud strong {
display: block;
font-size: 19px;
font-variant-numeric: tabular-nums;
}
.angle-hud span {
color: var(--muted);
font-size: 9px;
letter-spacing: .1em;
text-transform: uppercase;
}
.legend {
position: absolute;
left: 17px;
bottom: 15px;
z-index: 2;
display: flex;
flex-wrap: wrap;
gap: 9px 13px;
padding: 8px 10px;
border: 1px solid #243b4e;
border-radius: 7px;
background: #07131ebd;
color: #9eb4c5;
font-size: 9px;
pointer-events: none;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend i {
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--c);
}
.contact-hud {
position: absolute;
right: 17px;
bottom: 15px;
z-index: 2;
padding: 8px 10px;
border: 1px solid #2c5f4b;
border-radius: 7px;
background: #0c201bdd;
color: var(--green);
font-size: 9px;
font-weight: 850;
letter-spacing: .08em;
pointer-events: none;
}
.contact-hud.broken {
color: #ff8295;
border-color: #703143;
background: #29151ddd;
}
.reject-overlay {
position: absolute;
left: 50%;
top: 50%;
z-index: 3;
display: none;
min-width: 230px;
padding: 13px 17px;
transform: translate(-50%, -50%);
border: 1px solid #8d3b50;
border-radius: 8px;
background: #25131de8;
box-shadow: 0 12px 40px #0008;
color: #ff9aab;
text-align: center;
pointer-events: none;
}
.reject-overlay.show { display: block; }
.reject-overlay strong {
display: block;
font-size: 12px;
letter-spacing: .12em;
}
.reject-overlay small {
display: block;
margin-top: 5px;
color: #bf929c;
font-size: 9px;
}
.chart-panel {
min-width: 0;
min-height: 0;
display: grid;
grid-template-rows: 47px minmax(0, 1fr);
border-top: 1px solid var(--line);
background: #0a1723;
}
.chart-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 0 17px;
border-bottom: 1px solid #1c3143;
}
.chart-header h2 {
margin: 0;
font-size: 11px;
letter-spacing: .11em;
text-transform: uppercase;
}
.chart-header p {
margin: 3px 0 0;
color: var(--muted);
font-size: 9px;
}
.chart-legend {
display: flex;
gap: 11px;
color: var(--muted);
font-size: 9px;
}
.chart-legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.chart-legend i {
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--c);
}
.chart-wrap {
position: relative;
min-height: 0;
padding: 6px 8px 5px;
}
#profileChart {
display: block;
width: 100%;
height: 100%;
}
@media (max-width: 900px) {
.workspace { grid-template-columns: 305px minmax(0, 1fr); }
.sidebar { padding: 13px; }
.brand small { display: none; }
.chart-legend { display: none; }
}
@media (max-width: 700px) {
html, body { overflow: auto; }
.app { height: auto; min-height: 100dvh; grid-template-rows: 58px auto; }
.topbar { padding: 0 10px; }
.brand h1 { font-size: 13px; }
.brand-mark { width: 23px; height: 23px; }
.status { display: none; }
.button { padding: 0 9px; }
.workspace { display: flex; flex-direction: column; }
.right-pane { order: 1; height: 760px; grid-template-rows: 490px 270px; }
.sidebar { order: 2; overflow: visible; border-right: 0; border-top: 1px solid var(--line); }
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>DWELL LAB</h1>
<small>Voxel cam sequence teaching tool</small>
</div>
</div>
<div class="top-actions">
<div id="statusBadge" class="status">VALID CONTACT</div>
<button id="resetViewBtn" class="button" title="Reset camera view">Reset view</button>
<button id="playBtn" class="button primary">❚❚ Pause cycle</button>
</div>
</header>
<main class="workspace">
<aside class="sidebar">
<section class="section">
<div class="section-title">
<h2>1 · Cam geometry</h2>
<span>BOUNDED</span>
</div>
<div class="control">
<div class="control-head">
<label for="lift">Follower lift</label>
<output id="liftOut">18 mm</output>
</div>
<input id="lift" type="range" min="4" max="32" step="1" value="18">
<div class="bounds"><span>4 mm</span><span>32 mm maximum travel</span></div>
</div>
<div class="control">
<div class="control-head">
<label for="baseRadius">Base radius</label>
<output id="baseOut">48 mm</output>
</div>
<input id="baseRadius" type="range" min="30" max="70" step="1" value="48">
<div class="bounds"><span>30 mm</span><span>70 mm</span></div>
</div>
<div class="control">
<div class="control-head">
<label for="rpm">Cycle speed</label>
<output id="rpmOut">60 rpm</output>
</div>
<input id="rpm" type="range" min="10" max="120" step="1" value="60">
<div class="bounds"><span>10 rpm</span><span>120 rpm</span></div>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>2 · Cam sequence</h2>
<button id="balanceBtn" class="text-button">Balance low dwell</button>
</div>
<div class="sequence">
<div class="interval" style="--dot:#ff8552">
<i class="interval-dot"></i>
<div class="interval-name">Rise motion<small>Moving interval</small></div>
<label class="angle-input">
<input id="rise" type="number" min="1" max="358" step="1" value="72" aria-label="Rise angle">
°
</label>
</div>
<div class="interval" style="--dot:#ffd166">
<i class="interval-dot"></i>
<div class="interval-name">High dwell<small>Stationary at maximum lift</small></div>
<label class="angle-input">
<input id="highDwell" type="number" min="1" max="358" step="1" value="54" aria-label="High dwell angle">
°
</label>
</div>
<div class="interval" style="--dot:#b794ff">
<i class="interval-dot"></i>
<div class="interval-name">Return motion<small>Moving interval</small></div>
<label class="angle-input">
<input id="fall" type="number" min="1" max="358" step="1" value="72" aria-label="Return angle">
°
</label>
</div>
<div class="interval" style="--dot:#36d8c4">
<i class="interval-dot"></i>
<div class="interval-name">Low dwell<small>Stationary at base radius</small></div>
<label class="angle-input">
<input id="lowDwell" type="number" min="1" max="358" step="1" value="162" aria-label="Low dwell angle">
°
</label>
</div>
</div>
<div class="angle-total">
<span>Allocated cam angle</span>
<strong id="angleTotal">360°</strong>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>3 · Contact test</h2>
<span>STRESS TEST</span>
</div>
<div class="stress-row">
<div>
<strong>Break the rise → dwell edge</strong>
<small>Inject a 6 mm displacement jump to test whether the tool accepts an impossible contact event.</small>
</div>
<label class="switch" title="Inject a discontinuous profile edge">
<input id="jumpToggle" type="checkbox" aria-label="Inject a six millimeter profile jump">
<span></span>
</label>
</div>
<div id="validationBox" class="validation">
<div class="validation-head">
<span id="validationIcon" class="validation-icon">✓</span>
<span id="validationTitle">Profile accepted</span>
</div>
<p id="validationText">Contact assumptions are satisfied.</p>
<ul id="validationErrors"></ul>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>4 · Interval comparison</h2>
<span id="periodLabel">1.00 s / rev</span>
</div>
<div class="metric-grid">
<div class="metric">
<div class="metric-label">Motion time</div>
<div id="metricMotion" class="metric-value">0.40 <small>s</small></div>
</div>
<div class="metric">
<div class="metric-label">Dwell time</div>
<div id="metricDwell" class="metric-value">0.60 <small>s</small></div>
</div>
</div>
<div class="split-bar" aria-label="Motion and dwell angle comparison">
<div id="motionBar"></div>
<div id="dwellBar"></div>
</div>
<div class="split-labels">
<span id="motionShare">Motion 40%</span>
<span id="dwellShare">Dwell 60%</span>
</div>
<table>
<thead>
<tr>
<th>Interval</th>
<th>Angle</th>
<th>Time</th>
</tr>
</thead>
<tbody id="intervalRows"></tbody>
</table>
</section>
<section class="section notes">
<div class="section-title">
<h2>Simplified follower model</h2>
<span>TEACHING MODEL</span>
</div>
<p>
<strong>Rigid translating knife-edge follower.</strong> The tool assumes continuous
displacement, a maximum travel of <code>32 mm</code>, a maximum speed of
<code>900 mm/s</code>, and a maximum acceleration of <code>2500 mm/s²</code>.
</p>
<p style="margin-top:8px">
Pressure angle, friction, clearance, impact, spring dynamics, backlash, and
manufacturing tolerance are intentionally omitted.
</p>
</section>
</aside>
<section class="right-pane">
<div class="stage">
<div id="stage" aria-label="Interactive voxel cam and follower scene"></div>
<div class="scene-hud">
<div class="scene-kicker">Radial cam · translating follower</div>
<h3>Voxel cycle inspector</h3>
<p>Drag to orbit · wheel to zoom · double-click to reset</p>
</div>
<div class="angle-hud">
<strong id="angleReadout">0.0°</strong>
<span id="phaseReadout">Rise motion</span>
</div>
<div class="legend">
<span><i style="--c:#ff8552"></i> Rise</span>
<span><i style="--c:#ffd166"></i> High dwell</span>
<span><i style="--c:#b794ff"></i> Return</span>
<span><i style="--c:#36d8c4"></i> Low dwell</span>
</div>
<div id="contactHud" class="contact-hud">CONTACT MAINTAINED</div>
<div id="rejectOverlay" class="reject-overlay">
<strong>PROFILE REJECTED</strong>
<small>Cycle playback is locked until contact assumptions pass.</small>
</div>
</div>
<div class="chart-panel">
<div class="chart-header">
<div>
<h2>Follower lift profile</h2>
<p>Radial displacement versus cam angle · colored bands are sequence intervals</p>
</div>
<div class="chart-legend">
<span><i style="--c:#ff8552"></i> Motion</span>
<span><i style="--c:#36d8c4"></i> Dwell</span>
<span><i style="--c:#ff526d"></i> Rejected edge</span>
</div>
</div>
<div class="chart-wrap">
<canvas id="profileChart" aria-label="Cam follower lift chart"></canvas>
</div>
</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";
const $ = id => document.getElementById(id);
const COLORS = {
rise: 0xff8552,
high: 0xffd166,
fall: 0xb794ff,
low: 0x36d8c4
};
const CSS_COLORS = {
rise: "#ff8552",
high: "#ffd166",
fall: "#b794ff",
low: "#36d8c4"
};
const MAX_TRAVEL = 32;
const MAX_SPEED = 900;
const MAX_ACCELERATION = 2500;
const JUMP_SIZE = 6;
const DEG = Math.PI / 180;
const state = {
angle: 0,
playing: true,
theta: 0.48,
phi: 1.12,
radius: 175,
target: new THREE.Vector3(0, 34, 0),
pointerDown: false,
pointerX: 0,
pointerY: 0
};
let model;
let validation;
// ---------------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------------
const stage = $("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111c);
scene.fog = new THREE.Fog(0x07111c, 185, 340);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 600);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0x9fdfff, 0x172030, 2.05));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.0);
keyLight.position.set(-55, 105, 85);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -100;
keyLight.shadow.camera.right = 100;
keyLight.shadow.camera.top = 120;
keyLight.shadow.camera.bottom = -100;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 260;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x36d8c4, 1.65);
rimLight.position.set(85, 35, -70);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff8552, 85, 180, 2);
warmLight.position.set(-55, 15, 45);
scene.add(warmLight);
const camGroup = new THREE.Group();
const camVoxelGroup = new THREE.Group();
const camShaftGroup = new THREE.Group();
camGroup.add(camVoxelGroup, camShaftGroup);
scene.add(camGroup);
const followerGroup = new THREE.Group();
followerGroup.position.z = 10;
scene.add(followerGroup);
const followerMaterial = new THREE.MeshStandardMaterial({
color: 0x72e6d5,
roughness: 0.38,
metalness: 0.22,
emissive: 0x0d4a43,
emissiveIntensity: 0.32
});
const followerDarkMaterial = new THREE.MeshStandardMaterial({
color: 0x264353,
roughness: 0.54,
metalness: 0.34
});
const contactMaterial = new THREE.MeshStandardMaterial({
color: 0xb8fff3,
emissive: 0x36d8c4,
emissiveIntensity: 1.2,
roughness: 0.3
});
function addBox(parent, width, height, depth, x, y, z, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
addBox(
followerGroup, 10, 4, 9, 0, 2, 0,
new THREE.MeshStandardMaterial({
color: 0xe4fff9,
emissive: 0x36d8c4,
emissiveIntensity: 0.55,
roughness: 0.28
})
);
addBox(followerGroup, 18, 4, 14, 0, 6, 0, followerMaterial);
addBox(followerGroup, 5, 32, 5, 0, 24, 0, followerDarkMaterial);
addBox(followerGroup, 12, 5, 11, 0, 42, 0, followerMaterial);
const contactBlock = followerGroup.children[0];
const followerBodyMaterial = followerMaterial;
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x21394a,
roughness: 0.78,
metalness: 0.16
});
const frameAccentMaterial = new THREE.MeshStandardMaterial({
color: 0x315d69,
roughness: 0.62,
metalness: 0.25
});
const frame = new THREE.Group();
scene.add(frame);
// Block-built rear frame.
for (const side of [-1, 1]) {
for (let i = 0; i < 8; i++) {
addBox(
frame,
7,
18,
7,
side * 35,
-52 + i * 18,
-24,
i % 2 ? frameMaterial : frameAccentMaterial
);
}
}
addBox(frame, 84, 7, 8, 0, 92, -24, frameMaterial);
addBox(frame, 84, 4, 10, 0, 87, -24, frameAccentMaterial);
// Guide blocks around the follower stem.
addBox(frame, 5, 9, 15, -9, 101, 8, frameMaterial);
addBox(frame, 5, 9, 15, 9, 101, 8, frameMaterial);
addBox(frame, 23, 5, 15, 0, 106, 8, frameAccentMaterial);
// Rear bearing blocks around the shaft.
addBox(frame, 8, 36, 8, -15, 0, -33, frameMaterial);
addBox(frame, 8, 36, 8, 15, 0, -33, frameMaterial);
addBox(frame, 38, 8, 8, 0, -22, -33, frameAccentMaterial);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x0d1b27,
roughness: 0.95,
metalness: 0.02
});
addBox(scene, 260, 3, 210, 0, -70, 0, floorMaterial);
const gridMaterial = new THREE.MeshBasicMaterial({
color: 0x173247,
transparent: true,
opacity: 0.65
});
for (let i = -6; i <= 6; i++) {
addBox(scene, 0.35, 0.12, 205, i * 20, -68.35, 0, gridMaterial);
addBox(scene, 245, 0.12, 0.35, 0, -68.35, i * 16, gridMaterial);
}
// ---------------------------------------------------------------------------
// Custom orbit camera — no external controls module.
// ---------------------------------------------------------------------------
function updateCamera() {
const sinPhi = Math.sin(state.phi);
camera.position.set(
state.target.x + state.radius * sinPhi * Math.sin(state.theta),
state.target.y + state.radius * Math.cos(state.phi),
state.target.z + state.radius * sinPhi * Math.cos(state.theta)
);
camera.lookAt(state.target);
}
function resetCamera() {
state.theta = 0.48;
state.phi = 1.12;
state.radius = 175;
state.target.set(0, 34, 0);
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", event => {
state.pointerDown = true;
state.pointerX = event.clientX;
state.pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!state.pointerDown) return;
const dx = event.clientX - state.pointerX;
const dy = event.clientY - state.pointerY;
state.pointerX = event.clientX;
state.pointerY = event.clientY;
state.theta -= dx * 0.006;
state.phi = THREE.MathUtils.clamp(state.phi - dy * 0.005, 0.45, 2.42);
updateCamera();
});
function releasePointer(event) {
state.pointerDown = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
state.radius = THREE.MathUtils.clamp(
state.radius * Math.exp(event.deltaY * 0.001),
95,
290
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
// ---------------------------------------------------------------------------
// Profile model
// ---------------------------------------------------------------------------
function smootherStep(u) {
u = THREE.MathUtils.clamp(u, 0, 1);
return u * u * u * (10 - 15 * u + 6 * u * u);
}
function readModel() {
const lift = Number($("lift").value);
const baseRadius = Number($("baseRadius").value);
const rpm = Number($("rpm").value);
const rise = Number($("rise").value);
const highDwell = Number($("highDwell").value);
const fall = Number($("fall").value);
const lowDwell = Number($("lowDwell").value);
const injectJump = $("jumpToggle").checked;
const highValue = lift + (injectJump ? JUMP_SIZE : 0);
const a0 = 0;
const a1 = rise;
const a2 = rise + highDwell;
const a3 = a2 + fall;
const a4 = a3 + lowDwell;
const segments = [
{
key: "rise",
type: "motion",
label: "Rise motion",
a0, a1,
y0: 0,
y1: lift
},
{
key: "high",
type: "dwell",
label: "High dwell",
a0: a1, a1: a2,
y0: highValue,
y1: highValue
},
{
key: "fall",
type: "motion",
label: "Return motion",
a0: a2, a1: a3,
y0: highValue,
y1: 0
},
{
key: "low",
type: "dwell",
label: "Low dwell",
a0: a3, a1: a4,
y0: 0,
y1: 0
}
];
return {
lift,
baseRadius,
rpm,
rise,
highDwell,
fall,
lowDwell,
injectJump,
total: rise + highDwell + fall + lowDwell,
period: 60 / rpm,
segments
};
}
function segmentAt(angle) {
const a = ((angle % 360) + 360) % 360;
const m = model;
if (a < m.rise) return m.segments[0];
if (a < m.rise + m.highDwell) return m.segments[1];
if (a < m.rise + m.highDwell + m.fall) return m.segments[2];
return m.segments[3];
}
function profileAt(angle) {
const segment = segmentAt(angle);
const width = segment.a1 - segment.a0;
if (segment.type === "dwell" || width <= 0) {
return segment.y0;
}
const u = THREE.MathUtils.clamp(
(angle - segment.a0) / width,
0,
1
);
return segment.y0 + (segment.y1 - segment.y0) * smootherStep(u);
}
function validateProfile() {
const errors = [];
const m = model;
if (Math.abs(m.total - 360) > 0.001) {
errors.push(`The four intervals allocate ${m.total}°, not one complete 360° revolution.`);
}
if (m.rise <= 0 || m.fall <= 0) {
errors.push("Both rise and return motion require a positive angular interval.");
}
if (m.highDwell <= 0 || m.lowDwell <= 0) {
errors.push("At least one high-dwell and one low-dwell interval are required.");
}
if (m.lift < 4 || m.lift > MAX_TRAVEL) {
errors.push(`Follower lift must remain within 4–${MAX_TRAVEL} mm.`);
}
if (m.baseRadius < 30 || m.baseRadius > 70) {
errors.push("Base radius must remain within 30–70 mm.");
}
// Detect displacement discontinuities at every adjacent interval boundary.
for (let i = 0; i < m.segments.length - 1; i++) {
const previous = m.segments[i];
const next = m.segments[i + 1];
const jump = Math.abs(next.y0 - previous.y1);
if (jump > 0.001) {
errors.push(
`Rejected: follower displacement jumps ${jump.toFixed(1)} mm at the ` +
`${previous.label} → ${next.label} edge (${previous.a1.toFixed(0)}°).`
);
}
}
for (const segment of m.segments) {
const low = Math.min(segment.y0, segment.y1);
const high = Math.max(segment.y0, segment.y1);
if (low < -0.001 || high > MAX_TRAVEL + 0.001) {
errors.push(
`The ${segment.label} interval leaves the bounded 0–${MAX_TRAVEL} mm travel envelope.`
);
break;
}
}
const riseTime = (m.rise / 360) * m.period;
const fallTime = (m.fall / 360) * m.period;
const riseSpeed = riseTime > 0 ? 1.875 * m.lift / riseTime : Infinity;
const fallSpeed = fallTime > 0 ? 1.875 * m.lift / fallTime : Infinity;
const riseAcceleration = riseTime > 0
? (10 / Math.sqrt(3)) * m.lift / (riseTime * riseTime)
: Infinity;
const fallAcceleration = fallTime > 0
? (10 / Math.sqrt(3)) * m.lift / (fallTime * fallTime)
: Infinity;
if (Math.max(riseSpeed, fallSpeed) > MAX_SPEED) {
errors.push(
`Peak follower speed ${Math.max(riseSpeed, fallSpeed).toFixed(0)} mm/s exceeds ` +
`the ${MAX_SPEED} mm/s teaching limit.`
);
}
if (Math.max(riseAcceleration, fallAcceleration) > MAX_ACCELERATION) {
errors.push(
`Peak follower acceleration ${Math.max(riseAcceleration, fallAcceleration).toFixed(0)} mm/s² ` +
`exceeds the ${MAX_ACCELERATION} mm/s² contact limit.`
);
}
return {
valid: errors.length === 0,
errors,
riseSpeed,
fallSpeed,
riseAcceleration,
fallAcceleration
};
}
// ---------------------------------------------------------------------------
// Voxel cam construction
// ---------------------------------------------------------------------------
function disposeChildren(group) {
for (const child of [...group.children]) {
child.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
if (Array.isArray(object.material)) {
object.material.forEach(material => material.dispose());
} else {
object.material.dispose();
}
}
});
group.remove(child);
}
}
function makeInstancedVoxels(transforms, color, size = 2.35) {
if (!transforms.length) return null;
const geometry = new THREE.BoxGeometry(size, size, size);
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.76,
metalness: 0.08,
flatShading: true
});
const mesh = new THREE.InstancedMesh(geometry, material, transforms.length);
const matrix = new THREE.Matrix4();
transforms.forEach((transform, index) => {
matrix.makeTranslation(transform.x, transform.y, transform.z);
mesh.setMatrixAt(index, matrix);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function rebuildCam() {
disposeChildren(camVoxelGroup);
disposeChildren(camShaftGroup);
const cell = 2.6;
const extent = Math.ceil((model.baseRadius + model.lift + 4) / cell);
const data = { rise: [], high: [], fall: [], low: [] };
for (let ix = -extent; ix <= extent; ix++) {
for (let iy = -extent; iy <= extent; iy++) {
const x = ix * cell;
const y = iy * cell;
const radialDistance = Math.hypot(x, y);
const angle = (Math.atan2(y, x) / DEG + 360) % 360;
const boundary = model.baseRadius + profileAt(angle);
if (radialDistance <= boundary) {
const segment = segmentAt(angle);
for (const z of [-4.8, -1.6, 1.6, 4.8]) {
data[segment.key].push({ x, y, z });
}
}
}
}
for (const key of Object.keys(data)) {
const mesh = makeInstancedVoxels(data[key], COLORS[key]);
if (mesh) camVoxelGroup.add(mesh);
}
// Voxel shaft running through the cam.
const shaftData = [];
const shaftStep = 4.5;
for (let x = -6; x <= 6; x++) {
for (let y = -6; y <= 6; y++) {
if (Math.hypot(x * shaftStep, y * shaftStep) > 9) continue;
for (let z = -27; z <= 27; z += shaftStep) {
shaftData.push({
x: x * shaftStep,
y: y * shaftStep,
z
});
}
}
}
const shaft = makeInstancedVoxels(shaftData, 0x718b9b, 4.15);
if (shaft) camShaftGroup.add(shaft);
// A bright index block makes rotation easy to read.
const indexGeometry = new THREE.BoxGeometry(5, 5, 5);
const indexMaterial = new THREE.MeshStandardMaterial({
color: 0xf4fbff,
emissive: 0x9edfff,
emissiveIntensity: 0.35,
roughness: 0.4
});
const indexBlock = new THREE.Mesh(indexGeometry, indexMaterial);
indexBlock.position.set(model.baseRadius - 9, 0, 8);
indexBlock.castShadow = true;
camShaftGroup.add(indexBlock);
}
// ---------------------------------------------------------------------------
// Interface updates
// ---------------------------------------------------------------------------
function updateControlReadouts() {
$("liftOut").textContent = `${$("lift").value} mm`;
$("baseOut").textContent = `${$("baseRadius").value} mm`;
$("rpmOut").textContent = `${$("rpm").value} rpm`;
}
function updateValidationUI() {
const valid = validation.valid;
const badge = $("statusBadge");
const box = $("validationBox");
badge.classList.toggle("invalid", !valid);
badge.textContent = valid ? "VALID CONTACT" : "PROFILE REJECTED";
box.classList.toggle("invalid", !valid);
$("validationIcon").textContent = valid ? "✓" : "!";
$("validationTitle").textContent = valid
? "Profile accepted"
: "Profile rejected";
$("validationText").textContent = valid
? "The follower can remain in contact through every interval edge. Playback is permitted."
: "One or more teaching-model assumptions failed. The invalid cycle is not allowed to run.";
$("validationErrors").replaceChildren();
for (const error of validation.errors) {
const item = document.createElement("li");
item.textContent = error;
$("validationErrors").appendChild(item);
}
$("rejectOverlay").classList.toggle("show", !valid);
$("playBtn").disabled = !valid;
$("contactHud").classList.toggle("broken", !valid);
if (!valid && model.injectJump) {
$("contactHud").textContent = `CONTACT GAP · ${JUMP_SIZE.toFixed(1)} mm`;
} else if (!valid) {
$("contactHud").textContent = "CONTACT ASSUMPTION FAILED";
} else {
$("contactHud").textContent = "CONTACT MAINTAINED";
}
}
function updateMetrics() {
const m = model;
const motionAngle = m.rise + m.fall;
const dwellAngle = m.highDwell + m.lowDwell;
const motionTime = (motionAngle / 360) * m.period;
const dwellTime = (dwellAngle / 360) * m.period;
const highTime = (m.highDwell / 360) * m.period;
const lowTime = (m.lowDwell / 360) * m.period;
$("metricMotion").innerHTML = `${motionTime.toFixed(2)} <small>s</small>`;
$("metricDwell").innerHTML = `${dwellTime.toFixed(2)} <small>s</small>`;
$("periodLabel").textContent = `${m.period.toFixed(2)} s / rev`;
const denominator = Math.max(1, motionAngle + dwellAngle);
$("motionBar").style.width = `${motionAngle / denominator * 100}%`;
$("dwellBar").style.width = `${dwellAngle / denominator * 100}%`;
$("motionShare").textContent = `Motion ${(motionAngle / denominator * 100).toFixed(0)}%`;
$("dwellShare").textContent = `Dwell ${(dwellAngle / denominator * 100).toFixed(0)}%`;
const rows = [
["Rise motion", m.rise, motionAngle * 0 + (m.rise / 360) * m.period, CSS_COLORS.rise],
["High dwell", m.highDwell, highTime, CSS_COLORS.high],
["Return motion", m.fall, (m.fall / 360) * m.period, CSS_COLORS.fall],
["Low dwell", m.lowDwell, lowTime, CSS_COLORS.low]
];
$("intervalRows").replaceChildren();
for (const [name, angle, time, color] of rows) {
const row = document.createElement("tr");
const nameCell = document.createElement("td");
const dot = document.createElement("span");
dot.style.display = "inline-block";
dot.style.width = "7px";
dot.style.height = "7px";
dot.style.marginRight = "6px";
dot.style.borderRadius = "2px";
dot.style.background = color;
nameCell.append(dot, document.createTextNode(name));
const angleCell = document.createElement("td");
angleCell.textContent = `${angle}°`;
const timeCell = document.createElement("td");
timeCell.textContent = `${time.toFixed(2)} s`;
row.append(nameCell, angleCell, timeCell);
$("intervalRows").appendChild(row);
}
const totalRow = document.createElement("tr");
const totalName = document.createElement("td");
totalName.textContent = "Total";
totalName.style.color = "#e9f3fb";
totalName.style.fontWeight = "800";
const totalAngle = document.createElement("td");
totalAngle.textContent = `${m.total}°`;
const totalTime = document.createElement("td");
totalTime.textContent = `${m.period.toFixed(2)} s`;
totalRow.append(totalName, totalAngle, totalTime);
$("intervalRows").appendChild(totalRow);
}
function updateAll(rebuild = true) {
updateControlReadouts();
model = readModel();
validation = validateProfile();
const totalValid = Math.abs(model.total - 360) < 0.001;
$("angleTotal").textContent = `${model.total}°`;
$("angleTotal").classList.toggle("bad", !totalValid);
updateValidationUI();
updateMetrics();
if (!validation.valid) {
state.playing = false;
updatePlayButton();
if (model.injectJump) {
state.angle = model.rise + 0.8;
}
}
if (rebuild) rebuildCam();
drawChart();
}
function updatePlayButton() {
$("playBtn").textContent = state.playing ? "❚❚ Pause cycle" : "▶ Run cycle";
}
// ---------------------------------------------------------------------------
// Profile chart
// ---------------------------------------------------------------------------
const chartCanvas = $("profileChart");
const chartContext = chartCanvas.getContext("2d");
function drawChart() {
if (!model) return;
const rect = chartCanvas.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dpr = Math.min(window.devicePixelRatio, 2);
const pixelWidth = Math.round(rect.width * dpr);
const pixelHeight = Math.round(rect.height * dpr);
if (chartCanvas.width !== pixelWidth || chartCanvas.height !== pixelHeight) {
chartCanvas.width = pixelWidth;
chartCanvas.height = pixelHeight;
}
const ctx = chartContext;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, rect.width, rect.height);
const width = rect.width;
const height = rect.height;
const margin = { left: 47, right: 19, top: 17, bottom: 29 };
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
const yMax = Math.max(34, model.lift + (model.injectJump ? JUMP_SIZE : 0) + 5);
const yMin = -3;
const xFor = angle => margin.left + angle / 360 * plotWidth;
const yFor = lift => margin.top + (yMax - lift) / (yMax - yMin) * plotHeight;
// Interval bands.
for (const segment of model.segments) {
const start = Math.max(0, segment.a0);
const end = Math.min(360, segment.a1);
if (end <= start) continue;
ctx.fillStyle = `${CSS_COLORS[segment.key]}13`;
ctx.fillRect(xFor(start), margin.top, xFor(end) - xFor(start), plotHeight);
ctx.fillStyle = `${CSS_COLORS[segment.key]}d8`;
ctx.fillRect(xFor(start), margin.top, 2, plotHeight);
if (xFor(end) - xFor(start) > 42) {
ctx.fillStyle = CSS_COLORS[segment.key];
ctx.font = "700 9px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.fillText(
segment.type === "motion" ? "MOTION" : "DWELL",
(xFor(start) + xFor(end)) / 2,
margin.top + 11
);
}
}
// Grid and axes.
ctx.font = "9px system-ui, sans-serif";
ctx.textAlign = "right";
ctx.textBaseline = "middle";
for (let lift = 0; lift <= yMax; lift += 10) {
const y = yFor(lift);
ctx.strokeStyle = "#1d3346";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(margin.left, y);
ctx.lineTo(width - margin.right, y);
ctx.stroke();
ctx.fillStyle = "#6f899d";
ctx.fillText(`${lift}`, margin.left - 9, y);
}
ctx.textAlign = "center";
ctx.textBaseline = "top";
for (let angle = 0; angle <= 360; angle += 60) {
const x = xFor(angle);
ctx.strokeStyle = "#1b3042";
ctx.beginPath();
ctx.moveTo(x, margin.top);
ctx.lineTo(x, height - margin.bottom);
ctx.stroke();
ctx.fillStyle = "#6f899d";
ctx.fillText(`${angle}°`, x, height - margin.bottom + 8);
}
ctx.strokeStyle = "#385268";
ctx.lineWidth = 1;
ctx.strokeRect(margin.left, margin.top, plotWidth, plotHeight);
// Profile segments. Broken boundaries are intentionally not connected.
for (const segment of model.segments) {
const start = Math.max(0, segment.a0);
const end = Math.min(360, segment.a1);
if (end <= start) continue;
ctx.strokeStyle = CSS_COLORS[segment.key];
ctx.lineWidth = segment.type === "motion" ? 3 : 3;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.beginPath();
const samples = Math.max(24, Math.ceil((end - start) / 1.5));
for (let i = 0; i <= samples; i++) {
const angle = start + (end - start) * i / samples;
const lift = profileAt(angle);
const x = xFor(angle);
const y = yFor(lift);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.stroke();
}
// Highlight the rejected jump.
if (model.injectJump) {
const x = xFor(model.rise);
const y1 = yFor(model.lift);
const y2 = yFor(model.lift + JUMP_SIZE);
ctx.strokeStyle = "#ff526d";
ctx.lineWidth = 2;
ctx.setLineDash([4, 3]);
ctx.beginPath();
ctx.moveTo(x, y1);
ctx.lineTo(x, y2);
ctx.stroke();
ctx.setLineDash([]);
for (const y of [y1, y2]) {
ctx.fillStyle = "#ff526d";
ctx.beginPath();
ctx.arc(x, y, 3.5, 0, Math.PI * 2);
ctx.fill();
}
}
// Current cycle position.
const playheadX = xFor(state.angle);
const currentLift = profileAt(state.angle);
ctx.strokeStyle = "#d9f7ff";
ctx.globalAlpha = 0.65;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(playheadX, margin.top);
ctx.lineTo(playheadX, height - margin.bottom);
ctx.stroke();
ctx.globalAlpha = 1;
ctx.fillStyle = "#e7fbff";
ctx.beginPath();
ctx.arc(playheadX, yFor(currentLift), 4, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "#7995a9";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Follower lift (mm)", margin.left + 4, 3);
}
// ---------------------------------------------------------------------------
// Interaction
// ---------------------------------------------------------------------------
for (const id of ["lift", "baseRadius", "rpm", "rise", "highDwell", "fall", "lowDwell"]) {
$(id).addEventListener("input", () => {
updateAll(true);
if (id === "rise" && model.injectJump) {
state.angle = model.rise + 0.8;
}
});
}
$("jumpToggle").addEventListener("change", () => {
updateAll(true);
if ($("jumpToggle").checked) {
state.angle = model.rise + 0.8;
state.playing = false;
updatePlayButton();
}
});
$("balanceBtn").addEventListener("click", () => {
const lowDwell = 360 -
Number($("rise").value) -
Number($("highDwell").value) -
Number($("fall").value);
$("lowDwell").value = Math.max(1, lowDwell);
updateAll(true);
});
$("playBtn").addEventListener("click", () => {
if (!validation.valid) return;
state.playing = !state.playing;
updatePlayButton();
});
$("resetViewBtn").addEventListener("click", resetCamera);
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
if (validation.valid) {
state.playing = !state.playing;
updatePlayButton();
}
}
if (event.key.toLowerCase() === "r") resetCamera();
});
const stageResizeObserver = new ResizeObserver(() => {
const rect = stage.getBoundingClientRect();
renderer.setSize(rect.width, rect.height, false);
camera.aspect = rect.width / Math.max(1, rect.height);
camera.updateProjectionMatrix();
});
stageResizeObserver.observe(stage);
const chartResizeObserver = new ResizeObserver(drawChart);
chartResizeObserver.observe(chartCanvas.parentElement);
// ---------------------------------------------------------------------------
// Animation
// ---------------------------------------------------------------------------
function currentPhase(angle) {
const m = model;
if (angle < m.rise) return "Rise motion";
if (angle < m.rise + m.highDwell) return "High dwell";
if (angle < m.rise + m.highDwell + m.fall) return "Return motion";
return "Low dwell";
}
let previousTime = performance.now();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (state.playing && validation.valid) {
state.angle = (state.angle + model.rpm / 60 * 360 * delta) % 360;
}
// Put the currently read profile angle at the top of the cam.
camGroup.rotation.z = (90 - state.angle) * DEG;
const actualSurface = model.baseRadius + profileAt(state.angle);
let followerHeight = actualSurface;
// A broken profile cannot teleport the follower to maintain contact.
if (!validation.valid && model.injectJump) {
followerHeight = model.baseRadius + model.lift;
}
followerGroup.position.y = followerHeight;
const invalidColor = new THREE.Color(0xff526d);
const validColor = new THREE.Color(0x72e6d5);
followerBodyMaterial.color.copy(validation.valid ? validColor : invalidColor);
followerBodyMaterial.emissive.copy(
validation.valid ? new THREE.Color(0x0d4a43) : new THREE.Color(0x5a1122)
);
contactMaterial.color.copy(
validation.valid ? new THREE.Color(0xb8fff3) : invalidColor
);
contactMaterial.emissive.copy(
validation.valid ? new THREE.Color(0x36d8c4) : invalidColor
);
$("angleReadout").textContent = `${state.angle.toFixed(1)}°`;
$("phaseReadout").textContent = currentPhase(state.angle);
updateCamera();
drawChart();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
resetCamera();
updateAll(true);
updatePlayButton();
requestAnimationFrame(animate);
</script>
</body>
</html>
```