Prompt specification
Build or customize the Three.js 3D scene "Cooperative shadow puzzle stage" 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: Cooperative shadow puzzle stage
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/cooperative-shadow-puzzle-stage-x0372
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows shadow puppets. Create several simple solid shapes whose combined shadows form a target figure; users adjust positions and lamp angle while a preview shows how overlap changes the result. Low-poly.
Working Three.js Starter (cooperative-shadow-puzzle-stage-x0372):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Lumen — Shadow Atelier</title>
<style>
:root {
color-scheme: dark;
--bg: #081116;
--panel: #101b22;
--panel-2: #14232b;
--line: rgba(255, 255, 255, 0.09);
--text: #eef4f2;
--muted: #8ea3a8;
--amber: #f0b65c;
--amber-soft: rgba(240, 182, 92, 0.14);
--teal: #6dc1b6;
--shadow: #03070a;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background:
radial-gradient(circle at 15% -10%, rgba(66, 114, 121, 0.18), transparent 35%),
radial-gradient(circle at 95% 10%, rgba(240, 182, 92, 0.08), transparent 28%),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
width: min(1680px, 100%);
margin: 0 auto;
padding: 20px;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
min-height: 64px;
margin-bottom: 18px;
}
.brand {
display: flex;
align-items: center;
gap: 14px;
}
.brand-mark {
position: relative;
width: 42px;
height: 42px;
border: 1px solid rgba(240, 182, 92, 0.38);
border-radius: 50%;
background: radial-gradient(circle at 38% 36%, #ffe5a5, #d98b3b 45%, #6d3d24 100%);
box-shadow: 0 0 28px rgba(240, 182, 92, 0.15);
}
.brand-mark::after {
content: "";
position: absolute;
width: 29px;
height: 29px;
left: 11px;
top: 4px;
border-radius: 50%;
background: #0b151a;
}
.eyebrow {
margin: 0 0 3px;
color: var(--amber);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(22px, 2.5vw, 31px);
font-weight: 650;
letter-spacing: -0.035em;
}
.top-actions {
display: flex;
align-items: center;
gap: 10px;
}
.live-pill {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 999px;
color: #b9c9c9;
background: rgba(255, 255, 255, 0.025);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.live-pill::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 10px var(--teal);
}
.button {
border: 1px solid var(--line);
border-radius: 10px;
padding: 10px 13px;
background: rgba(255, 255, 255, 0.035);
cursor: pointer;
transition: 160ms ease;
}
.button:hover {
border-color: rgba(240, 182, 92, 0.4);
background: var(--amber-soft);
transform: translateY(-1px);
}
.button.primary {
border-color: rgba(240, 182, 92, 0.35);
background: var(--amber);
color: #24190e;
font-weight: 800;
}
.button.primary:hover {
background: #f7c778;
}
.app-grid {
display: grid;
grid-template-columns: 300px minmax(0, 1fr) 365px;
gap: 16px;
align-items: stretch;
}
.panel,
.stage-card,
.preview-card {
border: 1px solid var(--line);
border-radius: 18px;
background: linear-gradient(145deg, rgba(20, 35, 43, 0.96), rgba(12, 22, 28, 0.96));
box-shadow: 0 18px 70px rgba(0, 0, 0, 0.24);
overflow: hidden;
}
.controls {
padding: 19px;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 14px;
}
.section-heading h2,
.card-heading h2 {
margin: 0;
font-size: 13px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section-number {
color: #667c82;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
}
.control-section {
padding: 16px 0;
border-top: 1px solid var(--line);
}
.control-section:first-of-type {
border-top: 0;
padding-top: 0;
}
.field-title {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
color: #c9d4d3;
font-size: 12px;
font-weight: 650;
}
output {
color: var(--amber);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0 3px;
border-radius: 999px;
outline: none;
appearance: none;
background: linear-gradient(90deg, var(--amber), rgba(240, 182, 92, 0.18));
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
border: 3px solid #17242b;
border-radius: 50%;
appearance: none;
background: #ffd08a;
box-shadow: 0 0 0 1px rgba(240, 182, 92, 0.5), 0 3px 10px rgba(0, 0, 0, 0.35);
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 3px solid #17242b;
border-radius: 50%;
background: #ffd08a;
box-shadow: 0 0 0 1px rgba(240, 182, 92, 0.5);
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: #60767c;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.shape-list {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.shape-button {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
color: #aebfc0;
font-size: 11px;
font-weight: 650;
cursor: pointer;
transition: 140ms ease;
}
.shape-button:hover {
background: rgba(255, 255, 255, 0.055);
}
.shape-button.active {
border-color: rgba(240, 182, 92, 0.48);
color: #fff3dc;
background: var(--amber-soft);
}
.shape-dot {
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 3px;
background: var(--shape-color);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2);
}
.selected-title {
margin-bottom: 12px;
color: #f0f5f3;
font-size: 14px;
font-weight: 750;
}
.selected-title span {
color: var(--muted);
font-size: 11px;
font-weight: 500;
}
.axis-field + .axis-field {
margin-top: 14px;
}
.check-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
color: #b7c6c5;
font-size: 12px;
}
.check-label {
display: flex;
align-items: center;
gap: 9px;
cursor: pointer;
}
.check-label input {
width: 15px;
height: 15px;
accent-color: var(--amber);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.button-row .button {
padding: 9px 8px;
font-size: 11px;
}
.match-card {
padding: 13px;
border: 1px solid rgba(109, 193, 182, 0.16);
border-radius: 11px;
background: rgba(109, 193, 182, 0.055);
}
.match-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
color: #a8c3bf;
font-size: 11px;
}
#match-value {
color: var(--teal);
font-size: 22px;
font-weight: 800;
letter-spacing: -0.04em;
}
.meter {
height: 5px;
margin-top: 9px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.07);
}
#match-meter {
width: 100%;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #568e88, var(--teal));
transition: width 180ms ease;
}
.match-note {
margin: 8px 0 0;
color: #70898b;
font-size: 10px;
line-height: 1.45;
}
.workspace {
display: grid;
grid-template-columns: minmax(0, 1fr) 365px;
gap: 16px;
min-width: 0;
}
.stage-card {
position: relative;
min-height: 690px;
background: #0b151b;
}
#stage-canvas {
display: block;
width: 100%;
height: 100%;
min-height: 690px;
outline: none;
touch-action: none;
cursor: grab;
}
#stage-canvas:active {
cursor: grabbing;
}
.stage-top {
position: absolute;
top: 16px;
left: 16px;
right: 16px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.stage-label,
.stage-help {
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 9px;
background: rgba(8, 17, 22, 0.7);
backdrop-filter: blur(9px);
}
.stage-label {
padding: 10px 12px;
}
.stage-label strong {
display: block;
font-size: 12px;
letter-spacing: 0.05em;
}
.stage-label span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.stage-help {
padding: 8px 10px;
color: #8da1a5;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stage-bottom {
position: absolute;
bottom: 16px;
left: 16px;
right: 16px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.stage-caption {
max-width: 340px;
padding: 10px 12px;
border-left: 2px solid var(--amber);
color: #9fb0b1;
background: rgba(8, 17, 22, 0.66);
backdrop-filter: blur(8px);
font-size: 10px;
line-height: 1.45;
}
.stage-caption strong {
color: #e7edeb;
}
.recenter {
pointer-events: auto;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 9px;
padding: 9px 11px;
background: rgba(8, 17, 22, 0.76);
color: #b5c4c3;
font-size: 10px;
font-weight: 750;
cursor: pointer;
}
.preview-card {
display: flex;
flex-direction: column;
min-width: 0;
}
.card-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 17px 18px;
border-bottom: 1px solid var(--line);
}
.card-heading p {
margin: 4px 0 0;
color: #70868a;
font-size: 10px;
}
.screen-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-radius: 999px;
color: #ffd38d;
background: rgba(240, 182, 92, 0.1);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.screen-badge::before {
content: "";
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 7px var(--amber);
}
#preview-canvas {
display: block;
width: 100%;
height: 480px;
min-height: 420px;
background: #091217;
touch-action: none;
cursor: crosshair;
}
.preview-legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
padding: 13px 17px;
border-top: 1px solid var(--line);
color: #778e92;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.legend-swatch {
width: 14px;
height: 4px;
border-radius: 999px;
background: #020608;
}
.legend-swatch.guide {
height: 0;
border-top: 1px dashed var(--amber);
border-radius: 0;
background: none;
}
.legend-swatch.selected {
background: var(--teal);
}
.preview-tip {
margin: auto 17px 17px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 10px;
color: #91a5a7;
background: rgba(255, 255, 255, 0.025);
font-size: 10px;
line-height: 1.55;
}
.preview-tip strong {
color: #d8e2df;
}
.footer-note {
margin: 13px 3px 0;
color: #53696e;
font-size: 10px;
text-align: right;
}
@media (max-width: 1250px) {
.app-grid {
grid-template-columns: 280px minmax(0, 1fr);
}
.workspace {
grid-template-columns: 1fr;
}
.stage-card,
#stage-canvas {
min-height: 610px;
}
.preview-card {
display: grid;
grid-template-columns: 1fr 1fr;
}
.card-heading {
grid-column: 1 / -1;
}
#preview-canvas {
height: 440px;
}
.preview-legend,
.preview-tip {
align-self: end;
margin: 17px;
}
}
@media (max-width: 760px) {
.app {
padding: 11px;
}
.topbar {
align-items: flex-start;
}
.live-pill {
display: none;
}
.app-grid {
grid-template-columns: 1fr;
}
.controls {
order: 2;
}
.workspace {
order: 1;
}
.stage-card,
#stage-canvas {
min-height: 520px;
}
.preview-card {
display: block;
}
#preview-canvas {
height: 390px;
min-height: 390px;
}
.shape-list {
grid-template-columns: repeat(3, 1fr);
}
.stage-help {
display: none;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<p class="eyebrow">Lumen Laboratory</p>
<h1>Shadow Atelier</h1>
</div>
</div>
<div class="top-actions">
<div class="live-pill">Live projection</div>
<button class="button" id="reset-all">Reset composition</button>
</div>
</header>
<div class="app-grid">
<aside class="panel controls" aria-label="Shadow controls">
<div class="section-heading">
<h2>Controls</h2>
<span class="section-number">01 / 04</span>
</div>
<section class="control-section">
<div class="field-title">
<span>Lamp angle</span>
<output id="lamp-value">0°</output>
</div>
<input id="lamp-angle" type="range" min="-28" max="28" step="1" value="0" aria-label="Lamp angle" />
<div class="range-ends">
<span>Left</span>
<span>Center</span>
<span>Right</span>
</div>
</section>
<section class="control-section">
<div class="section-heading">
<h2>Puppet pieces</h2>
<span class="section-number">02 / 04</span>
</div>
<div class="shape-list" id="shape-list"></div>
</section>
<section class="control-section">
<div class="selected-title">
<span id="selected-name">Body</span>
<span>position</span>
</div>
<div class="axis-field">
<div class="field-title">
<span>Horizontal offset</span>
<output id="x-value">+0.00</output>
</div>
<input id="position-x" type="range" min="-1.8" max="1.8" step="0.01" value="0" aria-label="Selected puppet horizontal offset" />
</div>
<div class="axis-field">
<div class="field-title">
<span>Vertical offset</span>
<output id="y-value">+0.00</output>
</div>
<input id="position-y" type="range" min="-1.8" max="1.8" step="0.01" value="0" aria-label="Selected puppet vertical offset" />
</div>
<div class="button-row">
<button class="button" id="snap-selected">Snap to guide</button>
<button class="button" id="reset-selected">Reset piece</button>
</div>
</section>
<section class="control-section">
<div class="section-heading">
<h2>Projection</h2>
<span class="section-number">03 / 04</span>
</div>
<label class="check-row">
<span class="check-label">
<input id="show-guide" type="checkbox" checked />
Show target guide
</span>
<span id="part-count">7 pieces</span>
</label>
<div class="match-card" style="margin-top: 14px">
<div class="match-head">
<span>Target match</span>
<span id="match-value">100%</span>
</div>
<div class="meter"><div id="match-meter"></div></div>
<p class="match-note">Overlap is measured against the original cat silhouette.</p>
</div>
</section>
<section class="control-section">
<div class="section-heading">
<h2>Workspace</h2>
<span class="section-number">04 / 04</span>
</div>
<button class="button" id="reset-camera" style="width: 100%">Reset camera view</button>
</section>
</aside>
<main class="workspace">
<section class="stage-card" aria-label="Three-dimensional puppet workspace">
<canvas id="stage-canvas"></canvas>
<div class="stage-top">
<div class="stage-label">
<strong>Puppet table</strong>
<span>Drag a piece to move it · drag empty space to orbit</span>
</div>
<div class="stage-help">Scroll to zoom</div>
</div>
<div class="stage-bottom">
<div class="stage-caption">
<strong>Build the shadow, not the object.</strong>
Different depths react differently to the lamp, so small adjustments reveal new overlaps.
</div>
<button class="recenter" id="recenter-camera">Recenter ↗</button>
</div>
</section>
<section class="preview-card" aria-label="Shadow preview">
<div class="card-heading">
<div>
<h2>Shadow preview</h2>
<p>Drag the projected silhouette to fine-tune.</p>
</div>
<span class="screen-badge">Live</span>
</div>
<canvas id="preview-canvas"></canvas>
<div class="preview-legend">
<span class="legend-item"><i class="legend-swatch"></i> Shadow</span>
<span class="legend-item"><i class="legend-swatch guide"></i> Target</span>
<span class="legend-item"><i class="legend-swatch selected"></i> Selected</span>
</div>
<div class="preview-tip">
<strong>Overlap darkens the result.</strong> The gold dashed guide shows where each piece belongs. Use “Snap to guide” for a precise correction.
</div>
</section>
</main>
</div>
<p class="footer-note">Seven low-poly pieces · one projected cat</p>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stageCanvas = document.querySelector("#stage-canvas");
const previewCanvas = document.querySelector("#preview-canvas");
const previewContext = previewCanvas.getContext("2d");
const renderer = new THREE.WebGLRenderer({
canvas: stageCanvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a151b);
scene.fog = new THREE.Fog(0x0a151b, 12, 23);
const camera = new THREE.OrthographicCamera(-5, 5, 4, -4, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0.1, 1.55);
const orbit = {
radius: 12,
theta: 0.49,
phi: 1.16,
zoom: 1
};
function updateCamera() {
const offset = new THREE.Vector3(
orbit.radius * Math.sin(orbit.phi) * Math.sin(orbit.theta),
orbit.radius * Math.cos(orbit.phi),
orbit.radius * Math.sin(orbit.phi) * Math.cos(orbit.theta)
);
camera.position.copy(cameraTarget).add(offset);
camera.lookAt(cameraTarget);
camera.zoom = orbit.zoom;
camera.updateProjectionMatrix();
}
function resetCamera() {
orbit.theta = 0.49;
orbit.phi = 1.16;
orbit.radius = 12;
orbit.zoom = 1;
updateCamera();
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xb9dce3, 0x1b1713, 2.0));
const ambient = new THREE.AmbientLight(0xffffff, 0.62);
scene.add(ambient);
const screen = new THREE.Mesh(
new THREE.PlaneGeometry(7.2, 5.2),
new THREE.MeshBasicMaterial({ color: 0x14242c })
);
screen.position.set(0, 0.12, -0.09);
scene.add(screen);
const grid = new THREE.GridHelper(7.2, 18, 0x49616a, 0x263c45);
grid.rotation.x = Math.PI / 2;
grid.position.set(0, 0.12, -0.075);
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const screenFrameMaterial = new THREE.LineBasicMaterial({
color: 0x536b72,
transparent: true,
opacity: 0.55
});
const framePoints = [
new THREE.Vector3(-3.6, -2.48, -0.07),
new THREE.Vector3(3.6, -2.48, -0.07),
new THREE.Vector3(3.6, 2.72, -0.07),
new THREE.Vector3(-3.6, 2.72, -0.07),
new THREE.Vector3(-3.6, -2.48, -0.07)
];
scene.add(new THREE.Line(new THREE.BufferGeometry().setFromPoints(framePoints), screenFrameMaterial));
const lampGroup = new THREE.Group();
const lampOrb = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.17, 0),
new THREE.MeshStandardMaterial({
color: 0xffd47e,
emissive: 0xff9d32,
emissiveIntensity: 3.2,
roughness: 0.45,
flatShading: true
})
);
lampGroup.add(lampOrb);
const lampRing = new THREE.Mesh(
new THREE.TorusGeometry(0.27, 0.018, 5, 16),
new THREE.MeshBasicMaterial({ color: 0xffcc73, transparent: true, opacity: 0.55 })
);
lampRing.rotation.x = Math.PI / 2;
lampGroup.add(lampRing);
scene.add(lampGroup);
const pointLight = new THREE.PointLight(0xffbe67, 48, 17, 2);
scene.add(pointLight);
const beam = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 1, 1, 12, 1, true),
new THREE.MeshBasicMaterial({
color: 0xf2b85e,
transparent: true,
opacity: 0.045,
side: THREE.DoubleSide,
depthWrite: false
})
);
scene.add(beam);
function ellipsePoints(count, radiusX, radiusY) {
const points = [];
for (let i = 0; i < count; i++) {
const angle = Math.PI / 2 + (i / count) * Math.PI * 2;
points.push({
x: Math.cos(angle) * radiusX,
y: Math.sin(angle) * radiusY
});
}
return points;
}
function polygonPoints(vertices) {
return vertices.map(([x, y]) => ({ x, y }));
}
const DEFAULT_LAMP = { x: 0, y: 0.15, z: 6 };
const shapeDefinitions = [
{
id: "body",
name: "Body",
color: 0xc96f4a,
css: "#c96f4a",
depth: 1.55,
center: [-0.28, -0.18],
points: ellipsePoints(12, 0.88, 1.02)
},
{
id: "head",
name: "Head",
color: 0xe2aa54,
css: "#e2aa54",
depth: 1.85,
center: [0.48, 0.82],
points: ellipsePoints(10, 0.55, 0.55)
},
{
id: "ear-left",
name: "Ear L",
color: 0xef8b62,
css: "#ef8b62",
depth: 2.05,
center: [0.25, 1.28],
points: polygonPoints([[-0.22, -0.22], [0.22, -0.22], [0, 0.42]])
},
{
id: "ear-right",
name: "Ear R",
color: 0xf0c36b,
css: "#f0c36b",
depth: 2.10,
center: [0.72, 1.25],
points: polygonPoints([[-0.22, -0.22], [0.22, -0.22], [0, 0.42]])
},
{
id: "tail",
name: "Tail",
color: 0x4f9188,
css: "#4f9188",
depth: 1.30,
center: [-1.38, -0.66],
points: polygonPoints([
[0.48, 0.50],
[-0.50, 0.02],
[-0.38, -0.42],
[0.40, -0.10]
])
},
{
id: "leg-back",
name: "Hind leg",
color: 0x56799a,
css: "#56799a",
depth: 1.42,
center: [-0.46, -0.92],
points: polygonPoints([
[-0.16, -0.48],
[0.15, -0.50],
[0.18, 0.48],
[-0.14, 0.50]
])
},
{
id: "leg-front",
name: "Front leg",
color: 0x7892aa,
css: "#7892aa",
depth: 1.68,
center: [0.22, -0.94],
points: polygonPoints([
[-0.16, -0.48],
[0.15, -0.50],
[0.18, 0.48],
[-0.14, 0.50]
])
}
];
const puppetMeshes = [];
function createExtrudedGeometry(points) {
const path = new THREE.Shape();
points.forEach((point, index) => {
if (index === 0) path.moveTo(point.x, point.y);
else path.lineTo(point.x, point.y);
});
path.closePath();
const geometry = new THREE.ExtrudeGeometry(path, {
depth: 0.16,
bevelEnabled: false,
curveSegments: 1,
steps: 1
});
geometry.translate(0, 0, -0.08);
geometry.computeVertexNormals();
return geometry;
}
shapeDefinitions.forEach((definition, index) => {
const geometry = createExtrudedGeometry(definition.points);
const material = new THREE.MeshStandardMaterial({
color: definition.color,
roughness: 0.86,
metalness: 0.02,
flatShading: true,
side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(geometry, material);
const factor = (DEFAULT_LAMP.z - definition.depth) / DEFAULT_LAMP.z;
const initialX =
DEFAULT_LAMP.x +
(definition.center[0] - DEFAULT_LAMP.x) * factor;
const initialY =
DEFAULT_LAMP.y +
(definition.center[1] - DEFAULT_LAMP.y) * factor;
mesh.position.set(initialX, initialY, definition.depth);
mesh.userData.shapeId = definition.id;
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x19262b,
transparent: true,
opacity: 0.72
});
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 24),
edgeMaterial
);
mesh.add(edges);
scene.add(mesh);
puppetMeshes.push(mesh);
const shadow = new THREE.Mesh(
new THREE.BufferGeometry(),
new THREE.MeshBasicMaterial({
color: 0x010407,
transparent: true,
opacity: 0.58,
side: THREE.DoubleSide,
depthWrite: false
})
);
shadow.position.z = -0.055 + index * 0.00025;
shadow.renderOrder = 2 + index;
scene.add(shadow);
Object.assign(definition, {
mesh,
edges,
shadow,
basePosition: mesh.position.clone(),
projected: [],
projectedCenter: { x: 0, y: 0 }
});
});
let selectedId = "body";
let lampAngle = 0;
let currentLamp = { ...DEFAULT_LAMP };
const shapeList = document.querySelector("#shape-list");
const selectedName = document.querySelector("#selected-name");
const positionX = document.querySelector("#position-x");
const positionY = document.querySelector("#position-y");
const xValue = document.querySelector("#x-value");
const yValue = document.querySelector("#y-value");
const lampSlider = document.querySelector("#lamp-angle");
const lampValue = document.querySelector("#lamp-value");
const showGuide = document.querySelector("#show-guide");
const matchValue = document.querySelector("#match-value");
const matchMeter = document.querySelector("#match-meter");
const partCount = document.querySelector("#part-count");
shapeDefinitions.forEach((definition) => {
const button = document.createElement("button");
button.className = "shape-button";
button.dataset.shapeId = definition.id;
button.innerHTML = `
<span class="shape-dot" style="--shape-color:${definition.css}"></span>
<span>${definition.name}</span>
`;
button.addEventListener("click", () => selectShape(definition.id));
shapeList.appendChild(button);
});
function getSelectedShape() {
return shapeDefinitions.find((definition) => definition.id === selectedId);
}
function selectShape(id) {
selectedId = id;
const definition = getSelectedShape();
selectedName.textContent = definition.name;
document.querySelectorAll(".shape-button").forEach((button) => {
button.classList.toggle("active", button.dataset.shapeId === id);
});
shapeDefinitions.forEach((item) => {
item.edges.material.color.set(
item.id === id ? 0xffe0a4 : 0x19262b
);
item.edges.material.opacity = item.id === id ? 0.95 : 0.72;
});
updateControlValues();
drawPreview();
}
function formatOffset(value) {
return `${value >= 0 ? "+" : ""}${value.toFixed(2)}`;
}
function updateControlValues() {
const definition = getSelectedShape();
const offsetX = definition.mesh.position.x - definition.basePosition.x;
const offsetY = definition.mesh.position.y - definition.basePosition.y;
positionX.value = THREE.MathUtils.clamp(offsetX, -1.8, 1.8);
positionY.value = THREE.MathUtils.clamp(offsetY, -1.8, 1.8);
xValue.textContent = formatOffset(offsetX);
yValue.textContent = formatOffset(offsetY);
}
function getLampPosition() {
const radians = THREE.MathUtils.degToRad(lampAngle);
return {
x: Math.sin(radians) * 4.3,
y: DEFAULT_LAMP.y + Math.sin(radians * 1.55) * 0.55,
z: DEFAULT_LAMP.z
};
}
function updateLampModel() {
const lampVector = new THREE.Vector3(
currentLamp.x,
currentLamp.y,
currentLamp.z
);
lampGroup.position.copy(lampVector);
pointLight.position.copy(lampVector);
const screenTarget = new THREE.Vector3(0, 0.12, -0.08);
const direction = lampVector.clone().sub(screenTarget);
const distance = direction.length();
beam.position.copy(screenTarget).add(lampVector).multiplyScalar(0.5);
beam.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
beam.scale.set(2.65, distance, 2.65);
}
function projectDefinition(definition) {
const t = currentLamp.z / (currentLamp.z - definition.depth);
const projected = definition.points.map((point) => ({
x: currentLamp.x + t * (definition.mesh.position.x + point.x - currentLamp.x),
y: currentLamp.y + t * (definition.mesh.position.y + point.y - currentLamp.y)
}));
definition.projected = projected;
definition.projectedCenter = {
x: currentLamp.x + t * (definition.mesh.position.x - currentLamp.x),
y: currentLamp.y + t * (definition.mesh.position.y - currentLamp.y)
};
}
function replaceShadowGeometry(definition) {
const shape = new THREE.Shape();
definition.projected.forEach((point, index) => {
if (index === 0) shape.moveTo(point.x, point.y);
else shape.lineTo(point.x, point.y);
});
shape.closePath();
const geometry = new THREE.ShapeGeometry(shape);
definition.shadow.geometry.dispose();
definition.shadow.geometry = geometry;
}
const targetMaskCanvas = document.createElement("canvas");
const currentMaskCanvas = document.createElement("canvas");
targetMaskCanvas.width = currentMaskCanvas.width = 360;
targetMaskCanvas.height = currentMaskCanvas.height = 300;
const targetMaskContext = targetMaskCanvas.getContext("2d");
const currentMaskContext = currentMaskCanvas.getContext("2d");
function maskTransform(width, height) {
const bounds = { minX: -2.8, maxX: 2.8, minY: -1.9, maxY: 2.15 };
const worldWidth = bounds.maxX - bounds.minX;
const worldHeight = bounds.maxY - bounds.minY;
const scale = Math.min(width / worldWidth, height / worldHeight);
return {
scale,
offsetX: (width - worldWidth * scale) * 0.5,
offsetY: (height - worldHeight * scale) * 0.5,
bounds
};
}
function fillMask(context, polygons, width, height) {
context.clearRect(0, 0, width, height);
context.fillStyle = "#fff";
const transform = maskTransform(width, height);
polygons.forEach((polygon) => {
context.beginPath();
polygon.forEach((point, index) => {
const x = transform.offsetX + (point.x - transform.bounds.minX) * transform.scale;
const y = height - (transform.offsetY + (point.y - transform.bounds.minY) * transform.scale);
if (index === 0) context.moveTo(x, y);
else context.lineTo(x, y);
});
context.closePath();
context.fill();
});
}
function calculateMatch() {
const width = targetMaskCanvas.width;
const height = targetMaskCanvas.height;
const targetPolygons = shapeDefinitions.map((definition) =>
definition.points.map((point) => ({
x: point.x + definition.center[0],
y: point.y + definition.center[1]
}))
);
const currentPolygons = shapeDefinitions.map((definition) => definition.projected);
fillMask(targetMaskContext, targetPolygons, width, height);
fillMask(currentMaskContext, currentPolygons, width, height);
const targetData = targetMaskContext.getImageData(0, 0, width, height).data;
const currentData = currentMaskContext.getImageData(0, 0, width, height).data;
let intersection = 0;
let union = 0;
for (let index = 0; index < targetData.length; index += 4) {
const targetAlpha = targetData[index + 3] > 24;
const currentAlpha = currentData[index + 3] > 24;
if (targetAlpha && currentAlpha) intersection++;
if (targetAlpha || currentAlpha) union++;
}
return union === 0 ? 1 : intersection / union;
}
function updateMatch() {
const score = Math.round(calculateMatch() * 100);
matchValue.textContent = `${score}%`;
matchMeter.style.width = `${score}%`;
matchValue.style.color = score > 88 ? "#6dc1b6" : score > 65 ? "#f0b65c" : "#ef8b62";
}
const previewBounds = {
minX: -2.8,
maxX: 2.8,
minY: -1.9,
maxY: 2.15
};
function previewTransform() {
const width = previewCanvas.clientWidth;
const height = previewCanvas.clientHeight;
const worldWidth = previewBounds.maxX - previewBounds.minX;
const worldHeight = previewBounds.maxY - previewBounds.minY;
const scale = Math.min(width / worldWidth, height / worldHeight);
return {
width,
height,
scale,
offsetX: (width - worldWidth * scale) * 0.5,
offsetY: (height - worldHeight * scale) * 0.5
};
}
function worldToPreview(point, transform = previewTransform()) {
return {
x: transform.offsetX + (point.x - previewBounds.minX) * transform.scale,
y: transform.height - (
transform.offsetY +
(point.y - previewBounds.minY) * transform.scale
)
};
}
function previewToWorld(point, transform = previewTransform()) {
return {
x: previewBounds.minX + (point.x - transform.offsetX) / transform.scale,
y: previewBounds.minY + (
transform.height - transform.offsetY - point.y
) / transform.scale
};
}
function tracePolygon(context, polygon, transform) {
context.beginPath();
polygon.forEach((point, index) => {
const converted = worldToPreview(point, transform);
if (index === 0) context.moveTo(converted.x, converted.y);
else context.lineTo(converted.x, converted.y);
});
context.closePath();
}
function drawPreview() {
const rect = previewCanvas.getBoundingClientRect();
const width = Math.max(1, Math.round(rect.width));
const height = Math.max(1, Math.round(rect.height));
const dpr = Math.min(window.devicePixelRatio || 1, 2);
if (previewCanvas.width !== Math.round(width * dpr) ||
previewCanvas.height !== Math.round(height * dpr)) {
previewCanvas.width = Math.round(width * dpr);
previewCanvas.height = Math.round(height * dpr);
}
previewContext.setTransform(dpr, 0, 0, dpr, 0, 0);
previewContext.clearRect(0, 0, width, height);
const gradient = previewContext.createRadialGradient(
width * 0.5,
height * 0.45,
20,
width * 0.5,
height * 0.45,
Math.max(width, height) * 0.75
);
gradient.addColorStop(0, "#15232a");
gradient.addColorStop(1, "#071015");
previewContext.fillStyle = gradient;
previewContext.fillRect(0, 0, width, height);
const transform = previewTransform();
previewContext.strokeStyle = "rgba(143, 171, 175, 0.055)";
previewContext.lineWidth = 1;
for (let x = 0; x <= width; x += 24) {
previewContext.beginPath();
previewContext.moveTo(x, 0);
previewContext.lineTo(x, height);
previewContext.stroke();
}
for (let y = 0; y <= height; y += 24) {
previewContext.beginPath();
previewContext.moveTo(0, y);
previewContext.lineTo(width, y);
previewContext.stroke();
}
if (showGuide.checked) {
previewContext.save();
previewContext.setLineDash([5, 5]);
previewContext.lineWidth = 1;
previewContext.strokeStyle = "rgba(240, 182, 92, 0.42)";
shapeDefinitions.forEach((definition) => {
const target = definition.points.map((point) => ({
x: point.x + definition.center[0],
y: point.y + definition.center[1]
}));
tracePolygon(previewContext, target, transform);
previewContext.stroke();
});
previewContext.restore();
}
previewContext.save();
previewContext.shadowColor = "rgba(0, 0, 0, 0.7)";
previewContext.shadowBlur = 12;
previewContext.fillStyle = "rgba(1, 5, 8, 0.82)";
shapeDefinitions.forEach((definition) => {
tracePolygon(previewContext, definition.projected, transform);
previewContext.fill();
});
previewContext.restore();
shapeDefinitions.forEach((definition) => {
tracePolygon(previewContext, definition.projected, transform);
previewContext.strokeStyle = definition.id === selectedId
? "rgba(109, 193, 182, 0.95)"
: `${definition.css}42`;
previewContext.lineWidth = definition.id === selectedId ? 1.7 : 0.8;
previewContext.stroke();
});
const selected = getSelectedShape();
const selectedCenter = worldToPreview(selected.projectedCenter, transform);
previewContext.fillStyle = "#6dc1b6";
previewContext.beginPath();
previewContext.arc(selectedCenter.x, selectedCenter.y, 3.5, 0, Math.PI * 2);
previewContext.fill();
previewContext.strokeStyle = "rgba(109, 193, 182, 0.3)";
previewContext.beginPath();
previewContext.arc(selectedCenter.x, selectedCenter.y, 8, 0, Math.PI * 2);
previewContext.stroke();
previewContext.strokeStyle = "rgba(198, 222, 220, 0.14)";
previewContext.lineWidth = 1;
const corner = 14;
const margin = 10;
[
[margin, margin, 1, 1],
[width - margin, margin, -1, 1],
[margin, height - margin, 1, -1],
[width - margin, height - margin, -1, -1]
].forEach(([x, y, dx, dy]) => {
previewContext.beginPath();
previewContext.moveTo(x + dx * corner, y);
previewContext.lineTo(x, y);
previewContext.lineTo(x, y + dy * corner);
previewContext.stroke();
});
previewContext.fillStyle = "rgba(184, 204, 202, 0.48)";
previewContext.font = "700 9px system-ui, sans-serif";
previewContext.fillText("PROJECTION SCREEN", 18, height - 18);
}
function updateProjection() {
currentLamp = getLampPosition();
updateLampModel();
shapeDefinitions.forEach((definition) => {
projectDefinition(definition);
replaceShadowGeometry(definition);
});
lampValue.textContent = `${lampAngle > 0 ? "+" : ""}${lampAngle}°`;
updateControlValues();
updateMatch();
drawPreview();
}
lampSlider.addEventListener("input", () => {
lampAngle = Number(lampSlider.value);
updateProjection();
});
positionX.addEventListener("input", () => {
const definition = getSelectedShape();
definition.mesh.position.x =
definition.basePosition.x + Number(positionX.value);
updateProjection();
});
positionY.addEventListener("input", () => {
const definition = getSelectedShape();
definition.mesh.position.y =
definition.basePosition.y + Number(positionY.value);
updateProjection();
});
showGuide.addEventListener("change", drawPreview);
document.querySelector("#snap-selected").addEventListener("click", () => {
const definition = getSelectedShape();
const factor = (currentLamp.z - definition.depth) / currentLamp.z;
definition.mesh.position.x =
currentLamp.x + (definition.center[0] - currentLamp.x) * factor;
definition.mesh.position.y =
currentLamp.y + (definition.center[1] - currentLamp.y) * factor;
updateProjection();
});
document.querySelector("#reset-selected").addEventListener("click", () => {
const definition = getSelectedShape();
definition.mesh.position.copy(definition.basePosition);
updateProjection();
});
document.querySelector("#reset-all").addEventListener("click", () => {
lampAngle = 0;
lampSlider.value = 0;
shapeDefinitions.forEach((definition) => {
definition.mesh.position.copy(definition.basePosition);
});
updateProjection();
});
document.querySelector("#reset-camera").addEventListener("click", resetCamera);
document.querySelector("#recenter-camera").addEventListener("click", resetCamera);
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane();
const dragPoint = new THREE.Vector3();
const dragOffset = new THREE.Vector3();
let stageDragging = null;
let orbiting = false;
let lastPointerX = 0;
let lastPointerY = 0;
function setPointerFromEvent(event) {
const rect = stageCanvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function getStageIntersection(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
return raycaster.intersectObjects(puppetMeshes, false);
}
stageCanvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
const intersections = getStageIntersection(event);
if (intersections.length) {
const mesh = intersections[0].object;
const definition = shapeDefinitions.find(
(item) => item.id === mesh.userData.shapeId
);
selectShape(definition.id);
dragPlane.set(new THREE.Vector3(0, 0, 1), -definition.depth);
raycaster.ray.intersectPlane(dragPlane, dragPoint);
dragOffset.set(
dragPoint.x - definition.mesh.position.x,
dragPoint.y - definition.mesh.position.y,
0
);
stageDragging = definition;
stageCanvas.setPointerCapture(event.pointerId);
} else {
orbiting = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
stageCanvas.setPointerCapture(event.pointerId);
}
});
stageCanvas.addEventListener("pointermove", (event) => {
if (stageDragging) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
const definition = stageDragging;
const nextX = dragPoint.x - dragOffset.x;
const nextY = dragPoint.y - dragOffset.y;
definition.mesh.position.x = THREE.MathUtils.clamp(
nextX,
definition.basePosition.x - 1.8,
definition.basePosition.x + 1.8
);
definition.mesh.position.y = THREE.MathUtils.clamp(
nextY,
definition.basePosition.y - 1.8,
definition.basePosition.y + 1.8
);
updateProjection();
}
return;
}
if (orbiting) {
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
orbit.theta -= deltaX * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi + deltaY * 0.005,
0.62,
1.48
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
return;
}
const intersections = getStageIntersection(event);
stageCanvas.style.cursor = intersections.length ? "grab" : "default";
});
function endStagePointer(event) {
stageDragging = null;
orbiting = false;
if (stageCanvas.hasPointerCapture(event.pointerId)) {
stageCanvas.releasePointerCapture(event.pointerId);
}
}
stageCanvas.addEventListener("pointerup", endStagePointer);
stageCanvas.addEventListener("pointercancel", endStagePointer);
stageCanvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.zoom = THREE.MathUtils.clamp(
orbit.zoom * Math.exp(-event.deltaY * 0.001),
0.65,
1.8
);
updateCamera();
},
{ passive: false }
);
function pointInPolygon(point, polygon) {
let inside = false;
for (
let current = 0, previous = polygon.length - 1;
current < polygon.length;
previous = current++
) {
const currentPoint = polygon[current];
const previousPoint = polygon[previous];
const intersects =
currentPoint.y > point.y !== previousPoint.y > point.y &&
point.x <
((previousPoint.x - currentPoint.x) *
(point.y - currentPoint.y)) /
(previousPoint.y - currentPoint.y) +
currentPoint.x;
if (intersects) inside = !inside;
}
return inside;
}
let previewDragging = null;
let previewDragStart = null;
let previewMeshStart = null;
previewCanvas.addEventListener("pointerdown", (event) => {
const rect = previewCanvas.getBoundingClientRect();
const screenPoint = {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
const worldPoint = previewToWorld(screenPoint);
for (let index = shapeDefinitions.length - 1; index >= 0; index--) {
const definition = shapeDefinitions[index];
if (pointInPolygon(worldPoint, definition.projected)) {
selectShape(definition.id);
previewDragging = definition;
previewDragStart = worldPoint;
previewMeshStart = definition.mesh.position.clone();
previewCanvas.setPointerCapture(event.pointerId);
previewCanvas.style.cursor = "grabbing";
break;
}
}
});
previewCanvas.addEventListener("pointermove", (event) => {
if (!previewDragging) {
const rect = previewCanvas.getBoundingClientRect();
const screenPoint = {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
const worldPoint = previewToWorld(screenPoint);
const hovering = shapeDefinitions.some((definition) =>
pointInPolygon(worldPoint, definition.projected)
);
previewCanvas.style.cursor = hovering ? "grab" : "crosshair";
return;
}
const rect = previewCanvas.getBoundingClientRect();
const worldPoint = previewToWorld({
x: event.clientX - rect.left,
y: event.clientY - rect.top
});
const deltaX = worldPoint.x - previewDragStart.x;
const deltaY = worldPoint.y - previewDragStart.y;
const scale = (currentLamp.z - previewDragging.depth) / currentLamp.z;
previewDragging.mesh.position.x = THREE.MathUtils.clamp(
previewMeshStart.x + deltaX * scale,
previewDragging.basePosition.x - 1.8,
previewDragging.basePosition.x + 1.8
);
previewDragging.mesh.position.y = THREE.MathUtils.clamp(
previewMeshStart.y + deltaY * scale,
previewDragging.basePosition.y - 1.8,
previewDragging.basePosition.y + 1.8
);
updateProjection();
});
function endPreviewPointer(event) {
previewDragging = null;
previewDragStart = null;
previewMeshStart = null;
previewCanvas.style.cursor = "crosshair";
if (previewCanvas.hasPointerCapture(event.pointerId)) {
previewCanvas.releasePointerCapture(event.pointerId);
}
}
previewCanvas.addEventListener("pointerup", endPreviewPointer);
previewCanvas.addEventListener("pointercancel", endPreviewPointer);
function resizeRenderer() {
const rect = stageCanvas.getBoundingClientRect();
const width = Math.max(1, rect.width);
const height = Math.max(1, rect.height);
const aspect = width / height;
const viewHeight = 7.8;
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
drawPreview();
}
const stageObserver = new ResizeObserver(resizeRenderer);
stageObserver.observe(stageCanvas);
const previewObserver = new ResizeObserver(drawPreview);
previewObserver.observe(previewCanvas);
partCount.textContent = `${shapeDefinitions.length} pieces`;
selectShape(selectedId);
updateProjection();
resizeRenderer();
renderer.setAnimationLoop(() => {
lampOrb.rotation.x += 0.004;
lampOrb.rotation.y += 0.006;
lampRing.rotation.z += 0.003;
renderer.render(scene, camera);
});
</script>
</body>
</html>
```