Prompt specification
Build or customize the Three.js 3D scene "Gear-ratio prediction playground" 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: Gear-ratio prediction playground
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/gear-ratio-prediction-playground-x1388
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing meshing gears and their rotation ratios. Let users choose from a small set of compatible gears and predict output speed; validate the ratio, prevent incompatible center spacing, and show rotation direction explicitly. Low-poly.
Working Three.js Starter (gear-ratio-prediction-playground-x1388):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MeshLab — Interactive Gear Ratios</title>
<style>
:root {
color-scheme: dark;
--bg: #07101b;
--panel: #0d1826;
--panel-2: #111f30;
--line: rgba(158, 190, 218, 0.16);
--text: #edf5fb;
--muted: #91a6b9;
--driver: #ffb64d;
--output: #40d7c4;
--good: #60e3a2;
--bad: #ff6b75;
--blue: #72a9ff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
min-height: 100%;
margin: 0;
}
body {
overflow: hidden;
background:
radial-gradient(circle at 80% 0%, rgba(48, 95, 133, 0.18), transparent 32%),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input,
select {
font: inherit;
}
button,
select,
input[type="range"] {
cursor: pointer;
}
button:focus-visible,
select:focus-visible,
input:focus-visible {
outline: 2px solid var(--blue);
outline-offset: 2px;
}
.app {
height: 100vh;
min-height: 620px;
display: flex;
flex-direction: column;
}
header {
height: 74px;
flex: 0 0 74px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 24px;
border-bottom: 1px solid var(--line);
background: rgba(7, 16, 27, 0.78);
backdrop-filter: blur(16px);
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 42px;
height: 42px;
display: grid;
place-items: center;
border: 1px solid rgba(64, 215, 196, 0.28);
border-radius: 13px;
color: var(--output);
background: rgba(64, 215, 196, 0.08);
box-shadow: inset 0 0 20px rgba(64, 215, 196, 0.04);
}
.brand-mark svg {
width: 25px;
height: 25px;
}
.brand h1 {
margin: 0;
font-size: 20px;
line-height: 1.05;
letter-spacing: -0.03em;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.header-badge {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 999px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.08em;
white-space: nowrap;
}
.header-badge::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--good);
box-shadow: 0 0 12px rgba(96, 227, 162, 0.65);
}
main {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: 350px minmax(0, 1fr);
}
aside {
min-height: 0;
overflow-y: auto;
padding: 18px;
border-right: 1px solid var(--line);
background: rgba(10, 20, 32, 0.88);
scrollbar-width: thin;
scrollbar-color: rgba(126, 159, 188, 0.3) transparent;
}
.card {
margin-bottom: 13px;
padding: 16px;
border: 1px solid var(--line);
border-radius: 15px;
background: linear-gradient(145deg, rgba(18, 33, 49, 0.94), rgba(12, 24, 38, 0.94));
box-shadow: 0 12px 28px rgba(0, 0, 0, 0.12);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 13px;
}
.section-heading h2 {
margin: 0;
font-size: 13px;
letter-spacing: 0.055em;
text-transform: uppercase;
}
.step {
width: 24px;
height: 24px;
display: inline-grid;
place-items: center;
margin-right: 7px;
border-radius: 7px;
color: #b9c9d8;
background: rgba(132, 163, 192, 0.1);
font-size: 11px;
vertical-align: middle;
}
.compatible {
color: var(--good);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
}
.field {
margin-top: 13px;
}
.field:first-of-type {
margin-top: 0;
}
.field-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
color: #c9d6e2;
font-size: 12px;
font-weight: 650;
}
.field-label output,
.mono {
font-variant-numeric: tabular-nums;
}
select,
input[type="number"] {
width: 100%;
height: 42px;
border: 1px solid rgba(158, 190, 218, 0.2);
border-radius: 10px;
padding: 0 12px;
color: var(--text);
background: #0a1421;
}
select:hover,
input[type="number"]:hover {
border-color: rgba(158, 190, 218, 0.38);
}
.gear-fields {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.mini-note {
margin-top: 9px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.ratio-box {
margin-top: 13px;
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 10px;
padding: 11px 12px;
border: 1px solid rgba(114, 169, 255, 0.18);
border-radius: 11px;
background: rgba(114, 169, 255, 0.07);
}
.ratio-box small {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.ratio-value {
font-size: 19px;
font-weight: 800;
letter-spacing: -0.03em;
}
.ratio-kind {
padding: 5px 8px;
border-radius: 999px;
color: var(--blue);
background: rgba(114, 169, 255, 0.1);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.formula {
margin-top: 10px;
padding: 10px;
overflow-x: auto;
border-radius: 9px;
color: #a8bed1;
background: rgba(0, 0, 0, 0.18);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
white-space: nowrap;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 8px 0;
appearance: none;
border-radius: 999px;
background: linear-gradient(
90deg,
var(--driver) 0%,
var(--driver) var(--range-fill, 33%),
rgba(157, 186, 211, 0.16) var(--range-fill, 33%)
);
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
appearance: none;
border: 3px solid #132334;
border-radius: 50%;
background: var(--driver);
box-shadow: 0 0 0 1px rgba(255, 182, 77, 0.5);
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 3px solid #132334;
border-radius: 50%;
background: var(--driver);
box-shadow: 0 0 0 1px rgba(255, 182, 77, 0.5);
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px;
padding: 4px;
border: 1px solid rgba(158, 190, 218, 0.15);
border-radius: 11px;
background: #09131f;
}
.segmented button {
min-height: 34px;
border: 0;
border-radius: 8px;
color: var(--muted);
background: transparent;
font-size: 12px;
font-weight: 750;
}
.segmented button.active {
color: var(--text);
background: rgba(124, 160, 193, 0.16);
box-shadow: inset 0 0 0 1px rgba(158, 190, 218, 0.12);
}
.segmented.driver button.active {
color: var(--driver);
background: rgba(255, 182, 77, 0.1);
}
.segmented.output button.active {
color: var(--output);
background: rgba(64, 215, 196, 0.1);
}
.prediction-row {
display: grid;
grid-template-columns: 1fr;
gap: 9px;
}
.prediction-row input {
font-size: 16px;
font-weight: 750;
}
.primary,
.secondary,
.small-button {
border-radius: 10px;
font-weight: 750;
transition: 160ms ease;
}
.primary {
width: 100%;
min-height: 42px;
border: 0;
color: #06131a;
background: var(--output);
box-shadow: 0 8px 22px rgba(64, 215, 196, 0.15);
}
.primary:hover:not(:disabled) {
transform: translateY(-1px);
background: #62ead9;
}
.primary:disabled {
color: #70808d;
background: #26333e;
box-shadow: none;
cursor: not-allowed;
}
.feedback {
min-height: 42px;
margin-top: 10px;
padding: 10px 11px;
border: 1px solid rgba(158, 190, 218, 0.14);
border-radius: 10px;
color: var(--muted);
background: rgba(0, 0, 0, 0.13);
font-size: 11px;
line-height: 1.45;
}
.feedback.good {
border-color: rgba(96, 227, 162, 0.3);
color: #a8f2cb;
background: rgba(96, 227, 162, 0.07);
}
.feedback.bad {
border-color: rgba(255, 107, 117, 0.3);
color: #ffb1b6;
background: rgba(255, 107, 117, 0.07);
}
.result {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 11px;
padding: 11px;
border: 1px solid rgba(64, 215, 196, 0.16);
border-radius: 10px;
background: rgba(64, 215, 196, 0.055);
}
.result small {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.result strong {
display: block;
margin-top: 3px;
font-size: 14px;
}
#actualDirection {
color: var(--output);
font-size: 11px;
font-weight: 750;
text-align: right;
}
.spacing-status {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 10px;
padding: 10px 11px;
border-radius: 10px;
border: 1px solid rgba(96, 227, 162, 0.2);
color: #a8f2cb;
background: rgba(96, 227, 162, 0.06);
font-size: 11px;
}
.spacing-status.invalid {
border-color: rgba(255, 107, 117, 0.3);
color: #ffb1b6;
background: rgba(255, 107, 117, 0.06);
}
.small-button {
min-height: 31px;
padding: 0 10px;
border: 1px solid rgba(158, 190, 218, 0.2);
color: #c9d8e5;
background: rgba(158, 190, 218, 0.06);
font-size: 10px;
}
.small-button:hover {
border-color: rgba(158, 190, 218, 0.4);
background: rgba(158, 190, 218, 0.11);
}
.actions {
display: grid;
grid-template-columns: 1fr auto;
gap: 9px;
}
.actions .secondary {
min-height: 42px;
padding: 0 13px;
border: 1px solid rgba(158, 190, 218, 0.18);
color: #c9d8e5;
background: rgba(158, 190, 218, 0.06);
}
.actions .secondary:hover {
background: rgba(158, 190, 218, 0.11);
}
.viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 45%, rgba(44, 76, 105, 0.13), transparent 45%),
#08121e;
}
canvas {
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.viewport-top {
position: absolute;
top: 16px;
left: 16px;
right: 16px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
pointer-events: none;
}
.viewport-chip {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 9px 11px;
border: 1px solid rgba(158, 190, 218, 0.16);
border-radius: 10px;
color: #bed0df;
background: rgba(7, 16, 27, 0.76);
backdrop-filter: blur(10px);
font-size: 11px;
font-weight: 700;
}
.viewport-chip .dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--driver);
}
.status-chip {
color: var(--good);
}
.status-chip.locked {
color: var(--bad);
}
.status-chip.waiting {
color: var(--driver);
}
.world-label {
position: absolute;
top: 0;
left: 0;
z-index: 2;
min-width: 125px;
padding: 8px 10px;
border: 1px solid rgba(158, 190, 218, 0.17);
border-radius: 10px;
background: rgba(7, 16, 27, 0.84);
backdrop-filter: blur(10px);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.18);
pointer-events: none;
transform: translate(-50%, -100%);
}
.world-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -7px;
width: 12px;
height: 12px;
border-right: 1px solid rgba(158, 190, 218, 0.17);
border-bottom: 1px solid rgba(158, 190, 218, 0.17);
background: rgba(7, 16, 27, 0.84);
transform: translateX(-50%) rotate(45deg);
}
.world-label .kicker {
display: block;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.12em;
}
.world-label strong {
display: block;
margin: 2px 0 4px;
font-size: 12px;
}
.world-label .direction {
font-size: 10px;
font-weight: 800;
}
.world-label.driver {
border-color: rgba(255, 182, 77, 0.25);
}
.world-label.driver .direction {
color: var(--driver);
}
.world-label.output {
border-color: rgba(64, 215, 196, 0.25);
}
.world-label.output .direction {
color: var(--output);
}
#spacingLabel {
position: absolute;
top: 0;
left: 0;
z-index: 2;
padding: 5px 8px;
border: 1px solid rgba(64, 215, 196, 0.25);
border-radius: 999px;
color: var(--output);
background: rgba(7, 16, 27, 0.8);
pointer-events: none;
transform: translate(-50%, -50%);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.04em;
}
#spacingLabel.invalid {
border-color: rgba(255, 107, 117, 0.35);
color: var(--bad);
}
.viewport-bottom {
position: absolute;
left: 16px;
right: 16px;
bottom: 16px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 16px;
pointer-events: none;
}
.legend {
display: flex;
align-items: center;
gap: 13px;
padding: 9px 11px;
border: 1px solid rgba(158, 190, 218, 0.14);
border-radius: 10px;
color: var(--muted);
background: rgba(7, 16, 27, 0.76);
backdrop-filter: blur(10px);
font-size: 10px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.legend .amber {
color: var(--driver);
}
.legend .teal {
color: var(--output);
}
.camera-hint {
color: #748a9d;
font-size: 10px;
}
@media (max-width: 820px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
}
header {
padding: 0 15px;
}
.header-badge {
display: none;
}
main {
display: flex;
flex-direction: column;
}
.viewport {
order: -1;
height: 58vh;
min-height: 430px;
}
aside {
overflow: visible;
border-right: 0;
border-top: 1px solid var(--line);
}
.camera-hint {
display: none;
}
}
@media (max-width: 480px) {
.brand p {
display: none;
}
.viewport-top {
top: 10px;
left: 10px;
right: 10px;
}
.viewport-chip {
padding: 8px;
font-size: 9px;
}
.world-label {
min-width: 108px;
padding: 6px 8px;
}
.world-label strong {
font-size: 10px;
}
.viewport-bottom {
left: 10px;
right: 10px;
bottom: 10px;
}
.legend {
width: 100%;
justify-content: center;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 32 32" fill="none">
<path d="M13.6 3.8h4.8l.8 3a10.8 10.8 0 0 1 2.1.9l2.7-1.5 3.4 3.4-1.5 2.7c.4.7.7 1.4.9 2.1l3 .8v4.8l-3 .8a10.8 10.8 0 0 1-.9 2.1l1.5 2.7-3.4 3.4-2.7-1.5c-.7.4-1.4.7-2.1.9l-.8 3h-4.8l-.8-3a10.8 10.8 0 0 1-2.1-.9l-2.7 1.5-3.4-3.4 1.5-2.7a10.8 10.8 0 0 1-.9-2.1l-3-.8v-4.8l3-.8c.2-.7.5-1.4.9-2.1l-1.5-2.7 3.4-3.4 2.7 1.5c.7-.4 1.4-.7 2.1-.9l.8-3Z"
stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/>
<circle cx="16" cy="16" r="5.3" stroke="currentColor" stroke-width="1.7"/>
</svg>
</div>
<div>
<h1>MeshLab</h1>
<p>Interactive gear ratio trainer</p>
</div>
</div>
<div class="header-badge">LOW-POLY 3D · EXTERNAL GEARS</div>
</header>
<main>
<aside aria-label="Gear controls">
<section class="card">
<div class="section-heading">
<h2><span class="step">1</span>Gear train</h2>
<span class="compatible">● MODULE MATCHED</span>
</div>
<div class="gear-fields">
<label class="field" for="driverTeeth">
<span class="field-label">Driver</span>
<select id="driverTeeth">
<option value="12">12 teeth</option>
<option value="16">16 teeth</option>
<option value="18">18 teeth</option>
<option value="24">24 teeth</option>
<option value="36">36 teeth</option>
</select>
</label>
<label class="field" for="drivenTeeth">
<span class="field-label">Driven</span>
<select id="drivenTeeth">
<option value="12">12 teeth</option>
<option value="16">16 teeth</option>
<option value="18">18 teeth</option>
<option value="24" selected>24 teeth</option>
<option value="36">36 teeth</option>
</select>
</label>
</div>
<div class="mini-note">
All gears share the same module, so every selected pair is compatible.
Their pitch circles determine the required center distance.
</div>
<div class="ratio-box">
<div>
<small>Rotation ratio</small>
<div id="ratioValue" class="ratio-value">2.00 : 1</div>
</div>
<span id="ratioKind" class="ratio-kind">Reduction</span>
</div>
<div id="ratioFormula" class="formula">
ω₂ = −ω₁ × (12 / 24) = −0.50 ω₁
</div>
</section>
<section class="card">
<div class="section-heading">
<h2><span class="step">2</span>Driver input</h2>
</div>
<div class="field">
<label class="field-label" for="driverRpm">
<span>Drive speed</span>
<output id="rpmReadout" class="mono">30 RPM</output>
</label>
<input id="driverRpm" type="range" min="0" max="90" step="1" value="30">
</div>
<div class="field">
<div class="field-label"><span>Driver direction</span></div>
<div id="driverDirection" class="segmented driver" role="group" aria-label="Driver direction">
<button type="button" data-value="ccw" class="active">↺ Counter-clockwise</button>
<button type="button" data-value="cw">↻ Clockwise</button>
</div>
</div>
</section>
<section class="card">
<div class="section-heading">
<h2><span class="step">3</span>Your prediction</h2>
</div>
<div class="prediction-row">
<label class="field" for="predictionRpm">
<span class="field-label">Output speed in RPM</span>
<input id="predictionRpm" type="number" min="0" step="0.5" placeholder="Enter a value">
</label>
<div class="field">
<div class="field-label"><span>Output direction</span></div>
<div id="predictionDirection" class="segmented output" role="group" aria-label="Predicted output direction">
<button type="button" data-value="ccw" class="active">↺ Counter-clockwise</button>
<button type="button" data-value="cw">↻ Clockwise</button>
</div>
</div>
<button id="checkPrediction" class="primary" type="button">Check prediction</button>
</div>
<div id="feedback" class="feedback" aria-live="polite">
Use the tooth ratio and remember: external gears rotate in opposite directions.
</div>
<div class="result">
<div>
<small>Verified output</small>
<strong id="actualOutput">Locked</strong>
</div>
<span id="actualDirection">Check your prediction</span>
</div>
</section>
<section class="card">
<div class="section-heading">
<h2><span class="step">4</span>Center spacing</h2>
</div>
<label class="field-label" for="spacingSlider">
<span>Requested spacing</span>
<output id="spacingReadout" class="mono">1.35 u</output>
</label>
<input id="spacingSlider" type="range" min="80" max="120" step="0.1" value="100">
<div class="mini-note">
Required pitch-circle spacing: <strong id="requiredSpacing">1.35 u</strong>.
The train locks if the gears are pulled apart or pushed together.
</div>
<div id="spacingStatus" class="spacing-status">
<span>● Meshing clearance valid</span>
<button id="snapSpacing" class="small-button" type="button">Snap to mesh</button>
</div>
</section>
<div class="actions">
<button id="runButton" class="primary" type="button" disabled>Start train</button>
<button id="resetView" class="secondary" type="button">Reset view</button>
</div>
</aside>
<section id="viewport" class="viewport" aria-label="Interactive 3D gear visualization">
<div class="viewport-top">
<div class="viewport-chip">
<span class="dot"></span>
<span id="viewportRatio">12T → 24T · 2.00:1</span>
</div>
<div id="trainStatus" class="viewport-chip status-chip waiting">● PREDICT TO UNLOCK</div>
</div>
<div id="driverLabel" class="world-label driver"></div>
<div id="outputLabel" class="world-label output"></div>
<div id="spacingLabel">CENTER 1.35 u</div>
<div class="viewport-bottom">
<div class="legend">
<span class="amber">● Driver</span>
<span class="teal">● Driven</span>
<span>External gears rotate oppositely</span>
</div>
<div class="camera-hint">Drag to orbit · Scroll to zoom</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 viewport = document.getElementById("viewport");
const driverSelect = document.getElementById("driverTeeth");
const drivenSelect = document.getElementById("drivenTeeth");
const driverRpmInput = document.getElementById("driverRpm");
const rpmReadout = document.getElementById("rpmReadout");
const driverDirection = document.getElementById("driverDirection");
const predictionRpm = document.getElementById("predictionRpm");
const predictionDirection = document.getElementById("predictionDirection");
const checkPredictionButton = document.getElementById("checkPrediction");
const feedback = document.getElementById("feedback");
const actualOutput = document.getElementById("actualOutput");
const actualDirection = document.getElementById("actualDirection");
const spacingSlider = document.getElementById("spacingSlider");
const spacingReadout = document.getElementById("spacingReadout");
const requiredSpacing = document.getElementById("requiredSpacing");
const spacingStatus = document.getElementById("spacingStatus");
const snapSpacingButton = document.getElementById("snapSpacing");
const runButton = document.getElementById("runButton");
const resetViewButton = document.getElementById("resetView");
const ratioValue = document.getElementById("ratioValue");
const ratioKind = document.getElementById("ratioKind");
const ratioFormula = document.getElementById("ratioFormula");
const viewportRatio = document.getElementById("viewportRatio");
const trainStatus = document.getElementById("trainStatus");
const driverLabel = document.getElementById("driverLabel");
const outputLabel = document.getElementById("outputLabel");
const spacingLabel = document.getElementById("spacingLabel");
const MODULE = 0.075;
const DEPTH = 0.32;
const DRIVER_COLOR = 0xffb64d;
const OUTPUT_COLOR = 0x40d7c4;
const state = {
driverTeeth: 12,
drivenTeeth: 24,
driverRpm: 30,
driverCCW: true,
guessCCW: true,
predictionValid: false,
running: false,
spacingPercent: 100
};
// ---------- Three.js scene ----------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08121e);
scene.fog = new THREE.Fog(0x08121e, 9, 22);
const camera = new THREE.PerspectiveCamera(
42,
viewport.clientWidth / viewport.clientHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(viewport.clientWidth, viewport.clientHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Three-dimensional meshing gear train");
viewport.prepend(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xc9e6ff, 0x17202b, 2.1));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-3.5, 5.5, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
scene.add(keyLight);
const amberLight = new THREE.PointLight(DRIVER_COLOR, 16, 8, 2);
amberLight.position.set(-2.7, 1.8, 2.7);
scene.add(amberLight);
const tealLight = new THREE.PointLight(OUTPUT_COLOR, 16, 8, 2);
tealLight.position.set(2.7, -1.2, 2.7);
scene.add(tealLight);
const panel = new THREE.Mesh(
new THREE.PlaneGeometry(30, 20),
new THREE.MeshStandardMaterial({
color: 0x0b1724,
roughness: 0.96,
metalness: 0.08
})
);
panel.position.z = -0.5;
panel.receiveShadow = true;
scene.add(panel);
const grid = new THREE.GridHelper(24, 48, 0x35516b, 0x203448);
grid.rotation.x = Math.PI / 2;
grid.position.z = -0.47;
grid.material.transparent = true;
grid.material.opacity = 0.24;
scene.add(grid);
const spacingLineMaterial = new THREE.LineDashedMaterial({
color: OUTPUT_COLOR,
dashSize: 0.09,
gapSize: 0.055,
transparent: true,
opacity: 0.8
});
const spacingLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-0.5, 0, 0.29),
new THREE.Vector3(0.5, 0, 0.29)
]),
spacingLineMaterial
);
spacingLine.computeLineDistances();
scene.add(spacingLine);
const contactMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.055, 10, 6),
new THREE.MeshBasicMaterial({ color: OUTPUT_COLOR })
);
contactMarker.position.z = 0.31;
scene.add(contactMarker);
let driverGear = null;
let drivenGear = null;
let driverAngle = 0;
let drivenBasePhase = Math.PI - Math.PI / state.drivenTeeth;
// ---------- Custom camera controls ----------
const cameraState = {
yaw: -0.07,
pitch: 0.09,
radius: 5,
target: new THREE.Vector3(0, 0, 0)
};
function updateCamera() {
const cp = Math.cos(cameraState.pitch);
camera.position.set(
cameraState.radius * Math.sin(cameraState.yaw) * cp,
cameraState.radius * Math.sin(cameraState.pitch),
cameraState.radius * Math.cos(cameraState.yaw) * cp
);
camera.lookAt(cameraState.target);
}
function resetView() {
const required = getRequiredSpacing();
const outer = Math.max(
getGearDimensions(state.driverTeeth).outerRadius,
getGearDimensions(state.drivenTeeth).outerRadius
);
const halfWidth = required * 0.5 + outer + 0.42;
const halfHeight = outer + 0.48;
const aspect = Math.max(0.55, viewport.clientWidth / viewport.clientHeight);
const tangent = Math.tan(THREE.MathUtils.degToRad(camera.fov * 0.5));
cameraState.yaw = -0.07;
cameraState.pitch = 0.09;
cameraState.radius = THREE.MathUtils.clamp(
Math.max(halfHeight / tangent, halfWidth / (tangent * aspect)) * 1.13,
3.8,
14
);
updateCamera();
}
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.0045,
-0.58,
0.62
);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
3,
16
);
updateCamera();
},
{ passive: false }
);
resetViewButton.addEventListener("click", resetView);
// ---------- Low-poly gear geometry ----------
function getGearDimensions(teeth) {
const pitchRadius = teeth * MODULE * 0.5;
return {
pitchRadius,
outerRadius: pitchRadius + MODULE * 0.9,
rootRadius: pitchRadius - MODULE * 1.15
};
}
function createGearGeometry(teeth) {
const { pitchRadius, outerRadius, rootRadius } = getGearDimensions(teeth);
const step = (Math.PI * 2) / teeth;
const shape = new THREE.Shape();
let first = true;
for (let i = 0; i < teeth; i++) {
const center = i * step;
const points = [
[center - step * 0.48, rootRadius],
[center - step * 0.24, outerRadius],
[center + step * 0.24, outerRadius],
[center + step * 0.48, rootRadius]
];
for (const [angle, radius] of points) {
const x = Math.cos(angle) * radius;
const y = Math.sin(angle) * radius;
if (first) {
shape.moveTo(x, y);
first = false;
} else {
shape.lineTo(x, y);
}
}
}
shape.closePath();
const holeRadius = Math.max(0.085, pitchRadius * 0.17);
const hole = new THREE.Path();
const holeSegments = teeth <= 16 ? 12 : 16;
for (let i = 0; i <= holeSegments; i++) {
const angle = -(i / holeSegments) * Math.PI * 2;
const x = Math.cos(angle) * holeRadius;
const y = Math.sin(angle) * holeRadius;
if (i === 0) hole.moveTo(x, y);
else hole.lineTo(x, y);
}
hole.closePath();
shape.holes.push(hole);
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: DEPTH,
steps: 1,
bevelEnabled: false,
curveSegments: 1
});
geometry.translate(0, 0, -DEPTH * 0.5);
geometry.computeVertexNormals();
return { geometry, holeRadius, pitchRadius, outerRadius };
}
function createTurnIndicator(radius, color) {
const group = new THREE.Group();
const points = [];
for (let i = 0; i <= 18; i++) {
const angle = THREE.MathUtils.lerp(-0.62, 2.55, i / 18);
points.push(
new THREE.Vector3(
Math.cos(angle) * radius,
Math.sin(angle) * radius,
0.245
)
);
}
const curve = new THREE.CatmullRomCurve3(points);
const tube = new THREE.Mesh(
new THREE.TubeGeometry(curve, 24, 0.018, 4, false),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.86
})
);
group.add(tube);
const endAngle = 2.55;
const end = new THREE.Vector3(
Math.cos(endAngle) * radius,
Math.sin(endAngle) * radius,
0.25
);
const ccwTangent = new THREE.Vector3(
-Math.sin(endAngle),
Math.cos(endAngle),
0
).normalize();
const cwTangent = ccwTangent.clone().negate();
const yAxis = new THREE.Vector3(0, 1, 0);
const ccwHead = new THREE.Mesh(
new THREE.ConeGeometry(0.068, 0.17, 6),
new THREE.MeshBasicMaterial({ color })
);
ccwHead.position.copy(end);
ccwHead.quaternion.setFromUnitVectors(yAxis, ccwTangent);
group.add(ccwHead);
const cwHead = new THREE.Mesh(
new THREE.ConeGeometry(0.068, 0.17, 6),
new THREE.MeshBasicMaterial({ color })
);
cwHead.position.copy(end);
cwHead.quaternion.setFromUnitVectors(yAxis, cwTangent);
group.add(cwHead);
group.userData.ccwHead = ccwHead;
group.userData.cwHead = cwHead;
return group;
}
function createGear(teeth, color) {
const root = new THREE.Group();
const rotor = new THREE.Group();
root.add(rotor);
const dimensions = createGearGeometry(teeth);
const bodyMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.48,
metalness: 0.5,
flatShading: true
});
const body = new THREE.Mesh(dimensions.geometry, bodyMaterial);
body.castShadow = true;
body.receiveShadow = true;
rotor.add(body);
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x152332,
roughness: 0.42,
metalness: 0.72,
flatShading: true
});
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(
dimensions.holeRadius * 0.9,
dimensions.holeRadius * 0.9,
DEPTH * 1.22,
12
),
darkMaterial
);
hub.rotation.x = Math.PI / 2;
hub.castShadow = true;
rotor.add(hub);
const cap = new THREE.Mesh(
new THREE.CylinderGeometry(
dimensions.holeRadius * 0.52,
dimensions.holeRadius * 0.58,
0.055,
10
),
new THREE.MeshStandardMaterial({
color: 0xdce8f0,
roughness: 0.3,
metalness: 0.75,
flatShading: true
})
);
cap.rotation.x = Math.PI / 2;
cap.position.z = DEPTH * 0.62;
rotor.add(cap);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(
dimensions.pitchRadius * 0.48,
0.019,
4,
Math.max(12, teeth)
),
new THREE.MeshStandardMaterial({
color: 0x263b4b,
roughness: 0.48,
metalness: 0.58,
flatShading: true
})
);
ring.position.z = DEPTH * 0.53;
rotor.add(ring);
const boltMaterial = new THREE.MeshStandardMaterial({
color: 0xe1edf3,
roughness: 0.32,
metalness: 0.72,
flatShading: true
});
const boltRadius = dimensions.pitchRadius * 0.63;
for (let i = 0; i < 6; i++) {
const angle = (i / 6) * Math.PI * 2 + Math.PI / 6;
const bolt = new THREE.Mesh(
new THREE.CylinderGeometry(0.028, 0.028, 0.045, 6),
boltMaterial
);
bolt.rotation.x = Math.PI / 2;
bolt.position.set(
Math.cos(angle) * boltRadius,
Math.sin(angle) * boltRadius,
DEPTH * 0.55
);
rotor.add(bolt);
}
const pitchPoints = [];
const pitchSegments = Math.max(32, teeth * 2);
for (let i = 0; i < pitchSegments; i++) {
const angle = (i / pitchSegments) * Math.PI * 2;
pitchPoints.push(
new THREE.Vector3(
Math.cos(angle) * dimensions.pitchRadius,
Math.sin(angle) * dimensions.pitchRadius,
0.19
)
);
}
const pitchCircle = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(pitchPoints),
new THREE.LineBasicMaterial({
color: 0xe7f5ff,
transparent: true,
opacity: 0.27
})
);
root.add(pitchCircle);
const turnIndicator = createTurnIndicator(
dimensions.outerRadius + 0.18,
color
);
root.add(turnIndicator);
return {
root,
rotor,
pitchRadius: dimensions.pitchRadius,
outerRadius: dimensions.outerRadius,
turnIndicator
};
}
function disposeObject(object) {
object.traverse((child) => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
const materials = Array.isArray(child.material)
? child.material
: [child.material];
materials.forEach((material) => material.dispose());
}
});
}
function rebuildTrain() {
if (driverGear) {
scene.remove(driverGear.root);
disposeObject(driverGear.root);
}
if (drivenGear) {
scene.remove(drivenGear.root);
disposeObject(drivenGear.root);
}
driverGear = createGear(state.driverTeeth, DRIVER_COLOR);
drivenGear = createGear(state.drivenTeeth, OUTPUT_COLOR);
scene.add(driverGear.root);
scene.add(drivenGear.root);
driverAngle = 0;
drivenBasePhase = Math.PI - Math.PI / state.drivenTeeth;
positionTrain();
updateDirectionIndicators();
}
// ---------- Spacing and ratio calculations ----------
function getRequiredSpacing() {
return MODULE * (state.driverTeeth + state.drivenTeeth) * 0.5;
}
function getSpacingState() {
const required = getRequiredSpacing();
const actual = required * state.spacingPercent / 100;
const tolerance = Math.max(0.015, required * 0.012);
return {
required,
actual,
valid: Math.abs(actual - required) <= tolerance
};
}
function positionTrain() {
const spacing = getSpacingState();
const driverX = -spacing.actual * 0.5;
const drivenX = spacing.actual * 0.5;
driverGear.root.position.x = driverX;
drivenGear.root.position.x = drivenX;
const positions = spacingLine.geometry.getAttribute("position");
positions.setXYZ(0, driverX, 0, 0.29);
positions.setXYZ(1, drivenX, 0, 0.29);
positions.needsUpdate = true;
spacingLine.computeLineDistances();
const driverContactX = driverX + driverGear.pitchRadius;
const drivenContactX = drivenX - drivenGear.pitchRadius;
contactMarker.position.x = (driverContactX + drivenContactX) * 0.5;
const lineColor = spacing.valid ? OUTPUT_COLOR : 0xff6b75;
spacingLineMaterial.color.setHex(lineColor);
contactMarker.material.color.setHex(lineColor);
}
function updateDirectionIndicators() {
if (!driverGear || !drivenGear) return;
driverGear.turnIndicator.userData.ccwHead.visible = state.driverCCW;
driverGear.turnIndicator.userData.cwHead.visible = !state.driverCCW;
drivenGear.turnIndicator.userData.ccwHead.visible = !state.driverCCW;
drivenGear.turnIndicator.userData.cwHead.visible = state.driverCCW;
}
// ---------- UI state ----------
function invalidatePrediction(message = "Prediction cleared. Update it for the new input.") {
state.predictionValid = false;
state.running = false;
feedback.className = "feedback";
feedback.textContent = message;
actualOutput.textContent = "Locked";
actualDirection.textContent = "Check your prediction";
updateStatus();
}
function updateStatus() {
const spacing = getSpacingState();
if (!spacing.valid) {
trainStatus.className = "viewport-chip status-chip locked";
trainStatus.textContent = "● SPACING LOCK";
} else if (state.running) {
trainStatus.className = "viewport-chip status-chip";
trainStatus.textContent = "● MESHING";
} else if (state.predictionValid) {
trainStatus.className = "viewport-chip status-chip";
trainStatus.textContent = "● READY";
} else {
trainStatus.className = "viewport-chip status-chip waiting";
trainStatus.textContent = "● PREDICT TO UNLOCK";
}
runButton.disabled = !state.predictionValid || !spacing.valid;
runButton.textContent = state.running
? "Pause train"
: state.predictionValid
? "Start train"
: "Start train";
}
function updateUI() {
const ratio = state.driverTeeth / state.drivenTeeth;
const spacing = getSpacingState();
rpmReadout.textContent = `${state.driverRpm} RPM`;
ratioValue.textContent = `${ratio.toFixed(2)} : 1`;
ratioKind.textContent =
ratio > 1.0001 ? "Speed-up" :
ratio < 0.9999 ? "Reduction" :
"1:1 drive";
ratioFormula.textContent =
`ω₂ = −ω₁ × (${state.driverTeeth} / ${state.drivenTeeth}) = −${ratio.toFixed(2)} ω₁`;
viewportRatio.textContent =
`${state.driverTeeth}T → ${state.drivenTeeth}T · ${ratio.toFixed(2)}:1`;
spacingReadout.textContent = `${spacing.actual.toFixed(2)} u`;
requiredSpacing.textContent = `${spacing.required.toFixed(2)} u`;
spacingLabel.textContent = `CENTER ${spacing.actual.toFixed(2)} u`;
spacingStatus.classList.toggle("invalid", !spacing.valid);
spacingStatus.querySelector("span").textContent = spacing.valid
? "● Meshing clearance valid"
: "● Incompatible spacing — train locked";
spacingLabel.classList.toggle("invalid", !spacing.valid);
const driverDirectionText = state.driverCCW ? "↺ Counter-clockwise" : "↻ Clockwise";
const outputDirectionText = state.driverCCW ? "↻ Clockwise" : "↺ Counter-clockwise";
driverLabel.innerHTML = `
<span class="kicker">DRIVER</span>
<strong>${state.driverTeeth} TEETH</strong>
<span class="direction">${driverDirectionText}</span>
`;
outputLabel.innerHTML = `
<span class="kicker">DRIVEN</span>
<strong>${state.drivenTeeth} TEETH</strong>
<span class="direction">${outputDirectionText}</span>
`;
updateDirectionIndicators();
updateStatus();
}
function setSliderFill(input, color) {
const min = Number(input.min);
const max = Number(input.max);
const value = Number(input.value);
const percentage = ((value - min) / (max - min)) * 100;
input.style.setProperty("--range-fill", `${percentage}%`);
if (color) input.style.background = color;
}
function setSegmented(container, value) {
container.querySelectorAll("button").forEach((button) => {
button.classList.toggle("active", button.dataset.value === value);
});
}
// ---------- Events ----------
function onGearChange() {
state.driverTeeth = Number(driverSelect.value);
state.drivenTeeth = Number(drivenSelect.value);
state.spacingPercent = 100;
spacingSlider.value = 100;
rebuildTrain();
updateUI();
resetView();
invalidatePrediction("Gears changed. Predict the new output speed and direction.");
}
driverSelect.addEventListener("change", onGearChange);
drivenSelect.addEventListener("change", onGearChange);
driverRpmInput.addEventListener("input", () => {
state.driverRpm = Number(driverRpmInput.value);
setSliderFill(driverRpmInput);
updateUI();
invalidatePrediction("Driver speed changed. Check the output prediction again.");
});
driverDirection.addEventListener("click", (event) => {
const button = event.target.closest("button");
if (!button) return;
state.driverCCW = button.dataset.value === "ccw";
setSegmented(driverDirection, button.dataset.value);
updateUI();
invalidatePrediction("Driver direction changed. Check the output prediction again.");
});
predictionDirection.addEventListener("click", (event) => {
const button = event.target.closest("button");
if (!button) return;
state.guessCCW = button.dataset.value === "ccw";
setSegmented(predictionDirection, button.dataset.value);
});
checkPredictionButton.addEventListener("click", () => {
const guess = Number(predictionRpm.value);
const expectedSpeed = state.driverRpm * state.driverTeeth / state.drivenTeeth;
const expectedCCW = !state.driverCCW;
const tolerance = Math.max(0.5, expectedSpeed * 0.02);
if (!Number.isFinite(guess) || guess < 0) {
feedback.className = "feedback bad";
feedback.textContent = "Enter a valid non-negative output speed.";
return;
}
const speedCorrect = Math.abs(guess - expectedSpeed) <= tolerance;
const directionCorrect = state.guessCCW === expectedCCW;
if (speedCorrect && directionCorrect) {
state.predictionValid = true;
state.running = true;
feedback.className = "feedback good";
feedback.textContent =
`Correct. ${state.driverTeeth}T drives ${state.drivenTeeth}T at ` +
`${expectedSpeed.toFixed(1)} RPM ${expectedCCW ? "counter-clockwise" : "clockwise"}.`;
actualOutput.textContent = `${expectedSpeed.toFixed(1)} RPM`;
actualDirection.textContent = expectedCCW ? "↺ Counter-clockwise" : "↻ Clockwise";
updateStatus();
} else {
state.predictionValid = false;
state.running = false;
feedback.className = "feedback bad";
if (!speedCorrect && !directionCorrect) {
feedback.textContent =
"Not quite. Apply the tooth ratio, and remember that external gears rotate in opposite directions.";
} else if (!speedCorrect) {
feedback.textContent =
"The speed is not correct yet. Use the tooth ratio: driven RPM = driver RPM × driver teeth ÷ driven teeth.";
} else {
feedback.textContent =
"The speed is right, but the direction is not. External gears rotate oppositely.";
}
actualOutput.textContent = "Locked";
actualDirection.textContent = "Check your prediction";
updateStatus();
}
});
predictionRpm.addEventListener("keydown", (event) => {
if (event.key === "Enter") checkPredictionButton.click();
});
spacingSlider.addEventListener("input", () => {
state.spacingPercent = Number(spacingSlider.value);
setSliderFill(spacingSlider);
positionTrain();
updateUI();
if (!getSpacingState().valid) {
state.running = false;
updateStatus();
}
});
snapSpacingButton.addEventListener("click", () => {
state.spacingPercent = 100;
spacingSlider.value = 100;
setSliderFill(spacingSlider);
positionTrain();
updateUI();
});
runButton.addEventListener("click", () => {
if (!state.predictionValid || !getSpacingState().valid) return;
state.running = !state.running;
updateStatus();
});
// ---------- Labels and animation ----------
function projectElement(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const width = viewport.clientWidth;
const height = viewport.clientHeight;
if (projected.z < -1 || projected.z > 1) {
element.style.visibility = "hidden";
return;
}
element.style.visibility = "visible";
element.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
}
function updateLabels() {
if (!driverGear || !drivenGear) return;
const driverAnchor = driverGear.root.position.clone();
driverAnchor.y += driverGear.outerRadius + 0.37;
driverAnchor.z = 0.25;
const outputAnchor = drivenGear.root.position.clone();
outputAnchor.y += drivenGear.outerRadius + 0.37;
outputAnchor.z = 0.25;
projectElement(driverLabel, driverAnchor);
projectElement(outputLabel, outputAnchor);
const spacingAnchor = new THREE.Vector3(
0,
-Math.max(driverGear.outerRadius, drivenGear.outerRadius) * 0.58,
0.34
);
projectElement(spacingLabel, spacingAnchor);
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (state.running && state.predictionValid && getSpacingState().valid) {
const direction = state.driverCCW ? 1 : -1;
driverAngle += direction * state.driverRpm * Math.PI * 2 / 60 * delta;
}
if (driverGear && drivenGear) {
driverGear.rotor.rotation.z = driverAngle;
drivenGear.rotor.rotation.z =
drivenBasePhase - (state.driverTeeth / state.drivenTeeth) * driverAngle;
}
updateCamera();
updateLabels();
renderer.render(scene, camera);
}
// ---------- Resize and initialization ----------
const resizeObserver = new ResizeObserver(() => {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
});
resizeObserver.observe(viewport);
setSliderFill(driverRpmInput);
setSliderFill(spacingSlider);
rebuildTrain();
updateUI();
animate();
</script>
</body>
</html>
```