Prompt specification
Build or customize the Three.js 3D scene "Idler Gear Direction Puzzle" 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: Idler Gear Direction Puzzle
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/idler-gear-direction-puzzle-x3450
Scene Description Prompt:
Create a standalone cutaway scene in one HTML file using Three.js from cdnjs. Create matched tabletop gear trains, one direct and one with an idler, each with compatible shaft spacing. Compare rotation parity while preserving the same input-to-output tooth-count ratio.
Working Three.js Starter (idler-gear-direction-puzzle-x3450):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gear Train Parity Lab</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(12, 19, 28, 0.84);
--border: rgba(255, 255, 255, 0.13);
--text: #edf4fa;
--muted: #9eb0c0;
--orange: #ff913d;
--blue: #43adff;
--green: #57e3a6;
--pink: #ff6680;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #101722;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene.dragging {
cursor: grabbing;
}
.topbar {
position: fixed;
z-index: 5;
top: 20px;
left: 22px;
right: 22px;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 18px;
pointer-events: none;
}
.title-block {
max-width: 570px;
padding: 14px 17px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--panel);
backdrop-filter: blur(14px);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.22);
}
.eyebrow {
color: var(--orange);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 4px;
color: var(--text);
font-size: clamp(20px, 2.5vw, 31px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.status {
display: flex;
align-items: center;
gap: 9px;
padding: 10px 13px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--panel);
color: var(--muted);
font-size: 12px;
white-space: nowrap;
backdrop-filter: blur(14px);
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 12px var(--green);
}
.status-dot.paused {
background: var(--orange);
box-shadow: 0 0 12px var(--orange);
}
.bottom {
position: fixed;
z-index: 5;
left: 22px;
right: 22px;
bottom: 20px;
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 18px;
pointer-events: none;
}
.readouts {
display: grid;
grid-template-columns: repeat(2, minmax(260px, 1fr));
gap: 12px;
width: min(760px, 72vw);
}
.readout {
position: relative;
overflow: hidden;
padding: 13px 15px 12px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--panel);
backdrop-filter: blur(14px);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.22);
}
.readout::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: var(--accent);
}
.readout-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-bottom: 7px;
}
.readout-name {
color: var(--text);
font-size: 13px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.ratio {
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 16px;
font-weight: 800;
}
.train-line {
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.train-line strong {
color: var(--text);
}
.controls {
width: 280px;
padding: 12px 14px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--panel);
backdrop-filter: blur(14px);
pointer-events: auto;
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.22);
}
.control-row {
display: flex;
align-items: center;
gap: 9px;
}
button {
appearance: none;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 8px;
padding: 8px 10px;
background: rgba(255, 255, 255, 0.07);
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition: background 150ms ease, border-color 150ms ease;
}
button:hover {
background: rgba(255, 255, 255, 0.13);
border-color: rgba(255, 255, 255, 0.28);
}
button.primary {
border-color: rgba(255, 145, 61, 0.45);
background: rgba(255, 145, 61, 0.16);
}
.speed-row {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 9px;
margin-top: 10px;
color: var(--muted);
font-size: 11px;
}
input[type="range"] {
width: 100%;
accent-color: var(--orange);
}
#speedValue {
min-width: 38px;
color: var(--text);
text-align: right;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.hint {
margin-top: 8px;
color: #7f92a3;
font-size: 10px;
line-height: 1.4;
}
@media (max-width: 900px) {
.status,
.hint {
display: none;
}
.bottom {
display: block;
}
.readouts {
width: 100%;
grid-template-columns: 1fr 1fr;
}
.controls {
position: fixed;
right: 16px;
bottom: 185px;
width: 245px;
}
.title-block {
max-width: calc(100vw - 44px);
}
}
@media (max-width: 600px) {
.topbar {
top: 10px;
left: 10px;
right: 10px;
}
.bottom {
left: 10px;
right: 10px;
bottom: 10px;
}
.readouts {
gap: 7px;
}
.readout {
padding: 10px;
}
.readout-head {
display: block;
}
.ratio {
display: block;
margin-top: 3px;
}
.train-line {
font-size: 10px;
}
.controls {
right: 10px;
bottom: 158px;
width: 220px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive cutaway comparison of two tabletop gear trains"></canvas>
<header class="topbar">
<div class="title-block">
<div class="eyebrow">Mechanics Lab / Cutaway Comparison</div>
<h1>Idler Gears Change Parity, Not Ratio</h1>
<p class="subtitle">
Both trains use a 12-tooth input and a 24-tooth output. The idler adds a second
external mesh, reversing the output twice while preserving the 12:24 tooth ratio.
</p>
</div>
<div class="status">
<span id="statusDot" class="status-dot"></span>
<span id="liveState">Running</span>
</div>
</header>
<footer class="bottom">
<div class="readouts">
<section class="readout" style="--accent: var(--pink)">
<div class="readout-head">
<span class="readout-name">Direct / 1 Mesh</span>
<span class="ratio">−0.50×</span>
</div>
<div class="train-line">
<strong>12T → 24T</strong><br>
Output turns oppositely at half the input speed.
</div>
</section>
<section class="readout" style="--accent: var(--green)">
<div class="readout-head">
<span class="readout-name">Idler / 2 Meshes</span>
<span class="ratio">+0.50×</span>
</div>
<div class="train-line">
<strong>12T → 18T → 24T</strong><br>
Output turns in the same direction at half speed.
</div>
</section>
</div>
<div class="controls">
<div class="control-row">
<button id="pauseBtn" class="primary" type="button">Pause</button>
<button id="resetBtn" type="button">Reset View</button>
</div>
<label class="speed-row">
<span>Speed</span>
<input id="speedInput" type="range" min="0.2" max="2.2" step="0.1" value="1">
<span id="speedValue">1.0×</span>
</label>
<div class="hint">
Drag to orbit · Wheel to zoom · Shift-drag to pan
</div>
</div>
</footer>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, innerHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x101722);
scene.fog = new THREE.Fog(0x101722, 24, 45);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const clock = new THREE.Clock();
const TAU = Math.PI * 2;
// -------------------------------------------------------------------------
// Custom orbit / pan / zoom controls; no Three.js addons are used.
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0.45, 0),
radius: 19.5,
phi: 0.92,
theta: 0.0
};
const defaultCamera = {
target: cameraState.target.clone(),
radius: 19.5,
phi: 0.92,
theta: 0.0
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
updateCamera();
const pointer = {
active: false,
id: null,
x: 0,
y: 0,
shift: false
};
canvas.addEventListener("pointerdown", (event) => {
pointer.active = true;
pointer.id = event.pointerId;
pointer.x = event.clientX;
pointer.y = event.clientY;
pointer.shift = event.shiftKey;
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
});
canvas.addEventListener("pointermove", (event) => {
if (!pointer.active || event.pointerId !== pointer.id) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
if (pointer.shift || event.shiftKey) {
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)
);
const panScale = cameraState.radius * 0.0012;
cameraState.target.addScaledVector(right, -dx * panScale);
cameraState.target.addScaledVector(forward, -dy * panScale);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.38,
1.38
);
}
updateCamera();
});
function endPointer(event) {
if (event.pointerId !== pointer.id) return;
pointer.active = false;
pointer.id = null;
canvas.classList.remove("dragging");
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11,
29
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Materials and procedural textures
// -------------------------------------------------------------------------
function makeWoodTexture() {
const size = 512;
const c = document.createElement("canvas");
c.width = size;
c.height = size;
const ctx = c.getContext("2d");
const gradient = ctx.createLinearGradient(0, 0, size, size);
gradient.addColorStop(0, "#6f482c");
gradient.addColorStop(0.5, "#875a37");
gradient.addColorStop(1, "#684329");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, size, size);
let seed = 1187;
const random = () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
for (let i = 0; i < 90; i++) {
const y = random() * size;
const amplitude = 2 + random() * 8;
const frequency = 0.008 + random() * 0.025;
const phase = random() * TAU;
ctx.beginPath();
for (let x = 0; x <= size; x += 5) {
const yy =
y +
Math.sin(x * frequency + phase) * amplitude +
Math.sin(x * frequency * 0.27 + phase) * 3;
if (x === 0) ctx.moveTo(x, yy);
else ctx.lineTo(x, yy);
}
ctx.strokeStyle = `rgba(38, 20, 10, ${0.035 + random() * 0.08})`;
ctx.lineWidth = 0.5 + random() * 2;
ctx.stroke();
}
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(3, 1.4);
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
return texture;
}
const woodMaterial = new THREE.MeshStandardMaterial({
map: makeWoodTexture(),
color: 0xffffff,
roughness: 0.72,
metalness: 0.04
});
const cutFaceMaterial = new THREE.MeshStandardMaterial({
color: 0xc69a68,
roughness: 0.9
});
const panMaterial = new THREE.MeshStandardMaterial({
color: 0x17222d,
roughness: 0.55,
metalness: 0.62
});
const steelMaterial = new THREE.MeshStandardMaterial({
color: 0x52616f,
roughness: 0.32,
metalness: 0.82
});
const darkSteelMaterial = new THREE.MeshStandardMaterial({
color: 0x202b35,
roughness: 0.38,
metalness: 0.78
});
const orangeMaterial = new THREE.MeshStandardMaterial({
color: 0xff812e,
roughness: 0.25,
metalness: 0.68
});
const blueMaterial = new THREE.MeshStandardMaterial({
color: 0x238fdc,
roughness: 0.25,
metalness: 0.68
});
const silverMaterial = new THREE.MeshStandardMaterial({
color: 0xc4d0d8,
roughness: 0.22,
metalness: 0.78
});
const orangePaintMaterial = new THREE.MeshStandardMaterial({
color: 0xffd19a,
emissive: 0x8a3100,
emissiveIntensity: 0.22,
roughness: 0.35,
metalness: 0.2
});
const bluePaintMaterial = new THREE.MeshStandardMaterial({
color: 0xb9e5ff,
emissive: 0x006aa8,
emissiveIntensity: 0.2,
roughness: 0.35,
metalness: 0.2
});
const greenPaintMaterial = new THREE.MeshStandardMaterial({
color: 0xb8ffda,
emissive: 0x007a45,
emissiveIntensity: 0.2,
roughness: 0.35,
metalness: 0.2
});
// -------------------------------------------------------------------------
// Lighting
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xd9edff, 0x24170f, 1.7));
const keyLight = new THREE.DirectionalLight(0xfff0dc, 3.2);
keyLight.position.set(-6, 12, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x7ebeff, 1.25);
fillLight.position.set(8, 7, -8);
scene.add(fillLight);
const warmLight = new THREE.PointLight(0xff9b52, 1.8, 12, 2);
warmLight.position.set(-6, 4, 2);
scene.add(warmLight);
const coolLight = new THREE.PointLight(0x54b9ff, 1.5, 12, 2);
coolLight.position.set(5, 4, -1);
scene.add(coolLight);
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
function box(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 makeLabel(
text,
color = "#dceaf4",
background = "rgba(10, 16, 23, 0.82)",
width = 3.4
) {
const c = document.createElement("canvas");
c.width = 768;
c.height = 160;
const ctx = c.getContext("2d");
ctx.fillStyle = background;
ctx.fillRect(0, 0, c.width, c.height);
ctx.strokeStyle = color;
ctx.lineWidth = 6;
ctx.strokeRect(3, 3, c.width - 6, c.height - 6);
ctx.fillStyle = color;
ctx.font = "700 54px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, c.width / 2, c.height / 2 + 2);
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(width, width * (160 / 768), 1);
sprite.renderOrder = 20;
return sprite;
}
function circleLine(x, z, radius, y, color, opacity = 0.4) {
const points = [];
for (let i = 0; i < 100; i++) {
const angle = (i / 100) * TAU;
points.push(
new THREE.Vector3(
x + Math.cos(angle) * radius,
y,
z + Math.sin(angle) * radius
)
);
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity
});
return new THREE.LineLoop(geometry, material);
}
function dimension(x1, x2, z, label, color = "#a9bbc9") {
const y = 0.08;
const halfTick = 0.16;
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(x1, y, z),
new THREE.Vector3(x2, y, z),
new THREE.Vector3(x1, y, z - halfTick),
new THREE.Vector3(x1, y, z + halfTick),
new THREE.Vector3(x2, y, z - halfTick),
new THREE.Vector3(x2, y, z + halfTick)
]);
const line = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({ color })
);
scene.add(line);
const labelSprite = makeLabel(label, color, "rgba(10,16,23,0.86)", 1.65);
labelSprite.position.set((x1 + x2) / 2, 0.34, z);
scene.add(labelSprite);
}
function addArcArrow(x, z, radius, direction, color) {
const y = 2.05;
const start = 0.12;
const end = 1.82;
const points = [];
for (let i = 0; i <= 60; i++) {
const t = i / 60;
const angle = start + (end - start) * t;
const signedAngle = direction > 0 ? angle : 2 * Math.PI - angle;
points.push(
new THREE.Vector3(
x + Math.cos(signedAngle) * radius,
y,
z + Math.sin(signedAngle) * radius
)
);
}
const curve = new THREE.CatmullRomCurve3(points);
const tube = new THREE.Mesh(
new THREE.TubeGeometry(curve, 64, 0.035, 8, false),
new THREE.MeshBasicMaterial({ color })
);
scene.add(tube);
const endAngle = direction > 0 ? end : TAU - end;
const tangent = new THREE.Vector3(
-Math.sin(endAngle) * direction,
0,
Math.cos(endAngle) * direction
).normalize();
const cone = new THREE.Mesh(
new THREE.ConeGeometry(0.14, 0.38, 16),
new THREE.MeshBasicMaterial({ color })
);
cone.position.set(
x + Math.cos(endAngle) * radius,
y,
z + Math.sin(endAngle) * radius
);
cone.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
tangent
);
scene.add(cone);
}
// -------------------------------------------------------------------------
// Cutaway tabletop: an open wooden frame exposes two recessed gear bays.
// -------------------------------------------------------------------------
box(18.5, 0.22, 10.6, panMaterial, 0, -0.70, 0);
// Front and back wooden rails.
box(18, 0.55, 2.35, woodMaterial, 0, -0.275, 3.825);
box(18, 0.55, 2.35, woodMaterial, 0, -0.275, -3.825);
// Side and center rails leave two open cutaway bays.
box(0.70, 0.55, 5.3, woodMaterial, -8.65, -0.275, 0);
box(1.40, 0.55, 5.3, woodMaterial, -1.10, -0.275, 0);
box(0.60, 0.55, 5.3, woodMaterial, 8.70, -0.275, 0);
// Dark recessed bay floors.
box(6.42, 0.12, 5.25, panMaterial, -5.05, -0.51, 0);
box(8.75, 0.12, 5.25, panMaterial, 4.00, -0.51, 0);
// Light-colored section faces emphasize the cutaway edges.
box(0.07, 0.56, 5.30, cutFaceMaterial, -8.30, -0.275, 0);
box(0.07, 0.56, 5.30, cutFaceMaterial, -1.80, -0.275, 0);
box(0.07, 0.56, 5.30, cutFaceMaterial, -0.40, -0.275, 0);
box(0.07, 0.56, 5.30, cutFaceMaterial, 8.40, -0.275, 0);
// Bay accent strips.
box(6.3, 0.055, 0.08, bluePaintMaterial, -5.05, 0.025, 2.63);
box(8.6, 0.055, 0.08, greenPaintMaterial, 4.00, 0.025, 2.63);
// Bolts around the recessed pans.
const boltGeometry = new THREE.CylinderGeometry(0.09, 0.09, 0.06, 16);
const boltMaterial = new THREE.MeshStandardMaterial({
color: 0x9aabb8,
roughness: 0.3,
metalness: 0.88
});
const boltLocations = [
[-7.9, -2.25], [-7.9, 2.25], [-2.2, -2.25], [-2.2, 2.25],
[-0.05, -2.25], [-0.05, 2.25], [8.0, -2.25], [8.0, 2.25]
];
for (const [x, z] of boltLocations) {
const bolt = new THREE.Mesh(boltGeometry, boltMaterial);
bolt.position.set(x, -0.415, z);
bolt.castShadow = true;
scene.add(bolt);
}
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({
color: 0x0c1219,
roughness: 0.88,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.83;
floor.receiveShadow = true;
scene.add(floor);
// -------------------------------------------------------------------------
// Gear geometry
// -------------------------------------------------------------------------
const MODULE = 0.16;
const INPUT_TEETH = 12;
const IDLER_TEETH = 18;
const OUTPUT_TEETH = 24;
const gearGeometryCache = new Map();
function pitchRadius(teeth) {
return MODULE * teeth / 2;
}
function buildGearGeometry(teeth) {
if (gearGeometryCache.has(teeth)) return gearGeometryCache.get(teeth);
const rp = pitchRadius(teeth);
const addendum = MODULE * 0.86;
const dedendum = MODULE * 1.08;
const ra = rp + addendum;
const rf = Math.max(rp - dedendum, 0.34);
const step = TAU / teeth;
const outline = [];
for (let tooth = 0; tooth < teeth; tooth++) {
const center = tooth * step;
const points = [
[center - 0.50 * step, rf],
[center - 0.31 * step, rf],
[center - 0.22 * step, rp],
[center - 0.13 * step, ra],
[center + 0.13 * step, ra],
[center + 0.22 * step, rp],
[center + 0.31 * step, rf]
];
for (const [angle, radius] of points) {
outline.push([
Math.cos(angle) * radius,
Math.sin(angle) * radius
]);
}
}
const shape = new THREE.Shape();
shape.moveTo(outline[0][0], outline[0][1]);
for (let i = 1; i < outline.length; i++) {
shape.lineTo(outline[i][0], outline[i][1]);
}
shape.closePath();
const boreRadius = teeth <= 12 ? 0.17 : 0.22;
const bore = new THREE.Path();
bore.absarc(0, 0, boreRadius, 0, TAU, true);
shape.holes.push(bore);
// Six lightening holes make the gears read as machined cutaway parts.
const hubOuter = teeth <= 12 ? 0.34 : teeth <= 18 ? 0.42 : 0.48;
const holeRadius = Math.min(0.28, (rf - hubOuter) * 0.23);
const holeCenter = (rf + hubOuter) * 0.54;
for (let i = 0; i < 6; i++) {
const angle = (i / 6) * TAU;
const hole = new THREE.Path();
hole.absarc(
Math.cos(angle) * holeCenter,
Math.sin(angle) * holeCenter,
holeRadius,
0,
TAU,
true
);
shape.holes.push(hole);
}
const depth = 0.34;
const geometry = new THREE.ExtrudeGeometry(shape, {
depth,
steps: 1,
bevelEnabled: true,
bevelSegments: 1,
bevelSize: 0.018,
bevelThickness: 0.018,
curveSegments: 20
});
geometry.translate(0, 0, -depth / 2);
geometry.rotateX(-Math.PI / 2);
geometry.computeVertexNormals();
gearGeometryCache.set(teeth, geometry);
return geometry;
}
function createGear(teeth, x, z, material, markerMaterial, withHandwheel = false) {
const group = new THREE.Group();
group.position.set(x, 1.28, z);
const rp = pitchRadius(teeth);
const hubOuter = teeth <= 12 ? 0.34 : teeth <= 18 ? 0.42 : 0.48;
const gear = new THREE.Mesh(buildGearGeometry(teeth), material);
gear.castShadow = true;
gear.receiveShadow = true;
group.add(gear);
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(hubOuter, hubOuter, 0.52, 32),
material
);
hub.castShadow = true;
group.add(hub);
const cap = new THREE.Mesh(
new THREE.CylinderGeometry(hubOuter * 0.67, hubOuter * 0.67, 0.07, 32),
markerMaterial
);
cap.position.y = 0.30;
cap.castShadow = true;
group.add(cap);
// A painted radial stripe makes rotation and parity easy to read.
const stripeLength = rp * 0.72;
const stripe = new THREE.Mesh(
new THREE.BoxGeometry(stripeLength, 0.045, 0.10),
markerMaterial
);
stripe.position.set((0.18 + stripeLength) / 2, 0.205, 0);
stripe.castShadow = true;
group.add(stripe);
if (withHandwheel) {
const wheel = new THREE.Mesh(
new THREE.TorusGeometry(0.36, 0.055, 12, 48),
markerMaterial
);
wheel.rotation.x = Math.PI / 2;
wheel.position.y = 1.18;
wheel.castShadow = true;
group.add(wheel);
const spokeA = new THREE.Mesh(
new THREE.BoxGeometry(0.62, 0.055, 0.065),
markerMaterial
);
spokeA.position.y = 1.18;
group.add(spokeA);
const spokeB = new THREE.Mesh(
new THREE.BoxGeometry(0.065, 0.055, 0.62),
markerMaterial
);
spokeB.position.y = 1.18;
group.add(spokeB);
}
scene.add(group);
return { group, rp, teeth };
}
function addShaftSupport(x, z, accentMaterial) {
box(1.00, 0.20, 0.86, darkSteelMaterial, x, -0.30, z);
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(0.30, 0.38, 0.72, 24),
steelMaterial
);
pedestal.position.set(x, 0.16, z);
pedestal.castShadow = true;
pedestal.receiveShadow = true;
scene.add(pedestal);
const bearing = new THREE.Mesh(
new THREE.CylinderGeometry(0.37, 0.37, 0.26, 32),
darkSteelMaterial
);
bearing.position.set(x, 0.62, z);
bearing.castShadow = true;
scene.add(bearing);
const collar = new THREE.Mesh(
new THREE.TorusGeometry(0.29, 0.035, 10, 32),
accentMaterial
);
collar.rotation.x = Math.PI / 2;
collar.position.set(x, 0.77, z);
scene.add(collar);
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.13, 2.70, 24),
silverMaterial
);
shaft.position.set(x, 1.10, z);
shaft.castShadow = true;
scene.add(shaft);
}
// -------------------------------------------------------------------------
// Exact compatible center distances
//
// center distance = module * (teethA + teethB) / 2
// -------------------------------------------------------------------------
const directInputX = -6.70;
const directOutputX =
directInputX + (INPUT_TEETH + OUTPUT_TEETH) * MODULE / 2;
const idlerInputX = 0.70;
const idlerMiddleX =
idlerInputX + (INPUT_TEETH + IDLER_TEETH) * MODULE / 2;
const idlerOutputX =
idlerMiddleX + (IDLER_TEETH + OUTPUT_TEETH) * MODULE / 2;
addShaftSupport(directInputX, 0, orangePaintMaterial);
addShaftSupport(directOutputX, 0, bluePaintMaterial);
addShaftSupport(idlerInputX, 0, orangePaintMaterial);
addShaftSupport(idlerMiddleX, 0, silverMaterial);
addShaftSupport(idlerOutputX, 0, bluePaintMaterial);
const directInput = createGear(
INPUT_TEETH, directInputX, 0, orangeMaterial, orangePaintMaterial, true
);
const directOutput = createGear(
OUTPUT_TEETH, directOutputX, 0, blueMaterial, bluePaintMaterial
);
const idlerInput = createGear(
INPUT_TEETH, idlerInputX, 0, orangeMaterial, orangePaintMaterial, true
);
const idlerMiddle = createGear(
IDLER_TEETH, idlerMiddleX, 0, silverMaterial, greenPaintMaterial
);
const idlerOutput = createGear(
OUTPUT_TEETH, idlerOutputX, 0, blueMaterial, greenPaintMaterial
);
// Pitch circles show why the shaft spacing is compatible.
scene.add(circleLine(directInputX, 0, directInput.rp, 1.47, 0xffd28a, 0.38));
scene.add(circleLine(directOutputX, 0, directOutput.rp, 1.47, 0xffd28a, 0.38));
scene.add(circleLine(idlerInputX, 0, idlerInput.rp, 1.47, 0xffd28a, 0.38));
scene.add(circleLine(idlerMiddleX, 0, idlerMiddle.rp, 1.47, 0xffd28a, 0.38));
scene.add(circleLine(idlerOutputX, 0, idlerOutput.rp, 1.47, 0xffd28a, 0.38));
// Small markers identify the pitch-point contacts.
const contactMaterial = new THREE.MeshBasicMaterial({ color: 0x78e7ff });
const contactGeometry = new THREE.SphereGeometry(0.075, 12, 12);
const contactLocations = [
[directInputX + directInput.rp, 0],
[idlerInputX + idlerInput.rp, 0],
[idlerMiddleX + idlerMiddle.rp, 0]
];
for (const [x, z] of contactLocations) {
const contact = new THREE.Mesh(contactGeometry, contactMaterial);
contact.position.set(x, 1.49, z);
scene.add(contact);
}
// Shaft-spacing dimensions.
dimension(
directInputX,
directOutputX,
3.08,
"C = 2.88",
"#ff9d58"
);
dimension(
idlerInputX,
idlerMiddleX,
3.08,
"C = 2.40",
"#ff9d58"
);
dimension(
idlerMiddleX,
idlerOutputX,
4.08,
"C = 2.88",
"#66dfa8"
);
// Scene labels.
const directTitle = makeLabel(
"DIRECT / ONE MESH",
"#ff9d58",
"rgba(10,16,23,0.88)",
4.3
);
directTitle.position.set(-5.25, 3.22, 0);
scene.add(directTitle);
const idlerTitle = makeLabel(
"IDLER / TWO MESHES",
"#66dfa8",
"rgba(10,16,23,0.88)",
4.8
);
idlerTitle.position.set(4.20, 3.22, 0);
scene.add(idlerTitle);
const directLabels = [
["12T INPUT", directInputX, 2.78, "#ffb271"],
["24T OUTPUT", directOutputX, 2.78, "#79c7ff"]
];
const idlerLabels = [
["12T INPUT", idlerInputX, 2.78, "#ffb271"],
["18T IDLER", idlerMiddleX, 2.78, "#dce8ef"],
["24T OUTPUT", idlerOutputX, 2.78, "#7ce8b4"]
];
for (const [text, x, y, color] of [...directLabels, ...idlerLabels]) {
const label = makeLabel(text, color, "rgba(10,16,23,0.78)", 2.0);
label.position.set(x, y, 0);
scene.add(label);
}
addArcArrow(directOutputX, 0, directOutput.rp + 0.24, -1, 0xff6680);
addArcArrow(idlerOutputX, 0, idlerOutput.rp + 0.24, 1, 0x57e3a6);
// -------------------------------------------------------------------------
// Kinematics
//
// For every external mesh:
// omegaChild = -(omegaParent * teethParent / teethChild)
//
// The idler cancels algebraically:
// + input -> - idler -> + output
// Thus both trains retain |omegaOut / omegaIn| = 12/24 = 0.5.
// -------------------------------------------------------------------------
const directOutputPhase = -Math.PI - Math.PI / OUTPUT_TEETH;
const idlerMiddlePhase = -Math.PI - Math.PI / IDLER_TEETH;
const idlerOutputPhase = -Math.PI - Math.PI / OUTPUT_TEETH;
let driveAngle = 0;
let running = true;
let speed = 1;
function updateTrain() {
directInput.group.rotation.y = driveAngle;
idlerInput.group.rotation.y = driveAngle;
// One external mesh: opposite direction.
directOutput.group.rotation.y =
directOutputPhase -
(INPUT_TEETH / OUTPUT_TEETH) * driveAngle;
// First idler mesh.
idlerMiddle.group.rotation.y =
idlerMiddlePhase -
(INPUT_TEETH / IDLER_TEETH) * driveAngle;
// Second idler mesh: another reversal.
idlerOutput.group.rotation.y =
idlerOutputPhase -
(IDLER_TEETH / OUTPUT_TEETH) * idlerMiddle.group.rotation.y;
}
updateTrain();
// -------------------------------------------------------------------------
// Controls
// -------------------------------------------------------------------------
const pauseButton = document.querySelector("#pauseBtn");
const resetButton = document.querySelector("#resetBtn");
const speedInput = document.querySelector("#speedInput");
const speedValue = document.querySelector("#speedValue");
const statusDot = document.querySelector("#statusDot");
const liveState = document.querySelector("#liveState");
pauseButton.addEventListener("click", () => {
running = !running;
pauseButton.textContent = running ? "Pause" : "Play";
statusDot.classList.toggle("paused", !running);
liveState.textContent = running ? "Running" : "Paused";
});
resetButton.addEventListener("click", () => {
cameraState.target.copy(defaultCamera.target);
cameraState.radius = defaultCamera.radius;
cameraState.phi = defaultCamera.phi;
cameraState.theta = defaultCamera.theta;
updateCamera();
});
speedInput.addEventListener("input", () => {
speed = Number(speedInput.value);
speedValue.textContent = `${speed.toFixed(1)}×`;
});
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
}
window.addEventListener("resize", resize);
renderer.setAnimationLoop(() => {
const dt = Math.min(clock.getDelta(), 0.05);
if (running) {
driveAngle += dt * speed * 0.9;
updateTrain();
}
renderer.render(scene, camera);
});
</script>
</body>
</html>
```