Prompt specification
Build or customize the Three.js 3D scene "Support-polygon balance 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: Support-polygon balance sandbox
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/support-polygon-balance-sandbox-x1000
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing human stance and hip balance. Let viewers move a simplified figure's mass marker and foot positions; show whether the projected marker lies inside the stated static support region under explicit toy assumptions. Low-poly.
Working Three.js Starter (support-polygon-balance-sandbox-x1000):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hip / Base Balance Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #08111f;
--panel: rgba(13, 25, 43, 0.86);
--line: rgba(157, 189, 222, 0.19);
--text: #e5eef9;
--muted: #9db0c8;
--cyan: #4ee7d5;
--green: #45e3a4;
--red: #ff647c;
--amber: #f5bd62;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
appearance: none;
border: 1px solid rgba(157, 189, 222, 0.25);
border-radius: 9px;
padding: 8px 11px;
color: var(--text);
background: rgba(255, 255, 255, 0.055);
cursor: pointer;
font: inherit;
font-size: 12px;
transition:
background 120ms ease,
border-color 120ms ease,
transform 120ms ease;
}
button:hover {
background: rgba(78, 231, 213, 0.12);
border-color: rgba(78, 231, 213, 0.55);
}
button:active {
transform: translateY(1px);
}
#app {
position: fixed;
inset: 0;
}
#app canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 16px 45px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
}
#brand {
top: 18px;
left: 18px;
width: min(470px, calc(100vw - 36px));
padding: 17px 18px 15px;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 4px;
font-size: clamp(21px, 3vw, 29px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 13px;
}
.actions button.primary {
color: #05201d;
border-color: transparent;
background: var(--cyan);
font-weight: 750;
}
#model-card {
top: 18px;
right: 18px;
width: 370px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 17px 18px;
}
#model-card h2,
#readout h2 {
margin: 0 0 8px;
font-size: 14px;
letter-spacing: -0.01em;
}
#model-card p,
#model-card li {
color: var(--muted);
font-size: 12px;
line-height: 1.52;
}
#model-card p {
margin: 7px 0 10px;
}
#model-card ul {
margin: 0;
padding-left: 18px;
}
#model-card li {
margin: 7px 0;
}
.rule {
margin-top: 12px !important;
padding: 10px 11px;
border: 1px solid rgba(78, 231, 213, 0.22);
border-radius: 10px;
color: #c9f8f1 !important;
background: rgba(78, 231, 213, 0.065);
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 12px;
color: var(--muted);
font-size: 11px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 50%;
}
.swatch.cyan {
background: var(--cyan);
}
.swatch.amber {
background: var(--amber);
}
.swatch.region {
border-radius: 2px;
background: rgba(78, 231, 213, 0.3);
border: 1px solid var(--cyan);
}
#readout {
left: 18px;
bottom: 18px;
width: 360px;
padding: 15px 16px;
}
#verdict {
display: inline-block;
margin-bottom: 9px;
padding: 6px 9px;
border: 1px solid currentColor;
border-radius: 999px;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.08em;
}
#verdict.inside {
color: var(--green);
background: rgba(69, 227, 164, 0.08);
}
#verdict.outside {
color: var(--red);
background: rgba(255, 100, 124, 0.08);
}
#verdict.marginal {
color: #ffd071;
background: rgba(255, 208, 113, 0.08);
}
#status-detail {
min-height: 36px;
margin: 0 0 12px;
color: var(--muted);
font-size: 12px;
line-height: 1.48;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
padding: 8px 9px;
border: 1px solid rgba(157, 189, 222, 0.13);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
}
.metric-label {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.metric-value {
margin-top: 3px;
font-variant-numeric: tabular-nums;
font-size: 13px;
font-weight: 700;
}
#help {
right: 18px;
bottom: 18px;
max-width: 430px;
padding: 11px 13px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
#help strong {
color: var(--text);
}
.key {
display: inline-block;
padding: 1px 5px;
border: 1px solid rgba(157, 189, 222, 0.25);
border-radius: 4px;
color: var(--text);
background: rgba(255, 255, 255, 0.04);
font-size: 10px;
}
@media (max-width: 900px) {
#brand {
width: calc(100vw - 36px);
}
#model-card {
top: 166px;
right: 12px;
width: min(350px, calc(100vw - 24px));
max-height: 39vh;
}
#readout {
left: 12px;
bottom: 12px;
width: min(350px, calc(100vw - 24px));
}
#help {
display: none;
}
}
@media (max-width: 560px) {
#brand {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
}
#model-card {
top: 174px;
right: 10px;
width: calc(100vw - 20px);
}
#readout {
left: 10px;
bottom: 10px;
width: calc(100vw - 20px);
}
.metric {
padding: 6px 8px;
}
}
</style>
</</head>
<body>
<div id="app"></div>
<section id="brand" class="panel">
<div class="eyebrow">Interactive mechanics toy</div>
<h1>Hip / Base Balance Lab</h1>
<p class="subtitle">
Move the whole-body mass marker and reposition either foot.
The floor marker shows where gravity acts through the mass marker.
</p>
<div class="actions">
<button id="reset" class="primary">Reset stance</button>
<button id="narrow">Narrow stance</button>
<button id="wide">Wide stance</button>
<button id="unstable">Unstable example</button>
<button id="reset-camera">Reset camera</button>
</div>
</section>
<aside id="model-card" class="panel">
<div class="eyebrow">Explicit toy assumptions</div>
<h2>Static support model</h2>
<ul>
<li>Gravity is vertical; the floor is level; there is no acceleration.</li>
<li>The cyan marker represents the whole-body center of mass.</li>
<li>Each amber foot has a fixed rectangular contact patch on the floor.</li>
<li>
The <strong>stated support region</strong> is the convex hull of the
two rectangular foot-contact patches.
</li>
<li>
The marker is projected vertically onto the floor. Inside means a
toy static balance solution exists; on the edge is marginal.
</li>
<li>
No pressure distribution, friction limit, joint torque, perturbation,
or dynamic stability is modeled. Limb reach clamps are editing aids.
</li>
</ul>
<p class="rule">
<strong>Toy rule:</strong>
projected marker ∈ support region ⇒ statically supportable.
Outside ⇒ not statically supportable under these assumptions.
</p>
<div class="legend">
<span><i class="swatch cyan"></i>Mass marker / projection</span>
<span><i class="swatch amber"></i>Foot and contact patch</span>
<span><i class="swatch region"></i>Support region</span>
</div>
</aside>
<section id="readout" class="panel">
<div id="verdict" class="inside">INSIDE STATIC SUPPORT</div>
<p id="status-detail"></p>
<div class="metrics">
<div class="metric">
<div class="metric-label">Projection x, z</div>
<div id="projection-value" class="metric-value">0.00, 0.00</div>
</div>
<div class="metric">
<div class="metric-label">Edge clearance</div>
<div id="clearance-value" class="metric-value">0.00 u</div>
</div>
<div class="metric">
<div class="metric-label">Support area</div>
<div id="area-value" class="metric-value">0.00 u²</div>
</div>
<div class="metric">
<div class="metric-label">Foot separation</div>
<div id="separation-value" class="metric-value">0.00 u</div>
</div>
</div>
</section>
<div id="help" class="panel">
<strong>Controls:</strong>
drag the cyan marker or amber feet to edit the stance.
Drag empty space to orbit; scroll to zoom.
<span class="key">R</span> reset stance ·
<span class="key">C</span> reset camera.
</div>
<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 app = document.getElementById("app");
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08111f);
scene.fog = new THREE.Fog(0x08111f, 10, 25);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
theta: 0.72,
phi: 0.98,
radius: 6.4,
target: new THREE.Vector3(0, 1.15, 0)
};
function updateCamera() {
const { theta, phi, radius, target } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
target.x + radius * sinPhi * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * sinPhi * Math.cos(theta)
);
camera.lookAt(target);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xc8e6ff, 0x263342, 1.65);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.5);
keyLight.position.set(4, 7, 5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -5;
keyLight.shadow.camera.right = 5;
keyLight.shadow.camera.top = 5;
keyLight.shadow.camera.bottom = -5;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 18;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x53d9d0, 1.15);
rimLight.position.set(-4, 3, -4);
scene.add(rimLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({
color: 0x0e1a2b,
roughness: 0.96,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(16, 32, 0x31506a, 0x1b3045);
grid.position.y = 0.012;
grid.material.transparent = true;
grid.material.opacity = 0.62;
scene.add(grid);
// -------------------------------------------------------------------------
// Shared geometry/material helpers
// -------------------------------------------------------------------------
const yAxis = new THREE.Vector3(0, 1, 0);
function makeLabel(text, color = "#dce9f7", scale = 0.8) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 64;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(7, 15, 27, 0.78)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = color;
ctx.lineWidth = 3;
ctx.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
ctx.fillStyle = color;
ctx.font = "700 25px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(scale, scale * 0.25, 1);
sprite.renderOrder = 20;
return sprite;
}
function setSegment(mesh, a, b) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = Math.max(direction.length(), 0.0001);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(yAxis, direction.normalize());
mesh.scale.set(1, length, 1);
}
function makeLimb(radius, material) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius * 1.08, 1, 6),
material
);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
// -------------------------------------------------------------------------
// State
// -------------------------------------------------------------------------
const COM_HEIGHT = 1.48;
const FOOT_WIDTH = 0.46;
const FOOT_LENGTH = 0.88;
const MAX_HORIZONTAL_REACH = 1.02;
const markerPosition = new THREE.Vector3(0, COM_HEIGHT, 0);
const feet = [
{ x: -0.43, z: 0, group: null, body: null, label: null },
{ x: 0.43, z: 0, group: null, body: null, label: null }
];
const pickables = [];
// -------------------------------------------------------------------------
// Feet and contact patches
// -------------------------------------------------------------------------
function createFoot(foot, index) {
const group = new THREE.Group();
const footMaterial = new THREE.MeshStandardMaterial({
color: index === 0 ? 0xd59645 : 0xe3a956,
emissive: 0x4b2c08,
emissiveIntensity: 0.16,
roughness: 0.76,
metalness: 0.02,
flatShading: true
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(0.43, 0.20, 0.82),
footMaterial
);
body.position.y = 0.13;
body.castShadow = true;
body.receiveShadow = true;
body.userData.dragType = "foot";
body.userData.footIndex = index;
group.add(body);
const contactMaterial = new THREE.MeshBasicMaterial({
color: 0xf5bd62,
transparent: true,
opacity: 0.18,
side: THREE.DoubleSide,
depthWrite: false
});
const contact = new THREE.Mesh(
new THREE.PlaneGeometry(FOOT_WIDTH, FOOT_LENGTH),
contactMaterial
);
contact.rotation.x = -Math.PI / 2;
contact.position.y = 0.034;
group.add(contact);
const corners = [
new THREE.Vector3(-FOOT_WIDTH / 2, 0.044, -FOOT_LENGTH / 2),
new THREE.Vector3(FOOT_WIDTH / 2, 0.044, -FOOT_LENGTH / 2),
new THREE.Vector3(FOOT_WIDTH / 2, 0.044, FOOT_LENGTH / 2),
new THREE.Vector3(-FOOT_WIDTH / 2, 0.044, FOOT_LENGTH / 2)
];
const outline = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(corners),
new THREE.LineBasicMaterial({
color: 0xf5bd62,
transparent: true,
opacity: 0.95
})
);
group.add(outline);
const label = makeLabel(index === 0 ? "LEFT FOOT" : "RIGHT FOOT", "#f5bd62", 1.02);
label.position.set(0, 0.62, 0);
group.add(label);
foot.group = group;
foot.body = body;
foot.label = label;
group.position.set(foot.x, 0, foot.z);
scene.add(group);
pickables.push(body);
}
createFoot(feet[0], 0);
createFoot(feet[1], 1);
// -------------------------------------------------------------------------
// Low-poly figure
// -------------------------------------------------------------------------
const bodyGroup = new THREE.Group();
scene.add(bodyGroup);
const torsoMaterial = new THREE.MeshStandardMaterial({
color: 0x8297b4,
roughness: 0.82,
metalness: 0.02,
flatShading: true
});
const limbMaterial = new THREE.MeshStandardMaterial({
color: 0x536a88,
roughness: 0.88,
metalness: 0.01,
flatShading: true
});
const jointMaterial = new THREE.MeshStandardMaterial({
color: 0x314962,
roughness: 0.85,
flatShading: true
});
const pelvis = new THREE.Mesh(
new THREE.BoxGeometry(0.58, 0.28, 0.34),
torsoMaterial
);
pelvis.position.set(0, 1.45, -0.04);
pelvis.castShadow = true;
bodyGroup.add(pelvis);
const torso = new THREE.Mesh(
new THREE.CylinderGeometry(0.31, 0.38, 0.76, 6),
torsoMaterial
);
torso.position.set(0, 1.94, -0.04);
torso.castShadow = true;
bodyGroup.add(torso);
const neck = new THREE.Mesh(
new THREE.CylinderGeometry(0.105, 0.115, 0.22, 7),
jointMaterial
);
neck.position.set(0, 2.38, -0.04);
neck.castShadow = true;
bodyGroup.add(neck);
const head = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.235, 0),
new THREE.MeshStandardMaterial({
color: 0xc3d0de,
roughness: 0.86,
flatShading: true
})
);
head.position.set(0, 2.61, -0.025);
head.castShadow = true;
bodyGroup.add(head);
const armSegments = [];
for (const side of [-1, 1]) {
const shoulder = new THREE.Vector3(side * 0.31, 2.17, -0.04);
const elbow = new THREE.Vector3(side * 0.58, 1.72, 0.01);
const hand = new THREE.Vector3(side * 0.72, 1.40, 0.16);
const upperArm = makeLimb(0.075, limbMaterial);
const lowerArm = makeLimb(0.066, limbMaterial);
const handMesh = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.09, 0),
jointMaterial
);
setSegment(upperArm, shoulder, elbow);
setSegment(lowerArm, elbow, hand);
handMesh.position.copy(hand);
bodyGroup.add(upperArm, lowerArm, handMesh);
armSegments.push(upperArm, lowerArm);
}
const upperLegs = [
makeLimb(0.105, limbMaterial),
makeLimb(0.105, limbMaterial)
];
const lowerLegs = [
makeLimb(0.09, limbMaterial),
makeLimb(0.09, limbMaterial)
];
const knees = [
new THREE.Mesh(new THREE.IcosahedronGeometry(0.115, 0), jointMaterial),
new THREE.Mesh(new THREE.IcosahedronGeometry(0.115, 0), jointMaterial)
];
for (const mesh of [...upperLegs, ...lowerLegs, ...knees]) {
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
}
// -------------------------------------------------------------------------
// Center-of-mass marker and floor projection
// -------------------------------------------------------------------------
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0x4ee7d5,
emissive: 0x0b756c,
emissiveIntensity: 0.85,
roughness: 0.3,
metalness: 0.08,
flatShading: true
});
const markerGroup = new THREE.Group();
const markerMesh = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.22, 0),
markerMaterial
);
markerMesh.castShadow = true;
markerMesh.userData.dragType = "marker";
markerGroup.add(markerMesh);
pickables.push(markerMesh);
const markerWire = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.247, 0),
new THREE.MeshBasicMaterial({
color: 0x9ffff2,
wireframe: true,
transparent: true,
opacity: 0.65,
depthTest: false
})
);
markerWire.renderOrder = 15;
markerGroup.add(markerWire);
const markerLabel = makeLabel("MASS MARKER", "#9ffff2", 1.12);
markerLabel.position.set(0, 0.48, 0);
markerGroup.add(markerLabel);
scene.add(markerGroup);
const projectionLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, COM_HEIGHT, 0),
new THREE.Vector3(0, 0.065, 0)
]),
new THREE.LineDashedMaterial({
color: 0x4ee7d5,
dashSize: 0.085,
gapSize: 0.055,
transparent: true,
opacity: 0.95
})
);
projectionLine.computeLineDistances();
scene.add(projectionLine);
const projectionDisc = new THREE.Mesh(
new THREE.CircleGeometry(0.105, 24),
new THREE.MeshBasicMaterial({
color: 0x4ee7d5,
transparent: true,
opacity: 0.9,
depthTest: false,
depthWrite: false
})
);
projectionDisc.rotation.x = -Math.PI / 2;
projectionDisc.renderOrder = 12;
scene.add(projectionDisc);
const projectionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.145, 0.024, 8, 32),
new THREE.MeshBasicMaterial({
color: 0x4ee7d5,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
})
);
projectionRing.rotation.x = Math.PI / 2;
projectionRing.renderOrder = 13;
scene.add(projectionRing);
// -------------------------------------------------------------------------
// Support region
// -------------------------------------------------------------------------
const supportFill = new THREE.Mesh(
new THREE.BufferGeometry(),
new THREE.MeshBasicMaterial({
color: 0x2dd4bf,
transparent: true,
opacity: 0.14,
side: THREE.DoubleSide,
depthWrite: false
})
);
supportFill.renderOrder = 3;
scene.add(supportFill);
const supportEdge = new THREE.LineLoop(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: 0x62f3df,
transparent: true,
opacity: 0.95
})
);
supportEdge.renderOrder = 5;
scene.add(supportEdge);
const supportLabel = makeLabel("STATED SUPPORT REGION", "#62f3df", 1.55);
scene.add(supportLabel);
const nearestEdgeLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: 0x45e3a4,
transparent: true,
opacity: 0.9
})
);
scene.add(nearestEdgeLine);
const nearestPoint = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.05, 0),
new THREE.MeshBasicMaterial({ color: 0x45e3a4 })
);
scene.add(nearestPoint);
let supportHull = [];
// -------------------------------------------------------------------------
// Convex geometry helpers
// -------------------------------------------------------------------------
function cross2(a, b, c) {
return (
(b.x - a.x) * (c.z - a.z) -
(b.z - a.z) * (c.x - a.x)
);
}
function convexHull(points) {
const unique = [];
const seen = new Set();
for (const p of points) {
const key = `${p.x.toFixed(5)},${p.z.toFixed(5)}`;
if (!seen.has(key)) {
seen.add(key);
unique.push({ x: p.x, z: p.z });
}
}
unique.sort((a, b) => a.x - b.x || a.z - b.z);
if (unique.length <= 2) return unique;
const lower = [];
for (const p of unique) {
while (
lower.length >= 2 &&
cross2(lower[lower.length - 2], lower[lower.length - 1], p) <= 0
) {
lower.pop();
}
lower.push(p);
}
const upper = [];
for (let i = unique.length - 1; i >= 0; i--) {
const p = unique[i];
while (
upper.length >= 2 &&
cross2(upper[upper.length - 2], upper[upper.length - 1], p) <= 0
) {
upper.pop();
}
upper.push(p);
}
lower.pop();
upper.pop();
return lower.concat(upper);
}
function polygonArea(polygon) {
let area = 0;
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
area += a.x * b.z - b.x * a.z;
}
return Math.abs(area) * 0.5;
}
function pointInsideConvexPolygon(polygon, point) {
if (polygon.length < 3) return false;
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
const cross =
(b.x - a.x) * (point.z - a.z) -
(b.z - a.z) * (point.x - a.x);
if (cross < -1e-7) return false;
}
return true;
}
function distanceToSegment(point, a, b) {
const dx = b.x - a.x;
const dz = b.z - a.z;
const lengthSquared = dx * dx + dz * dz;
if (lengthSquared < 1e-12) {
return {
distance: Math.hypot(point.x - a.x, point.z - a.z),
point: { x: a.x, z: a.z }
};
}
const t = THREE.MathUtils.clamp(
((point.x - a.x) * dx + (point.z - a.z) * dz) /
lengthSquared,
0,
1
);
const closest = {
x: a.x + t * dx,
z: a.z + t * dz
};
return {
distance: Math.hypot(point.x - closest.x, point.z - closest.z),
point: closest
};
}
function signedDistanceToPolygon(polygon, point) {
let minDistance = Infinity;
let closest = null;
for (let i = 0; i < polygon.length; i++) {
const result = distanceToSegment(
point,
polygon[i],
polygon[(i + 1) % polygon.length]
);
if (result.distance < minDistance) {
minDistance = result.distance;
closest = result.point;
}
}
const inside = pointInsideConvexPolygon(polygon, point);
return {
distance: inside ? minDistance : -minDistance,
closest
};
}
function updateSupportGeometry() {
const corners = [];
for (const foot of feet) {
corners.push(
{ x: foot.x - FOOT_WIDTH / 2, z: foot.z - FOOT_LENGTH / 2 },
{ x: foot.x + FOOT_WIDTH / 2, z: foot.z - FOOT_LENGTH / 2 },
{ x: foot.x + FOOT_WIDTH / 2, z: foot.z + FOOT_LENGTH / 2 },
{ x: foot.x - FOOT_WIDTH / 2, z: foot.z + FOOT_LENGTH / 2 }
);
}
supportHull = convexHull(corners);
const shape = new THREE.Shape();
supportHull.forEach((p, index) => {
if (index === 0) shape.moveTo(p.x, p.z);
else shape.lineTo(p.x, p.z);
});
shape.closePath();
const fillGeometry = new THREE.ShapeGeometry(shape);
fillGeometry.rotateX(Math.PI / 2);
supportFill.geometry.dispose();
supportFill.geometry = fillGeometry;
const edgePoints = supportHull.map(
(p) => new THREE.Vector3(p.x, 0.065, p.z)
);
supportEdge.geometry.dispose();
supportEdge.geometry = new THREE.BufferGeometry().setFromPoints(edgePoints);
if (supportHull.length) {
const center = supportHull.reduce(
(sum, p) => ({ x: sum.x + p.x, z: sum.z + p.z }),
{ x: 0, z: 0 }
);
supportLabel.position.set(
center.x / supportHull.length,
0.13,
center.z / supportHull.length
);
}
}
// -------------------------------------------------------------------------
// Leg inverse kinematics
// -------------------------------------------------------------------------
const UPPER_LEG_LENGTH = 0.88;
const LOWER_LEG_LENGTH = 0.92;
function solveKnee(hip, ankle) {
const direction = new THREE.Vector3().subVectors(ankle, hip);
const distance = THREE.MathUtils.clamp(
direction.length(),
Math.abs(UPPER_LEG_LENGTH - LOWER_LEG_LENGTH) + 0.001,
UPPER_LEG_LENGTH + LOWER_LEG_LENGTH - 0.001
);
direction.normalize();
const along =
(UPPER_LEG_LENGTH * UPPER_LEG_LENGTH -
LOWER_LEG_LENGTH * LOWER_LEG_LENGTH +
distance * distance) /
(2 * distance);
const height = Math.sqrt(
Math.max(0, UPPER_LEG_LENGTH * UPPER_LEG_LENGTH - along * along)
);
const alongPoint = hip.clone().addScaledVector(direction, along);
const forward = new THREE.Vector3(0, 0, 1);
const bend = forward
.clone()
.addScaledVector(direction, -forward.dot(direction));
if (bend.lengthSq() < 1e-8) {
bend.set(1, 0, 0);
bend.addScaledVector(direction, -bend.dot(direction));
}
bend.normalize();
return alongPoint.addScaledVector(bend, height);
}
function updateFigure() {
markerGroup.position.copy(markerPosition);
bodyGroup.position.set(
markerPosition.x,
0,
markerPosition.z - 0.14
);
for (let i = 0; i < feet.length; i++) {
const foot = feet[i];
foot.group.position.set(foot.x, 0, foot.z);
const hip = new THREE.Vector3(
markerPosition.x + (i === 0 ? -0.18 : 0.18),
1.47,
markerPosition.z - 0.14
);
const ankle = new THREE.Vector3(
foot.x,
0.28,
foot.z - 0.14
);
const knee = solveKnee(hip, ankle);
setSegment(upperLegs[i], hip, knee);
setSegment(lowerLegs[i], knee, ankle);
knees[i].position.copy(knee);
}
}
function updateProjection() {
projectionLine.geometry.setFromPoints([
new THREE.Vector3(markerPosition.x, COM_HEIGHT, markerPosition.z),
new THREE.Vector3(markerPosition.x, 0.065, markerPosition.z)
]);
projectionLine.computeLineDistances();
projectionDisc.position.set(markerPosition.x, 0.073, markerPosition.z);
projectionRing.position.set(markerPosition.x, 0.078, markerPosition.z);
}
// -------------------------------------------------------------------------
// Status readout
// -------------------------------------------------------------------------
const verdictElement = document.getElementById("verdict");
const statusDetailElement = document.getElementById("status-detail");
const projectionValue = document.getElementById("projection-value");
const clearanceValue = document.getElementById("clearance-value");
const areaValue = document.getElementById("area-value");
const separationValue = document.getElementById("separation-value");
function updateStatus() {
const projection = {
x: markerPosition.x,
z: markerPosition.z
};
const inside = pointInsideConvexPolygon(supportHull, projection);
const edge = signedDistanceToPolygon(supportHull, projection);
const marginal = inside && edge.distance < 0.035;
let statusColor = 0xff647c;
let statusClass = "outside";
if (inside) {
statusColor = 0x45e3a4;
statusClass = "inside";
}
if (marginal) {
statusColor = 0xffd071;
statusClass = "marginal";
}
markerMaterial.color.setHex(statusColor);
markerMaterial.emissive.setHex(statusColor).multiplyScalar(0.28);
markerWire.material.color.setHex(statusColor);
projectionDisc.material.color.setHex(statusColor);
projectionRing.material.color.setHex(statusColor);
projectionLine.material.color.setHex(statusColor);
nearestEdgeLine.material.color.setHex(statusColor);
nearestPoint.material.color.setHex(statusColor);
if (marginal) {
verdictElement.textContent = "MARGINAL — ON SUPPORT EDGE";
verdictElement.className = "marginal";
statusDetailElement.textContent =
"The gravity projection is on the boundary of the stated support region, so the toy model has zero edge margin.";
} else if (inside) {
verdictElement.textContent = "INSIDE STATIC SUPPORT";
verdictElement.className = "inside";
statusDetailElement.textContent =
"The vertical gravity line falls inside the foot-contact hull. A toy static balance solution exists.";
} else {
verdictElement.textContent = "OUTSIDE STATIC SUPPORT";
verdictElement.className = "outside";
statusDetailElement.textContent =
"The gravity line misses the foot-contact hull. Under the stated toy rule, this stance has no static support.";
}
projectionValue.textContent =
`${markerPosition.x.toFixed(2)}, ${markerPosition.z.toFixed(2)}`;
clearanceValue.textContent =
`${edge.distance >= 0 ? "+" : ""}${edge.distance.toFixed(2)} u`;
areaValue.textContent = `${polygonArea(supportHull).toFixed(2)} u²`;
separationValue.textContent =
`${Math.hypot(
feet[0].x - feet[1].x,
feet[0].z - feet[1].z
).toFixed(2)} u`;
if (edge.closest) {
nearestEdgeLine.geometry.dispose();
nearestEdgeLine.geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(markerPosition.x, 0.09, markerPosition.z),
new THREE.Vector3(edge.closest.x, 0.09, edge.closest.z)
]);
nearestPoint.position.set(edge.closest.x, 0.095, edge.closest.z);
}
}
function updateAll() {
updateSupportGeometry();
updateFigure();
updateProjection();
updateStatus();
}
// -------------------------------------------------------------------------
// Reach constraints
// -------------------------------------------------------------------------
function constrainMarker(x, z) {
for (let iteration = 0; iteration < 4; iteration++) {
for (const foot of feet) {
const dx = x - foot.x;
const dz = z - foot.z;
const distance = Math.hypot(dx, dz);
if (distance > MAX_HORIZONTAL_REACH) {
const scale = MAX_HORIZONTAL_REACH / distance;
x = foot.x + dx * scale;
z = foot.z + dz * scale;
}
}
}
return { x, z };
}
function constrainFoot(index, x, z) {
const other = feet[1 - index];
for (let iteration = 0; iteration < 4; iteration++) {
const markerDx = x - markerPosition.x;
const markerDz = z - markerPosition.z;
const markerDistance = Math.hypot(markerDx, markerDz);
if (markerDistance > MAX_HORIZONTAL_REACH) {
const scale = MAX_HORIZONTAL_REACH / markerDistance;
x = markerPosition.x + markerDx * scale;
z = markerPosition.z + markerDz * scale;
}
const pairDx = x - other.x;
const pairDz = z - other.z;
const pairDistance = Math.hypot(pairDx, pairDz);
const maxPairDistance = MAX_HORIZONTAL_REACH * 2;
if (pairDistance > maxPairDistance) {
const scale = maxPairDistance / pairDistance;
x = other.x + pairDx * scale;
z = other.z + pairDz * scale;
}
}
return { x, z };
}
function setMarker(x, z) {
const constrained = constrainMarker(x, z);
markerPosition.x = constrained.x;
markerPosition.z = constrained.z;
updateAll();
}
function setFoot(index, x, z) {
const constrained = constrainFoot(index, x, z);
feet[index].x = constrained.x;
feet[index].z = constrained.z;
updateAll();
}
// -------------------------------------------------------------------------
// Direct manipulation: dragging and custom camera controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
let dragState = null;
let orbitState = null;
let hoveredObject = null;
function setPointerFromEvent(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 groundHit(event) {
setPointerFromEvent(event);
return raycaster.ray.intersectPlane(groundPlane, new THREE.Vector3());
}
function pickInteractive(event) {
setPointerFromEvent(event);
const hits = raycaster.intersectObjects(pickables, false);
return hits.length ? hits[0].object : null;
}
function setHover(object) {
if (hoveredObject === object) return;
if (
hoveredObject?.userData.dragType === "foot"
) {
hoveredObject.material.emissiveIntensity = 0.16;
}
hoveredObject = object;
if (object?.userData.dragType === "foot") {
object.material.emissiveIntensity = 0.65;
}
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
const object = event.button === 0 ? pickInteractive(event) : null;
if (object) {
const hit = groundHit(event);
if (!hit) return;
const dragType = object.userData.dragType;
const current =
dragType === "marker"
? markerPosition
: feet[object.userData.footIndex];
dragState = {
type: dragType,
footIndex: object.userData.footIndex,
offsetX: current.x - hit.x,
offsetZ: current.z - hit.z
};
renderer.domElement.style.cursor = "grabbing";
} else {
orbitState = {
x: event.clientX,
y: event.clientY
};
renderer.domElement.style.cursor = "grabbing";
}
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (dragState) {
const hit = groundHit(event);
if (!hit) return;
const x = hit.x + dragState.offsetX;
const z = hit.z + dragState.offsetZ;
if (dragState.type === "marker") {
setMarker(x, z);
} else {
setFoot(dragState.footIndex, x, z);
}
return;
}
if (orbitState) {
const dx = event.clientX - orbitState.x;
const dy = event.clientY - orbitState.y;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.005,
0.35,
1.38
);
orbitState.x = event.clientX;
orbitState.y = event.clientY;
updateCamera();
return;
}
const object = pickInteractive(event);
setHover(object);
renderer.domElement.style.cursor = object ? "grab" : "default";
});
function endPointerInteraction(event) {
dragState = null;
orbitState = null;
renderer.domElement.style.cursor = hoveredObject ? "grab" : "default";
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointerInteraction);
renderer.domElement.addEventListener("pointercancel", endPointerInteraction);
renderer.domElement.addEventListener("pointerleave", () => {
if (!dragState && !orbitState) setHover(null);
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.0035,
4.2,
11
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Presets and UI actions
// -------------------------------------------------------------------------
function resetCamera() {
cameraState.theta = 0.72;
cameraState.phi = 0.98;
cameraState.radius = 6.4;
cameraState.target.set(0, 1.15, 0);
updateCamera();
}
function resetStance() {
markerPosition.set(0, COM_HEIGHT, 0);
feet[0].x = -0.43;
feet[0].z = 0;
feet[1].x = 0.43;
feet[1].z = 0;
updateAll();
}
function narrowStance() {
markerPosition.set(0, COM_HEIGHT, 0);
feet[0].x = -0.25;
feet[0].z = 0;
feet[1].x = 0.25;
feet[1].z = 0;
updateAll();
}
function wideStance() {
markerPosition.set(0, COM_HEIGHT, 0);
feet[0].x = -0.70;
feet[0].z = 0;
feet[1].x = 0.70;
feet[1].z = 0;
updateAll();
}
function unstableExample() {
markerPosition.set(0.52, COM_HEIGHT, 0);
feet[0].x = -0.42;
feet[0].z = 0;
feet[1].x = 0.08;
feet[1].z = 0;
updateAll();
}
document.getElementById("reset").addEventListener("click", resetStance);
document.getElementById("narrow").addEventListener("click", narrowStance);
document.getElementById("wide").addEventListener("click", wideStance);
document.getElementById("unstable").addEventListener(
"click",
unstableExample
);
document.getElementById("reset-camera").addEventListener(
"click",
resetCamera
);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") resetStance();
if (event.key.toLowerCase() === "c") resetCamera();
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
updateAll();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```