Prompt specification
Build or customize the Three.js 3D scene "Orchard access and support planner" 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: Orchard access and support planner
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/orchard-access-and-support-planner-x1092
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: orchard access and support planner. Create a toy orchard with configurable supports and collection points; users maintain reachable fruit zones and unobstructed paths while a schematic load diagram explains each chosen support. Return one self-contained HTML file.
Working Three.js Starter (orchard-access-and-support-planner-x1092):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Orchard Access & Support Planner</title>
<style>
:root {
--ink: #173a30;
--ink-2: #285344;
--muted: #718078;
--paper: #f6f4ec;
--panel: #fffdf8;
--line: #dfe4da;
--green: #347d5d;
--green-soft: #e2efe7;
--lime: #dce99a;
--orange: #df9954;
--orange-soft: #faead8;
--danger: #d76f60;
--danger-soft: #f9e4df;
--shadow: 0 14px 36px rgba(23, 58, 48, 0.11);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
min-height: 100%;
margin: 0;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button, select, input { font: inherit; }
button {
color: inherit;
}
button:focus-visible, select:focus-visible, input:focus-visible {
outline: 3px solid rgba(52, 125, 93, 0.24);
outline-offset: 2px;
}
.app-header {
height: 72px;
display: flex;
align-items: center;
gap: 24px;
padding: 0 22px;
background: var(--ink);
color: #f8f7ef;
position: relative;
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 286px;
}
.brand-mark {
width: 42px;
height: 42px;
display: grid;
place-items: center;
border-radius: 13px;
background: var(--lime);
color: var(--ink);
flex: 0 0 auto;
}
.brand-mark svg { width: 27px; height: 27px; }
.brand h1 {
font-size: 15px;
line-height: 1.2;
margin: 0;
letter-spacing: -0.01em;
}
.brand p {
margin: 4px 0 0;
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: #a9c0b5;
}
.header-metrics {
display: flex;
align-items: center;
gap: 8px;
margin-left: auto;
}
.header-metric {
min-width: 98px;
padding: 8px 13px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 12px;
background: rgba(255, 255, 255, 0.05);
}
.header-metric span {
display: block;
color: #a9c0b5;
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.header-metric strong {
display: block;
margin-top: 2px;
font-size: 15px;
font-weight: 720;
}
.readiness {
display: flex;
align-items: center;
gap: 9px;
margin-left: 5px;
padding: 10px 14px;
border-radius: 13px;
background: var(--lime);
color: var(--ink);
font-size: 12px;
font-weight: 760;
}
.readiness-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 4px rgba(52, 125, 93, 0.14);
}
.readiness.warning { background: #f4c78f; }
.readiness.warning .readiness-dot { background: var(--danger); }
.workspace {
height: calc(100vh - 72px);
display: grid;
grid-template-columns: 292px minmax(420px, 1fr) 338px;
grid-template-areas: "left stage right";
overflow: hidden;
}
.sidebar {
min-height: 0;
overflow: auto;
background: var(--panel);
scrollbar-width: thin;
scrollbar-color: #cbd4cc transparent;
}
.left-panel {
grid-area: left;
border-right: 1px solid var(--line);
}
.right-panel {
grid-area: right;
border-left: 1px solid var(--line);
}
.section {
padding: 19px 18px;
border-bottom: 1px solid var(--line);
}
.section:last-child { border-bottom: 0; }
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 14px;
}
.section-heading h2, .section-heading h3 {
margin: 0;
font-size: 11px;
letter-spacing: 0.095em;
text-transform: uppercase;
font-weight: 800;
}
.step {
display: grid;
place-items: center;
width: 22px;
height: 22px;
border-radius: 7px;
background: var(--green-soft);
color: var(--green);
font-size: 10px;
font-weight: 800;
}
.field { margin-bottom: 12px; }
.field:last-child { margin-bottom: 0; }
.field label,
.field-label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 10px;
font-weight: 720;
letter-spacing: 0.045em;
text-transform: uppercase;
}
select {
width: 100%;
height: 39px;
padding: 0 31px 0 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: #fffefa;
color: var(--ink);
font-size: 12px;
font-weight: 620;
appearance: none;
background-image:
linear-gradient(45deg, transparent 50%, #738078 50%),
linear-gradient(135deg, #738078 50%, transparent 50%);
background-position:
calc(100% - 15px) 16px,
calc(100% - 11px) 16px;
background-size: 4px 4px, 4px 4px;
background-repeat: no-repeat;
}
select:hover { border-color: #b7c7bd; }
.range-row {
display: flex;
align-items: center;
gap: 10px;
}
input[type="range"] {
width: 100%;
accent-color: var(--green);
}
.range-value {
min-width: 48px;
padding: 5px 7px;
border-radius: 7px;
background: var(--green-soft);
color: var(--green);
text-align: center;
font-size: 11px;
font-weight: 800;
}
.button {
min-height: 38px;
border: 1px solid var(--line);
border-radius: 10px;
padding: 9px 12px;
background: #fffefa;
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition: transform 0.15s ease, border-color 0.15s ease, background 0.15s ease;
}
.button:hover {
transform: translateY(-1px);
border-color: #b8c9bd;
background: #f8faf4;
}
.button.primary {
width: 100%;
border-color: var(--green);
background: var(--green);
color: white;
box-shadow: 0 7px 16px rgba(52, 125, 93, 0.18);
}
.button.primary:hover { background: #286c50; }
.button.soft {
border-color: #d7e5da;
background: var(--green-soft);
color: var(--green);
}
.button.danger {
border-color: #edcbc4;
background: var(--danger-soft);
color: #aa4f42;
}
.button.small {
min-height: 31px;
padding: 6px 9px;
font-size: 11px;
}
.button-row {
display: flex;
gap: 8px;
margin-top: 10px;
}
.button-row > .button { flex: 1; }
.hint {
margin: 8px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.inventory {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
}
.tree-chip {
min-height: 45px;
padding: 6px 3px;
border: 1px solid var(--line);
border-radius: 9px;
background: #fffefa;
cursor: pointer;
text-align: center;
}
.tree-chip span {
display: block;
font-size: 11px;
font-weight: 820;
}
.tree-chip small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.tree-chip i {
display: inline-block;
width: 5px;
height: 5px;
margin-right: 3px;
border-radius: 50%;
background: var(--green);
vertical-align: 1px;
}
.tree-chip.missing i { background: var(--orange); }
.tree-chip.blocked i { background: var(--danger); }
.tree-chip.active {
border-color: var(--green);
background: var(--green-soft);
box-shadow: inset 0 0 0 1px var(--green);
}
.collection-list {
display: grid;
gap: 7px;
}
.collection-row {
display: grid;
grid-template-columns: 1fr 82px 26px;
gap: 6px;
align-items: center;
padding: 7px;
border: 1px solid var(--line);
border-radius: 10px;
background: #fffefa;
}
.collection-select {
min-width: 0;
padding: 0;
border: 0;
background: transparent;
text-align: left;
cursor: pointer;
}
.collection-select strong {
display: block;
font-size: 11px;
}
.collection-select small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.collection-row select {
height: 30px;
padding-left: 7px;
font-size: 9px;
background-position:
calc(100% - 11px) 12px,
calc(100% - 7px) 12px;
}
.icon-button {
width: 26px;
height: 26px;
padding: 0;
border: 0;
border-radius: 7px;
background: transparent;
color: var(--muted);
cursor: pointer;
}
.icon-button:hover { background: var(--danger-soft); color: var(--danger); }
.toggle {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 7px 0;
cursor: pointer;
color: var(--ink-2);
font-size: 11px;
font-weight: 650;
}
.toggle input {
width: 35px;
height: 20px;
margin: 0;
accent-color: var(--green);
cursor: pointer;
}
.health-list { display: grid; gap: 9px; }
.health-row {
display: grid;
grid-template-columns: 9px 1fr auto;
align-items: center;
gap: 8px;
font-size: 11px;
}
.health-row i {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
}
.health-row.warn i { background: var(--orange); }
.health-row.bad i { background: var(--danger); }
.health-row strong { font-size: 10px; }
.stage {
grid-area: stage;
position: relative;
min-width: 0;
overflow: hidden;
background: #e7eadf;
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#viewport canvas:active { cursor: grabbing; }
.stage.placing #viewport canvas { cursor: crosshair; }
.stage-top {
position: absolute;
top: 17px;
left: 18px;
right: 18px;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 14px;
pointer-events: none;
}
.stage-title {
padding: 11px 13px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 13px;
background: rgba(255, 253, 248, 0.88);
backdrop-filter: blur(8px);
box-shadow: var(--shadow);
}
.stage-title strong {
display: block;
font-size: 13px;
}
.stage-title span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.view-tools {
display: flex;
gap: 5px;
padding: 5px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 12px;
background: rgba(255, 253, 248, 0.9);
backdrop-filter: blur(8px);
box-shadow: var(--shadow);
pointer-events: auto;
}
.view-tools button {
min-width: 34px;
height: 32px;
padding: 0 10px;
border: 0;
border-radius: 8px;
background: transparent;
color: var(--ink-2);
cursor: pointer;
font-size: 11px;
font-weight: 760;
}
.view-tools button:hover,
.view-tools button.active {
background: var(--green-soft);
color: var(--green);
}
.placement-hint {
position: absolute;
top: 88px;
left: 50%;
max-width: calc(100% - 40px);
padding: 9px 13px;
border-radius: 10px;
background: var(--ink);
color: white;
box-shadow: var(--shadow);
transform: translateX(-50%);
font-size: 11px;
pointer-events: none;
}
.placement-hint[hidden] { display: none; }
.stage-bottom {
position: absolute;
left: 18px;
right: 18px;
bottom: 16px;
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 14px;
pointer-events: none;
}
.compass {
width: 47px;
height: 47px;
display: grid;
place-items: center;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 50%;
background: rgba(255, 253, 248, 0.86);
box-shadow: var(--shadow);
}
.compass-arrow {
position: relative;
width: 16px;
height: 28px;
transform-origin: 50% 50%;
}
.compass-arrow::before {
content: "";
position: absolute;
left: 3px;
top: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 15px solid var(--ink);
}
.compass-arrow::after {
content: "N";
position: absolute;
left: 4px;
bottom: -2px;
color: var(--muted);
font-size: 8px;
font-weight: 850;
}
.legend {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 7px 12px;
max-width: 330px;
padding: 9px 11px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 11px;
background: rgba(255, 253, 248, 0.87);
box-shadow: var(--shadow);
color: var(--ink-2);
font-size: 9px;
}
.legend span { display: flex; align-items: center; gap: 5px; }
.legend i { width: 8px; height: 8px; border-radius: 50%; }
.legend .reachable { background: #59a477; }
.legend .cutoff { background: var(--danger); }
.legend .path { background: #d2b98d; }
.legend .footprint { border: 2px solid var(--orange); background: transparent; }
.inspector-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
}
.eyebrow {
margin: 0 0 5px;
color: var(--green);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.inspector-title {
margin: 0;
font-size: 20px;
letter-spacing: -0.035em;
}
.support-pill {
flex: 0 0 auto;
padding: 5px 8px;
border-radius: 999px;
background: var(--green-soft);
color: var(--green);
font-size: 9px;
font-weight: 820;
}
.support-pill.warning {
background: var(--orange-soft);
color: #a45d29;
}
.diagram-card {
margin-top: 14px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 13px;
background: #f5f7ef;
}
.diagram-title {
display: flex;
justify-content: space-between;
align-items: center;
padding: 9px 11px;
border-bottom: 1px solid var(--line);
color: var(--muted);
font-size: 8px;
font-weight: 820;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.diagram-card svg {
display: block;
width: 100%;
height: auto;
}
.load-path {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 5px;
margin-top: 12px;
padding: 10px;
border-radius: 10px;
background: #f3f5ed;
color: var(--ink-2);
font-size: 9px;
font-weight: 700;
}
.load-path b {
color: var(--orange);
font-size: 11px;
}
.spec-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
margin-top: 12px;
}
.spec {
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: #fffefa;
}
.spec span {
display: block;
color: var(--muted);
font-size: 8px;
font-weight: 760;
letter-spacing: 0.055em;
text-transform: uppercase;
}
.spec strong {
display: block;
margin-top: 4px;
font-size: 12px;
}
.capacity {
margin-top: 13px;
}
.capacity-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
font-size: 10px;
font-weight: 730;
}
.capacity-track {
height: 7px;
overflow: hidden;
border-radius: 99px;
background: #e7ebe3;
}
.capacity-fill {
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--green), #8eb85d);
}
.explanation {
margin: 12px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.warning-card {
margin-top: 12px;
padding: 10px 11px;
border: 1px solid #edc7b0;
border-radius: 10px;
background: var(--orange-soft);
color: #8e542f;
font-size: 10px;
line-height: 1.45;
}
.empty-inspector {
padding: 30px 12px;
text-align: center;
color: var(--muted);
}
.empty-inspector .empty-icon {
width: 48px;
height: 48px;
margin: 0 auto 10px;
display: grid;
place-items: center;
border-radius: 15px;
background: var(--green-soft);
color: var(--green);
font-size: 22px;
}
.issue-list { display: grid; gap: 8px; }
.issue {
display: grid;
grid-template-columns: 8px 1fr;
gap: 8px;
align-items: start;
padding: 9px;
border-radius: 9px;
background: #f7f6ef;
color: var(--ink-2);
font-size: 10px;
line-height: 1.45;
}
.issue i {
width: 7px;
height: 7px;
margin-top: 3px;
border-radius: 50%;
background: var(--orange);
}
.issue.good i { background: var(--green); }
.toast {
position: fixed;
left: 50%;
bottom: 22px;
z-index: 50;
max-width: min(420px, calc(100% - 32px));
padding: 11px 15px;
border-radius: 11px;
background: var(--ink);
color: white;
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.2);
transform: translate(-50%, 18px);
opacity: 0;
pointer-events: none;
transition: opacity 0.2s ease, transform 0.2s ease;
font-size: 11px;
text-align: center;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 1180px) {
.workspace { grid-template-columns: 270px minmax(390px, 1fr) 300px; }
.header-metric { min-width: 84px; }
.brand { min-width: 250px; }
}
@media (max-width: 980px) {
body { overflow: auto; }
.app-header { height: auto; min-height: 72px; flex-wrap: wrap; padding-block: 12px; }
.header-metrics { width: 100%; margin-left: 0; overflow-x: auto; }
.workspace {
height: auto;
min-height: calc(100vh - 72px);
overflow: visible;
grid-template-columns: 280px minmax(0, 1fr);
grid-template-areas:
"left stage"
"right right";
}
.left-panel, .right-panel { overflow: visible; }
.stage { min-height: 680px; }
.right-panel { display: grid; grid-template-columns: 1fr 1fr; }
.right-panel .section { border-right: 1px solid var(--line); }
}
@media (max-width: 700px) {
.app-header { gap: 12px; }
.brand { min-width: 100%; }
.header-metric { min-width: 80px; }
.readiness { display: none; }
.workspace {
display: grid;
grid-template-columns: 1fr;
grid-template-areas:
"stage"
"left"
"right";
}
.stage { min-height: 58vh; }
.right-panel { display: block; }
.stage-top { left: 10px; right: 10px; top: 10px; }
.stage-title { padding: 9px 10px; }
.view-tools button { min-width: 30px; padding: 0 7px; }
.stage-bottom { left: 10px; right: 10px; }
.legend { max-width: 240px; }
}
</style>
</head>
<body>
<header class="app-header">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 32 32" fill="none">
<path d="M16 27V14M16 19l-7-6M16 17l7-7" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/>
<path d="M16 4c-4 0-6 3-6 6 0 2 1 4 3 5-1 3 1 5 3 5s4-2 3-5c2-1 3-3 3-5 0-3-2-6-6-6Z" fill="currentColor"/>
</svg>
</div>
<div>
<h1>Orchard Access Planner</h1>
<p>Supports · reach · collection</p>
</div>
</div>
<div class="header-metrics">
<div class="header-metric">
<span>Reach zones</span>
<strong id="metricReach">12 / 12</strong>
</div>
<div class="header-metric">
<span>Clear paths</span>
<strong id="metricPaths">5 / 5</strong>
</div>
<div class="header-metric">
<span>Supported</span>
<strong id="metricSupports">10 / 12</strong>
</div>
<div class="header-metric">
<span>Collection</span>
<strong id="metricCollections">2</strong>
</div>
<div class="readiness" id="readinessBadge">
<i class="readiness-dot"></i>
<span id="readinessText">95% ready</span>
</div>
</div>
</header>
<main class="workspace">
<aside class="sidebar left-panel">
<section class="section">
<div class="section-heading">
<h2>Tree support</h2>
<span class="step">01</span>
</div>
<div class="field">
<label for="treeSelect">Select tree</label>
<select id="treeSelect"></select>
</div>
<div class="field">
<label for="supportType">Support system</label>
<select id="supportType">
<option value="tpost">Post & brace</option>
<option value="aframe">A-frame</option>
<option value="stake">Anchored stake</option>
<option value="trellis">Trellis span</option>
</select>
</div>
<div class="field">
<label for="supportHeight">Support height</label>
<div class="range-row">
<input id="supportHeight" type="range" min="1.8" max="3.2" step="0.1" value="2.4" />
<output class="range-value" id="heightValue">2.4 m</output>
</div>
</div>
<div class="field">
<label for="supportFinish">Material finish</label>
<select id="supportFinish">
<option value="cedar">Weathered cedar</option>
<option value="galvanised">Galvanised steel</option>
<option value="composite">Dark composite</option>
</select>
</div>
<button class="button primary" id="applySupport">Apply support to selected tree</button>
<div class="button-row">
<button class="button small danger" id="removeSupport">Remove support</button>
</div>
<p class="hint">Choose a tree in the scene or inventory, configure its support, then apply.</p>
</section>
<section class="section">
<div class="section-heading">
<h2>Support inventory</h2>
<span class="step">12</span>
</div>
<div class="inventory" id="treeInventory"></div>
</section>
<section class="section">
<div class="section-heading">
<h2>Collection points</h2>
<span class="step">02</span>
</div>
<div class="field">
<label for="collectionType">New point type</label>
<select id="collectionType">
<option value="pallet">Double pallet bay</option>
<option value="crate">Field crate station</option>
<option value="cart">Cooling cart</option>
</select>
</div>
<button class="button soft" id="placeCollection" style="width:100%">Place collection point</button>
<div class="collection-list" id="collectionList" style="margin-top:10px"></div>
<p class="hint">Points should remain within easy reach of a clear service path.</p>
</section>
<section class="section">
<div class="section-heading">
<h2>Field obstructions</h2>
<span class="step">03</span>
</div>
<div class="button-row" style="margin-top:0">
<button class="button small" id="placeBoulder">Place boulder</button>
<button class="button small" id="placePallet">Place pallet stack</button>
</div>
<div class="button-row">
<button class="button small danger" id="deleteObstacle" disabled>Remove selected</button>
<button class="button small" id="clearObstacles">Clear all</button>
</div>
<p class="hint">Place an obstruction on a path to test clearance. Select it in the scene to remove it.</p>
</section>
<section class="section">
<div class="section-heading">
<h3>Plan overlays</h3>
</div>
<label class="toggle">
<span>Reachable fruit zones</span>
<input type="checkbox" id="toggleReach" checked />
</label>
<label class="toggle">
<span>Support footprints</span>
<input type="checkbox" id="toggleFootprints" checked />
</label>
</section>
<section class="section">
<div class="section-heading">
<h3>Live plan checks</h3>
</div>
<div class="health-list" id="healthList"></div>
</section>
</aside>
<section class="stage" id="stage">
<div id="viewport"></div>
<div class="stage-top">
<div class="stage-title">
<strong>North Orchard · 12 trees</strong>
<span>Drag to orbit · Shift-drag to pan · Scroll to zoom</span>
</div>
<div class="view-tools" aria-label="Camera controls">
<button id="zoomOut" title="Zoom out">−</button>
<button id="zoomIn" title="Zoom in">+</button>
<button id="topView">Plan</button>
<button id="resetView">Reset</button>
</div>
</div>
<div class="placement-hint" id="placementHint" hidden></div>
<div class="stage-bottom">
<div class="compass" aria-hidden="true">
<div class="compass-arrow" id="compassArrow"></div>
</div>
<div class="legend">
<span><i class="reachable"></i>Reachable zone</span>
<span><i class="cutoff"></i>Cut-off zone</span>
<span><i class="path"></i>Service path</span>
<span><i class="footprint"></i>Support footprint</span>
</div>
</div>
</section>
<aside class="sidebar right-panel">
<section class="section" id="inspectorSection">
<div id="inspector"></div>
</section>
<section class="section">
<div class="section-heading">
<h3>Plan checks</h3>
<span class="step">✓</span>
</div>
<div class="issue-list" id="issueList"></div>
</section>
</aside>
</main>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const viewport = $("#viewport");
const stage = $("#stage");
const supportDefs = {
tpost: {
name: "Post & brace",
short: "T-post",
radius: 0.74,
baseCapacity: 30,
lateral: 18,
uplift: 8,
anchor: "Drive-in diagonal brace",
loadPath: ["Canopy", "Tie", "Post", "Brace", "Soil"],
note: "A single braced post carries bending and uplift loads through a diagonal ground brace. Keep the braced footprint clear of the adjacent service lane."
},
aframe: {
name: "A-frame",
short: "A-frame",
radius: 0.92,
baseCapacity: 34,
lateral: 25,
uplift: 12,
anchor: "Two spread footings",
loadPath: ["Canopy", "Tie", "A-frame", "Two feet", "Soil"],
note: "Two angled members share vertical and lateral loads. The wider footprint improves stability, but needs more clearance from paths and moving equipment."
},
stake: {
name: "Anchored stake",
short: "Stake",
radius: 0.52,
baseCapacity: 22,
lateral: 13,
uplift: 14,
anchor: "Angled stake + guy line",
loadPath: ["Canopy", "Tie", "Stake", "Anchor", "Soil"],
note: "A compact angled stake is useful for young trees. Its small footprint preserves access, while the guy line resists wind-driven uplift."
},
trellis: {
name: "Trellis span",
short: "Trellis",
radius: 1.04,
baseCapacity: 38,
lateral: 22,
uplift: 10,
anchor: "Paired posts + wire anchors",
loadPath: ["Canopy", "Wire", "Posts", "Anchors", "Soil"],
note: "A trellis distributes load along the wire and across two posts. It provides strong training control, but the full span must remain outside vehicle paths."
}
};
const collectionDefs = {
pallet: { name: "Double pallet bay", short: "Pallet bay" },
crate: { name: "Field crate station", short: "Crate station" },
cart: { name: "Cooling cart", short: "Cooling cart" }
};
const finishDefs = {
cedar: { name: "Weathered cedar", color: 0x9c6845 },
galvanised: { name: "Galvanised steel", color: 0x84928d },
composite: { name: "Dark composite", color: 0x354b42 }
};
const state = {
selectedTreeId: "T-07",
selectedCollectionId: null,
selectedObstacleId: null,
supportDraft: "trellis",
heightDraft: 2.4,
finishDraft: "cedar",
mode: null,
supports: {
"T-01": { type: "tpost", height: 2.4, finish: "cedar" },
"T-02": { type: "aframe", height: 2.5, finish: "galvanised" },
"T-03": { type: "stake", height: 1.9, finish: "cedar" },
"T-04": { type: "trellis", height: 2.6, finish: "composite" },
"T-05": { type: "tpost", height: 2.3, finish: "cedar" },
"T-06": { type: "aframe", height: 2.5, finish: "cedar" },
"T-07": { type: "trellis", height: 2.6, finish: "galvanised" },
"T-08": { type: "stake", height: 2.0, finish: "cedar" },
"T-10": { type: "tpost", height: 2.4, finish: "composite" },
"T-11": { type: "aframe", height: 2.3, finish: "galvanised" }
},
collections: [
{ id: "C-01", type: "pallet", x: -9, z: -2 },
{ id: "C-02", type: "crate", x: 9, z: 2 }
],
obstacles: []
};
let analysis;
let toastTimer;
let idCounter = 20;
// ----- Three.js scene -----
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe7eadf);
scene.fog = new THREE.Fog(0xe7eadf, 29, 49);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf7f5dc, 0x6b8062, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1d2, 3.1);
sun.position.set(-9, 16, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -17;
sun.shadow.camera.right = 17;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0007;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xcfe8e2, 0.65);
fill.position.set(12, 7, -10);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(42, 34),
new THREE.MeshStandardMaterial({ color: 0xd8dfca, roughness: 1 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.32;
ground.receiveShadow = true;
ground.userData.kind = "ground";
scene.add(ground);
const plot = new THREE.Mesh(
new THREE.BoxGeometry(21.4, 0.32, 15.2),
new THREE.MeshStandardMaterial({ color: 0x93aa77, roughness: 1 })
);
plot.position.y = -0.18;
plot.receiveShadow = true;
scene.add(plot);
const plotEdge = new THREE.Mesh(
new THREE.BoxGeometry(21.8, 0.18, 15.6),
new THREE.MeshStandardMaterial({ color: 0x6f835c, roughness: 1 })
);
plotEdge.position.y = -0.28;
plotEdge.receiveShadow = true;
scene.add(plotEdge);
const pathGroup = new THREE.Group();
const reachGroup = new THREE.Group();
const footprintGroup = new THREE.Group();
const collectionGroup = new THREE.Group();
const obstacleGroup = new THREE.Group();
scene.add(pathGroup, reachGroup, footprintGroup, collectionGroup, obstacleGroup);
const paths = [
{ id: "P-01", name: "North edge lane", x: 0, z: -6, w: 18, d: 1.35 },
{ id: "P-02", name: "Upper picking lane", x: 0, z: -2, w: 18, d: 1.35 },
{ id: "P-03", name: "Lower picking lane", x: 0, z: 2, w: 18, d: 1.35 },
{ id: "P-04", name: "South edge lane", x: 0, z: 6, w: 18, d: 1.35 },
{ id: "P-05", name: "Central service aisle", x: 0, z: 0, w: 1.35, d: 12 }
];
for (const p of paths) {
p.material = new THREE.MeshStandardMaterial({
color: 0xd7c39a,
roughness: 0.96,
transparent: true,
opacity: 0.97
});
p.mesh = new THREE.Mesh(new THREE.BoxGeometry(p.w, 0.07, p.d), p.material);
p.mesh.position.set(p.x, 0.005, p.z);
p.mesh.receiveShadow = true;
pathGroup.add(p.mesh);
}
// Low-poly perimeter details.
const fenceMaterial = new THREE.MeshStandardMaterial({ color: 0xd7c9aa, roughness: 0.9 });
for (let x = -10; x <= 10; x += 2.5) {
for (const z of [-7.2, 7.2]) {
const post = new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.09, 0.7, 6), fenceMaterial);
post.position.set(x, 0.2, z);
post.castShadow = true;
scene.add(post);
}
}
for (const z of [-7.2, 7.2]) {
const rail = new THREE.Mesh(new THREE.BoxGeometry(20.4, 0.07, 0.07), fenceMaterial);
rail.position.set(0, 0.43, z);
scene.add(rail);
}
const rockMaterial = new THREE.MeshStandardMaterial({ color: 0xb6b29e, roughness: 1, flatShading: true });
for (let i = 0; i < 28; i++) {
const angle = (i / 28) * Math.PI * 2;
const radius = 14 + (i % 3) * 0.8;
const rock = new THREE.Mesh(new THREE.DodecahedronGeometry(0.28 + (i % 4) * 0.08, 0), rockMaterial);
rock.position.set(Math.cos(angle) * radius, -0.08, Math.sin(angle) * radius * 0.7);
rock.rotation.set(i * 0.4, i * 0.8, i * 0.2);
rock.scale.y = 0.6;
rock.receiveShadow = true;
scene.add(rock);
}
// ----- Trees -----
const trees = [];
const treeById = new Map();
const canopyColors = [0x5d8b57, 0x6f9559, 0x789d5f, 0x527e50];
function makeLabel(text, background = "#173a30", foreground = "#ffffff", width = 1.1, height = 0.5) {
const canvas = document.createElement("canvas");
canvas.width = 192;
canvas.height = 80;
const ctx = canvas.getContext("2d");
ctx.fillStyle = background;
ctx.beginPath();
ctx.roundRect(5, 5, 182, 70, 18);
ctx.fill();
ctx.fillStyle = foreground;
ctx.font = "700 30px Inter, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 96, 42);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({ map: texture, transparent: true, depthWrite: false });
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, height, 1);
return sprite;
}
function makeBeam(a, b, radius, material, sides = 6) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(radius, radius, length, sides);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction.normalize());
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function buildTree(id, x, z, index) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.userData.kind = "tree";
group.userData.treeId = id;
const barkMaterial = new THREE.MeshStandardMaterial({ color: 0x7b5439, roughness: 1, flatShading: true });
const trunk = new THREE.Mesh(new THREE.CylinderGeometry(0.14, 0.22, 1.55, 7), barkMaterial);
trunk.position.y = 0.76;
trunk.castShadow = true;
trunk.receiveShadow = true;
group.add(trunk);
const branchMaterial = barkMaterial.clone();
const branchA = makeBeam(new THREE.Vector3(0, 1.1, 0), new THREE.Vector3(-0.48, 1.75, 0.08), 0.075, branchMaterial);
const branchB = makeBeam(new THREE.Vector3(0, 1.25, 0), new THREE.Vector3(0.48, 1.85, -0.06), 0.07, branchMaterial);
group.add(branchA, branchB);
const canopyMaterial = new THREE.MeshStandardMaterial({
color: canopyColors[index % canopyColors.length],
roughness: 0.95,
flatShading: true
});
const canopyA = new THREE.Mesh(new THREE.IcosahedronGeometry(0.83, 0), canopyMaterial);
canopyA.position.set(-0.34, 2.13, 0.05);
canopyA.scale.set(1.0, 0.9, 0.92);
const canopyB = new THREE.Mesh(new THREE.IcosahedronGeometry(0.74, 0), canopyMaterial);
canopyB.position.set(0.43, 2.28, -0.03);
canopyB.scale.set(0.95, 1.04, 0.9);
const canopyC = new THREE.Mesh(new THREE.IcosahedronGeometry(0.66, 0), canopyMaterial.clone());
canopyC.position.set(0.03, 2.66, 0.12);
canopyC.material.color.offsetHSL(0, 0, 0.04);
canopyA.castShadow = canopyB.castShadow = canopyC.castShadow = true;
group.add(canopyA, canopyB, canopyC);
const fruitMaterial = new THREE.MeshStandardMaterial({ color: 0xe79a43, roughness: 0.8, flatShading: true });
const fruitPoints = [
[-0.74, 2.05, 0.48], [-0.15, 2.48, 0.66], [0.54, 2.09, 0.51],
[0.77, 2.38, -0.05], [-0.48, 2.48, -0.35], [0.12, 1.92, -0.61]
];
fruitPoints.forEach((p) => {
const fruit = new THREE.Mesh(new THREE.DodecahedronGeometry(0.105, 0), fruitMaterial);
fruit.position.set(...p);
fruit.castShadow = true;
group.add(fruit);
});
const hitbox = new THREE.Mesh(
new THREE.SphereGeometry(1.28, 8, 6),
new THREE.MeshBasicMaterial({ transparent: true, opacity: 0, depthWrite: false })
);
hitbox.position.y = 1.7;
group.add(hitbox);
const label = makeLabel(id.replace("T-", ""), "#173a30", "#ffffff", 0.58, 0.29);
label.position.set(0, 3.48, 0);
group.add(label);
const tree = { id, x, z, group, supportGroup: null, zone: null };
trees.push(tree);
treeById.set(id, tree);
const disk = new THREE.Mesh(
new THREE.CircleGeometry(1.55, 40),
new THREE.MeshBasicMaterial({ color: 0x4d9a69, transparent: true, opacity: 0.11, depthWrite: false })
);
disk.rotation.x = -Math.PI / 2;
disk.position.set(x, 0.055, z);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(1.55, 0.025, 6, 48),
new THREE.MeshBasicMaterial({ color: 0x4d9a69, transparent: true, opacity: 0.72 })
);
ring.rotation.x = Math.PI / 2;
ring.position.set(x, 0.075, z);
reachGroup.add(disk, ring);
tree.zone = { disk, ring };
scene.add(group);
return tree;
}
let treeNumber = 1;
for (const z of [-4, 0, 4]) {
for (const x of [-6, -2, 2, 6]) {
const id = `T-${String(treeNumber).padStart(2, "0")}`;
buildTree(id, x, z, treeNumber - 1);
treeNumber++;
}
}
const selectionRing = new THREE.Mesh(
new THREE.RingGeometry(1.72, 1.82, 48),
new THREE.MeshBasicMaterial({ color: 0xf1c45d, transparent: true, opacity: 0.95, side: THREE.DoubleSide })
);
selectionRing.rotation.x = -Math.PI / 2;
selectionRing.position.y = 0.085;
scene.add(selectionRing);
// ----- Support models -----
function supportMaterial(finish) {
return new THREE.MeshStandardMaterial({
color: finishDefs[finish].color,
roughness: finish === "galvanised" ? 0.45 : 0.84,
metalness: finish === "galvanised" ? 0.48 : 0.03,
flatShading: true
});
}
function rebuildSupport(tree) {
if (tree.supportGroup) {
tree.group.remove(tree.supportGroup);
tree.supportGroup.traverse((obj) => {
if (obj.geometry) obj.geometry.dispose();
});
tree.supportGroup = null;
}
const config = state.supports[tree.id];
if (!config) return;
const group = new THREE.Group();
group.userData.kind = "tree";
group.userData.treeId = tree.id;
const wood = supportMaterial(config.finish);
const metal = new THREE.MeshStandardMaterial({ color: 0x6d7772, roughness: 0.45, metalness: 0.55 });
const tie = new THREE.MeshStandardMaterial({ color: 0x495b52, roughness: 0.8 });
const h = config.height;
if (config.type === "tpost") {
group.add(makeBeam(new THREE.Vector3(0.72, 0, 0), new THREE.Vector3(0.72, h, 0), 0.075, wood));
group.add(makeBeam(new THREE.Vector3(0.72, h * 0.58, 0), new THREE.Vector3(1.28, 0, 0), 0.055, wood));
group.add(makeBeam(new THREE.Vector3(0.35, h, 0), new THREE.Vector3(1.1, h, 0), 0.065, wood));
const collar = new THREE.Mesh(new THREE.TorusGeometry(0.25, 0.025, 6, 18), tie);
collar.rotation.x = Math.PI / 2;
collar.position.y = 1.15;
group.add(collar);
} else if (config.type === "aframe") {
group.add(makeBeam(new THREE.Vector3(-0.64, 0, 0.05), new THREE.Vector3(-0.08, h, 0), 0.075, wood));
group.add(makeBeam(new THREE.Vector3(0.64, 0, -0.05), new THREE.Vector3(0.08, h, 0), 0.075, wood));
group.add(makeBeam(new THREE.Vector3(-0.31, h * 0.6, 0), new THREE.Vector3(0.31, h * 0.6, 0), 0.048, wood));
const collar = new THREE.Mesh(new THREE.TorusGeometry(0.25, 0.027, 6, 18), tie);
collar.rotation.x = Math.PI / 2;
collar.position.y = 1.18;
group.add(collar);
} else if (config.type === "stake") {
group.add(makeBeam(new THREE.Vector3(0.48, 0, 0.08), new THREE.Vector3(0.82, h, 0), 0.065, wood));
group.add(makeBeam(new THREE.Vector3(0.72, h * 0.74, 0), new THREE.Vector3(1.23, 0, -0.12), 0.018, metal, 5));
const collar = new THREE.Mesh(new THREE.TorusGeometry(0.24, 0.025, 6, 18), tie);
collar.rotation.x = Math.PI / 2;
collar.position.y = 1.08;
group.add(collar);
} else if (config.type === "trellis") {
group.add(makeBeam(new THREE.Vector3(-0.86, 0, 0), new THREE.Vector3(-0.86, h, 0), 0.075, wood));
group.add(makeBeam(new THREE.Vector3(0.86, 0, 0), new THREE.Vector3(0.86, h, 0), 0.075, wood));
group.add(makeBeam(new THREE.Vector3(-1.0, h, 0), new THREE.Vector3(1.0, h, 0), 0.07, wood));
for (let y = 0.65; y < h - 0.08; y += 0.42) {
group.add(makeBeam(new THREE.Vector3(-0.86, y, 0), new THREE.Vector3(0.86, y, 0), 0.018, metal, 5));
}
const collar = new THREE.Mesh(new THREE.TorusGeometry(0.25, 0.025, 6, 18), tie);
collar.rotation.x = Math.PI / 2;
collar.position.y = 1.18;
group.add(collar);
}
group.traverse((obj) => {
if (obj.isMesh) {
obj.castShadow = true;
obj.receiveShadow = true;
}
});
tree.supportGroup = group;
tree.group.add(group);
}
trees.forEach(rebuildSupport);
// ----- Collections and obstacles -----
function buildCollection(collection) {
const group = new THREE.Group();
group.position.set(collection.x, 0, collection.z);
group.userData.kind = "collection";
group.userData.collectionId = collection.id;
const wood = new THREE.MeshStandardMaterial({ color: 0xa77a4e, roughness: 0.9, flatShading: true });
const green = new THREE.MeshStandardMaterial({ color: 0x63845c, roughness: 0.85, flatShading: true });
const dark = new THREE.MeshStandardMaterial({ color: 0x34473f, roughness: 0.65 });
const orange = new THREE.MeshStandardMaterial({ color: 0xe1984f, roughness: 0.72 });
function crate(x, y, z, scale = 1) {
const box = new THREE.Mesh(new THREE.BoxGeometry(0.76 * scale, 0.52 * scale, 0.62 * scale), green);
box.position.set(x, y, z);
box.castShadow = true;
box.receiveShadow = true;
group.add(box);
const slat = new THREE.Mesh(new THREE.BoxGeometry(0.8 * scale, 0.055 * scale, 0.66 * scale), dark);
slat.position.set(x, y + 0.12 * scale, z);
group.add(slat);
}
function pallet(x, z) {
const base = new THREE.Mesh(new THREE.BoxGeometry(1.22, 0.12, 0.9), wood);
base.position.set(x, 0.08, z);
base.castShadow = true;
group.add(base);
for (const dz of [-0.32, 0, 0.32]) {
const slat = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.06, 0.16), wood);
slat.position.set(x, 0.17, z + dz);
group.add(slat);
}
}
if (collection.type === "pallet") {
pallet(-0.36, 0);
pallet(0.42, 0);
crate(-0.36, 0.48, 0);
crate(0.42, 0.48, 0);
crate(-0.36, 1.02, 0);
} else if (collection.type === "crate") {
crate(0, 0.3, 0, 1.05);
const fruit = new THREE.Mesh(new THREE.DodecahedronGeometry(0.22, 0), orange);
fruit.position.set(0, 0.67, 0);
fruit.castShadow = true;
group.add(fruit);
} else {
const body = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.52, 0.8), dark);
body.position.y = 0.48;
body.castShadow = true;
group.add(body);
crate(0, 1.0, 0, 0.9);
for (const x of [-0.46, 0.46]) {
for (const z of [-0.28, 0.28]) {
const wheel = new THREE.Mesh(new THREE.CylinderGeometry(0.16, 0.16, 0.1, 10), orange);
wheel.rotation.z = Math.PI / 2;
wheel.position.set(x, 0.18, z);
group.add(wheel);
}
}
}
const label = makeLabel(collection.id, "#dce99a", "#173a30", 0.8, 0.35);
label.position.set(0, collection.type === "pallet" ? 1.72 : 1.35, 0);
group.add(label);
const footprint = new THREE.Mesh(
new THREE.RingGeometry(0.92, 1.0, 40),
new THREE.MeshBasicMaterial({ color: 0x4e8392, transparent: true, opacity: 0.85, side: THREE.DoubleSide })
);
footprint.rotation.x = -Math.PI / 2;
footprint.position.y = 0.075;
group.add(footprint);
collection.visual = { group, footprint };
collectionGroup.add(group);
}
function rebuildCollections() {
collectionGroup.clear();
state.collections.forEach(buildCollection);
}
function buildObstacle(obstacle) {
const group = new THREE.Group();
group.position.set(obstacle.x, 0, obstacle.z);
group.userData.kind = "obstacle";
group.userData.obstacleId = obstacle.id;
if (obstacle.type === "boulder") {
const material = new THREE.MeshStandardMaterial({ color: 0x999887, roughness: 1, flatShading: true });
const rock = new THREE.Mesh(new THREE.DodecahedronGeometry(0.7, 0), material);
rock.position.y = 0.55;
rock.scale.set(1, 0.85, 0.9);
rock.rotation.set(0.3, obstacle.id.length, 0.2);
rock.castShadow = true;
rock.receiveShadow = true;
group.add(rock);
} else {
const wood = new THREE.MeshStandardMaterial({ color: 0xa87a4e, roughness: 0.9, flatShading: true });
const green = new THREE.MeshStandardMaterial({ color: 0x617b57, roughness: 0.85, flatShading: true });
for (let i = 0; i < 3; i++) {
const box = new THREE.Mesh(new THREE.BoxGeometry(1.0, 0.42, 0.74), i === 1 ? green : wood);
box.position.set(0, 0.22 + i * 0.43, 0);
box.rotation.y = i * 0.05;
box.castShadow = true;
box.receiveShadow = true;
group.add(box);
}
}
const footprint = new THREE.Mesh(
new THREE.RingGeometry(0.78, 0.86, 32),
new THREE.MeshBasicMaterial({ color: 0xd76f60, transparent: true, opacity: 0.95, side: THREE.DoubleSide })
);
footprint.rotation.x = -Math.PI / 2;
footprint.position.y = 0.08;
group.add(footprint);
obstacle.visual = { group, footprint };
obstacleGroup.add(group);
}
function rebuildObstacles() {
obstacleGroup.clear();
state.obstacles.forEach(buildObstacle);
}
rebuildCollections();
rebuildObstacles();
// ----- Reachability and clearance analysis -----
function circleRectDistance(cx, cz, radius, rect) {
const nearestX = THREE.MathUtils.clamp(cx, rect.x - rect.w / 2, rect.x + rect.w / 2);
const nearestZ = THREE.MathUtils.clamp(cz, rect.z - rect.d / 2, rect.z + rect.d / 2);
const dx = cx - nearestX;
const dz = cz - nearestZ;
return Math.hypot(dx, dz) - radius;
}
function circleIntersectsRect(cx, cz, radius, rect) {
return circleRectDistance(cx, cz, radius, rect) <= 0;
}
function analyze() {
const pathStatus = {};
const pathBlockers = {};
for (const path of paths) {
const blockers = [];
for (const obstacle of state.obstacles) {
if (circleIntersectsRect(obstacle.x, obstacle.z, obstacle.type === "boulder" ? 0.78 : 0.72, path)) {
blockers.push({ type: "obstacle", id: obstacle.id, name: obstacle.type === "boulder" ? "Boulder" : "Pallet stack" });
}
}
for (const tree of trees) {
const support = state.supports[tree.id];
if (!support) continue;
const radius = supportDefs[support.type].radius;
if (circleIntersectsRect(tree.x, tree.z, radius, path)) {
blockers.push({ type: "support", id: tree.id, name: `${tree.id} support` });
}
}
pathBlockers[path.id] = blockers;
pathStatus[path.id] = blockers.length === 0;
}
const treeStatus = {};
for (const tree of trees) {
const reachablePaths = paths.filter((path) =>
pathStatus[path.id] &&
circleIntersectsRect(tree.x, tree.z, 1.55, path)
);
const support = state.supports[tree.id];
const conflictPaths = support ? paths.filter((path) =>
circleIntersectsRect(tree.x, tree.z, supportDefs[support.type].radius, path)
) : [];
treeStatus[tree.id] = {
reachable: reachablePaths.length > 0,
supported: Boolean(support),
conflictPaths: conflictPaths.map((p) => p.id)
};
}
const collectionStatus = {};
for (const collection of state.collections) {
const availablePaths = paths.filter((path) =>
pathStatus[path.id] && circleRectDistance(collection.x, collection.z, 0, path) <= 0.72
);
collectionStatus[collection.id] = {
accessible: availablePaths.length > 0,
paths: availablePaths.map((p) => p.id)
};
}
const reachableCount = Object.values(treeStatus).filter((s) => s.reachable).length;
const clearPathCount = Object.values(pathStatus).filter(Boolean).length;
const supportCount = Object.keys(state.supports).length;
const accessibleCollections = Object.values(collectionStatus).filter((s) => s.accessible).length;
const readiness = Math.round(
(reachableCount / trees.length) * 45 +
(clearPathCount / paths.length) * 25 +
(supportCount / trees.length) * 20 +
(state.collections.length ? accessibleCollections / state.collections.length * 10 : 0)
);
return {
pathStatus,
pathBlockers,
treeStatus,
collectionStatus,
reachableCount,
clearPathCount,
supportCount,
accessibleCollections,
readiness
};
}
function rebuildFootprints() {
footprintGroup.clear();
for (const tree of trees) {
const support = state.supports[tree.id];
if (!support) continue;
const radius = supportDefs[support.type].radius;
const fill = new THREE.Mesh(
new THREE.CircleGeometry(radius, 40),
new THREE.MeshBasicMaterial({ color: 0xdf9954, transparent: true, opacity: 0.13, depthWrite: false })
);
fill.rotation.x = -Math.PI / 2;
fill.position.set(tree.x, 0.09, tree.z);
const ring = new THREE.Mesh(
new THREE.RingGeometry(radius - 0.035, radius, 40),
new THREE.MeshBasicMaterial({ color: 0xdf9954, transparent: true, opacity: 0.9, side: THREE.DoubleSide })
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(tree.x, 0.095, tree.z);
footprintGroup.add(fill, ring);
}
}
function updateAnalysisVisuals() {
for (const path of paths) {
const blocked = !analysis.pathStatus[path.id];
path.material.color.setHex(blocked ? 0xd98776 : 0xd7c39a);
path.material.opacity = blocked ? 0.95 : 0.97;
}
for (const tree of trees) {
const status = analysis.treeStatus[tree.id];
const color = status.reachable ? 0x4d9a69 : 0xd76f60;
tree.zone.disk.material.color.setHex(color);
tree.zone.ring.material.color.setHex(color);
tree.zone.disk.material.opacity = status.reachable ? 0.11 : 0.15;
tree.zone.ring.material.opacity = status.reachable ? 0.72 : 0.92;
}
for (const collection of state.collections) {
const selected = state.selectedCollectionId === collection.id;
const accessible = analysis.collectionStatus[collection.id].accessible;
collection.visual.footprint.material.color.setHex(selected ? 0xf1c45d : accessible ? 0x4e8392 : 0xd76f60);
collection.visual.footprint.material.opacity = selected ? 1 : 0.78;
}
for (const obstacle of state.obstacles) {
const selected = state.selectedObstacleId === obstacle.id;
obstacle.visual.footprint.material.color.setHex(selected ? 0xf1c45d : 0xd76f60);
obstacle.visual.footprint.scale.setScalar(selected ? 1.12 : 1);
}
}
// ----- Schematics -----
function supportDiagram(type) {
const defs = `
<defs>
<marker id="loadArrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M0 0L10 5L0 10Z" fill="#df9954"/>
</marker>
<marker id="greenArrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M0 0L10 5L0 10Z" fill="#347d5d"/>
</marker>
</defs>
<rect x="0" y="0" width="320" height="190" fill="#f5f7ef"/>
<path d="M0 151H320" stroke="#b7bcae" stroke-width="2"/>
<path d="M0 158H320" stroke="#d6d9ce" stroke-width="7" opacity=".6"/>
<g stroke="#8a6345" stroke-width="10" stroke-linecap="round">
<path d="M148 43V151"/>
</g>
<g fill="#62845d" opacity=".92">
<circle cx="145" cy="43" r="30"/><circle cx="168" cy="50" r="24"/><circle cx="127" cy="55" r="22"/>
</g>
`;
let graphic = "";
if (type === "tpost") {
graphic = `
<g stroke="#8a6345" stroke-width="7" stroke-linecap="round" fill="none">
<path d="M213 151V29"/><path d="M213 91L254 151"/><path d="M190 29H238"/>
</g>
<path d="M137 77H215" stroke="#495b52" stroke-width="4"/>
<path d="M132 25V94" stroke="#df9954" stroke-width="3" marker-end="url(#loadArrow)"/>
<path d="M168 63H207" stroke="#df9954" stroke-width="3" marker-end="url(#loadArrow)"/>
<path d="M213 127V181" stroke="#347d5d" stroke-width="3" marker-end="url(#greenArrow)"/>
<text x="214" y="21" fill="#66756d" font-size="9" font-family="sans-serif">POST</text>
`;
} else if (type === "aframe") {
graphic = `
<g stroke="#8a6345" stroke-width="7" stroke-linecap="round" fill="none">
<path d="M113 151L146 32"/><path d="M181 151L150 32"/><path d="M129 90H168"/>
</g>
<path d="M134 82H171" stroke="#495b52" stroke-width="4"/>
<path d="M133 26V93" stroke="#df9954" stroke-width="3" marker-end="url(#loadArrow)"/>
<path d="M112 145L77 161" stroke="#347d5d" stroke-width="3" marker-end="url(#greenArrow)"/>
<path d="M182 145L217 161" stroke="#347d5d" stroke-width="3" marker-end="url(#greenArrow)"/>
<text x="106" y="22" fill="#66756d" font-size="9" font-family="sans-serif">TWO SPREAD FEET</text>
`;
} else if (type === "stake") {
graphic = `
<g stroke="#8a6345" stroke-width="7" stroke-linecap="round" fill="none">
<path d="M205 151L222 37"/><path d="M219 83L263 151"/>
</g>
<path d="M146 75L222 75" stroke="#495b52" stroke-width="4"/>
<path d="M196 29V89" stroke="#df9954" stroke-width="3" marker-end="url(#loadArrow)"/>
<path d="M223 105L263 151" stroke="#347d5d" stroke-width="2"/>
<path d="M206 139V180" stroke="#347d5d" stroke-width="3" marker-end="url(#greenArrow)"/>
<text x="215" y="27" fill="#66756d" font-size="9" font-family="sans-serif">ANGLED STAKЕ</text>
`;
} else {
graphic = `
<g stroke="#8a6345" stroke-width="7" stroke-linecap="round" fill="none">
<path d="M101 151V25"/><path d="M194 151V25"/><path d="M88 25H207"/>
</g>
<g stroke="#7d8984" stroke-width="1.7">
<path d="M101 53H194"/><path d="M101 79H194"/><path d="M101 105H194"/><path d="M101 131H194"/>
</g>
<path d="M134 83H173" stroke="#495b52" stroke-width="4"/>
<path d="M125 29V112" stroke="#df9954" stroke-width="3" marker-end="url(#loadArrow)"/>
<path d="M151 29V112" stroke="#df9954" stroke-width="3" marker-end="url(#loadArrow)"/>
<path d="M177 29V112" stroke="#df9954" stroke-width="3" marker-end="url(#loadArrow)"/>
<path d="M101 132V180" stroke="#347d5d" stroke-width="3" marker-end="url(#greenArrow)"/>
<path d="M194 132V180" stroke="#347d5d" stroke-width="3" marker-end="url(#greenArrow)"/>
<text x="113" y="19" fill="#66756d" font-size="9" font-family="sans-serif">WIRE SPAN + ANCHORED POSTS</text>
`;
}
return `<svg viewBox="0 0 320 190" role="img" aria-label="${supportDefs[type].name} load path schematic">${defs}${graphic}</svg>`;
}
// ----- Interface rendering -----
function syncSupportControls() {
const support = state.supports[state.selectedTreeId];
$("#supportType").value = support?.type || state.supportDraft;
$("#supportHeight").value = support?.height || state.heightDraft;
$("#supportFinish").value = support?.finish || state.finishDraft;
$("#heightValue").textContent = `${Number($("#supportHeight").value).toFixed(1)} m`;
$("#removeSupport").disabled = !support;
$("#removeSupport").style.opacity = support ? "1" : "0.45";
}
function renderInventory() {
$("#treeInventory").innerHTML = trees.map((tree) => {
const support = state.supports[tree.id];
const status = analysis.treeStatus[tree.id];
const classes = [
"tree-chip",
tree.id === state.selectedTreeId ? "active" : "",
!support ? "missing" : "",
!status.reachable ? "blocked" : ""
].filter(Boolean).join(" ");
return `
<button class="${classes}" data-tree="${tree.id}" title="${tree.id}: ${support ? supportDefs[support.type].name : "No support"}">
<i></i><span>${tree.id.replace("T-", "")}</span>
<small>${support ? supportDefs[support.type].short : "Add"}</small>
</button>
`;
}).join("");
}
function renderCollections() {
$("#collectionList").innerHTML = state.collections.length ? state.collections.map((collection) => {
const status = analysis.collectionStatus[collection.id];
return `
<div class="collection-row">
<button class="collection-select" data-collection="${collection.id}">
<strong>${collection.id}</strong>
<small>${status.accessible ? "Path access clear" : "No clear path access"}</small>
</button>
<select data-collection-type="${collection.id}" aria-label="Collection point type">
${Object.entries(collectionDefs).map(([key, def]) =>
`<option value="${key}" ${collection.type === key ? "selected" : ""}>${def.short}</option>`
).join("")}
</select>
<button class="icon-button" data-delete-collection="${collection.id}" title="Remove collection point">×</button>
</div>
`;
}).join("") : `<p class="hint">No collection points placed.</p>`;
}
function renderInspector() {
const tree = treeById.get(state.selectedTreeId);
const support = state.supports[tree.id];
const status = analysis.treeStatus[tree.id];
if (!support) {
$("#inspector").innerHTML = `
<div class="inspector-header">
<div>
<p class="eyebrow">Selected tree</p>
<h2 class="inspector-title">${tree.id}</h2>
</div>
<span class="support-pill warning">Support needed</span>
</div>
<div class="empty-inspector">
<div class="empty-icon">⌁</div>
<strong>No support configured</strong>
<p class="explanation">Choose a support system in the left panel, then apply it to this tree.</p>
</div>
`;
return;
}
const def = supportDefs[support.type];
const capacity = Math.round(def.baseCapacity + (support.height - 2.2) * 7);
const estimatedLoad = 18;
const utilisation = Math.min(100, Math.round((estimatedLoad / capacity) * 100));
const hasConflict = status.conflictPaths.length > 0;
const safe = support.height >= 1.9 && utilisation < 85;
$("#inspector").innerHTML = `
<div class="inspector-header">
<div>
<p class="eyebrow">Selected tree · ${tree.id}</p>
<h2 class="inspector-title">${def.name}</h2>
</div>
<span class="support-pill ${hasConflict ? "warning" : ""}">${hasConflict ? "Check clearance" : "Support adequate"}</span>
</div>
<div class="diagram-card">
<div class="diagram-title">
<span>Load path schematic</span>
<span>Not to scale</span>
</div>
${supportDiagram(support.type)}
</div>
<div class="load-path">
${def.loadPath.map((part, i) => `${i ? "<b>→</b>" : ""}<span>${part}</span>`).join("")}
</div>
<div class="spec-grid">
<div class="spec"><span>Height</span><strong>${support.height.toFixed(1)} m</strong></div>
<div class="spec"><span>Material</span><strong>${finishDefs[support.finish].name}</strong></div>
<div class="spec"><span>Lateral capacity</span><strong>${def.lateral} kg</strong></div>
<div class="spec"><span>Uplift resistance</span><strong>${def.uplift} kN</strong></div>
</div>
<div class="capacity">
<div class="capacity-label">
<span>Estimated working load</span>
<span>${estimatedLoad} / ${capacity} kg</span>
</div>
<div class="capacity-track">
<div class="capacity-fill" style="width:${utilisation}%"></div>
</div>
</div>
<p class="explanation"><strong>${def.anchor}.</strong> ${def.note}</p>
${hasConflict ? `
<div class="warning-card">
<strong>Clearance conflict:</strong> this support footprint touches ${status.conflictPaths.map((id) => paths.find((p) => p.id === id).name.toLowerCase()).join(", ")}. Move the support or adjust the path width.
</div>
` : ""}
<div class="button-row">
<button class="button small" id="inspectorRemove">Remove selected support</button>
</div>
`;
const remove = $("#inspectorRemove");
if (remove) remove.addEventListener("click", removeSelectedSupport);
}
function renderHealth() {
const collectionTotal = state.collections.length;
const rows = [
{
label: "Reachable fruit zones",
value: `${analysis.reachableCount}/${trees.length}`,
level: analysis.reachableCount === trees.length ? "" : "bad"
},
{
label: "Unobstructed paths",
value: `${analysis.clearPathCount}/${paths.length}`,
level: analysis.clearPathCount === paths.length ? "" : "bad"
},
{
label: "Trees with supports",
value: `${analysis.supportCount}/${trees.length}`,
level: analysis.supportCount === trees.length ? "" : "warn"
},
{
label: "Collection access",
value: `${analysis.accessibleCollections}/${collectionTotal}`,
level: analysis.accessibleCollections === collectionTotal ? "" : "bad"
}
];
$("#healthList").innerHTML = rows.map((row) => `
<div class="health-row ${row.level}">
<i></i><span>${row.label}</span><strong>${row.value}</strong>
</div>
`).join("");
}
function renderIssues() {
const issues = [];
for (const path of paths) {
if (!analysis.pathStatus[path.id]) {
const blockers = analysis.pathBlockers[path.id].map((b) => b.name.toLowerCase());
issues.push(`${path.name} is obstructed by ${blockers.join(", ")}.`);
}
}
for (const tree of trees) {
if (!state.supports[tree.id]) issues.push(`${tree.id} does not yet have a support system.`);
}
for (const collection of state.collections) {
if (!analysis.collectionStatus[collection.id].accessible) {
issues.push(`${collection.id} is not connected to a clear service path.`);
}
}
if (!issues.length) {
$("#issueList").innerHTML = `
<div class="issue good"><i></i><span>All fruit zones are reachable, all paths are clear, and every tree has a configured support.</span></div>
`;
} else {
$("#issueList").innerHTML = issues.slice(0, 6).map((issue) => `
<div class="issue"><i></i><span>${issue}</span></div>
`).join("");
}
}
function updateHeader() {
$("#metricReach").textContent = `${analysis.reachableCount} / ${trees.length}`;
$("#metricPaths").textContent = `${analysis.clearPathCount} / ${paths.length}`;
$("#metricSupports").textContent = `${analysis.supportCount} / ${trees.length}`;
$("#metricCollections").textContent = `${state.collections.length}`;
$("#readinessText").textContent = `${analysis.readiness}% ready`;
$("#readinessBadge").classList.toggle("warning", analysis.readiness < 100);
}
function updateAll() {
analysis = analyze();
updateAnalysisVisuals();
renderInventory();
renderCollections();
renderInspector();
renderHealth();
renderIssues();
updateHeader();
const selected = treeById.get(state.selectedTreeId);
selectionRing.position.x = selected.x;
selectionRing.position.z = selected.z;
}
function selectTree(id) {
if (!treeById.has(id)) return;
state.selectedTreeId = id;
state.selectedCollectionId = null;
state.selectedObstacleId = null;
syncSupportControls();
updateAll();
}
function removeSelectedSupport() {
const id = state.selectedTreeId;
if (!state.supports[id]) return;
delete state.supports[id];
rebuildSupport(treeById.get(id));
rebuildFootprints();
syncSupportControls();
updateAll();
showToast(`Support removed from ${id}.`);
}
function showToast(message) {
const toast = $("#toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2300);
}
function setMode(mode) {
state.mode = state.mode === mode ? null : mode;
$("#placeCollection").classList.toggle("active", state.mode === "collection");
$("#placeBoulder").classList.toggle("active", state.mode === "boulder");
$("#placePallet").classList.toggle("active", state.mode === "pallet");
stage.classList.toggle("placing", Boolean(state.mode));
const hint = $("#placementHint");
if (state.mode === "collection") {
hint.textContent = "Click an open patch of ground to place the collection point.";
hint.hidden = false;
} else if (state.mode === "boulder") {
hint.textContent = "Click the ground to place a boulder and test path clearance.";
hint.hidden = false;
} else if (state.mode === "pallet") {
hint.textContent = "Click the ground to place a pallet stack.";
hint.hidden = false;
} else {
hint.hidden = true;
}
}
// ----- UI events -----
const treeSelect = $("#treeSelect");
treeSelect.innerHTML = trees.map((tree) => `<option value="${tree.id}">${tree.id} · row ${Math.ceil(trees.indexOf(tree) / 4)}</option>`).join("");
treeSelect.value = state.selectedTreeId;
treeSelect.addEventListener("change", () => selectTree(treeSelect.value));
$("#supportType").addEventListener("change", (event) => {
state.supportDraft = event.target.value;
});
$("#supportHeight").addEventListener("input", (event) => {
state.heightDraft = Number(event.target.value);
$("#heightValue").textContent = `${state.heightDraft.toFixed(1)} m`;
});
$("#supportFinish").addEventListener("change", (event) => {
state.finishDraft = event.target.value;
});
$("#applySupport").addEventListener("click", () => {
const id = state.selectedTreeId;
state.supports[id] = {
type: $("#supportType").value,
height: Number($("#supportHeight").value),
finish: $("#supportFinish").value
};
state.supportDraft = state.supports[id].type;
state.heightDraft = state.supports[id].height;
state.finishDraft = state.supports[id].finish;
rebuildSupport(treeById.get(id));
rebuildFootprints();
syncSupportControls();
updateAll();
showToast(`${supportDefs[state.supports[id].type].name} applied to ${id}.`);
});
$("#removeSupport").addEventListener("click", removeSelectedSupport);
$("#treeInventory").addEventListener("click", (event) => {
const button = event.target.closest("[data-tree]");
if (button) selectTree(button.dataset.tree);
});
$("#placeCollection").addEventListener("click", () => setMode("collection"));
$("#placeBoulder").addEventListener("click", () => setMode("boulder"));
$("#placePallet").addEventListener("click", () => setMode("pallet"));
$("#collectionList").addEventListener("click", (event) => {
const selectButton = event.target.closest("[data-collection]");
const deleteButton = event.target.closest("[data-delete-collection]");
if (selectButton) {
state.selectedCollectionId = selectButton.dataset.collection;
state.selectedObstacleId = null;
updateAll();
}
if (deleteButton) {
state.collections = state.collections.filter((c) => c.id !== deleteButton.dataset.deleteCollection);
if (state.selectedCollectionId === deleteButton.dataset.deleteCollection) state.selectedCollectionId = null;
rebuildCollections();
updateAll();
showToast("Collection point removed.");
}
});
$("#collectionList").addEventListener("change", (event) => {
const select = event.target.closest("[data-collection-type]");
if (!select) return;
const collection = state.collections.find((c) => c.id === select.dataset.collectionType);
if (!collection) return;
collection.type = select.value;
rebuildCollections();
updateAll();
showToast(`${collection.id} changed to ${collectionDefs[collection.type].name}.`);
});
$("#deleteObstacle").addEventListener("click", () => {
if (!state.selectedObstacleId) return;
state.obstacles = state.obstacles.filter((o) => o.id !== state.selectedObstacleId);
state.selectedObstacleId = null;
rebuildObstacles();
updateAll();
$("#deleteObstacle").disabled = true;
showToast("Selected obstruction removed.");
});
$("#clearObstacles").addEventListener("click", () => {
state.obstacles = [];
state.selectedObstacleId = null;
rebuildObstacles();
updateAll();
$("#deleteObstacle").disabled = true;
showToast("All field obstructions cleared.");
});
$("#toggleReach").addEventListener("change", (event) => {
reachGroup.visible = event.target.checked;
});
$("#toggleFootprints").addEventListener("change", (event) => {
footprintGroup.visible = event.target.checked;
});
// ----- Picking and placement -----
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function metadataFrom(object) {
let current = object;
while (current && current !== scene) {
if (current.userData.kind) return current.userData;
current = current.parent;
}
return null;
}
function pickRoots() {
return [
...trees.map((tree) => tree.group),
...state.collections.map((collection) => collection.visual.group),
...state.obstacles.map((obstacle) => obstacle.visual.group)
];
}
function validPlacement(x, z) {
if (Math.abs(x) > 9.7 || Math.abs(z) > 6.8) {
showToast("Keep placements inside the orchard boundary.");
return false;
}
const nearTree = trees.some((tree) => Math.hypot(tree.x - x, tree.z - z) < 1.35);
if (nearTree) {
showToast("Choose a clear patch away from tree trunks.");
return false;
}
return true;
}
function handleSceneClick(event) {
pointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
if (state.mode) {
const groundHit = raycaster.intersectObject(ground, false)[0];
if (!groundHit) return;
const point = groundHit.point;
if (!validPlacement(point.x, point.z)) return;
if (state.mode === "collection") {
const id = `C-${String(idCounter++).padStart(2, "0")}`;
state.collections.push({
id,
type: $("#collectionType").value,
x: Number(point.x.toFixed(2)),
z: Number(point.z.toFixed(2))
});
state.selectedCollectionId = id;
rebuildCollections();
showToast(`${id} placed. Check that it connects to a clear path.`);
} else if (state.mode === "boulder" || state.mode === "pallet") {
const id = `O-${String(idCounter++).padStart(2, "0")}`;
state.obstacles.push({
id,
type: state.mode,
x: Number(point.x.toFixed(2)),
z: Number(point.z.toFixed(2))
});
state.selectedObstacleId = id;
rebuildObstacles();
showToast(`${id} placed. Path clearance recalculated.`);
}
setMode(state.mode);
updateAll();
return;
}
const hits = raycaster.intersectObjects(pickRoots(), true);
if (!hits.length) {
state.selectedCollectionId = null;
state.selectedObstacleId = null;
updateAll();
return;
}
const meta = metadataFrom(hits[0].object);
if (!meta) return;
if (meta.kind === "tree") {
selectTree(meta.treeId);
} else if (meta.kind === "collection") {
state.selectedCollectionId = meta.collectionId;
state.selectedObstacleId = null;
updateAll();
} else if (meta.kind === "obstacle") {
state.selectedObstacleId = meta.obstacleId;
state.selectedCollectionId = null;
$("#deleteObstacle").disabled = false;
updateAll();
}
}
// ----- Custom camera controls -----
const cameraState = {
yaw: 0.58,
elevation: 0.72,
distance: 24.5,
target: new THREE.Vector3(0, 0.75, 0)
};
function updateCamera() {
const horizontal = cameraState.distance * Math.cos(cameraState.elevation);
camera.position.set(
cameraState.target.x + horizontal * Math.sin(cameraState.yaw),
cameraState.target.y + cameraState.distance * Math.sin(cameraState.elevation),
cameraState.target.z + horizontal * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
$("#compassArrow").style.transform = `rotate(${-cameraState.yaw}rad)`;
}
let drag = null;
renderer.domElement.addEventListener("pointerdown", (event) => {
drag = {
x: event.clientX,
y: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: 0,
pan: event.shiftKey || event.button === 2,
button: event.button
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!drag) return;
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
drag.moved += Math.abs(dx) + Math.abs(dy);
drag.lastX = event.clientX;
drag.lastY = event.clientY;
if (drag.pan) {
const scale = cameraState.distance * 0.0015;
const right = new THREE.Vector3(Math.cos(cameraState.yaw), 0, -Math.sin(cameraState.yaw));
const forward = new THREE.Vector3(Math.sin(cameraState.yaw), 0, Math.cos(cameraState.yaw));
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, -dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -8, 8);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -6, 6);
} else {
cameraState.yaw -= dx * 0.006;
cameraState.elevation = THREE.MathUtils.clamp(cameraState.elevation + dy * 0.005, 0.28, 1.48);
}
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (drag && drag.moved < 6 && drag.button === 0) handleSceneClick(event);
drag = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => { drag = null; });
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
10,
38
);
updateCamera();
}, { passive: false });
$("#zoomIn").addEventListener("click", () => {
cameraState.distance = Math.max(10, cameraState.distance - 2);
updateCamera();
});
$("#zoomOut").addEventListener("click", () => {
cameraState.distance = Math.min(38, cameraState.distance + 2);
updateCamera();
});
$("#resetView").addEventListener("click", () => {
cameraState.yaw = 0.58;
cameraState.elevation = 0.72;
cameraState.distance = 24.5;
cameraState.target.set(0, 0.75, 0);
updateCamera();
});
let planView = false;
$("#topView").addEventListener("click", () => {
planView = !planView;
cameraState.yaw = planView ? 0 : 0.58;
cameraState.elevation = planView ? 1.48 : 0.72;
cameraState.distance = planView ? 23 : 24.5;
$("#topView").classList.toggle("active", planView);
updateCamera();
});
// ----- Resize and animation -----
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(viewport);
resize();
rebuildFootprints();
syncSupportControls();
updateAll();
updateCamera();
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
const pulse = 1 + Math.sin(elapsed * 2.2) * 0.025;
selectionRing.scale.set(pulse, pulse, pulse);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```