Prompt specification
Build or customize the Three.js 3D scene "Chopping size comparison" 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: Chopping size comparison
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/chopping-size-comparison-x0118
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this low-poly scene: Animate a stylized knife passing over herb leaves in several safe display steps; the resulting pieces become smaller while an approximate total-area indicator remains constant.
Working Three.js Starter (chopping-size-comparison-x0118):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Herb Cutting Display — Area Conservation</title>
<style>
:root {
--ink: #243026;
--muted: #687269;
--panel: rgba(250, 249, 242, 0.88);
--line: rgba(42, 61, 43, 0.14);
--green: #4d8c3d;
--green-dark: #2f6332;
--gold: #c78d3b;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9e3d6;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 10;
}
.panel {
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 14px 45px rgba(47, 45, 33, 0.09),
inset 0 1px 0 rgba(255, 255, 255, 0.75);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
}
.intro {
position: absolute;
top: 22px;
left: 22px;
width: min(360px, calc(100vw - 44px));
padding: 18px 19px 16px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
color: var(--green-dark);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 4px rgba(77, 140, 61, 0.12);
content: "";
}
h1 {
margin: 0;
font-size: clamp(21px, 3vw, 29px);
font-weight: 750;
letter-spacing: -0.035em;
line-height: 1.04;
}
.intro p {
margin: 10px 0 14px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.safety {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
border: 1px solid rgba(199, 141, 59, 0.28);
border-radius: 999px;
background: rgba(199, 141, 59, 0.09);
color: #795726;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metrics {
position: absolute;
top: 22px;
right: 22px;
width: min(300px, calc(100vw - 44px));
padding: 17px 18px;
}
.metric-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.metric-label {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#area-value {
margin-top: 3px;
color: var(--green-dark);
font-size: 31px;
font-weight: 780;
letter-spacing: -0.055em;
line-height: 1;
}
.target {
margin-top: 8px;
color: var(--muted);
font-size: 11px;
text-align: right;
}
.meter {
position: relative;
height: 8px;
margin: 14px 0 9px;
overflow: hidden;
border-radius: 99px;
background: rgba(47, 99, 50, 0.12);
}
#area-fill {
position: absolute;
inset: 0 auto 0 0;
width: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #3b7936, #79ad52);
transition: width 180ms ease;
}
.meter::after {
position: absolute;
top: -2px;
bottom: -2px;
left: 100%;
width: 2px;
background: #294d2d;
content: "";
opacity: 0.35;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 13px;
}
.metric-grid div {
min-width: 0;
padding: 9px 8px;
border-radius: 11px;
background: rgba(48, 87, 50, 0.055);
}
.metric-grid strong {
display: block;
overflow: hidden;
font-size: 14px;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-grid span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.status-wrap {
position: absolute;
right: 22px;
bottom: 22px;
left: 22px;
display: flex;
justify-content: center;
}
.status {
width: min(680px, 100%);
padding: 13px 16px 14px;
}
.status-row {
display: flex;
align-items: center;
gap: 14px;
}
#pass-label {
flex: 0 0 auto;
padding: 7px 9px;
border-radius: 9px;
background: rgba(47, 99, 50, 0.09);
color: var(--green-dark);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#status-text {
min-width: 0;
font-size: 12px;
font-weight: 650;
line-height: 1.4;
}
.steps {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 5px;
margin-top: 11px;
}
.step {
position: relative;
overflow: hidden;
padding-top: 9px;
border-top: 3px solid rgba(47, 99, 50, 0.12);
color: #8a9189;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-align: center;
text-transform: uppercase;
transition: color 180ms ease, border-color 180ms ease;
}
.step.active {
border-color: var(--gold);
color: #7c5929;
}
.step.done {
border-color: var(--green);
color: var(--green-dark);
}
.controls {
position: absolute;
bottom: 137px;
left: 22px;
display: flex;
gap: 8px;
pointer-events: auto;
}
button {
min-width: 84px;
padding: 10px 13px;
border: 1px solid rgba(44, 67, 46, 0.18);
border-radius: 11px;
background: rgba(250, 249, 242, 0.91);
color: var(--ink);
box-shadow: 0 8px 24px rgba(47, 45, 33, 0.08);
cursor: pointer;
font: inherit;
font-size: 11px;
font-weight: 750;
transition:
transform 140ms ease,
background 140ms ease;
}
button:hover {
transform: translateY(-1px);
background: #fffef8;
}
button:active {
transform: translateY(0);
}
.help {
position: absolute;
right: 24px;
bottom: 9px;
color: rgba(50, 62, 52, 0.58);
font-size: 10px;
pointer-events: none;
}
@media (max-width: 760px) {
.intro {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
}
.intro p {
display: none;
}
.metrics {
top: 130px;
right: 12px;
width: 240px;
padding: 13px;
}
.metric-grid {
grid-template-columns: 1fr 1fr;
}
.metric-grid div:last-child {
display: none;
}
.status-wrap {
right: 12px;
bottom: 12px;
left: 12px;
}
.controls {
bottom: 125px;
left: 12px;
}
.help {
display: none;
}
.status-row {
align-items: flex-start;
}
#pass-label {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly herb and knife display"></canvas>
<div class="hud">
<section class="panel intro">
<div class="eyebrow">Geometric food study</div>
<h1>Herb / Area Study</h1>
<p>
A slow, staged knife pass reveals progressively smaller leaf pieces.
Polygon clipping preserves the measured leaf-blade footprint.
</p>
<div class="safety">Safe display · no physical cutting</div>
</section>
<section class="panel metrics" aria-label="Area conservation metrics">
<div class="metric-head">
<div>
<div class="metric-label">Total leaf area</div>
<div id="area-value">100.0%</div>
</div>
<div class="target">
Target 100%<br />
<span id="area-target">0.00 units²</span>
</div>
</div>
<div class="meter"><div id="area-fill"></div></div>
<div class="metric-grid">
<div>
<strong id="piece-count">5</strong>
<span>Pieces</span>
</div>
<div>
<strong id="mean-area">0.00</strong>
<span>Mean area</span>
</div>
<div>
<strong id="area-delta">+0.0%</strong>
<span>Difference</span>
</div>
</div>
</section>
<div class="controls">
<button id="pause" type="button">Pause</button>
<button id="replay" type="button">Replay</button>
</div>
<div class="status-wrap">
<section class="panel status">
<div class="status-row">
<div id="pass-label">Pass 1 / 3</div>
<div id="status-text" aria-live="polite">
Align the blade above the first display guide.
</div>
</div>
<div class="steps" aria-hidden="true">
<div class="step active">Align</div>
<div class="step">Lower</div>
<div class="step">Pass</div>
<div class="step">Reveal</div>
<div class="step">Lift</div>
</div>
</section>
</div>
<div class="help">Drag to orbit · scroll to zoom · Space to pause</div>
</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 canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9e3d6);
scene.fog = new THREE.Fog(0xe9e3d6, 11, 24);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.05, 0);
const cameraState = {
azimuth: 0.68,
polar: 0.72,
radius: 8.8,
dragging: false,
pointerX: 0,
pointerY: 0
};
function updateCamera() {
const { azimuth, polar, radius } = cameraState;
const horizontal = Math.sin(polar) * radius;
camera.position.set(
cameraTarget.x + horizontal * Math.sin(azimuth),
cameraTarget.y + Math.cos(polar) * radius,
cameraTarget.z + horizontal * Math.cos(azimuth)
);
camera.lookAt(cameraTarget);
}
updateCamera();
// Direct camera controls: no addons are used.
canvas.addEventListener("pointerdown", (event) => {
cameraState.dragging = true;
cameraState.pointerX = event.clientX;
cameraState.pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!cameraState.dragging) return;
const dx = event.clientX - cameraState.pointerX;
const dy = event.clientY - cameraState.pointerY;
cameraState.pointerX = event.clientX;
cameraState.pointerY = event.clientY;
cameraState.azimuth -= dx * 0.006;
cameraState.polar = THREE.MathUtils.clamp(
cameraState.polar + dy * 0.005,
0.35,
1.25
);
updateCamera();
});
function endCameraDrag(event) {
cameraState.dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endCameraDrag);
canvas.addEventListener("pointercancel", endCameraDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.006,
5.8,
13.5
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Lighting
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xfff7df, 0x6d7863, 2.0));
const sun = new THREE.DirectionalLight(0xfff4d6, 3.2);
sun.position.set(4.5, 7.5, 4.0);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -5;
sun.shadow.camera.right = 5;
sun.shadow.camera.top = 5;
sun.shadow.camera.bottom = -5;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 20;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb7d7c3, 1.2);
fill.position.set(-5, 4, -4);
scene.add(fill);
// -------------------------------------------------------------------------
// Chopping board and surrounding floor
// -------------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: 0xded8c9,
roughness: 1
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.15;
floor.receiveShadow = true;
scene.add(floor);
const boardBase = new THREE.Mesh(
new THREE.BoxGeometry(5.6, 0.18, 3.9),
new THREE.MeshStandardMaterial({
color: 0x765239,
roughness: 0.9
})
);
boardBase.position.y = -0.025;
boardBase.castShadow = true;
boardBase.receiveShadow = true;
scene.add(boardBase);
const plankColors = [
0xa97547,
0x9d6c43,
0xaf7c4e,
0xa47148,
0x9e6941
];
for (let i = 0; i < 5; i++) {
const plank = new THREE.Mesh(
new THREE.BoxGeometry(5.34, 0.12, 0.69),
new THREE.MeshStandardMaterial({
color: plankColors[i],
roughness: 0.93
})
);
plank.position.set(0, 0.02, (i - 2) * 0.75);
plank.castShadow = true;
plank.receiveShadow = true;
scene.add(plank);
}
const rimMaterial = new THREE.MeshStandardMaterial({
color: 0x64452f,
roughness: 0.92
});
const rimPieces = [
[5.55, 0.19, 0.13, 0, 0.065, 1.93],
[5.55, 0.19, 0.13, 0, 0.065, -1.93],
[0.13, 0.19, 3.84, 2.75, 0.065, 0],
[0.13, 0.19, 3.84, -2.75, 0.065, 0]
];
for (const [w, h, d, x, y, z] of rimPieces) {
const rim = new THREE.Mesh(
new THREE.BoxGeometry(w, h, d),
rimMaterial
);
rim.position.set(x, y, z);
rim.castShadow = true;
rim.receiveShadow = true;
scene.add(rim);
}
// Deterministic wood grain.
let grainSeed = 9127;
function random() {
grainSeed = (grainSeed * 16807) % 2147483647;
return (grainSeed - 1) / 2147483646;
}
const grainPositions = [];
for (let i = 0; i < 48; i++) {
const z = -1.65 + random() * 3.3;
const x = -2.5 + random() * 1.8;
const length = 0.7 + random() * 2.2;
const bend = (random() - 0.5) * 0.035;
grainPositions.push(
x, 0.083, z,
Math.min(2.55, x + length), 0.083, z + bend
);
}
const grainGeometry = new THREE.BufferGeometry();
grainGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(grainPositions, 3)
);
const grain = new THREE.LineSegments(
grainGeometry,
new THREE.LineBasicMaterial({
color: 0x5f412d,
transparent: true,
opacity: 0.13
})
);
scene.add(grain);
// -------------------------------------------------------------------------
// Cut guides
// -------------------------------------------------------------------------
const CUT_X = [-0.56, 0.56, 0.0];
const cutGuides = [];
for (const x of CUT_X) {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(x, 0.092, -1.58),
new THREE.Vector3(x, 0.092, 1.58)
]);
const material = new THREE.LineDashedMaterial({
color: 0xc78d3b,
dashSize: 0.09,
gapSize: 0.065,
transparent: true,
opacity: 0.17
});
const guide = new THREE.Line(geometry, material);
guide.computeLineDistances();
scene.add(guide);
cutGuides.push(guide);
}
// -------------------------------------------------------------------------
// Low-poly herb leaves
// -------------------------------------------------------------------------
const localLeaf = [
[-1.20, 0.00],
[-1.06, -0.15],
[-0.82, -0.30],
[-0.57, -0.27],
[-0.31, -0.39],
[-0.02, -0.31],
[ 0.27, -0.40],
[ 0.56, -0.30],
[ 0.82, -0.22],
[ 1.08, -0.11],
[ 1.27, 0.00],
[ 1.08, 0.16],
[ 0.78, 0.25],
[ 0.50, 0.23],
[ 0.18, 0.38],
[-0.13, 0.29],
[-0.46, 0.35],
[-0.78, 0.22],
[-1.04, 0.12]
];
const leafDefinitions = [
{ z: -0.69, x: 0.02, angle: -0.085, sx: 1.00, sz: 0.90, color: 0x3f7f38 },
{ z: -0.35, x: -0.05, angle: 0.055, sx: 0.97, sz: 0.94, color: 0x4e913d },
{ z: 0.00, x: 0.04, angle: -0.045, sx: 1.06, sz: 0.92, color: 0x5b9b45 },
{ z: 0.35, x: -0.03, angle: 0.075, sx: 0.99, sz: 0.89, color: 0x46883a },
{ z: 0.69, x: 0.03, angle: -0.060, sx: 1.03, sz: 0.93, color: 0x619d48 }
];
function transformLeafPoints(definition) {
const cosine = Math.cos(definition.angle);
const sine = Math.sin(definition.angle);
return localLeaf.map(([x, z]) => ({
x:
definition.x +
x * cosine * definition.sx -
z * sine * definition.sz,
z:
definition.z +
x * sine * definition.sx +
z * cosine * definition.sz
}));
}
function polygonArea(polygon) {
let sum = 0;
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
sum += a.x * b.z - b.x * a.z;
}
return Math.abs(sum) * 0.5;
}
function polygonBounds(polygon) {
let minX = Infinity;
let maxX = -Infinity;
for (const point of polygon) {
minX = Math.min(minX, point.x);
maxX = Math.max(maxX, point.x);
}
return { minX, maxX };
}
function polygonCentroid(polygon) {
let area = 0;
let x = 0;
let z = 0;
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
const cross = a.x * b.z - b.x * a.z;
area += cross;
x += (a.x + b.x) * cross;
z += (a.z + b.z) * cross;
}
area *= 0.5;
if (Math.abs(area) < 1e-8) {
const average = polygon.reduce(
(result, point) => ({
x: result.x + point.x / polygon.length,
z: result.z + point.z / polygon.length
}),
{ x: 0, z: 0 }
);
return average;
}
return {
x: x / (6 * area),
z: z / (6 * area)
};
}
function cleanPolygon(polygon) {
const cleaned = [];
for (const point of polygon) {
const previous = cleaned[cleaned.length - 1];
if (
!previous ||
Math.hypot(point.x - previous.x, point.z - previous.z) > 0.00001
) {
cleaned.push(point);
}
}
if (cleaned.length > 1) {
const first = cleaned[0];
const last = cleaned[cleaned.length - 1];
if (Math.hypot(first.x - last.x, first.z - last.z) < 0.00001) {
cleaned.pop();
}
}
return cleaned.length >= 3 ? cleaned : [];
}
const leafMeshes = new THREE.Group();
scene.add(leafMeshes);
const stemGroup = new THREE.Group();
scene.add(stemGroup);
const stemMaterial = new THREE.MeshStandardMaterial({
color: 0x4e8738,
roughness: 0.88
});
function cylinderBetween(start, end, radius, material) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius * 1.05, length, 6),
material
);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
return mesh;
}
for (const definition of leafDefinitions) {
const cosine = Math.cos(definition.angle);
const sine = Math.sin(definition.angle);
const localStart = { x: -1.48, z: 0 };
const localEnd = { x: -1.13, z: 0 };
const start = new THREE.Vector3(
definition.x + localStart.x * cosine * definition.sx,
0.115,
definition.z + localStart.x * sine * definition.sx
);
const end = new THREE.Vector3(
definition.x + localEnd.x * cosine * definition.sx,
0.115,
definition.z + localEnd.x * sine * definition.sx
);
stemGroup.add(cylinderBetween(start, end, 0.032, stemMaterial));
}
function createLeafGeometry(polygon, colorHex, variation) {
const center = polygonCentroid(polygon);
const outline = polygon.map(
(point) => new THREE.Vector2(point.x, point.z)
);
const triangles = THREE.ShapeUtils.triangulateShape(outline, []);
const positions = [];
const colors = [];
const baseColor = new THREE.Color(colorHex);
const hsl = {};
baseColor.getHSL(hsl);
const pushTriangle = (a, b, c, color) => {
for (const point of [a, b, c]) {
positions.push(
point.x - center.x,
0,
point.z - center.z
);
colors.push(color.r, color.g, color.b);
}
};
triangles.forEach((triangle, index) => {
const a = outline[triangle[0]];
const b = outline[triangle[1]];
const c = outline[triangle[2]];
const shade = 0.84 + ((index + variation) % 4) * 0.055;
const hueShift = (((index + variation) % 3) - 1) * 0.008;
const color = new THREE.Color().setHSL(
(hsl.h + hueShift + 1) % 1,
hsl.s,
Math.min(0.72, hsl.l * shade)
);
pushTriangle(a, b, c, color);
pushTriangle(c, b, a, color.clone().multiplyScalar(0.94));
});
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.computeVertexNormals();
geometry.computeBoundingSphere();
return { geometry, center };
}
const originalPieces = leafDefinitions.map((definition, leafId) => ({
polygon: transformLeafPoints(definition),
leafId,
shiftX: 0
}));
let pieces = originalPieces.map((piece) => ({
...piece,
polygon: piece.polygon.map((point) => ({ ...point }))
}));
let pieceObjects = [];
function disposeLeafObjects() {
for (const child of [...leafMeshes.children]) {
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of materials) material.dispose();
}
});
leafMeshes.remove(child);
}
pieceObjects = [];
}
function createVein(piece, center) {
const definition = leafDefinitions[piece.leafId];
const bounds = polygonBounds(piece.polygon);
const startX = definition.x - 1.12 * Math.cos(definition.angle) * definition.sx;
const endX = definition.x + 1.12 * Math.cos(definition.angle) * definition.sx;
const fromX = Math.max(bounds.minX, startX);
const toX = Math.min(bounds.maxX, endX);
if (toX - fromX < 0.025) return null;
const zAt = (x) =>
definition.z + (x - definition.x) * Math.tan(definition.angle);
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(fromX - center.x, 0.007, zAt(fromX) - center.z),
new THREE.Vector3(toX - center.x, 0.007, zAt(toX) - center.z)
]);
const material = new THREE.LineBasicMaterial({
color: 0xc0dc83,
transparent: true,
opacity: 0.7
});
return new THREE.Line(geometry, material);
}
function rebuildLeafMeshes(reveal = true) {
disposeLeafObjects();
pieces.forEach((piece, index) => {
const definition = leafDefinitions[piece.leafId];
const { geometry, center } = createLeafGeometry(
piece.polygon,
definition.color,
index + piece.leafId
);
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
side: THREE.DoubleSide,
roughness: 0.78,
metalness: 0,
transparent: true,
opacity: reveal ? 0 : 1
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
const group = new THREE.Group();
group.position.set(
center.x + piece.shiftX,
0.115 + piece.leafId * 0.004,
center.z
);
group.scale.setScalar(reveal ? 0.86 : 1);
group.add(mesh);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 18),
new THREE.LineBasicMaterial({
color: 0x244d28,
transparent: true,
opacity: reveal ? 0 : 0.32
})
);
group.add(edges);
const vein = createVein(piece, center);
if (vein) group.add(vein);
group.userData = {
material,
edgeMaterial: edges.material,
baseX: group.position.x,
baseZ: group.position.z
};
leafMeshes.add(group);
pieceObjects.push(group);
});
}
function animatePieceReveal(progress) {
const eased = 1 - Math.pow(1 - progress, 3);
for (const group of pieceObjects) {
group.scale.setScalar(0.86 + eased * 0.14);
group.userData.material.opacity = eased;
group.userData.edgeMaterial.opacity = eased * 0.32;
if (group.userData.veinMaterial) {
group.userData.veinMaterial.opacity = eased * 0.7;
}
}
}
// -------------------------------------------------------------------------
// Knife
// -------------------------------------------------------------------------
const knife = new THREE.Group();
scene.add(knife);
function makePrismGeometry(outline, thickness) {
const contour = outline.map(([x, z]) => new THREE.Vector2(x, z));
const triangles = THREE.ShapeUtils.triangulateShape(contour, []);
const positions = [];
const push = (a, b, c, y) => {
positions.push(a.x, y, a.z, b.x, y, b.z, c.x, y, c.z);
};
for (const triangle of triangles) {
const a = contour[triangle[0]];
const b = contour[triangle[1]];
const c = contour[triangle[2]];
push(a, b, c, thickness / 2);
push(c, b, a, -thickness / 2);
}
for (let i = 0; i < contour.length; i++) {
const a = contour[i];
const b = contour[(i + 1) % contour.length];
positions.push(
a.x, thickness / 2, a.z,
b.x, thickness / 2, b.z,
b.x, -thickness / 2, b.z,
a.x, thickness / 2, a.z,
b.x, -thickness / 2, b.z,
a.x, -thickness / 2, a.z
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
return geometry;
}
const blade = new THREE.Mesh(
makePrismGeometry(
[
[-0.13, -0.48],
[ 0.13, -0.48],
[ 0.14, 0.34],
[ 0.05, 0.68],
[-0.10, 0.57]
],
0.055
),
new THREE.MeshStandardMaterial({
color: 0xc7d0cd,
metalness: 0.78,
roughness: 0.25,
side: THREE.DoubleSide
})
);
blade.castShadow = true;
blade.receiveShadow = true;
knife.add(blade);
const spine = new THREE.Mesh(
new THREE.BoxGeometry(0.045, 0.073, 0.95),
new THREE.MeshStandardMaterial({
color: 0x899794,
metalness: 0.8,
roughness: 0.3
})
);
spine.position.set(-0.095, 0.012, 0.03);
spine.castShadow = true;
knife.add(spine);
const handle = new THREE.Mesh(
new THREE.BoxGeometry(0.27, 0.13, 0.72),
new THREE.MeshStandardMaterial({
color: 0x31483a,
roughness: 0.82
})
);
handle.position.set(0, 0.015, -0.83);
handle.castShadow = true;
knife.add(handle);
const rivetMaterial = new THREE.MeshStandardMaterial({
color: 0xc2a86d,
metalness: 0.7,
roughness: 0.35
});
for (const z of [-0.61, -0.93]) {
const rivet = new THREE.Mesh(
new THREE.CylinderGeometry(0.025, 0.025, 0.012, 10),
rivetMaterial
);
rivet.position.set(0, 0.085, z);
rivet.castShadow = true;
knife.add(rivet);
}
// -------------------------------------------------------------------------
// Polygon clipping: exact area conservation
// -------------------------------------------------------------------------
function clipPolygonAtX(polygon, lineX, keepLeft) {
if (polygon.length === 0) return [];
const output = [];
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
const aInside = keepLeft ? a.x <= lineX : a.x >= lineX;
const bInside = keepLeft ? b.x <= lineX : b.x >= lineX;
if (aInside && bInside) {
output.push({ ...b });
} else if (aInside && !bInside) {
const t = (lineX - a.x) / (b.x - a.x);
output.push({
x: lineX,
z: a.z + (b.z - a.z) * t
});
} else if (!aInside && bInside) {
const t = (lineX - a.x) / (b.x - a.x);
output.push({
x: lineX,
z: a.z + (b.z - a.z) * t
});
output.push({ ...b });
}
}
return cleanPolygon(output);
}
function splitPiecesAt(lineX) {
const nextPieces = [];
for (const piece of pieces) {
const left = clipPolygonAtX(piece.polygon, lineX, true);
const right = clipPolygonAtX(piece.polygon, lineX, false);
if (left.length && right.length) {
nextPieces.push({
...piece,
polygon: left,
shiftX: piece.shiftX - 0.028
});
nextPieces.push({
...piece,
polygon: right,
shiftX: piece.shiftX + 0.028
});
} else if (left.length) {
nextPieces.push({ ...piece, polygon: left });
} else if (right.length) {
nextPieces.push({ ...piece, polygon: right });
}
}
pieces = nextPieces;
rebuildLeafMeshes(true);
updateMetrics();
}
// -------------------------------------------------------------------------
// Area indicator
// -------------------------------------------------------------------------
const originalArea = pieces.reduce(
(total, piece) => total + polygonArea(piece.polygon),
0
);
const areaValue = document.querySelector("#area-value");
const areaTarget = document.querySelector("#area-target");
const areaFill = document.querySelector("#area-fill");
const areaDelta = document.querySelector("#area-delta");
const pieceCount = document.querySelector("#piece-count");
const meanArea = document.querySelector("#mean-area");
function updateMetrics() {
const currentArea = pieces.reduce(
(total, piece) => total + polygonArea(piece.polygon),
0
);
const ratio = originalArea > 0 ? currentArea / originalArea : 1;
const percentage = ratio * 100;
const difference = percentage - 100;
areaValue.textContent = `${percentage.toFixed(1)}%`;
areaTarget.textContent = `${originalArea.toFixed(2)} units²`;
areaFill.style.width = `${Math.min(100, Math.max(0, percentage))}%`;
areaDelta.textContent = `${difference >= 0 ? "+" : ""}${difference.toFixed(1)}%`;
pieceCount.textContent = String(pieces.length);
meanArea.textContent = (currentArea / Math.max(1, pieces.length)).toFixed(2);
}
// -------------------------------------------------------------------------
// Staged animation
// -------------------------------------------------------------------------
const PHASES = ["align", "lower", "sweep", "reveal", "lift"];
const PHASE_DURATION = {
align: 1.2,
lower: 0.8,
sweep: 2.45,
reveal: 0.85,
lift: 0.95
};
const passLabel = document.querySelector("#pass-label");
const statusText = document.querySelector("#status-text");
const stepElements = [...document.querySelectorAll(".step")];
let cutIndex = 0;
let phase = "align";
let phaseTime = 0;
let splitApplied = false;
let paused = false;
const alignFrom = new THREE.Vector3();
const alignTo = new THREE.Vector3();
const statusByPhase = {
align: "Align the blade above the next display guide.",
lower: "Lower slowly; the blade remains suspended above the board.",
sweep: "Slow visual pass over the herbs — no physical cutting.",
reveal: "Reveal smaller polygon pieces while preserving total area.",
lift: "Lift clear, then move to the next guide."
};
function smoothStep(value) {
return value * value * (3 - 2 * value);
}
function setPhase(nextPhase) {
phase = nextPhase;
phaseTime = 0;
splitApplied = false;
if (phase === "align") {
alignFrom.copy(knife.position);
alignTo.set(CUT_X[cutIndex], 0.66, -1.48);
}
updateInterface();
}
function updateInterface() {
const phaseIndex = PHASES.indexOf(phase);
stepElements.forEach((element, index) => {
element.classList.toggle("active", index === phaseIndex);
element.classList.toggle("done", index < phaseIndex || phase === "done");
});
if (phase === "done") {
passLabel.textContent = "Complete";
statusText.textContent =
`Finished with ${pieces.length} smaller pieces and ${(
(pieces.reduce(
(total, piece) => total + polygonArea(piece.polygon),
0
) /
originalArea) *
100
).toFixed(1)}% conserved leaf area.`;
return;
}
passLabel.textContent = `Pass ${cutIndex + 1} / ${CUT_X.length}`;
statusText.textContent = statusByPhase[phase];
}
function updateGuides() {
cutGuides.forEach((guide, index) => {
guide.material.opacity = index === cutIndex ? 0.86 : 0.15;
});
}
function advancePhase() {
if (phase === "align") {
setPhase("lower");
} else if (phase === "lower") {
setPhase("sweep");
} else if (phase === "sweep") {
setPhase("reveal");
} else if (phase === "reveal") {
setPhase("lift");
} else if (phase === "lift") {
if (cutIndex < CUT_X.length - 1) {
cutIndex++;
setPhase("align");
} else {
phase = "done";
phaseTime = 0;
updateInterface();
cutGuides.forEach((guide) => {
guide.material.opacity = 0.22;
});
}
}
}
function updateAnimation(dt) {
if (phase === "done") return;
phaseTime += dt;
const duration = PHASE_DURATION[phase];
const rawProgress = Math.min(1, phaseTime / duration);
const eased = smoothStep(rawProgress);
if (phase === "align") {
knife.position.lerpVectors(alignFrom, alignTo, eased);
} else if (phase === "lower") {
knife.position.x = CUT_X[cutIndex];
knife.position.z = -1.48;
knife.position.y = THREE.MathUtils.lerp(0.66, 0.19, eased);
} else if (phase === "sweep") {
knife.position.x = CUT_X[cutIndex];
knife.position.y = 0.19 + Math.sin(rawProgress * Math.PI) * 0.008;
knife.position.z = THREE.MathUtils.lerp(-1.48, 1.48, eased);
} else if (phase === "reveal") {
knife.position.x = CUT_X[cutIndex];
knife.position.y = 0.19;
knife.position.z = 1.48;
if (!splitApplied) {
splitApplied = true;
splitPiecesAt(CUT_X[cutIndex]);
}
animatePieceReveal(eased);
} else if (phase === "lift") {
knife.position.x = CUT_X[cutIndex];
knife.position.z = 1.48;
knife.position.y = THREE.MathUtils.lerp(0.19, 0.66, eased);
}
updateGuides();
if (phaseTime >= duration) {
advancePhase();
}
}
function replay() {
pieces = originalPieces.map((piece) => ({
...piece,
polygon: piece.polygon.map((point) => ({ ...point }))
}));
cutIndex = 0;
phaseTime = 0;
splitApplied = false;
paused = false;
document.querySelector("#pause").textContent = "Pause";
knife.position.set(CUT_X[0], 0.66, -1.48);
rebuildLeafMeshes(false);
updateMetrics();
setPhase("align");
updateGuides();
}
// -------------------------------------------------------------------------
// UI controls
// -------------------------------------------------------------------------
const pauseButton = document.querySelector("#pause");
const replayButton = document.querySelector("#replay");
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
});
replayButton.addEventListener("click", replay);
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
}
if (event.key.toLowerCase() === "r") {
replay();
}
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", resize);
rebuildLeafMeshes(false);
updateMetrics();
knife.position.set(CUT_X[0], 0.66, -1.48);
setPhase("align");
updateGuides();
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const dt = Math.min(clock.getDelta(), 0.05);
if (!paused) {
updateAnimation(dt);
}
renderer.render(scene, camera);
});
</script>
</body>
</html>
```