Prompt specification
Build or customize the Three.js 3D scene "Force-vector composition sandbox" 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: Force-vector composition sandbox
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/force-vector-composition-sandbox-x1440
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows force vectors and their resultant. Provide angle and magnitude controls for two or three forces on a point mass; update the resultant and motion while separating the diagram scale from scene geometry. Low-poly.
Working Three.js Starter (force-vector-composition-sandbox-x1440):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Force Lab — Resultant & Motion</title>
<style>
:root {
color-scheme: dark;
--bg: #08111a;
--panel: rgba(11, 20, 31, 0.88);
--panel-solid: #0d1825;
--border: rgba(159, 190, 218, 0.16);
--text: #e9f2fb;
--muted: #8ea5ba;
--cyan: #67e8f9;
--gold: #f8d36d;
--red: #ff6b6b;
--green: #4dd4ac;
--purple: #a78bfa;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.glass {
background: var(--panel);
border: 1px solid var(--border);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.34);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
bottom: 18px;
left: 18px;
width: 342px;
padding: 18px;
border-radius: 18px;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: #30465b transparent;
}
.panel::-webkit-scrollbar {
width: 6px;
}
.panel::-webkit-scrollbar-thumb {
background: #30465b;
border-radius: 99px;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
padding-bottom: 16px;
}
.brand-mark {
display: grid;
width: 44px;
height: 44px;
place-items: center;
border: 1px solid rgba(103, 232, 249, 0.28);
border-radius: 13px;
background:
linear-gradient(145deg, rgba(103, 232, 249, 0.18), rgba(167, 139, 250, 0.08)),
#0b1722;
color: var(--cyan);
font-size: 25px;
font-weight: 800;
box-shadow: inset 0 0 20px rgba(103, 232, 249, 0.05);
}
.brand h1 {
margin: 0;
font-size: 20px;
line-height: 1.1;
letter-spacing: -0.03em;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
}
.live {
margin-left: auto;
padding: 5px 8px;
border: 1px solid rgba(77, 212, 172, 0.24);
border-radius: 99px;
background: rgba(77, 212, 172, 0.08);
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
}
section {
padding: 16px 0;
border-top: 1px solid var(--border);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.section-title small {
color: #668096;
font-size: 9px;
letter-spacing: 0.08em;
font-weight: 600;
text-transform: none;
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 4px;
padding: 4px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(3, 9, 15, 0.4);
}
.segmented button {
padding: 9px;
border: 0;
border-radius: 8px;
background: transparent;
color: var(--muted);
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
.segmented button.active {
background: #1a2b3d;
color: var(--text);
box-shadow: 0 3px 12px rgba(0, 0, 0, 0.22);
}
.force-card {
--accent: var(--red);
margin-top: 10px;
padding: 12px;
border: 1px solid var(--border);
border-left: 3px solid var(--accent);
border-radius: 12px;
background: rgba(4, 11, 18, 0.38);
}
.force-card[hidden] {
display: none;
}
.force-heading {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
font-size: 12px;
font-weight: 750;
}
.force-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 12px color-mix(in srgb, var(--accent), transparent 35%);
}
.force-heading span:last-child {
margin-left: auto;
color: var(--muted);
font-size: 10px;
font-weight: 600;
}
.control {
margin-top: 10px;
}
.control-label {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 7px;
color: #b7c7d7;
font-size: 11px;
}
output {
color: var(--text);
font-variant-numeric: tabular-nums;
font-weight: 700;
}
input[type="range"] {
--fill: 50%;
width: 100%;
height: 4px;
margin: 0;
border-radius: 99px;
outline: none;
appearance: none;
-webkit-appearance: none;
background: linear-gradient(
to right,
var(--accent, var(--cyan)) 0,
var(--accent, var(--cyan)) var(--fill),
rgba(135, 165, 192, 0.18) var(--fill),
rgba(135, 165, 192, 0.18) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #10202e;
border-radius: 50%;
appearance: none;
-webkit-appearance: none;
background: var(--accent, var(--cyan));
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.12);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #10202e;
border-radius: 50%;
background: var(--accent, var(--cyan));
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.12);
}
.control-grid {
display: grid;
gap: 11px;
}
.scale-note {
padding: 12px;
border: 1px solid rgba(103, 232, 249, 0.15);
border-radius: 12px;
background: rgba(103, 232, 249, 0.045);
}
.scale-note strong {
display: block;
margin-bottom: 5px;
color: var(--cyan);
font-size: 11px;
}
.scale-note p {
margin: 0;
color: #94aabc;
font-size: 10px;
line-height: 1.55;
}
.panel-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
padding-top: 2px;
}
button.action {
min-height: 39px;
border: 1px solid var(--border);
border-radius: 10px;
background: #142536;
color: var(--text);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition:
background 0.15s ease,
transform 0.15s ease;
}
button.action:hover {
background: #1b3146;
transform: translateY(-1px);
}
button.action.primary {
border-color: rgba(103, 232, 249, 0.25);
background: rgba(103, 232, 249, 0.12);
color: #bff7ff;
}
.hud {
position: fixed;
z-index: 8;
top: 18px;
right: 18px;
width: 286px;
padding: 15px;
border-radius: 16px;
}
.hud-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.hud-header span:first-child {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.state-pill {
padding: 4px 7px;
border-radius: 99px;
background: rgba(248, 211, 109, 0.1);
color: var(--gold);
font-size: 9px;
font-weight: 800;
}
.state-pill.equilibrium {
background: rgba(77, 212, 172, 0.1);
color: var(--green);
}
.result-main {
display: flex;
align-items: center;
gap: 14px;
}
.result-number {
flex: 1;
}
.result-number strong {
display: block;
font-size: 32px;
line-height: 1;
letter-spacing: -0.05em;
font-variant-numeric: tabular-nums;
}
.result-number strong small {
color: var(--muted);
font-size: 13px;
font-weight: 600;
letter-spacing: 0;
}
.result-number span {
display: block;
margin-top: 7px;
color: var(--muted);
font-size: 10px;
}
.dial {
position: relative;
width: 70px;
height: 70px;
flex: 0 0 70px;
border: 1px solid rgba(142, 165, 186, 0.2);
border-radius: 50%;
background:
linear-gradient(rgba(142, 165, 186, 0.09) 1px, transparent 1px),
linear-gradient(90deg, rgba(142, 165, 186, 0.09) 1px, transparent 1px),
rgba(2, 8, 14, 0.35);
background-size: 50% 50%;
}
.dial::after {
content: "";
position: absolute;
top: 50%;
left: 50%;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--gold);
transform: translate(-50%, -50%);
box-shadow: 0 0 10px rgba(248, 211, 109, 0.5);
}
.needle {
position: absolute;
z-index: 1;
top: 50%;
left: 50%;
width: 30px;
height: 2px;
margin-top: -1px;
border-radius: 99px;
background: var(--gold);
transform-origin: 0 50%;
transform: rotate(0deg);
}
.needle::after {
content: "";
position: absolute;
top: -3px;
right: -1px;
width: 0;
height: 0;
border-top: 4px solid transparent;
border-bottom: 4px solid transparent;
border-left: 6px solid var(--gold);
}
.hud-stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 13px;
}
.hud-stat {
padding: 9px 8px;
border: 1px solid rgba(142, 165, 186, 0.12);
border-radius: 9px;
background: rgba(2, 8, 14, 0.28);
}
.hud-stat span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 8px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.hud-stat strong {
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.legend {
position: fixed;
z-index: 8;
right: 18px;
bottom: 18px;
display: flex;
align-items: center;
gap: 15px;
padding: 10px 13px;
border-radius: 12px;
color: var(--muted);
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.legend-line {
width: 19px;
height: 3px;
border-radius: 99px;
background: currentColor;
}
.legend-item.resultant {
color: var(--gold);
}
.legend-item.trail {
color: var(--cyan);
}
.camera-hint {
position: fixed;
z-index: 6;
left: 50%;
bottom: 20px;
padding: 8px 12px;
border: 1px solid rgba(142, 165, 186, 0.12);
border-radius: 99px;
background: rgba(6, 13, 21, 0.7);
color: #8399ac;
font-size: 10px;
transform: translateX(-50%);
pointer-events: none;
}
.view-button {
padding: 6px 8px;
border: 1px solid var(--border);
border-radius: 7px;
background: transparent;
color: var(--muted);
font: inherit;
font-size: 9px;
font-weight: 700;
cursor: pointer;
}
.view-button:hover {
color: var(--text);
background: rgba(255, 255, 255, 0.05);
}
@media (max-width: 780px) {
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 54vh;
}
.hud {
top: 12px;
right: 12px;
width: 238px;
}
.legend,
.camera-hint {
display: none;
}
}
@media (max-width: 480px) {
.hud {
width: 206px;
padding: 12px;
}
.result-number strong {
font-size: 27px;
}
.dial {
width: 58px;
height: 58px;
flex-basis: 58px;
}
.hud-stats {
gap: 4px;
}
.hud-stat {
padding: 7px 5px;
}
.panel {
max-height: 56vh;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<aside class="panel glass">
<div class="brand">
<div class="brand-mark">Σ</div>
<div>
<h1>Force Lab</h1>
<p>Vector composition and Newtonian motion</p>
</div>
<div class="live">LIVE</div>
</div>
<section>
<div class="section-title">
<span>Applied forces</span>
<small>0° = +X · 90° = +Y</small>
</div>
<div class="segmented" aria-label="Number of forces">
<button type="button" data-count="2" aria-pressed="false">2 forces</button>
<button type="button" data-count="3" class="active" aria-pressed="true">3 forces</button>
</div>
<div id="forceControls"></div>
</section>
<section>
<div class="section-title">
<span>Mass & motion</span>
<small>F = ma</small>
</div>
<div class="control-grid">
<div class="control">
<div class="control-label">
<span>Point mass</span>
<output id="massOut">3.0 kg</output>
</div>
<input id="mass" type="range" min="1" max="10" step="0.1" value="3" />
</div>
<div class="control">
<div class="control-label">
<span>Motion scale</span>
<output id="motionScaleOut">0.08 scene/m</output>
</div>
<input
id="motionScale"
type="range"
min="0.02"
max="0.16"
step="0.005"
value="0.08"
/>
</div>
<div class="control">
<div class="control-label">
<span>Time scale</span>
<output id="timeScaleOut">0.70×</output>
</div>
<input
id="timeScale"
type="range"
min="0.1"
max="2"
step="0.05"
value="0.7"
/>
</div>
<div class="control">
<div class="control-label">
<span>Damping</span>
<output id="dampingOut">0.65 s⁻¹</output>
</div>
<input
id="damping"
type="range"
min="0.05"
max="1.5"
step="0.05"
value="0.65"
/>
</div>
</div>
</section>
<section>
<div class="section-title">
<span>Diagram display</span>
<small>Scene geometry stays fixed</small>
</div>
<div class="control">
<div class="control-label">
<span>Arrow scale</span>
<output id="arrowScaleOut">0.42 scene/N</output>
</div>
<input
id="arrowScale"
type="range"
min="0.12"
max="0.65"
step="0.01"
value="0.42"
/>
</div>
<div class="scale-note">
<strong>Independent display scales</strong>
<p>
Arrow scale changes only the displayed force lengths. Motion scale maps
physical distance into the fixed 24 × 24 scene. Grid size, mass size,
and camera framing never change with force magnitude.
</p>
</div>
</section>
<section>
<div class="panel-actions">
<button id="pauseButton" class="action primary" type="button">Pause motion</button>
<button id="resetMotion" class="action" type="button">Reset motion</button>
</div>
</section>
</aside>
<div class="hud glass">
<div class="hud-header">
<span>Resultant</span>
<div id="statePill" class="state-pill">Accelerating</div>
</div>
<div class="result-main">
<div class="result-number">
<strong><span id="resultMagnitude">13.4</span> <small>N</small></strong>
<span id="resultDirection">Direction 71°</span>
</div>
<div class="dial" aria-label="Resultant direction dial">
<div id="needle" class="needle"></div>
</div>
</div>
<div class="hud-stats">
<div class="hud-stat">
<span>Acceleration</span>
<strong id="acceleration">4.47 m/s²</strong>
</div>
<div class="hud-stat">
<span>Speed</span>
<strong id="speed">0.00 m/s</strong>
</div>
<div class="hud-stat">
<span>Distance</span>
<strong id="distance">0.00 m</strong>
</div>
</div>
</div>
<div class="legend glass">
<div class="legend-item"><span class="legend-line"></span> Applied force</div>
<div class="legend-item resultant">
<span class="legend-line"></span> Resultant
</div>
<div class="legend-item trail"><span class="legend-line"></span> Motion trail</div>
<button id="resetView" class="view-button" type="button">Reset view</button>
</div>
<div class="camera-hint">Drag to orbit · Scroll to zoom · Double-click to reset view</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// State
// -------------------------------------------------------------------------
const forceColors = [0xff6b6b, 0x4dd4ac, 0xa78bfa];
const forceCssColors = ["#ff6b6b", "#4dd4ac", "#a78bfa"];
const forceNames = ["Force 1", "Force 2", "Force 3"];
const forceSubscripts = ["₁", "₂", "₃"];
const state = {
count: 3,
magnitudes: [12, 8, 4],
angles: [20, 145, 265],
mass: 3,
arrowScale: 0.42,
motionScale: 0.08,
timeScale: 0.7,
damping: 0.65,
running: true,
position: { x: 0, z: 0 },
velocity: { x: 0, z: 0 },
acceleration: { x: 0, z: 0 },
resultant: { x: 0, z: 0, magnitude: 0, direction: 0 },
forces: []
};
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const sceneHost = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x08111a);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08111a);
scene.fog = new THREE.Fog(0x08111a, 18, 43);
const camera = new THREE.PerspectiveCamera(
48,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0, 0);
const cameraState = {
yaw: 0.72,
phi: 0.92,
radius: 17
};
const defaultCamera = { ...cameraState };
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraTarget.x +
cameraState.radius * sinPhi * Math.cos(cameraState.yaw),
cameraTarget.y + cameraState.radius * Math.cos(cameraState.phi),
cameraTarget.z +
cameraState.radius * sinPhi * Math.sin(cameraState.yaw)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraState.yaw = defaultCamera.yaw;
cameraState.phi = defaultCamera.phi;
cameraState.radius = defaultCamera.radius;
updateCamera();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xb9e8ff, 0x172231, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(6, 11, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 13;
keyLight.shadow.camera.bottom = -13;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x67e8f9, 1.4);
fillLight.position.set(-7, 5, -8);
scene.add(fillLight);
const rimLight = new THREE.DirectionalLight(0xa78bfa, 1.1);
rimLight.position.set(5, 4, -9);
scene.add(rimLight);
// Low-poly, subtly faceted ground. Its dimensions remain fixed.
const groundGeometry = new THREE.PlaneGeometry(30, 24, 12, 10);
const groundPositions = groundGeometry.attributes.position;
for (let i = 0; i < groundPositions.count; i++) {
const x = groundPositions.getX(i);
const y = groundPositions.getY(i);
const displacement =
Math.sin(x * 0.58) * 0.035 +
Math.cos(y * 0.72) * 0.025 +
Math.sin((x + y) * 0.31) * 0.025;
groundPositions.setZ(i, displacement);
}
groundGeometry.computeVertexNormals();
const ground = new THREE.Mesh(
groundGeometry,
new THREE.MeshStandardMaterial({
color: 0x111d29,
roughness: 0.96,
metalness: 0.02,
flatShading: true
})
);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(24, 24, 0x355068, 0x203244);
grid.position.y = 0.045;
grid.material.transparent = true;
grid.material.opacity = 0.52;
scene.add(grid);
function makeLine(points, color, opacity = 1) {
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color,
transparent: opacity < 1,
opacity
});
return new THREE.Line(geometry, material);
}
const boundary = makeLine(
[
new THREE.Vector3(-12, 0.055, -12),
new THREE.Vector3(12, 0.055, -12),
new THREE.Vector3(12, 0.055, 12),
new THREE.Vector3(-12, 0.055, 12),
new THREE.Vector3(-12, 0.055, -12)
],
0x456078,
0.5
);
scene.add(boundary);
const xAxis = makeLine(
[
new THREE.Vector3(-10.5, 0.07, 0),
new THREE.Vector3(10.5, 0.07, 0)
],
0x7f5360,
0.42
);
scene.add(xAxis);
// Diagram +Y is represented by scene -Z so positive angles appear counter-
// clockwise when viewed from the default camera.
const yAxis = makeLine(
[
new THREE.Vector3(0, 0.07, 10.5),
new THREE.Vector3(0, 0.07, -10.5)
],
0x4b766c,
0.42
);
scene.add(yAxis);
const originRing = new THREE.Mesh(
new THREE.RingGeometry(1.03, 1.065, 40),
new THREE.MeshBasicMaterial({
color: 0x67e8f9,
transparent: true,
opacity: 0.23,
side: THREE.DoubleSide
})
);
originRing.rotation.x = -Math.PI / 2;
originRing.position.y = 0.075;
scene.add(originRing);
// -------------------------------------------------------------------------
// Labels rendered as self-contained canvas sprites
// -------------------------------------------------------------------------
function createLabel(text, color = "#ffffff") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(2.05, 0.5125, 1);
sprite.renderOrder = 20;
sprite.userData.canvas = canvas;
sprite.userData.context = context;
sprite.userData.texture = texture;
sprite.userData.text = null;
sprite.userData.color = color;
setLabel(sprite, text, color);
scene.add(sprite);
return sprite;
}
function setLabel(sprite, text, color = sprite.userData.color) {
if (
sprite.userData.text === text &&
sprite.userData.color === color
) {
return;
}
sprite.userData.text = text;
sprite.userData.color = color;
const context = sprite.userData.context;
const canvas = sprite.userData.canvas;
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(5, 12, 20, 0.88)";
context.strokeStyle = color;
context.lineWidth = 4;
context.beginPath();
if (context.roundRect) {
context.roundRect(4, 4, 504, 120, 22);
} else {
context.rect(4, 4, 504, 120);
}
context.fill();
context.stroke();
context.fillStyle = color;
context.font = "700 38px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 65);
sprite.userData.texture.needsUpdate = true;
}
createLabel("+X", "#b88c98").position.set(10.9, 0.35, 0);
createLabel("+Y", "#8bc6b7").position.set(0, 0.35, -10.9);
createLabel("0°", "#7f94a8").position.set(1.65, 0.2, 0);
createLabel("90°", "#7f94a8").position.set(0, 0.2, -1.8);
// -------------------------------------------------------------------------
// Low-poly arrows
// -------------------------------------------------------------------------
const localUp = new THREE.Vector3(0, 1, 0);
function createArrow(color, radius = 0.06) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.18,
roughness: 0.34,
metalness: 0.04,
flatShading: true
});
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, 1, 6),
material
);
shaft.castShadow = true;
const cone = new THREE.Mesh(
new THREE.CylinderGeometry(0, radius * 2.7, 1, 6),
material
);
cone.castShadow = true;
group.add(shaft, cone);
scene.add(group);
return { group, shaft, cone };
}
function setArrow(arrow, origin, direction, length) {
if (length <= 0.015) {
arrow.group.visible = false;
return;
}
arrow.group.visible = true;
arrow.group.position.copy(origin);
arrow.group.quaternion.setFromUnitVectors(localUp, direction);
const headLength = Math.min(0.48, Math.max(0.18, length * 0.22));
const shaftLength = Math.max(0.025, length - headLength);
arrow.shaft.scale.set(1, shaftLength, 1);
arrow.shaft.position.y = shaftLength * 0.5;
arrow.cone.scale.set(1, headLength, 1);
arrow.cone.position.y = shaftLength + headLength * 0.5;
}
const forceArrows = forceColors.map((color) => createArrow(color, 0.052));
const forceLabels = forceColors.map((color) =>
createLabel("", `#${color.toString(16).padStart(6, "0")}`)
);
const resultantArrow = createArrow(0xf8d36d, 0.086);
const resultantLabel = createLabel("R 0.0 N", "#f8d36d");
// -------------------------------------------------------------------------
// Point mass
// -------------------------------------------------------------------------
const massGroup = new THREE.Group();
const massPosition = new THREE.Vector3(0, 0.56, 0);
const massMesh = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.44, 1),
new THREE.MeshStandardMaterial({
color: 0xe8f3fb,
emissive: 0x15354a,
emissiveIntensity: 0.65,
roughness: 0.4,
metalness: 0.1,
flatShading: true
})
);
massMesh.castShadow = true;
massMesh.receiveShadow = true;
const massRing = new THREE.Mesh(
new THREE.TorusGeometry(0.61, 0.025, 6, 28),
new THREE.MeshStandardMaterial({
color: 0x67e8f9,
emissive: 0x67e8f9,
emissiveIntensity: 0.7,
roughness: 0.28,
flatShading: true
})
);
massRing.rotation.x = Math.PI / 2;
const massHalo = new THREE.Mesh(
new THREE.RingGeometry(0.69, 0.72, 32),
new THREE.MeshBasicMaterial({
color: 0x67e8f9,
transparent: true,
opacity: 0.18,
side: THREE.DoubleSide
})
);
massHalo.rotation.x = -Math.PI / 2;
massHalo.position.y = -0.47;
massGroup.add(massMesh, massRing, massHalo);
scene.add(massGroup);
// -------------------------------------------------------------------------
// Motion trail
// -------------------------------------------------------------------------
const trailCapacity = 900;
const trailData = new Float32Array(trailCapacity * 3);
const trailGeometry = new THREE.BufferGeometry();
const trailAttribute = new THREE.BufferAttribute(trailData, 3);
trailAttribute.setUsage(THREE.DynamicDrawUsage);
trailGeometry.setAttribute("position", trailAttribute);
trailGeometry.setDrawRange(0, 0);
const trail = new THREE.Line(
trailGeometry,
new THREE.LineBasicMaterial({
color: 0x67e8f9,
transparent: true,
opacity: 0.65
})
);
trail.frustumCulled = false;
scene.add(trail);
let trailCount = 0;
function updateTrailGeometry() {
trailAttribute.array.set(trailData.subarray(0, trailCount * 3));
trailAttribute.needsUpdate = true;
trailGeometry.setDrawRange(0, trailCount);
}
function addTrailPoint(point) {
if (trailCount > 0) {
const index = (trailCount - 1) * 3;
const dx = point.x - trailData[index];
const dz = point.z - trailData[index + 2];
if (dx * dx + dz * dz < 0.0016) {
return;
}
}
if (trailCount >= trailCapacity) {
trailData.copyWithin(0, 3);
trailCount--;
}
const index = trailCount * 3;
trailData[index] = point.x;
trailData[index + 1] = 0.095;
trailData[index + 2] = point.z;
trailCount++;
updateTrailGeometry();
}
// -------------------------------------------------------------------------
// Physics and vector calculations
// -------------------------------------------------------------------------
function calculateForces() {
let resultX = 0;
let resultZ = 0;
const forces = [];
for (let i = 0; i < state.count; i++) {
const magnitude = state.magnitudes[i];
const radians = THREE.MathUtils.degToRad(state.angles[i]);
// Screen/diagram +Y is scene -Z.
const force = {
x: magnitude * Math.cos(radians),
z: -magnitude * Math.sin(radians),
magnitude,
angle: state.angles[i]
};
forces.push(force);
resultX += force.x;
resultZ += force.z;
}
const magnitude = Math.hypot(resultX, resultZ);
let direction = THREE.MathUtils.radToDeg(Math.atan2(-resultZ, resultX));
if (direction < 0) {
direction += 360;
}
state.forces = forces;
state.resultant.x = resultX;
state.resultant.z = resultZ;
state.resultant.magnitude = magnitude;
state.resultant.direction = direction;
state.acceleration.x = resultX / state.mass;
state.acceleration.z = resultZ / state.mass;
}
function syncReadout() {
calculateForces();
document.getElementById("resultMagnitude").textContent =
state.resultant.magnitude.toFixed(1);
document.getElementById("resultDirection").textContent =
`Direction ${Math.round(state.resultant.direction)}°`;
document.getElementById("acceleration").textContent =
`${Math.hypot(state.acceleration.x, state.acceleration.z).toFixed(2)} m/s²`;
document.getElementById("needle").style.transform =
`rotate(${-state.resultant.direction}deg)`;
const statePill = document.getElementById("statePill");
const equilibrium = state.resultant.magnitude < 0.05;
statePill.textContent = equilibrium ? "Equilibrium" : "Accelerating";
statePill.classList.toggle("equilibrium", equilibrium);
for (let i = 0; i < state.count; i++) {
setLabel(
forceLabels[i],
`F${forceSubscripts[i]} ${state.magnitudes[i].toFixed(1)} N`,
forceCssColors[i]
);
}
setLabel(
resultantLabel,
`R ${state.resultant.magnitude.toFixed(1)} N`,
"#f8d36d"
);
}
function updateVectorDiagram() {
const origin = massPosition.clone();
origin.y = 0.64;
for (let i = 0; i < state.count; i++) {
const force = state.forces[i];
const magnitude = force.magnitude;
if (magnitude < 0.01) {
forceArrows[i].group.visible = false;
forceLabels[i].visible = false;
continue;
}
forceLabels[i].visible = true;
const direction = new THREE.Vector3(
force.x / magnitude,
0,
force.z / magnitude
);
const length = magnitude * state.arrowScale;
setArrow(forceArrows[i], origin, direction, length);
const labelPosition = origin
.clone()
.addScaledVector(direction, length + 0.34);
labelPosition.y += 0.24;
forceLabels[i].position.copy(labelPosition);
}
for (let i = state.count; i < forceArrows.length; i++) {
forceArrows[i].group.visible = false;
forceLabels[i].visible = false;
}
if (state.resultant.magnitude > 0.01) {
const direction = new THREE.Vector3(
state.resultant.x / state.resultant.magnitude,
0,
state.resultant.z / state.resultant.magnitude
);
const length = state.resultant.magnitude * state.arrowScale;
setArrow(resultantArrow, origin, direction, length);
const labelPosition = origin
.clone()
.addScaledVector(direction, length + 0.55);
labelPosition.y += 0.55;
resultantLabel.position.copy(labelPosition);
resultantLabel.visible = true;
} else {
resultantArrow.group.visible = false;
resultantLabel.visible = false;
}
}
function resetMotion() {
state.position.x = 0;
state.position.z = 0;
state.velocity.x = 0;
state.velocity.z = 0;
massPosition.set(0, 0.56, 0);
massGroup.position.copy(massPosition);
trailCount = 0;
updateTrailGeometry();
addTrailPoint(massPosition);
}
// -------------------------------------------------------------------------
// Interface construction
// -------------------------------------------------------------------------
const forceControls = document.getElementById("forceControls");
for (let i = 0; i < 3; i++) {
const card = document.createElement("div");
card.className = "force-card";
card.id = `forceCard${i}`;
card.style.setProperty("--accent", forceCssColors[i]);
card.innerHTML = `
<div class="force-heading">
<span class="force-dot"></span>
<span>${forceNames[i]}</span>
<span>${i < 2 ? "plane XY" : "optional"}</span>
</div>
<div class="control">
<div class="control-label">
<span>Magnitude</span>
<output id="magnitudeOut${i}">${state.magnitudes[i].toFixed(1)} N</output>
</div>
<input
id="magnitude${i}"
type="range"
min="0"
max="25"
step="0.1"
value="${state.magnitudes[i]}"
aria-label="${forceNames[i]} magnitude"
/>
</div>
<div class="control">
<div class="control-label">
<span>Angle</span>
<output id="angleOut${i}">${state.angles[i]}°</output>
</div>
<input
id="angle${i}"
type="range"
min="0"
max="359"
step="1"
value="${state.angles[i]}"
aria-label="${forceNames[i]} angle"
/>
</div>
`;
forceControls.appendChild(card);
const magnitudeInput = card.querySelector(`#magnitude${i}`);
const angleInput = card.querySelector(`#angle${i}`);
const magnitudeOutput = card.querySelector(`#magnitudeOut${i}`);
const angleOutput = card.querySelector(`#angleOut${i}`);
paintRange(magnitudeInput);
paintRange(angleInput);
magnitudeInput.addEventListener("input", () => {
state.magnitudes[i] = Number(magnitudeInput.value);
magnitudeOutput.textContent = `${state.magnitudes[i].toFixed(1)} N`;
paintRange(magnitudeInput);
syncReadout();
});
angleInput.addEventListener("input", () => {
state.angles[i] = Number(angleInput.value);
angleOutput.textContent = `${state.angles[i]}°`;
paintRange(angleInput);
syncReadout();
});
}
function paintRange(input) {
const minimum = Number(input.min);
const maximum = Number(input.max);
const value = Number(input.value);
const percent = ((value - minimum) / (maximum - minimum)) * 100;
input.style.setProperty("--fill", `${percent}%`);
}
document.querySelectorAll("[data-count]").forEach((button) => {
button.addEventListener("click", () => {
state.count = Number(button.dataset.count);
document.querySelectorAll("[data-count]").forEach((item) => {
const active = Number(item.dataset.count) === state.count;
item.classList.toggle("active", active);
item.setAttribute("aria-pressed", String(active));
});
for (let i = 0; i < 3; i++) {
document.getElementById(`forceCard${i}`).hidden = i >= state.count;
}
syncReadout();
});
});
function bindSimpleControl({
id,
outputId,
property,
format,
onChange
}) {
const input = document.getElementById(id);
const output = document.getElementById(outputId);
paintRange(input);
input.addEventListener("input", () => {
state[property] = Number(input.value);
output.textContent = format(state[property]);
paintRange(input);
if (onChange) onChange();
});
input.addEventListener("change", () => {
if (onChange) onChange();
});
}
bindSimpleControl({
id: "mass",
outputId: "massOut",
property: "mass",
format: (value) => `${value.toFixed(1)} kg`,
onChange: syncReadout
});
bindSimpleControl({
id: "arrowScale",
outputId: "arrowScaleOut",
property: "arrowScale",
format: (value) => `${value.toFixed(2)} scene/N`
});
bindSimpleControl({
id: "motionScale",
outputId: "motionScaleOut",
property: "motionScale",
format: (value) => `${value.toFixed(3)} scene/m`,
onChange: resetMotion
});
bindSimpleControl({
id: "timeScale",
outputId: "timeScaleOut",
property: "timeScale",
format: (value) => `${value.toFixed(2)}×`
});
bindSimpleControl({
id: "damping",
outputId: "dampingOut",
property: "damping",
format: (value) => `${value.toFixed(2)} s⁻¹`
});
const pauseButton = document.getElementById("pauseButton");
pauseButton.addEventListener("click", () => {
state.running = !state.running;
pauseButton.textContent = state.running ? "Pause motion" : "Resume motion";
});
document.getElementById("resetMotion").addEventListener("click", resetMotion);
document.getElementById("resetView").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Direct camera controls — no external examples or addons
// -------------------------------------------------------------------------
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.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraState.yaw -= deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - deltaY * 0.005,
0.28,
1.38
);
updateCamera();
});
function stopDragging(event) {
dragging = false;
renderer.domElement.style.cursor = "grab";
if (event && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener("pointerleave", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7,
31
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.style.cursor = "grab";
// -------------------------------------------------------------------------
// Animation and simulation
// -------------------------------------------------------------------------
let previousTime = performance.now();
function animate(time) {
requestAnimationFrame(animate);
const deltaTime = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
if (state.running) {
const simulationDelta = deltaTime * state.timeScale;
state.velocity.x += state.acceleration.x * simulationDelta;
state.velocity.z += state.acceleration.z * simulationDelta;
const dampingFactor = Math.exp(-state.damping * simulationDelta);
state.velocity.x *= dampingFactor;
state.velocity.z *= dampingFactor;
state.position.x += state.velocity.x * simulationDelta;
state.position.z += state.velocity.z * simulationDelta;
}
// Physical state is stored in meters. Only this presentation mapping uses
// motionScale; it does not affect the arrow diagram or scene dimensions.
massPosition.set(
state.position.x * state.motionScale,
0.56,
state.position.z * state.motionScale
);
massGroup.position.copy(massPosition);
massMesh.rotation.x += deltaTime * 0.18;
massMesh.rotation.y += deltaTime * 0.32;
massRing.rotation.z += deltaTime * 0.45;
massHalo.material.opacity = 0.15 + Math.sin(time * 0.0025) * 0.04;
addTrailPoint(massPosition);
updateVectorDiagram();
const speed = Math.hypot(state.velocity.x, state.velocity.z);
const distance = Math.hypot(state.position.x, state.position.z);
document.getElementById("speed").textContent = `${speed.toFixed(2)} m/s`;
document.getElementById("distance").textContent = `${distance.toFixed(2)} m`;
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
resetMotion();
syncReadout();
requestAnimationFrame(animate);
</script>
</body>
</html>
```