Prompt specification
Build or customize the Three.js 3D scene "Shape-matching seal puzzle" 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: Shape-matching seal puzzle
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/shape-matching-seal-puzzle-x0264
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: shape-matching seal puzzle. Create several noncircular containers and flexible ring candidates; users choose continuous matching boundaries, and an animated tracer tests whether any opening remains along the seam. Return one self-contained HTML file.
Working Three.js Starter (shape-matching-seal-puzzle-x0264):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Seam — Shape-Matching Seal Puzzle</title>
<style>
:root {
--ink: #17333b;
--muted: #6d7e80;
--paper: #f4eee1;
--panel: rgba(255, 252, 244, 0.91);
--line: rgba(23, 51, 59, 0.13);
--green: #168b75;
--green-soft: #d9eee5;
--red: #d94b48;
--red-soft: #f8dfd9;
--gold: #e3a92f;
--shadow: 0 16px 44px rgba(43, 61, 57, 0.14);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e8dfce;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
#app, #scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
#scene {
display: block;
touch-action: none;
cursor: grab;
outline: none;
}
#scene:active { cursor: grabbing; }
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 5;
}
.topbar {
position: absolute;
top: 22px;
left: 24px;
right: 24px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
padding: 10px 13px 10px 10px;
border: 1px solid rgba(255,255,255,.48);
border-radius: 17px;
background: rgba(255, 252, 244, .78);
box-shadow: 0 8px 28px rgba(43,61,57,.08);
backdrop-filter: blur(14px);
}
.brand-mark {
width: 43px;
height: 43px;
border-radius: 12px;
display: grid;
place-items: center;
background: var(--ink);
color: #f9d36d;
box-shadow: inset 0 0 0 1px rgba(255,255,255,.1);
}
.brand-mark svg { width: 27px; height: 27px; }
.brand h1 {
margin: 0;
font-size: 16px;
line-height: 1;
letter-spacing: .16em;
text-transform: uppercase;
}
.brand p {
margin: 5px 0 0;
font-size: 11px;
color: var(--muted);
letter-spacing: .025em;
}
.top-actions {
display: flex;
align-items: center;
gap: 9px;
pointer-events: auto;
}
.progress-pill {
min-width: 112px;
padding: 11px 15px;
border: 1px solid rgba(255,255,255,.48);
border-radius: 15px;
background: rgba(255,252,244,.8);
box-shadow: 0 8px 28px rgba(43,61,57,.08);
backdrop-filter: blur(14px);
text-align: center;
}
.progress-pill small {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: .15em;
text-transform: uppercase;
}
.progress-pill strong {
display: block;
margin-top: 2px;
font-size: 18px;
letter-spacing: .04em;
}
.icon-button {
width: 42px;
height: 42px;
border: 1px solid rgba(255,255,255,.5);
border-radius: 13px;
background: rgba(255,252,244,.82);
color: var(--ink);
cursor: pointer;
box-shadow: 0 8px 28px rgba(43,61,57,.08);
transition: transform .16s ease, background .16s ease;
}
.icon-button:hover { transform: translateY(-1px); background: #fffdf7; }
.panel {
position: absolute;
top: 96px;
width: 264px;
padding: 17px;
border: 1px solid rgba(255,255,255,.55);
border-radius: 22px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
pointer-events: auto;
}
.panel.left { left: 24px; }
.panel.right { right: 24px; width: 292px; }
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin: 0 0 5px;
color: var(--muted);
font-size: 9px;
font-weight: 850;
letter-spacing: .17em;
text-transform: uppercase;
}
.step-number {
width: 22px;
height: 22px;
border-radius: 8px;
display: grid;
place-items: center;
background: var(--ink);
color: white;
font-size: 10px;
letter-spacing: 0;
}
.panel h2 {
margin: 0;
font-size: 19px;
letter-spacing: -.025em;
}
.panel-intro {
margin: 6px 0 14px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.candidate-list {
display: grid;
gap: 8px;
max-height: 48vh;
overflow: auto;
padding: 1px;
scrollbar-width: thin;
}
.candidate {
position: relative;
display: grid;
grid-template-columns: 56px 1fr auto;
align-items: center;
gap: 10px;
min-height: 66px;
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(255,255,255,.53);
cursor: grab;
transition: transform .16s ease, border-color .16s ease, background .16s ease;
}
.candidate:hover {
transform: translateY(-1px);
border-color: rgba(23,51,59,.28);
background: rgba(255,255,255,.84);
}
.candidate.armed {
border-color: var(--gold);
box-shadow: 0 0 0 2px rgba(227,169,47,.16);
}
.candidate.active {
border-color: var(--green);
box-shadow: 0 0 0 2px rgba(22,139,117,.12);
}
.candidate.placed::after {
content: "";
position: absolute;
top: -3px;
right: -3px;
width: 10px;
height: 10px;
border: 2px solid var(--panel);
border-radius: 50%;
background: var(--green);
}
.candidate.dragging { opacity: .55; }
.shape-preview {
width: 54px;
height: 54px;
display: grid;
place-items: center;
border-radius: 12px;
background: rgba(23,51,59,.055);
}
.shape-preview svg {
width: 48px;
height: 48px;
overflow: visible;
}
.candidate-copy { min-width: 0; }
.candidate-name {
display: block;
font-size: 12px;
font-weight: 800;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.candidate-note {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
line-height: 1.25;
}
.candidate-state {
align-self: stretch;
min-width: 34px;
display: grid;
place-items: center;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: .07em;
text-transform: uppercase;
}
.candidate-state.sealed { color: var(--green); }
.candidate-state.mismatch { color: var(--red); }
.tip {
display: flex;
gap: 8px;
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.tip b { color: var(--ink); }
.selected-name {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 15px 0 13px;
padding: 10px 11px;
border-radius: 12px;
background: rgba(23,51,59,.055);
}
.selected-name span {
font-size: 11px;
font-weight: 800;
}
.selected-name small {
color: var(--muted);
font-size: 9px;
}
.control { margin: 13px 0; }
.control-row {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 7px;
}
.control label {
font-size: 10px;
font-weight: 800;
letter-spacing: .04em;
text-transform: uppercase;
}
.control output {
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
appearance: none;
border-radius: 999px;
background: linear-gradient(90deg, var(--green), #b9d6cb);
outline: none;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
appearance: none;
border: 3px solid white;
border-radius: 50%;
background: var(--green);
box-shadow: 0 2px 7px rgba(23,51,59,.25);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid white;
border-radius: 50%;
background: var(--green);
box-shadow: 0 2px 7px rgba(23,51,59,.25);
}
input[type="range"]:disabled { opacity: .35; cursor: not-allowed; }
.diagnostic {
margin-top: 14px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255,255,255,.5);
}
.diagnostic-head {
display: flex;
justify-content: space-between;
gap: 8px;
font-size: 10px;
font-weight: 800;
}
.diagnostic-head span:last-child { color: var(--green); }
.diagnostic-head span.bad { color: var(--red); }
.meter {
height: 5px;
margin: 9px 0 7px;
overflow: hidden;
border-radius: 99px;
background: rgba(23,51,59,.09);
}
.meter > i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--green);
transition: width .15s ease, background .15s ease;
}
.diagnostic p {
margin: 0;
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.button-row {
display: flex;
gap: 8px;
margin-top: 12px;
}
.small-button {
flex: 1;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255,255,255,.66);
color: var(--ink);
font-size: 9px;
font-weight: 800;
letter-spacing: .055em;
text-transform: uppercase;
cursor: pointer;
transition: background .15s ease, transform .15s ease;
}
.small-button:hover { transform: translateY(-1px); background: white; }
.small-button:disabled { opacity: .4; cursor: not-allowed; transform: none; }
.actionbar {
position: absolute;
left: 50%;
bottom: 22px;
display: flex;
align-items: center;
gap: 13px;
transform: translateX(-50%);
pointer-events: auto;
}
.trace-readout {
min-width: 220px;
padding: 11px 15px;
border: 1px solid rgba(255,255,255,.5);
border-radius: 16px;
background: rgba(255,252,244,.87);
box-shadow: 0 10px 32px rgba(43,61,57,.1);
backdrop-filter: blur(14px);
text-align: center;
}
.trace-readout small {
display: block;
color: var(--muted);
font-size: 8px;
font-weight: 850;
letter-spacing: .15em;
text-transform: uppercase;
}
.trace-readout strong {
display: block;
margin-top: 3px;
font-size: 11px;
}
.trace-button {
min-width: 178px;
padding: 15px 21px;
border: 0;
border-radius: 16px;
background: var(--ink);
color: white;
box-shadow: 0 12px 28px rgba(23,51,59,.24);
font-size: 10px;
font-weight: 850;
letter-spacing: .12em;
text-transform: uppercase;
cursor: pointer;
transition: transform .16s ease, background .16s ease;
}
.trace-button:hover { transform: translateY(-2px); background: #214650; }
.trace-button:disabled { opacity: .45; cursor: not-allowed; transform: none; }
.scene-hint {
position: absolute;
left: 24px;
bottom: 24px;
padding: 8px 11px;
border-radius: 10px;
background: rgba(255,252,244,.67);
color: var(--muted);
font-size: 8px;
font-weight: 750;
letter-spacing: .09em;
text-transform: uppercase;
backdrop-filter: blur(10px);
}
.world-label {
position: absolute;
z-index: 4;
padding: 6px 9px;
border: 1px solid rgba(255,255,255,.55);
border-radius: 9px;
background: rgba(255,252,244,.75);
color: var(--ink);
font-size: 8px;
font-weight: 850;
letter-spacing: .12em;
text-transform: uppercase;
pointer-events: none;
transform: translate(-50%, -50%);
backdrop-filter: blur(9px);
white-space: nowrap;
}
.gap-label {
position: absolute;
z-index: 8;
display: none;
padding: 8px 11px;
border: 2px solid white;
border-radius: 11px;
background: var(--red);
color: white;
font-size: 9px;
font-weight: 900;
letter-spacing: .1em;
text-transform: uppercase;
pointer-events: none;
transform: translate(-50%, -135%);
box-shadow: 0 8px 24px rgba(149,39,37,.25);
}
.gap-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -7px;
width: 10px;
height: 10px;
border-right: 2px solid white;
border-bottom: 2px solid white;
background: var(--red);
transform: translateX(-50%) rotate(45deg);
}
.toast {
position: absolute;
left: 50%;
top: 88px;
z-index: 12;
max-width: min(430px, calc(100vw - 32px));
padding: 11px 15px;
border: 1px solid rgba(255,255,255,.58);
border-radius: 13px;
background: rgba(23,51,59,.91);
color: white;
box-shadow: 0 12px 30px rgba(23,51,59,.18);
font-size: 11px;
line-height: 1.45;
text-align: center;
pointer-events: none;
opacity: 0;
transform: translate(-50%, -8px);
transition: opacity .2s ease, transform .2s ease;
}
.toast.show { opacity: 1; transform: translate(-50%, 0); }
@media (max-width: 900px) {
.panel.left { width: 225px; }
.panel.right { width: 250px; }
.candidate { grid-template-columns: 47px 1fr; }
.shape-preview { width: 45px; height: 45px; }
.shape-preview svg { width: 41px; height: 41px; }
.candidate-state { display: none; }
.scene-hint { display: none; }
}
@media (max-width: 650px) {
.topbar { top: 12px; left: 12px; right: 12px; }
.brand p { display: none; }
.brand { padding-right: 11px; }
.progress-pill { min-width: 86px; padding: 8px 10px; }
.panel { top: 74px; padding: 12px; border-radius: 16px; }
.panel.left { left: 10px; width: 172px; }
.panel.right { right: 10px; width: 184px; }
.panel h2 { font-size: 15px; }
.panel-intro, .tip { display: none; }
.candidate-list { max-height: 43vh; }
.candidate { grid-template-columns: 37px 1fr; min-height: 52px; gap: 7px; }
.shape-preview { width: 36px; height: 36px; }
.shape-preview svg { width: 34px; height: 34px; }
.candidate-name { font-size: 10px; }
.candidate-note { font-size: 8px; }
.selected-name { margin: 9px 0; padding: 7px; }
.control { margin: 9px 0; }
.diagnostic { display: none; }
.actionbar { bottom: 12px; gap: 7px; }
.trace-readout { display: none; }
.trace-button { min-width: 145px; padding: 14px 15px; }
}
</style>
</head>
<body>
<div id="app">
<canvas id="scene" aria-label="Interactive three-dimensional seal matching puzzle"></canvas>
<div class="hud">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 32 32" fill="none">
<path d="M7 13.5C7 9.9 10.2 7 14 7h4c3.8 0 7 2.9 7 6.5S21.8 20 18 20h-4c-3.8 0-7-2.9-7-6.5Z"
stroke="currentColor" stroke-width="2"/>
<path d="M10.5 7 9 3.5M21.5 7 23 3.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
</div>
<div>
<h1>Seam</h1>
<p>Shape-matching seal laboratory</p>
</div>
</div>
<div class="top-actions">
<div class="progress-pill">
<small>Seams sealed</small>
<strong id="progressText">0 / 3</strong>
</div>
<button class="icon-button" id="homeView" title="Reset camera view" aria-label="Reset camera view">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<path d="M4 10 12 4l8 6v9a1 1 0 0 1-1 1h-5v-6h-4v6H5a1 1 0 0 1-1-1v-9Z"
stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
</svg>
</button>
</div>
</header>
<aside class="panel left">
<p class="eyebrow"><span class="step-number">1</span> Choose a boundary</p>
<h2>Flexible rings</h2>
<p class="panel-intro">Click a ring, then click a vessel. You can also drag a ring directly onto a vessel.</p>
<div class="candidate-list" id="candidateList"></div>
<div class="tip">
<span>↗</span>
<span><b>Shape first:</b> choose the candidate whose continuous outline resembles the vessel opening.</span>
</div>
</aside>
<aside class="panel right">
<p class="eyebrow"><span class="step-number">2</span> Fit the boundary</p>
<h2>Seam tuner</h2>
<p class="panel-intro">Shape the ring, align it with the rim, and make the contact continuous all the way around.</p>
<div class="selected-name">
<span id="selectedName">No ring selected</span>
<small id="selectedState">Waiting</small>
</div>
<div class="control">
<div class="control-row">
<label for="scaleRange">Scale</label>
<output id="scaleValue">1.00×</output>
</div>
<input id="scaleRange" type="range" min="0.72" max="1.24" step="0.01" value="1" disabled>
</div>
<div class="control">
<div class="control-row">
<label for="flexRange">Flex</label>
<output id="flexValue">1.00×</output>
</div>
<input id="flexRange" type="range" min="0" max="2" step="0.01" value="1" disabled>
</div>
<div class="control">
<div class="control-row">
<label for="rotationRange">Rotation</label>
<output id="rotationValue">0°</output>
</div>
<input id="rotationRange" type="range" min="-180" max="180" step="1" value="0" disabled>
</div>
<div class="diagnostic">
<div class="diagnostic-head">
<span>Contour agreement</span>
<span id="agreementValue">—</span>
</div>
<div class="meter"><i id="agreementMeter"></i></div>
<p id="diagnosticText">Select a ring to inspect its boundary.</p>
</div>
<div class="button-row">
<button class="small-button" id="removeButton" disabled>Remove ring</button>
<button class="small-button" id="testButton" disabled>Test this seam</button>
</div>
</aside>
<div class="actionbar">
<div class="trace-readout">
<small>Seam tracer</small>
<strong id="traceStatus">Ready when you are</strong>
</div>
<button class="trace-button" id="traceButton" disabled>Trace all seams</button>
</div>
<div class="scene-hint">Drag to orbit · Scroll to zoom · Click a vessel to place</div>
<div class="gap-label" id="gapLabel">Opening</div>
<div class="toast" id="toast"></div>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const candidateList = document.querySelector("#candidateList");
const selectedName = document.querySelector("#selectedName");
const selectedState = document.querySelector("#selectedState");
const scaleRange = document.querySelector("#scaleRange");
const flexRange = document.querySelector("#flexRange");
const rotationRange = document.querySelector("#rotationRange");
const scaleValue = document.querySelector("#scaleValue");
const flexValue = document.querySelector("#flexValue");
const rotationValue = document.querySelector("#rotationValue");
const agreementValue = document.querySelector("#agreementValue");
const agreementMeter = document.querySelector("#agreementMeter");
const diagnosticText = document.querySelector("#diagnosticText");
const removeButton = document.querySelector("#removeButton");
const testButton = document.querySelector("#testButton");
const traceButton = document.querySelector("#traceButton");
const traceStatus = document.querySelector("#traceStatus");
const progressText = document.querySelector("#progressText");
const gapLabel = document.querySelector("#gapLabel");
const toastElement = document.querySelector("#toast");
const TARGETS = [
{
id: "orchard",
name: "Orchard Vessel",
short: "Orchard",
x: -3.15,
color: 0x248b82,
dark: 0x155d5b,
accent: 0xffd37b,
profile: {
base: 1.27,
harmonics: [{ n: 4, a: 0.17, p: 0 }]
}
},
{
id: "twin",
name: "Twin Basin",
short: "Twin Bay",
x: 0,
color: 0xe46d58,
dark: 0x873f3a,
accent: 0xffc1a8,
profile: {
base: 1.27,
harmonics: [
{ n: 2, a: 0.13, p: 0 },
{ n: 3, a: 0.055, p: 0.25 }
]
}
},
{
id: "delta",
name: "Delta Cup",
short: "Delta",
x: 3.15,
color: 0x477eaf,
dark: 0x294f74,
accent: 0xa8d4ed,
profile: {
base: 1.27,
harmonics: [
{ n: 3, a: 0.11, p: 0.32 },
{ n: 6, a: 0.035, p: 0 }
]
}
}
];
const CANDIDATES = [
{
id: "quad",
name: "Quad Loop",
note: "four broad corners",
color: 0xe7a934,
profile: {
base: 1.27,
harmonics: [{ n: 4, a: 0.17, p: 0 }]
}
},
{
id: "twin",
name: "Twin Loop",
note: "double-lobed curve",
color: 0xd75d52,
profile: {
base: 1.27,
harmonics: [
{ n: 2, a: 0.13, p: 0 },
{ n: 3, a: 0.055, p: 0.25 }
]
}
},
{
id: "delta",
name: "Delta Loop",
note: "soft triangular wave",
color: 0x397cae,
profile: {
base: 1.27,
harmonics: [
{ n: 3, a: 0.11, p: 0.32 },
{ n: 6, a: 0.035, p: 0 }
]
}
},
{
id: "crown",
name: "Crown Loop",
note: "five shallow peaks",
color: 0x8e6bb2,
profile: {
base: 1.27,
harmonics: [
{ n: 5, a: 0.115, p: 0 },
{ n: 10, a: 0.032, p: 0 }
]
}
},
{
id: "tidal",
name: "Tidal Loop",
note: "wide oval with ripples",
color: 0x4a9b72,
profile: {
base: 1.27,
harmonics: [
{ n: 2, a: 0.19, p: 0 },
{ n: 4, a: 0.055, p: 0.2 }
]
}
}
];
const TOLERANCE = 0.029;
const TRACE_SAMPLES = 144;
const targetById = new Map(TARGETS.map(target => [target.id, target]));
const candidateById = new Map();
let activeCandidateId = null;
let armedCandidateId = null;
let toastTimer = 0;
let traceAnimation = null;
let pointerDown = null;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8dfce);
scene.fog = new THREE.Fog(0xe8dfce, 15, 31);
const camera = new THREE.PerspectiveCamera(42, innerWidth / innerHeight, 0.1, 80);
const cameraState = {
target: new THREE.Vector3(0, 0.95, 0),
radius: 11.6,
theta: 0.58,
phi: 1.03
};
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const hemi = new THREE.HemisphereLight(0xfff7e5, 0x71847d, 2.05);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff0cf, 3.0);
sun.position.set(-6, 11, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xaed9e6, 0.8);
fill.position.set(7, 5, -8);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(50, 50),
new THREE.MeshStandardMaterial({ color: 0xe3d9c6, roughness: 1 })
);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(32, 32, 0x9fafaa, 0xb9c3b9);
grid.position.y = 0.008;
grid.material.transparent = true;
grid.material.opacity = 0.18;
scene.add(grid);
const worldLabels = [];
const vesselPickMeshes = [];
const ringPickMeshes = [];
function profileRadius(profile, theta, flex = 1) {
let radius = profile.base;
for (const harmonic of profile.harmonics) {
radius += harmonic.a * flex * Math.cos(harmonic.n * theta + harmonic.p);
}
return radius;
}
function pushTriangle(positions, colors, a, b, c, color) {
positions.push(a.x, a.y, a.z, b.x, b.y, b.z, c.x, c.y, c.z);
for (let i = 0; i < 3; i++) colors.push(color.r, color.g, color.b);
}
function geometryFromTriangles(positions, colors) {
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;
}
function colorVariation(base, variation) {
const color = new THREE.Color(base);
color.offsetHSL(0, 0, variation);
return color;
}
function makeVessel(target) {
const group = new THREE.Group();
group.position.x = target.x;
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(1.56, 1.7, 0.2, 12),
new THREE.MeshStandardMaterial({
color: 0xf0e6d3,
roughness: 0.92,
flatShading: true
})
);
pedestal.position.y = 0.1;
pedestal.castShadow = true;
pedestal.receiveShadow = true;
group.add(pedestal);
const pedestalTop = new THREE.Mesh(
new THREE.CylinderGeometry(1.48, 1.48, 0.035, 12),
new THREE.MeshStandardMaterial({ color: 0xf8efdf, roughness: 0.9, flatShading: true })
);
pedestalTop.position.y = 0.22;
pedestalTop.receiveShadow = true;
group.add(pedestalTop);
const segments = 40;
const outerPositions = [];
const outerColors = [];
const outerRings = [
{ y: 0.34, scale: 0.70 },
{ y: 0.91, scale: 0.96 },
{ y: 1.52, scale: 1.00 }
];
const outerPoint = (theta, ring) => {
const radius = profileRadius(target.profile, theta) * ring.scale;
return new THREE.Vector3(Math.cos(theta) * radius, ring.y, Math.sin(theta) * radius);
};
for (let r = 0; r < outerRings.length - 1; r++) {
for (let i = 0; i < segments; i++) {
const a = i / segments * Math.PI * 2;
const b = (i + 1) / segments * Math.PI * 2;
const p00 = outerPoint(a, outerRings[r]);
const p01 = outerPoint(b, outerRings[r]);
const p10 = outerPoint(a, outerRings[r + 1]);
const p11 = outerPoint(b, outerRings[r + 1]);
const shade = 0.92 + 0.075 * Math.sin(i * 1.73 + r * 2.1);
const color = colorVariation(target.color, (shade - 1) * 0.65);
pushTriangle(outerPositions, outerColors, p00, p10, p01, color);
pushTriangle(outerPositions, outerColors, p01, p10, p11, color);
}
}
const outerMesh = new THREE.Mesh(
geometryFromTriangles(outerPositions, outerColors),
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.76,
metalness: 0.025,
flatShading: true
})
);
outerMesh.castShadow = true;
outerMesh.receiveShadow = true;
outerMesh.userData.targetId = target.id;
group.add(outerMesh);
vesselPickMeshes.push(outerMesh);
const innerPositions = [];
const innerColors = [];
const innerRings = [
{ y: 1.52, scale: 1.00, inset: 0.145 },
{ y: 0.78, scale: 0.70, inset: 0.12 },
{ y: 0.43, scale: 0.48, inset: 0.10 }
];
const innerPoint = (theta, ring) => {
const radius = profileRadius(target.profile, theta) * ring.scale - ring.inset;
return new THREE.Vector3(Math.cos(theta) * radius, ring.y, Math.sin(theta) * radius);
};
for (let r = 0; r < innerRings.length - 1; r++) {
for (let i = 0; i < segments; i++) {
const a = i / segments * Math.PI * 2;
const b = (i + 1) / segments * Math.PI * 2;
const p00 = innerPoint(a, innerRings[r]);
const p01 = innerPoint(b, innerRings[r]);
const p10 = innerPoint(a, innerRings[r + 1]);
const p11 = innerPoint(b, innerRings[r + 1]);
const color = colorVariation(target.dark, 0.035 * Math.sin(i * 1.4 + r));
pushTriangle(innerPositions, innerColors, p00, p01, p10, color);
pushTriangle(innerPositions, innerColors, p01, p11, p10, color);
}
}
const innerMesh = new THREE.Mesh(
geometryFromTriangles(innerPositions, innerColors),
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.9,
flatShading: true
})
);
innerMesh.receiveShadow = true;
group.add(innerMesh);
const rimPositions = [];
const rimColors = [];
for (let i = 0; i < segments; i++) {
const a = i / segments * Math.PI * 2;
const b = (i + 1) / segments * Math.PI * 2;
const outerA = profileRadius(target.profile, a);
const outerB = profileRadius(target.profile, b);
const o0 = new THREE.Vector3(Math.cos(a) * outerA, 1.525, Math.sin(a) * outerA);
const o1 = new THREE.Vector3(Math.cos(b) * outerB, 1.525, Math.sin(b) * outerB);
const i0 = new THREE.Vector3(Math.cos(a) * (outerA - 0.145), 1.525, Math.sin(a) * (outerA - 0.145));
const i1 = new THREE.Vector3(Math.cos(b) * (outerB - 0.145), 1.525, Math.sin(b) * (outerB - 0.145));
const color = colorVariation(target.accent, -0.015 * Math.sin(i));
pushTriangle(rimPositions, rimColors, o0, i0, o1, color);
pushTriangle(rimPositions, rimColors, o1, i0, i1, color);
}
const rim = new THREE.Mesh(
geometryFromTriangles(rimPositions, rimColors),
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.72,
flatShading: true
})
);
rim.castShadow = true;
rim.receiveShadow = true;
group.add(rim);
const floorPositions = [];
const floorColors = [];
const center = new THREE.Vector3(0, 0.435, 0);
for (let i = 0; i < segments; i++) {
const a = i / segments * Math.PI * 2;
const b = (i + 1) / segments * Math.PI * 2;
const ra = profileRadius(target.profile, a) * 0.48 - 0.10;
const rb = profileRadius(target.profile, b) * 0.48 - 0.10;
const p0 = new THREE.Vector3(Math.cos(a) * ra, 0.435, Math.sin(a) * ra);
const p1 = new THREE.Vector3(Math.cos(b) * rb, 0.435, Math.sin(b) * rb);
pushTriangle(floorPositions, floorColors, center, p1, p0, colorVariation(target.dark, 0.015));
}
const floor = new THREE.Mesh(
geometryFromTriangles(floorPositions, floorColors),
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.94,
flatShading: true
})
);
floor.receiveShadow = true;
group.add(floor);
const outlinePoints = [];
for (let i = 0; i < 64; i++) {
const theta = i / 64 * Math.PI * 2;
const radius = profileRadius(target.profile, theta);
outlinePoints.push(new THREE.Vector3(Math.cos(theta) * radius, 1.585, Math.sin(theta) * radius));
}
const outlineCurve = new THREE.CatmullRomCurve3(outlinePoints, true, "centripetal");
const outline = new THREE.Mesh(
new THREE.TubeGeometry(outlineCurve, 96, 0.025, 4, true),
new THREE.MeshStandardMaterial({
color: target.accent,
roughness: 0.55,
emissive: target.accent,
emissiveIntensity: 0.08
})
);
group.add(outline);
scene.add(group);
const label = document.createElement("div");
label.className = "world-label";
label.textContent = `${String(TARGETS.indexOf(target) + 1).padStart(2, "0")} / ${target.short}`;
document.querySelector(".hud").appendChild(label);
worldLabels.push({
element: label,
position: new THREE.Vector3(target.x, 2.25, 0)
});
return group;
}
function makeRingGeometry(candidate) {
const positions = [];
const colors = [];
const segments = 64;
const width = 0.15;
const halfHeight = 0.047;
const baseColor = new THREE.Color(candidate.color);
const topColor = colorVariation(candidate.color, 0.12);
const sideColor = colorVariation(candidate.color, -0.06);
const innerColor = colorVariation(candidate.color, -0.13);
const point = (theta, outward, top) => {
const radius = profileRadius(candidate.profile, theta, candidate.flex)
+ (outward ? width * 0.5 : -width * 0.5);
return new THREE.Vector3(
Math.cos(theta) * radius,
top ? halfHeight : -halfHeight,
Math.sin(theta) * radius
);
};
for (let i = 0; i < segments; i++) {
const a = i / segments * Math.PI * 2;
const b = (i + 1) / segments * Math.PI * 2;
const ia = point(a, false, true);
const ib = point(b, false, true);
const oa = point(a, true, true);
const ob = point(b, true, true);
const iab = point(a, false, false);
const ibb = point(b, false, false);
const oab = point(a, true, false);
const obb = point(b, true, false);
const segmentShade = 0.92 + 0.055 * Math.sin(i * 1.31);
const tc = topColor.clone().multiplyScalar(segmentShade);
const sc = sideColor.clone().multiplyScalar(segmentShade);
pushTriangle(positions, colors, ia, ib, oa, tc);
pushTriangle(positions, colors, ib, ob, oa, tc);
pushTriangle(positions, colors, ia, oa, ib, tc.clone().multiplyScalar(0.92));
pushTriangle(positions, colors, ib, oa, ob, tc.clone().multiplyScalar(0.92));
pushTriangle(positions, colors, oab, oa, obb, sc);
pushTriangle(positions, colors, obb, oa, ob, sc);
pushTriangle(positions, colors, iab, ibb, ia, innerColor);
pushTriangle(positions, colors, ibb, ib, ia, innerColor);
}
return geometryFromTriangles(positions, colors);
}
function miniShapePath(profile) {
const points = [];
for (let i = 0; i < 48; i++) {
const theta = i / 48 * Math.PI * 2;
const radius = profileRadius(profile, theta);
points.push([
50 + Math.cos(theta) * radius * 25,
50 + Math.sin(theta) * radius * 25
]);
}
return `M ${points.map(p => `${p[0].toFixed(2)} ${p[1].toFixed(2)}`).join(" L ")} Z`;
}
function createCandidateUI(candidate) {
const button = document.createElement("button");
button.type = "button";
button.className = "candidate";
button.draggable = true;
button.dataset.candidateId = candidate.id;
button.innerHTML = `
<span class="shape-preview">
<svg viewBox="0 0 100 100" aria-hidden="true">
<path d="${miniShapePath(candidate.profile)}"
fill="rgba(255,255,255,.18)"
stroke="#${new THREE.Color(candidate.color).getHexString()}"
stroke-width="6"
stroke-linejoin="round"/>
</svg>
</span>
<span class="candidate-copy">
<span class="candidate-name">${candidate.name}</span>
<span class="candidate-note">${candidate.note}</span>
</span>
<span class="candidate-state">Open</span>
`;
button.addEventListener("click", () => {
if (candidate.targetId) {
armedCandidateId = null;
selectCandidate(candidate.id);
} else {
selectCandidate(candidate.id);
armedCandidateId = armedCandidateId === candidate.id ? null : candidate.id;
if (armedCandidateId) {
toast("Boundary armed. Click a vessel to place it, or drag it onto the rim.");
}
}
updateUI();
});
button.addEventListener("dragstart", event => {
armedCandidateId = candidate.id;
activeCandidateId = candidate.id;
event.dataTransfer.setData("text/plain", candidate.id);
event.dataTransfer.effectAllowed = "move";
button.classList.add("dragging");
updateUI();
});
button.addEventListener("dragend", () => {
button.classList.remove("dragging");
});
candidateList.appendChild(button);
candidate.element = button;
}
function selectCandidate(id) {
activeCandidateId = id;
const candidate = candidateById.get(id);
if (!candidate) return;
candidate.group.scale.set(candidate.scale, 1, candidate.scale);
candidate.group.rotation.y = THREE.MathUtils.degToRad(candidate.rotation);
if (candidate.flex !== candidate.lastFlex) rebuildCandidate(candidate);
updateUI();
}
function rebuildCandidate(candidate) {
const oldGeometry = candidate.mesh.geometry;
candidate.mesh.geometry = makeRingGeometry(candidate);
oldGeometry.dispose();
candidate.lastFlex = candidate.flex;
}
function createCandidates() {
for (const candidate of CANDIDATES) {
candidate.targetId = null;
candidate.scale = 1;
candidate.flex = 1;
candidate.rotation = 0;
candidate.lastFlex = 1;
candidate.sealed = false;
candidate.dropTime = 0;
const group = new THREE.Group();
group.visible = false;
group.position.y = 1.57;
const mesh = new THREE.Mesh(
makeRingGeometry(candidate),
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.48,
metalness: 0.07,
flatShading: true,
side: THREE.DoubleSide,
emissive: candidate.color,
emissiveIntensity: 0.055
})
);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.candidateId = candidate.id;
group.add(mesh);
scene.add(group);
candidate.group = group;
candidate.mesh = mesh;
candidateById.set(candidate.id, candidate);
ringPickMeshes.push(mesh);
createCandidateUI(candidate);
}
}
function placeCandidate(candidateId, targetId) {
const candidate = candidateById.get(candidateId);
const target = targetById.get(targetId);
if (!candidate || !target) return;
const occupant = [...candidateById.values()].find(c => c.targetId === targetId && c.id !== candidateId);
if (occupant) unplaceCandidate(occupant, true);
candidate.targetId = targetId;
candidate.sealed = false;
candidate.group.visible = true;
candidate.group.position.set(target.x, 2.8, 0);
candidate.dropTime = 0;
activeCandidateId = candidateId;
armedCandidateId = null;
toast(`${candidate.name} placed on ${target.name}. Tune its scale, flex, and rotation.`);
updateUI();
}
function unplaceCandidate(candidate, quiet = false) {
candidate.targetId = null;
candidate.sealed = false;
candidate.group.visible = false;
candidate.group.position.y = 1.57;
if (!quiet) {
toast(`${candidate.name} returned to the rack.`);
updateUI();
}
}
function evaluateCandidate(candidate) {
if (!candidate.targetId) {
return { coverage: 0, maxError: Infinity, firstBadIndex: null, firstBadDiff: 0 };
}
const target = targetById.get(candidate.targetId);
const rotation = THREE.MathUtils.degToRad(candidate.rotation);
let maxError = 0;
let firstBadIndex = null;
let firstBadDiff = 0;
let good = 0;
for (let i = 0; i < TRACE_SAMPLES; i++) {
const theta = i / TRACE_SAMPLES * Math.PI * 2;
const candidateRadius = profileRadius(candidate.profile, theta + rotation, candidate.flex) * candidate.scale;
const targetRadius = profileRadius(target.profile, theta, 1);
const difference = candidateRadius - targetRadius;
const error = Math.abs(difference);
if (error > maxError) maxError = error;
if (error <= TOLERANCE) {
good++;
} else if (firstBadIndex === null) {
firstBadIndex = i;
firstBadDiff = difference;
}
}
return {
coverage: good / TRACE_SAMPLES,
maxError,
firstBadIndex,
firstBadDiff
};
}
function updateUI() {
const active = activeCandidateId ? candidateById.get(activeCandidateId) : null;
for (const candidate of candidateById.values()) {
candidate.element.classList.toggle("armed", candidate.id === armedCandidateId);
candidate.element.classList.toggle("active", candidate.id === activeCandidateId);
candidate.element.classList.toggle("placed", Boolean(candidate.targetId));
const stateElement = candidate.element.querySelector(".candidate-state");
stateElement.classList.remove("sealed", "mismatch");
if (candidate.sealed) {
stateElement.textContent = "Sealed";
stateElement.classList.add("sealed");
} else if (candidate.targetId) {
const diagnostic = evaluateCandidate(candidate);
stateElement.textContent = diagnostic.coverage > 0.98 ? "Ready" : "Adjust";
stateElement.classList.add("mismatch");
} else {
stateElement.textContent = "Open";
}
}
const hasActive = Boolean(active);
scaleRange.disabled = !hasActive;
flexRange.disabled = !hasActive;
rotationRange.disabled = !hasActive;
removeButton.disabled = !active || !active.targetId;
testButton.disabled = !active || !active.targetId;
if (!active) {
selectedName.textContent = "No ring selected";
selectedState.textContent = "Waiting";
scaleValue.textContent = "1.00×";
flexValue.textContent = "1.00×";
rotationValue.textContent = "0°";
agreementValue.textContent = "—";
agreementValue.classList.remove("bad");
agreementMeter.style.width = "0%";
diagnosticText.textContent = "Select a ring to inspect its boundary.";
return;
}
selectedName.textContent = active.name;
selectedState.textContent = active.targetId
? targetById.get(active.targetId).short
: "Not seated";
scaleRange.value = active.scale;
flexRange.value = active.flex;
rotationRange.value = active.rotation;
scaleValue.textContent = `${active.scale.toFixed(2)}×`;
flexValue.textContent = `${active.flex.toFixed(2)}×`;
rotationValue.textContent = `${Math.round(active.rotation)}°`;
if (!active.targetId) {
agreementValue.textContent = "—";
agreementValue.classList.remove("bad");
agreementMeter.style.width = "0%";
agreementMeter.style.background = "var(--green)";
diagnosticText.textContent = "Place this ring on a vessel to compare its boundary.";
return;
}
const diagnostic = evaluateCandidate(active);
const percent = Math.round(diagnostic.coverage * 100);
agreementValue.textContent = `${percent}%`;
agreementValue.classList.toggle("bad", diagnostic.coverage < 0.98);
agreementMeter.style.width = `${percent}%`;
agreementMeter.style.background = diagnostic.coverage >= 0.98 ? "var(--green)" : "var(--red)";
if (diagnostic.coverage >= 0.98) {
diagnosticText.textContent = "The outlines align continuously. Trace the seam to verify that no opening remains.";
} else {
diagnosticText.textContent = "The boundaries diverge somewhere along the rim. Adjust the shape and trace to locate the first opening.";
}
const placedCount = [...candidateById.values()].filter(candidate => candidate.targetId).length;
traceButton.disabled = placedCount === 0;
const sealedCount = [...candidateById.values()].filter(candidate => candidate.sealed).length;
progressText.textContent = `${sealedCount} / ${TARGETS.length}`;
}
function updateActiveTransform(rebuild = false) {
const candidate = activeCandidateId ? candidateById.get(activeCandidateId) : null;
if (!candidate) return;
candidate.scale = Number(scaleRange.value);
candidate.flex = Number(flexRange.value);
candidate.rotation = Number(rotationRange.value);
candidate.sealed = false;
candidate.group.scale.set(candidate.scale, 1, candidate.scale);
candidate.group.rotation.y = THREE.MathUtils.degToRad(candidate.rotation);
if (rebuild || candidate.flex !== candidate.lastFlex) rebuildCandidate(candidate);
updateUI();
}
scaleRange.addEventListener("input", () => updateActiveTransform(false));
flexRange.addEventListener("input", () => updateActiveTransform(true));
rotationRange.addEventListener("input", () => updateActiveTransform(false));
removeButton.addEventListener("click", () => {
const candidate = activeCandidateId ? candidateById.get(activeCandidateId) : null;
if (candidate) unplaceCandidate(candidate);
});
testButton.addEventListener("click", () => {
const candidate = activeCandidateId ? candidateById.get(activeCandidateId) : null;
if (candidate?.targetId) startTrace([candidate]);
});
traceButton.addEventListener("click", () => {
const placed = [...candidateById.values()].filter(candidate => candidate.targetId);
startTrace(placed);
});
const tracePositions = new Float32Array(1800 * 3);
const traceColors = new Float32Array(1800 * 3);
const traceGeometry = new THREE.BufferGeometry();
traceGeometry.setAttribute("position", new THREE.BufferAttribute(tracePositions, 3).setUsage(THREE.DynamicDrawUsage));
traceGeometry.setAttribute("color", new THREE.BufferAttribute(traceColors, 3).setUsage(THREE.DynamicDrawUsage));
traceGeometry.setDrawRange(0, 0);
const traceLine = new THREE.Line(
traceGeometry,
new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.96,
depthTest: false
})
);
traceLine.frustumCulled = false;
traceLine.renderOrder = 20;
scene.add(traceLine);
const tracer = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.095, 1),
new THREE.MeshBasicMaterial({ color: 0x49c9a9, depthTest: false })
);
tracer.renderOrder = 21;
tracer.visible = false;
scene.add(tracer);
const tracerLight = new THREE.PointLight(0x49c9a9, 1.8, 2.5);
tracer.add(tracerLight);
let tracePointCount = 0;
function clearTraceLine() {
tracePointCount = 0;
traceGeometry.setDrawRange(0, 0);
}
function addTracePoint(point, color) {
if (tracePointCount >= 1800) return;
const index = tracePointCount * 3;
tracePositions[index] = point.x;
tracePositions[index + 1] = point.y;
tracePositions[index + 2] = point.z;
traceColors[index] = color.r;
traceColors[index + 1] = color.g;
traceColors[index + 2] = color.b;
tracePointCount++;
traceGeometry.attributes.position.needsUpdate = true;
traceGeometry.attributes.color.needsUpdate = true;
traceGeometry.setDrawRange(0, tracePointCount);
traceGeometry.computeBoundingSphere();
}
function startTrace(list) {
if (!list.length) {
toast("Place at least one flexible ring on a vessel first.");
return;
}
traceAnimation = {
queue: list.slice(),
index: 0,
sample: 0,
accumulator: 0,
mode: "scan",
hold: 0,
failures: 0
};
clearTraceLine();
gapLabel.style.display = "none";
tracer.visible = true;
tracer.material.color.set(0x49c9a9);
tracerLight.color.set(0x49c9a9);
traceNext();
}
function traceNext() {
if (!traceAnimation) return;
if (traceAnimation.index >= traceAnimation.queue.length) {
finishTrace();
return;
}
const candidate = traceAnimation.queue[traceAnimation.index];
candidate.sealed = false;
selectCandidate(candidate.id);
traceAnimation.sample = 0;
traceAnimation.accumulator = 0;
traceAnimation.mode = "scan";
traceAnimation.currentDiagnostic = evaluateCandidate(candidate);
clearTraceLine();
tracer.visible = true;
tracer.material.color.set(0x49c9a9);
tracerLight.color.set(0x49c9a9);
traceStatus.textContent = `Tracing ${candidate.name} · ${traceAnimation.index + 1}/${traceAnimation.queue.length}`;
updateUI();
}
function finishTrace() {
const failures = traceAnimation?.failures || 0;
const passed = [...candidateById.values()].filter(candidate => candidate.sealed).length;
traceStatus.textContent = failures
? `Trace complete · ${failures} seam${failures === 1 ? "" : "s"} need attention`
: "Trace complete · every tested boundary is continuous";
toast(failures
? `${failures} seam${failures === 1 ? " still has" : "s still have"} a discontinuity. The tracer marked the first problem.`
: "No opening remains along the tested seams.");
traceAnimation = null;
tracer.visible = false;
gapLabel.style.display = "none";
updateUI();
}
function updateTrace(delta) {
if (!traceAnimation) return;
if (traceAnimation.mode === "hold") {
traceAnimation.hold -= delta;
if (traceAnimation.hold <= 0) {
traceAnimation.index++;
traceNext();
}
return;
}
const candidate = traceAnimation.queue[traceAnimation.index];
const target = targetById.get(candidate.targetId);
const diagnostic = traceAnimation.currentDiagnostic;
const rotation = THREE.MathUtils.degToRad(candidate.rotation);
const green = new THREE.Color(0x49c9a9);
const red = new THREE.Color(0xef5b52);
traceAnimation.accumulator += delta;
const steps = Math.floor(traceAnimation.accumulator * 58);
traceAnimation.accumulator -= steps / 58;
for (let step = 0; step < steps; step++) {
const sample = traceAnimation.sample;
const theta = sample / TRACE_SAMPLES * Math.PI * 2;
const radius = profileRadius(candidate.profile, theta + rotation, candidate.flex) * candidate.scale;
const point = new THREE.Vector3(
target.x + Math.cos(theta) * radius,
1.72,
Math.sin(theta) * radius
);
const isFailure = diagnostic.firstBadIndex !== null && sample === diagnostic.firstBadIndex;
addTracePoint(point, isFailure ? red : green);
tracer.position.copy(point);
tracer.rotation.x += 0.08;
tracer.rotation.y += 0.12;
if (isFailure) {
candidate.sealed = false;
traceAnimation.failures++;
traceAnimation.mode = "hold";
traceAnimation.hold = 1.05;
tracer.material.color.set(0xef5b52);
tracerLight.color.set(0xef5b52);
const opening = diagnostic.firstBadDiff < 0;
gapLabel.textContent = opening
? `Opening · ${Math.round(theta * 180 / Math.PI)}°`
: `Ridge · ${Math.round(theta * 180 / Math.PI)}°`;
gapLabel.style.display = "block";
traceStatus.textContent = opening
? "Opening detected — tracer stopped at the first gap"
: "Boundary collision — tracer found a raised mismatch";
updateUI();
break;
}
traceAnimation.sample++;
if (traceAnimation.sample > TRACE_SAMPLES) {
candidate.sealed = true;
traceAnimation.mode = "hold";
traceAnimation.hold = 0.42;
tracer.material.color.set(0x49c9a9);
tracerLight.color.set(0x49c9a9);
traceStatus.textContent = `${candidate.name} passed · boundary is continuous`;
updateUI();
break;
}
}
}
function toast(message) {
clearTimeout(toastTimer);
toastElement.textContent = message;
toastElement.classList.add("show");
toastTimer = setTimeout(() => toastElement.classList.remove("show"), 4200);
}
function updateCamera() {
const { target, radius, theta, phi } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.radius = 11.6;
cameraState.theta = 0.58;
cameraState.phi = 1.03;
updateCamera();
}
document.querySelector("#homeView").addEventListener("click", resetCamera);
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function setRayFromEvent(event) {
const rect = canvas.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 pickTarget(event) {
setRayFromEvent(event);
const hits = raycaster.intersectObjects(vesselPickMeshes, false);
return hits.length ? hits[0].object.userData.targetId : null;
}
function pickObject(event) {
setRayFromEvent(event);
const hits = raycaster.intersectObjects([...ringPickMeshes, ...vesselPickMeshes], false);
if (!hits.length) return null;
const object = hits[0].object;
if (object.userData.candidateId) {
return { type: "candidate", id: object.userData.candidateId };
}
if (object.userData.targetId) {
return { type: "target", id: object.userData.targetId };
}
return null;
}
canvas.addEventListener("pointerdown", event => {
pointerDown = {
x: event.clientX,
y: event.clientY,
moved: false,
pointerId: event.pointerId
};
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!pointerDown) return;
const dx = event.clientX - pointerDown.x;
const dy = event.clientY - pointerDown.y;
if (Math.hypot(dx, dy) > 5) pointerDown.moved = true;
if (!pointerDown.moved) return;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(cameraState.phi - dy * 0.005, 0.48, 1.35);
updateCamera();
});
canvas.addEventListener("pointerup", event => {
if (!pointerDown) return;
const wasClick = !pointerDown.moved;
pointerDown = null;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
if (!wasClick) return;
const picked = pickObject(event);
if (!picked) return;
if (picked.type === "candidate") {
armedCandidateId = null;
selectCandidate(picked.id);
toast(`${candidateById.get(picked.id).name} selected. Tune it or remove it.`);
} else if (picked.type === "target") {
if (armedCandidateId) {
placeCandidate(armedCandidateId, picked.id);
} else {
const occupied = [...candidateById.values()].find(candidate => candidate.targetId === picked.id);
if (occupied) {
armedCandidateId = null;
selectCandidate(occupied.id);
toast(`${occupied.name} is already seated on this vessel.`);
} else {
toast("Choose or drag a flexible ring onto this vessel.");
}
}
}
});
canvas.addEventListener("pointercancel", () => {
pointerDown = null;
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.009,
7.2,
17.5
);
updateCamera();
}, { passive: false });
canvas.addEventListener("dragover", event => {
event.preventDefault();
event.dataTransfer.dropEffect = "move";
});
canvas.addEventListener("drop", event => {
event.preventDefault();
const candidateId = event.dataTransfer.getData("text/plain") || armedCandidateId;
const targetId = pickTarget(event);
if (candidateId && targetId) placeCandidate(candidateId, targetId);
else toast("Drop the ring directly onto a vessel rim.");
});
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight, false);
}
addEventListener("resize", resize);
function addLowPolyRock(x, z, scale, color, rotation = 0) {
const rock = new THREE.Mesh(
new THREE.IcosahedronGeometry(scale, 0),
new THREE.MeshStandardMaterial({
color,
roughness: 0.95,
flatShading: true
})
);
rock.position.set(x, scale * 0.55, z);
rock.scale.y = 0.72;
rock.rotation.set(0.2, rotation, 0.08);
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
addLowPolyRock(-6.3, -2.6, 0.65, 0xb9c0a8, 0.4);
addLowPolyRock(-7.1, -1.8, 0.38, 0xc8c8af, 1.1);
addLowPolyRock(6.8, -2.9, 0.72, 0x9eb5a9, 2.2);
addLowPolyRock(7.4, -2.0, 0.34, 0xc3b9a0, 0.5);
addLowPolyRock(-4.9, 4.5, 0.42, 0xc0b09c, 1.7);
addLowPolyRock(5.3, 4.3, 0.55, 0xabb7a5, 0.8);
TARGETS.forEach(makeVessel);
createCandidates();
updateCamera();
updateUI();
toast("Choose a flexible boundary, place it on a vessel, then trace the seam to hunt for openings.");
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
for (const candidate of candidateById.values()) {
if (candidate.targetId && candidate.dropTime < 1) {
candidate.dropTime = Math.min(1, candidate.dropTime + delta * 2.8);
const t = 1 - Math.pow(1 - candidate.dropTime, 3);
candidate.group.position.y = THREE.MathUtils.lerp(2.8, 1.57, t);
}
}
updateTrace(delta);
if (tracer.visible) {
const pulse = 1 + Math.sin(performance.now() * 0.012) * 0.12;
tracer.scale.setScalar(pulse);
}
for (const label of worldLabels) {
const projected = label.position.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
label.element.style.display = visible ? "block" : "none";
label.element.style.left = `${(projected.x * 0.5 + 0.5) * innerWidth}px`;
label.element.style.top = `${(-projected.y * 0.5 + 0.5) * innerHeight}px`;
}
if (gapLabel.style.display === "block") {
const projected = tracer.position.clone().project(camera);
gapLabel.style.left = `${(projected.x * 0.5 + 0.5) * innerWidth}px`;
gapLabel.style.top = `${(-projected.y * 0.5 + 0.5) * innerHeight}px`;
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```