Prompt specification
Build or customize the Three.js 3D scene "Lever beam with adjustable fulcrum" 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: Lever beam with adjustable fulcrum
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/lever-beam-with-adjustable-fulcrum-x1409
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: lever beam with adjustable fulcrum. Build a rigid beam on a pivot with movable load markers and perpendicular force arrows; display moment arms from the pivot rather than total beam length. Return one self-contained HTML file.
Working Three.js Starter (lever-beam-with-adjustable-fulcrum-x1409):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lever Lab — Adjustable Fulcrum</title>
<style>
:root {
--ink: #183044;
--muted: #607286;
--panel: rgba(250, 252, 254, 0.94);
--line: #d8e0e8;
--accent-a: #ef6a5b;
--accent-b: #16a6a1;
--fulcrum: #f4b942;
--green: #258b67;
--orange: #cc673e;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #e8edf2;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
canvas {
display: block;
touch-action: none;
cursor: grab;
}
.title-block {
position: fixed;
top: 24px;
left: 26px;
z-index: 3;
pointer-events: none;
}
.eyebrow {
margin-bottom: 6px;
color: #61758a;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(26px, 3vw, 42px);
line-height: 1;
letter-spacing: -0.045em;
}
.subtitle {
margin-top: 8px;
color: var(--muted);
font-size: 13px;
}
.panel {
position: fixed;
top: 20px;
right: 20px;
z-index: 5;
width: min(350px, calc(100vw - 40px));
max-height: calc(100vh - 40px);
overflow: auto;
padding: 18px;
border: 1px solid rgba(255, 255, 255, 0.86);
border-radius: 20px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(40, 58, 78, 0.16);
backdrop-filter: blur(15px);
}
.panel-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.panel h2 {
margin: 0;
font-size: 17px;
letter-spacing: -0.02em;
}
.panel-note {
margin-top: 4px;
color: var(--muted);
font-size: 12px;
line-height: 1.35;
}
.status {
flex: 0 0 auto;
padding: 6px 9px;
border-radius: 999px;
font-size: 11px;
font-weight: 800;
white-space: nowrap;
background: #e5ece9;
color: var(--green);
}
.status.unbalanced {
color: var(--orange);
background: #f8e9df;
}
.control {
margin-top: 15px;
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
font-size: 12px;
font-weight: 750;
}
output {
color: var(--muted);
font-variant-numeric: tabular-nums;
font-weight: 700;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 0;
border-radius: 99px;
outline: none;
accent-color: #42647f;
cursor: pointer;
}
.segments {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.segments button,
.small-button {
border: 1px solid var(--line);
border-radius: 10px;
background: #fff;
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
}
.segments button {
padding: 9px;
}
.segments button.active[data-load="0"] {
color: #fff;
border-color: var(--accent-a);
background: var(--accent-a);
}
.segments button.active[data-load="1"] {
color: #fff;
border-color: var(--accent-b);
background: var(--accent-b);
}
.stats {
margin-top: 18px;
padding-top: 15px;
border-top: 1px solid var(--line);
}
.net-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.net-row span {
color: var(--muted);
font-size: 12px;
font-weight: 700;
}
.net-row strong {
font-size: 15px;
font-variant-numeric: tabular-nums;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
}
th {
padding: 0 0 7px;
color: #7a8998;
font-size: 10px;
text-align: left;
letter-spacing: 0.05em;
text-transform: uppercase;
}
th:nth-child(n+2),
td:nth-child(n+2) {
text-align: right;
}
td {
padding: 9px 0;
border-top: 1px solid #e4e9ee;
font-variant-numeric: tabular-nums;
}
tbody tr {
cursor: pointer;
}
tbody tr.selected {
background: rgba(66, 100, 127, 0.045);
}
.load-name {
display: inline-flex;
align-items: center;
gap: 7px;
font-weight: 800;
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--accent-a);
}
.dot.b {
background: var(--accent-b);
}
td small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.formula {
margin-top: 12px;
padding: 10px 11px;
border-radius: 10px;
background: #edf2f6;
color: #52677b;
font-size: 11px;
line-height: 1.45;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
.small-button {
padding: 9px;
}
.small-button:hover,
.segments button:hover {
filter: brightness(0.97);
}
.hint {
position: fixed;
left: 26px;
bottom: 22px;
z-index: 3;
max-width: 420px;
padding: 9px 12px;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 10px;
color: #586c7f;
background: rgba(250, 252, 254, 0.78);
box-shadow: 0 8px 24px rgba(44, 61, 79, 0.08);
font-size: 11px;
pointer-events: none;
}
.scene-label {
position: fixed;
z-index: 2;
left: 0;
top: 0;
padding: 5px 8px;
border: 1px solid rgba(255, 255, 255, 0.9);
border-radius: 8px;
color: var(--ink);
background: rgba(250, 252, 254, 0.9);
box-shadow: 0 5px 15px rgba(43, 59, 76, 0.12);
font-size: 11px;
font-weight: 800;
white-space: nowrap;
pointer-events: none;
transform: translate(-50%, -50%);
transition: opacity 120ms linear;
}
.scene-label.pivot {
color: #77560b;
background: rgba(255, 247, 218, 0.94);
}
.scene-label.arm-a {
color: #a13931;
border-color: rgba(239, 106, 91, 0.38);
}
.scene-label.arm-b {
color: #08726f;
border-color: rgba(22, 166, 161, 0.38);
}
.scene-label.force {
color: #fff;
background: rgba(24, 48, 68, 0.9);
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
color: var(--muted);
background: #e8edf2;
font-size: 13px;
font-weight: 700;
}
@media (max-width: 760px) {
.title-block {
top: 16px;
left: 16px;
}
.subtitle,
.hint {
display: none;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 46vh;
padding: 14px;
border-radius: 16px;
}
.panel-header {
margin-bottom: 9px;
}
.control {
margin-top: 11px;
}
.stats {
margin-top: 12px;
padding-top: 11px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="title-block">
<div class="eyebrow">Interactive mechanics</div>
<h1>Lever Lab</h1>
<div class="subtitle">Rigid beam, adjustable fulcrum, and true pivot-to-load moment arms.</div>
</header>
<aside class="panel">
<div class="panel-header">
<div>
<h2>Balance the lever</h2>
<div class="panel-note">Moment arm = distance from the pivot to each load.</div>
</div>
<div id="status" class="status">Balanced</div>
</div>
<div class="control">
<div class="control-row">
<label for="fulcrum">Fulcrum position</label>
<output id="fulcrumOut" for="fulcrum">+0.40 m</output>
</div>
<input id="fulcrum" type="range" min="-4.2" max="4.2" step="0.05" value="0.4">
</div>
<div class="control">
<div class="control-row">
<span>Selected marker</span>
<output id="selectedOut">Load A</output>
</div>
<div class="segments">
<button type="button" class="active" data-load="0">Load A</button>
<button type="button" data-load="1">Load B</button>
</div>
</div>
<div class="control">
<div class="control-row">
<label for="position">Marker position</label>
<output id="positionOut" for="position">−3.00 m</output>
</div>
<input id="position" type="range" min="-4.6" max="4.6" step="0.05" value="-3">
</div>
<div class="control">
<div class="control-row">
<label for="force">Downward force</label>
<output id="forceOut" for="force">100 N</output>
</div>
<input id="force" type="range" min="20" max="250" step="5" value="100">
</div>
<section class="stats">
<div class="net-row">
<span>Net moment</span>
<strong id="netMoment">+4 N·m CCW</strong>
</div>
<table>
<thead>
<tr>
<th>Load</th>
<th>Moment arm</th>
<th>Moment</th>
</tr>
</thead>
<tbody id="loadRows"></tbody>
</table>
<div class="formula">
<strong>τ = F × d</strong>, where <strong>d = |x<sub>load</sub> − x<sub>pivot</sub>|</strong>.
The forces are perpendicular to the level beam.
</div>
</section>
<div class="buttons">
<button type="button" class="small-button" id="resetScene">Reset scene</button>
<button type="button" class="small-button" id="resetView">Reset view</button>
</div>
</aside>
<div class="hint">Drag a marker or the yellow fulcrum · drag empty space to orbit · scroll to zoom</div>
<div id="labelPivot" class="scene-label pivot">PIVOT</div>
<div id="labelArmA" class="scene-label arm-a">d = 3.40 m</div>
<div id="labelArmB" class="scene-label arm-b">d = 2.10 m</div>
<div id="labelForceA" class="scene-label force">100 N ↓</div>
<div id="labelForceB" class="scene-label force">160 N ↓</div>
<div id="loading">Loading Three.js…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneHost = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8edf2);
scene.fog = new THREE.Fog(0xe8edf2, 19, 36);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
sceneHost.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xffffff, 0x718196, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.1);
sun.position.set(5, 10, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb8d7ff, 1.1);
fill.position.set(-7, 5, -5);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
new THREE.MeshStandardMaterial({
color: 0xe7ecf1,
roughness: 0.95,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.015;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(20, 20, 0xb8c4cf, 0xd6dee6);
grid.position.y = 0.002;
grid.material.transparent = true;
grid.material.opacity = 0.55;
scene.add(grid);
const BEAM_Y = 1.35;
const BEAM_HEIGHT = 0.28;
const BEAM_DEPTH = 0.5;
const MARKER_Y = 1.79;
const MARKER_TOP = 2.0;
const ARROW_TAIL = 3.7;
const state = {
pivot: 0.4,
selected: 0,
loads: [
{ x: -3.0, force: 100, color: 0xef6a5b },
{ x: 2.5, force: 160, color: 0x16a6a1 }
]
};
const beam = new THREE.Mesh(
new THREE.BoxGeometry(10, BEAM_HEIGHT, BEAM_DEPTH),
new THREE.MeshStandardMaterial({
color: 0x24455f,
roughness: 0.7,
metalness: 0.12,
flatShading: true
})
);
beam.position.y = BEAM_Y;
beam.castShadow = true;
beam.receiveShadow = true;
beam.userData.type = "beam";
scene.add(beam);
const beamTop = new THREE.Mesh(
new THREE.BoxGeometry(10, 0.035, BEAM_DEPTH + 0.015),
new THREE.MeshStandardMaterial({
color: 0x3d6179,
roughness: 0.75,
metalness: 0.08
})
);
beamTop.position.y = BEAM_Y + BEAM_HEIGHT / 2 + 0.017;
beamTop.receiveShadow = true;
scene.add(beamTop);
for (const end of [-1, 1]) {
const cap = new THREE.Mesh(
new THREE.BoxGeometry(0.09, BEAM_HEIGHT + 0.025, BEAM_DEPTH + 0.025),
new THREE.MeshStandardMaterial({
color: 0xf4b942,
roughness: 0.68,
flatShading: true
})
);
cap.position.set(end * 5, BEAM_Y, 0);
cap.castShadow = true;
scene.add(cap);
}
const fulcrumGroup = new THREE.Group();
scene.add(fulcrumGroup);
const supportShape = new THREE.Shape();
supportShape.moveTo(-0.52, 0);
supportShape.lineTo(0.52, 0);
supportShape.lineTo(0, 1.16);
supportShape.closePath();
const supportGeometry = new THREE.ExtrudeGeometry(supportShape, {
depth: 0.68,
bevelEnabled: false,
steps: 1
});
supportGeometry.translate(0, 0, -0.34);
const fulcrumMaterial = new THREE.MeshStandardMaterial({
color: 0xf4b942,
roughness: 0.64,
metalness: 0.06,
flatShading: true
});
const fulcrumBody = new THREE.Mesh(supportGeometry, fulcrumMaterial);
fulcrumBody.position.y = 0.01;
fulcrumBody.castShadow = true;
fulcrumBody.receiveShadow = true;
fulcrumBody.userData.type = "fulcrum";
fulcrumGroup.add(fulcrumBody);
const axleMaterial = new THREE.MeshStandardMaterial({
color: 0x60798d,
roughness: 0.34,
metalness: 0.72,
emissive: 0x000000,
emissiveIntensity: 0
});
const axle = new THREE.Mesh(
new THREE.CylinderGeometry(0.145, 0.145, 0.88, 12),
axleMaterial
);
axle.rotation.x = Math.PI / 2;
axle.position.y = BEAM_Y;
axle.castShadow = true;
fulcrumGroup.add(axle);
const pivotRing = new THREE.Mesh(
new THREE.TorusGeometry(0.205, 0.035, 6, 18),
new THREE.MeshStandardMaterial({
color: 0xdba928,
roughness: 0.5,
metalness: 0.25
})
);
pivotRing.position.set(0, BEAM_Y, 0.29);
fulcrumGroup.add(pivotRing);
function makeBadgeTexture(letter, color) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const context = canvas.getContext("2d");
context.beginPath();
context.arc(64, 64, 55, 0, Math.PI * 2);
context.fillStyle = `#${new THREE.Color(color).getHexString()}`;
context.fill();
context.lineWidth = 7;
context.strokeStyle = "rgba(255,255,255,0.9)";
context.stroke();
context.fillStyle = "#ffffff";
context.font = "800 62px system-ui";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(letter, 64, 67);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const loadVisuals = [];
const armVisuals = [];
const pickables = [fulcrumBody];
function createLoadVisual(load, index) {
const group = new THREE.Group();
scene.add(group);
const baseMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(load.color).multiplyScalar(0.72),
roughness: 0.72,
flatShading: true
});
const markerMaterial = new THREE.MeshStandardMaterial({
color: load.color,
roughness: 0.55,
metalness: 0.05,
emissive: load.color,
emissiveIntensity: 0.04,
flatShading: true
});
const base = new THREE.Mesh(
new THREE.BoxGeometry(0.64, 0.1, 0.68),
baseMaterial
);
base.position.y = 1.54;
base.castShadow = true;
base.receiveShadow = true;
base.userData = { type: "load", index };
group.add(base);
const marker = new THREE.Mesh(
new THREE.BoxGeometry(0.48, 0.42, 0.56),
markerMaterial
);
marker.position.y = MARKER_Y;
marker.castShadow = true;
marker.receiveShadow = true;
marker.userData = { type: "load", index };
group.add(marker);
const badge = new THREE.Sprite(
new THREE.SpriteMaterial({
map: makeBadgeTexture(index === 0 ? "A" : "B", load.color),
transparent: true,
depthWrite: false
})
);
badge.position.set(0, MARKER_Y, 0.02);
badge.scale.set(0.42, 0.42, 0.42);
group.add(badge);
const arrowMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(load.color).multiplyScalar(0.8),
roughness: 0.48,
metalness: 0.08,
flatShading: true
});
const shaftLength = ARROW_TAIL - (MARKER_TOP + 0.28);
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.035, 1, 8),
arrowMaterial
);
shaft.position.y = ARROW_TAIL - shaftLength / 2;
shaft.castShadow = true;
group.add(shaft);
const cone = new THREE.Mesh(
new THREE.ConeGeometry(0.115, 0.28, 8),
arrowMaterial
);
cone.rotation.x = Math.PI;
cone.position.y = MARKER_TOP + 0.14;
cone.castShadow = true;
group.add(cone);
const tail = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.07, 0),
arrowMaterial
);
tail.position.y = ARROW_TAIL;
group.add(tail);
const rightAngleGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, MARKER_TOP, 0.315),
new THREE.Vector3(0.28, MARKER_TOP, 0.315),
new THREE.Vector3(0.28, MARKER_TOP + 0.28, 0.315),
new THREE.Vector3(0, MARKER_TOP + 0.28, 0.315)
]);
const rightAngle = new THREE.Line(
rightAngleGeometry,
new THREE.LineBasicMaterial({
color: 0x6e8090,
transparent: true,
opacity: 0.8
})
);
group.add(rightAngle);
pickables.push(base, marker);
loadVisuals.push({ group, markerMaterial, shaft, cone, tail });
}
function createArmVisual(load, index) {
const group = new THREE.Group();
scene.add(group);
const y = 0.27 + index * 0.23;
const z = 0.72;
const line = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: load.color,
dashSize: 0.14,
gapSize: 0.075,
transparent: true,
opacity: 0.95
})
);
const caps = new THREE.LineSegments(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: load.color,
transparent: true,
opacity: 0.95
})
);
group.add(line, caps);
armVisuals.push({ group, line, caps, y, z, anchor: new THREE.Vector3() });
}
state.loads.forEach((load, index) => {
createLoadVisual(load, index);
createArmVisual(load, index);
});
const fulcrumInput = document.getElementById("fulcrum");
const positionInput = document.getElementById("position");
const forceInput = document.getElementById("force");
const fulcrumOut = document.getElementById("fulcrumOut");
const positionOut = document.getElementById("positionOut");
const forceOut = document.getElementById("forceOut");
const selectedOut = document.getElementById("selectedOut");
const statusElement = document.getElementById("status");
const netMomentElement = document.getElementById("netMoment");
const loadRows = document.getElementById("loadRows");
const loadButtons = [...document.querySelectorAll(".segments button")];
function formatSigned(value) {
if (Math.abs(value) < 0.0001) return "0";
return value > 0 ? `+${value.toFixed(0)}` : `−${Math.abs(value).toFixed(0)}`;
}
function formatPosition(value) {
return `${value < 0 ? "−" : "+"}${Math.abs(value).toFixed(2)} m`;
}
function signedMoment(load) {
// Counterclockwise is positive. A downward force on the right is clockwise.
return -load.force * (load.x - state.pivot);
}
function updateStats() {
const moments = state.loads.map(signedMoment);
const net = moments.reduce((sum, value) => sum + value, 0);
const largest = Math.max(...moments.map(Math.abs));
const balanced = Math.abs(net) <= Math.max(5, largest * 0.02);
statusElement.textContent = balanced ? "Balanced" : net > 0 ? "Net CCW" : "Net CW";
statusElement.classList.toggle("unbalanced", !balanced);
const netDirection = Math.abs(net) < 0.0001 ? "" : net > 0 ? " CCW" : " CW";
netMomentElement.textContent = `${formatSigned(net)} N·m${netDirection}`;
axleMaterial.emissive.set(balanced ? 0x1d8a64 : 0xb65b30);
axleMaterial.emissiveIntensity = balanced ? 0.16 : 0.11;
loadRows.innerHTML = state.loads.map((load, index) => {
const arm = Math.abs(load.x - state.pivot);
const moment = moments[index];
const direction = Math.abs(moment) < 0.0001 ? "" : moment > 0 ? "CCW" : "CW";
const selected = index === state.selected ? "selected" : "";
return `
<tr class="${selected}" data-load="${index}">
<td>
<span class="load-name">
<span class="dot ${index === 1 ? "b" : ""}"></span>
${index === 0 ? "A" : "B"}
</span>
</td>
<td>${arm.toFixed(2)} m</td>
<td>
${formatSigned(moment)} N·m
<small>${direction}</small>
</td>
</tr>
`;
}).join("");
document.getElementById("labelArmA").textContent =
`d = ${Math.abs(state.loads[0].x - state.pivot).toFixed(2)} m`;
document.getElementById("labelArmB").textContent =
`d = ${Math.abs(state.loads[1].x - state.pivot).toFixed(2)} m`;
document.getElementById("labelForceA").textContent =
`${state.loads[0].force.toFixed(0)} N ↓`;
document.getElementById("labelForceB").textContent =
`${state.loads[1].force.toFixed(0)} N ↓`;
}
function syncControls() {
fulcrumInput.value = state.pivot;
fulcrumOut.textContent = formatPosition(state.pivot);
const selectedLoad = state.loads[state.selected];
positionInput.value = selectedLoad.x;
positionOut.textContent = formatPosition(selectedLoad.x);
forceInput.value = selectedLoad.force;
forceOut.textContent = `${selectedLoad.force.toFixed(0)} N`;
selectedOut.textContent = `Load ${state.selected === 0 ? "A" : "B"}`;
loadButtons.forEach((button) => {
const active = Number(button.dataset.load) === state.selected;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
}
function updateArmVisual(index) {
const visual = armVisuals[index];
const load = state.loads[index];
const x0 = state.pivot;
const x1 = load.x;
visual.line.geometry.setFromPoints([
new THREE.Vector3(x0, visual.y, visual.z),
new THREE.Vector3(x1, visual.y, visual.z)
]);
visual.line.geometry.computeBoundingSphere();
visual.line.computeLineDistances();
visual.caps.geometry.setFromPoints([
new THREE.Vector3(x0, visual.y - 0.095, visual.z),
new THREE.Vector3(x0, visual.y + 0.095, visual.z),
new THREE.Vector3(x1, visual.y - 0.095, visual.z),
new THREE.Vector3(x1, visual.y + 0.095, visual.z)
]);
visual.caps.geometry.computeBoundingSphere();
visual.anchor.set((x0 + x1) / 2, visual.y + 0.02, visual.z);
}
function applyState() {
fulcrumGroup.position.x = state.pivot;
state.loads.forEach((load, index) => {
const visual = loadVisuals[index];
visual.group.position.x = load.x;
const thickness = 0.78 + (load.force / 250) * 0.52;
visual.shaft.scale.set(thickness, 1, thickness);
visual.cone.scale.set(thickness, 1, thickness);
visual.tail.scale.setScalar(thickness);
visual.markerMaterial.emissiveIntensity =
index === state.selected ? 0.24 : 0.035;
updateArmVisual(index);
});
updateStats();
syncControls();
}
function selectLoad(index) {
state.selected = index;
applyState();
}
fulcrumInput.addEventListener("input", () => {
state.pivot = Number(fulcrumInput.value);
applyState();
});
positionInput.addEventListener("input", () => {
state.loads[state.selected].x = Number(positionInput.value);
applyState();
});
forceInput.addEventListener("input", () => {
state.loads[state.selected].force = Number(forceInput.value);
applyState();
});
loadButtons.forEach((button) => {
button.addEventListener("click", () => {
selectLoad(Number(button.dataset.load));
});
});
loadRows.addEventListener("click", (event) => {
const row = event.target.closest("tr[data-load]");
if (row) selectLoad(Number(row.dataset.load));
});
document.getElementById("resetScene").addEventListener("click", () => {
state.pivot = 0.4;
state.selected = 0;
state.loads[0].x = -3;
state.loads[0].force = 100;
state.loads[1].x = 2.5;
state.loads[1].force = 160;
applyState();
});
const cameraTarget = new THREE.Vector3(0, 1.25, 0);
const spherical = new THREE.Spherical(12.3, 1.08, 0.28);
function updateCamera() {
spherical.phi = THREE.MathUtils.clamp(spherical.phi, 0.25, 1.38);
spherical.radius = THREE.MathUtils.clamp(spherical.radius, 7.2, 20);
camera.position.setFromSpherical(spherical).add(cameraTarget);
camera.lookAt(cameraTarget);
}
document.getElementById("resetView").addEventListener("click", () => {
spherical.set(12.3, 1.08, 0.28);
updateCamera();
});
updateCamera();
// Direct, dependency-free camera controls.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane();
const planeHit = new THREE.Vector3();
let drag = null;
let orbit = null;
function setPointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function pointerPlaneX(event, y) {
setPointer(event);
dragPlane.set(new THREE.Vector3(0, 1, 0), -y);
const hit = raycaster.ray.intersectPlane(dragPlane, planeHit);
return hit ? hit.x : null;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
setPointer(event);
const hits = raycaster.intersectObjects(pickables, false);
if (hits.length) {
const data = hits[0].object.userData;
if (data.type === "load") {
selectLoad(data.index);
drag = { type: "load", index: data.index, y: MARKER_Y };
} else if (data.type === "fulcrum") {
drag = { type: "fulcrum", y: BEAM_Y };
}
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "ew-resize";
event.preventDefault();
} else {
orbit = {
x: event.clientX,
y: event.clientY
};
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (drag) {
const x = pointerPlaneX(event, drag.y);
if (x !== null) {
if (drag.type === "load") {
state.loads[drag.index].x = THREE.MathUtils.clamp(x, -4.6, 4.6);
} else {
state.pivot = THREE.MathUtils.clamp(x, -4.2, 4.2);
}
applyState();
}
return;
}
if (orbit) {
const dx = event.clientX - orbit.x;
const dy = event.clientY - orbit.y;
orbit.x = event.clientX;
orbit.y = event.clientY;
spherical.theta -= dx * 0.006;
spherical.phi -= dy * 0.005;
updateCamera();
return;
}
setPointer(event);
const hovering = raycaster.intersectObjects(pickables, false);
renderer.domElement.style.cursor = hovering.length ? "ew-resize" : "grab";
});
function endPointer(event) {
drag = null;
orbit = null;
renderer.domElement.style.cursor = "grab";
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
spherical.radius += event.deltaY * 0.008;
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
spherical.set(12.3, 1.08, 0.28);
updateCamera();
});
const labelElements = {
pivot: document.getElementById("labelPivot"),
armA: document.getElementById("labelArmA"),
armB: document.getElementById("labelArmB"),
forceA: document.getElementById("labelForceA"),
forceB: document.getElementById("labelForceB")
};
const projected = new THREE.Vector3();
function placeLabel(element, x, y, z) {
projected.set(x, y, z).project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.opacity = visible ? "1" : "0";
element.style.left = `${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
function updateLabels() {
placeLabel(labelElements.pivot, state.pivot, 0.08, 0.78);
placeLabel(
labelElements.armA,
armVisuals[0].anchor.x,
armVisuals[0].anchor.y + 0.04,
armVisuals[0].anchor.z
);
placeLabel(
labelElements.armB,
armVisuals[1].anchor.x,
armVisuals[1].anchor.y + 0.04,
armVisuals[1].anchor.z
);
placeLabel(labelElements.forceA, state.loads[0].x, 4.03, 0);
placeLabel(labelElements.forceB, state.loads[1].x, 4.03, 0);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
applyState();
document.getElementById("loading").style.display = "none";
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
updateLabels();
});
</script>
</body>
</html>
```