Prompt specification
Build or customize the Three.js 3D scene "Cleanup allocation strategy game" 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: Cleanup allocation strategy game
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/cleanup-allocation-strategy-game-x3888
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring cooperative neighborhood cleanup. Create a bounded park with litter clusters and fictional task durations; users assign teams and collection points while tracking cleared areas, material categories, and continuous walking routes. Low-poly.
Working Three.js Starter (cleanup-allocation-strategy-game-x3888):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Common Ground — Cooperative Cleanup</title>
<style>
:root {
--ink: #19372f;
--muted: #687a72;
--cream: #f5f2e8;
--paper: #fffdf7;
--green: #277458;
--green-dark: #18533e;
--line: #dce2d9;
--orange: #ed7b4f;
--yellow: #e4b64b;
--shadow: 0 16px 45px rgba(26, 55, 44, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--cream);
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
color: inherit;
}
.app {
width: 100%;
height: 100%;
display: grid;
grid-template-rows: 68px 1fr;
}
.topbar {
position: relative;
z-index: 20;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 0 22px;
background: rgba(255, 253, 247, 0.96);
border-bottom: 1px solid var(--line);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
width: 38px;
height: 38px;
display: grid;
place-items: center;
flex: 0 0 auto;
border-radius: 12px 12px 12px 4px;
background: var(--green);
color: white;
font-weight: 900;
letter-spacing: -1px;
box-shadow: 0 6px 15px rgba(39, 116, 88, 0.22);
}
.brand-copy {
min-width: 0;
}
.brand-copy strong {
display: block;
font-size: 15px;
line-height: 1.1;
letter-spacing: 0.02em;
}
.brand-copy span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 11px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.top-actions {
display: flex;
align-items: center;
gap: 10px;
}
.live-pill {
display: flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
border: 1px solid #cfe1d7;
border-radius: 999px;
background: #eef7f1;
color: var(--green-dark);
font-size: 11px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.07em;
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: #36a36f;
box-shadow: 0 0 0 4px rgba(54, 163, 111, 0.12);
}
.live-pill.paused .live-dot {
background: #df7b52;
box-shadow: 0 0 0 4px rgba(223, 123, 82, 0.12);
}
.clock {
min-width: 74px;
font-size: 13px;
font-weight: 800;
font-variant-numeric: tabular-nums;
text-align: right;
}
.button {
min-height: 36px;
padding: 8px 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: var(--paper);
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition:
transform 0.15s ease,
border-color 0.15s ease,
background 0.15s ease;
}
.button:hover {
border-color: #a8bbb1;
transform: translateY(-1px);
}
.button.primary {
border-color: var(--green);
background: var(--green);
color: white;
}
.button.primary:hover {
background: var(--green-dark);
}
.button.ghost {
background: transparent;
}
.workspace {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 20% 15%, #f6f4df 0, transparent 28%),
linear-gradient(145deg, #dce9e0, #cbded4);
}
#canvasHost,
#mapLabels {
position: absolute;
inset: 0;
}
#canvasHost canvas {
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
}
#canvasHost canvas:active {
cursor: grabbing;
}
#mapLabels {
z-index: 3;
pointer-events: none;
overflow: hidden;
}
.stats {
position: absolute;
z-index: 6;
top: 18px;
left: 18px;
display: grid;
grid-template-columns: repeat(4, minmax(110px, 1fr));
gap: 8px;
max-width: calc(100% - 230px);
pointer-events: none;
}
.stat {
min-height: 68px;
padding: 11px 13px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 14px;
background: rgba(255, 253, 247, 0.87);
box-shadow: 0 8px 24px rgba(33, 67, 55, 0.1);
backdrop-filter: blur(9px);
}
.stat-label {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 850;
text-transform: uppercase;
letter-spacing: 0.1em;
}
.stat-value {
display: block;
margin-top: 5px;
font-size: 21px;
font-weight: 850;
letter-spacing: -0.04em;
}
.stat-value small {
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0;
}
.map-actions {
position: absolute;
z-index: 7;
right: 18px;
bottom: 18px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 7px;
max-width: 360px;
}
.map-actions .button {
background: rgba(255, 253, 247, 0.9);
box-shadow: 0 7px 18px rgba(32, 64, 52, 0.1);
backdrop-filter: blur(8px);
}
.map-actions .button.active {
border-color: var(--green);
background: #e7f2eb;
color: var(--green-dark);
}
.map-note {
position: absolute;
z-index: 6;
left: 18px;
bottom: 18px;
width: min(390px, calc(100% - 36px));
padding: 12px 14px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 14px;
background: rgba(255, 253, 247, 0.87);
box-shadow: 0 8px 24px rgba(33, 67, 55, 0.1);
backdrop-filter: blur(9px);
}
.map-note strong {
display: block;
margin-bottom: 4px;
font-size: 11px;
}
.map-note span {
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.map-label {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
transform: translate(-50%, -50%);
white-space: nowrap;
transition:
opacity 0.15s ease,
filter 0.15s ease;
}
.task-label {
width: 39px;
height: 39px;
gap: 4px;
padding: 0;
border: 2px solid white;
border-radius: 12px 12px 12px 4px;
color: white;
cursor: pointer;
pointer-events: auto;
box-shadow: 0 5px 13px rgba(27, 53, 44, 0.25);
font-size: 10px;
font-weight: 900;
}
.task-label::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
opacity: 0.85;
}
.task-label.active {
outline: 3px solid rgba(237, 123, 79, 0.38);
animation: labelPulse 1.4s ease-in-out infinite;
}
.task-label.cleared {
background: var(--green) !important;
opacity: 0.76;
}
.task-label.selected {
filter: brightness(1.12);
transform: translate(-50%, -50%) scale(1.16);
}
@keyframes labelPulse {
50% {
outline-color: rgba(237, 123, 79, 0.08);
}
}
.collection-label,
.team-map-label {
gap: 6px;
padding: 5px 8px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 999px;
background: rgba(255, 253, 247, 0.9);
box-shadow: 0 4px 12px rgba(27, 53, 44, 0.15);
color: var(--ink);
font-size: 9px;
font-weight: 800;
}
.collection-label i,
.team-map-label i {
width: 7px;
height: 7px;
border-radius: 50%;
}
.team-map-label {
padding: 4px 7px;
font-size: 8px;
}
.sidebar {
position: relative;
z-index: 10;
min-height: 0;
overflow-y: auto;
background: var(--paper);
border-left: 1px solid var(--line);
scrollbar-width: thin;
scrollbar-color: #bdc9c2 transparent;
}
.panel-heading {
padding: 19px 18px 15px;
border-bottom: 1px solid var(--line);
}
.eyebrow {
color: var(--green);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.panel-heading h1 {
margin: 5px 0 6px;
font-size: 20px;
letter-spacing: -0.035em;
}
.panel-heading p {
margin: 0 0 13px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.heading-actions {
display: flex;
gap: 7px;
}
.heading-actions .button {
flex: 1;
}
.materials {
padding: 14px 18px 16px;
border-bottom: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section-title span {
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0;
text-transform: none;
}
.material-row {
display: grid;
grid-template-columns: 64px 1fr 22px;
align-items: center;
gap: 8px;
margin-top: 7px;
font-size: 10px;
}
.material-name {
display: flex;
align-items: center;
gap: 6px;
font-weight: 750;
}
.material-name i {
width: 8px;
height: 8px;
border-radius: 3px;
}
.material-track {
height: 6px;
overflow: hidden;
border-radius: 999px;
background: #e8ece6;
}
.material-fill {
width: 0;
height: 100%;
border-radius: inherit;
transition: width 0.35s ease;
}
.material-count {
color: var(--muted);
font-weight: 800;
text-align: right;
}
.board-section {
padding: 14px 12px 4px;
}
.board-section .section-title {
padding: 0 6px;
}
.task-list {
display: grid;
gap: 8px;
}
.task-card {
padding: 11px;
border: 1px solid var(--line);
border-radius: 13px;
background: white;
transition:
border-color 0.15s ease,
box-shadow 0.15s ease;
}
.task-card:hover,
.task-card.selected {
border-color: #9fb8ab;
box-shadow: 0 7px 18px rgba(32, 64, 52, 0.08);
}
.task-card.cleared {
background: #f4f8f3;
}
.task-top {
display: grid;
grid-template-columns: 28px 1fr auto;
align-items: center;
gap: 8px;
}
.task-number {
width: 28px;
height: 28px;
display: grid;
place-items: center;
border-radius: 9px 9px 9px 3px;
color: white;
font-size: 10px;
font-weight: 900;
}
.task-name {
min-width: 0;
}
.task-name strong {
display: block;
overflow: hidden;
font-size: 11px;
text-overflow: ellipsis;
white-space: nowrap;
}
.task-name span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.task-status {
padding: 4px 6px;
border-radius: 999px;
background: #eef1ec;
color: var(--muted);
font-size: 8px;
font-weight: 850;
text-transform: uppercase;
}
.task-status[data-kind="active"] {
background: #fff0e9;
color: #bd5935;
}
.task-status[data-kind="queued"] {
background: #e9f3ed;
color: var(--green-dark);
}
.task-status[data-kind="cleared"] {
background: #dff0e5;
color: #23704d;
}
.task-meta {
display: flex;
gap: 6px;
margin: 9px 0;
}
.task-meta span {
padding: 4px 6px;
border-radius: 6px;
background: #f3f4f0;
color: #52655c;
font-size: 8px;
font-weight: 700;
}
.assignment-row {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) 56px;
gap: 5px;
}
.assignment-row select {
width: 100%;
min-width: 0;
height: 31px;
padding: 0 6px;
border: 1px solid #d7ded8;
border-radius: 8px;
outline: none;
background: #fafbf8;
color: var(--ink);
font-size: 9px;
cursor: pointer;
}
.assignment-row select:focus {
border-color: var(--green);
}
.assign-button {
height: 31px;
padding: 0 5px;
border: 1px solid var(--green);
border-radius: 8px;
background: var(--green);
color: white;
cursor: pointer;
font-size: 9px;
font-weight: 850;
}
.assign-button:hover {
background: var(--green-dark);
}
.teams-section {
margin-top: 8px;
padding: 14px 18px 20px;
border-top: 1px solid var(--line);
}
.team-list {
display: grid;
gap: 7px;
}
.team-card {
position: relative;
overflow: hidden;
padding: 10px 10px 9px 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: white;
cursor: pointer;
transition:
transform 0.15s ease,
border-color 0.15s ease;
}
.team-card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 4px;
background: var(--team-color);
}
.team-card:hover,
.team-card.selected {
border-color: var(--team-color);
transform: translateX(2px);
}
.team-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.team-name {
font-size: 11px;
font-weight: 850;
}
.team-open {
color: var(--muted);
font-size: 8px;
font-weight: 800;
}
.team-state {
display: block;
min-height: 14px;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.team-progress {
height: 4px;
margin-top: 7px;
overflow: hidden;
border-radius: 999px;
background: #e9ede8;
}
.team-progress span {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--team-color);
transition: width 0.15s linear;
}
.footnote {
margin: 12px 0 0;
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
.toast {
position: absolute;
z-index: 30;
left: 50%;
bottom: 28px;
max-width: min(420px, calc(100% - 40px));
padding: 10px 14px;
transform: translateX(-50%);
border-radius: 10px;
background: #19372f;
color: white;
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 700;
text-align: center;
animation: toastIn 0.2s ease-out;
}
@keyframes toastIn {
from {
opacity: 0;
transform: translate(-50%, 8px);
}
}
@media (max-width: 1050px) {
.workspace {
grid-template-columns: minmax(0, 1fr) 340px;
}
.stats {
grid-template-columns: repeat(2, minmax(105px, 1fr));
max-width: 230px;
}
.map-note {
max-width: 330px;
}
}
@media (max-width: 760px) {
html,
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100%;
grid-template-rows: auto auto;
}
.topbar {
min-height: 64px;
padding: 10px 12px;
}
.brand-copy span,
.clock {
display: none;
}
.workspace {
display: block;
}
.stage {
height: 58vh;
min-height: 430px;
}
.sidebar {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.stats {
top: 10px;
left: 10px;
gap: 5px;
}
.stat {
min-height: 58px;
padding: 8px 10px;
}
.stat-value {
font-size: 17px;
}
.map-note {
display: none;
}
.map-actions {
right: 10px;
bottom: 10px;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark">CG</div>
<div class="brand-copy">
<strong>Common Ground</strong>
<span>Cooperative neighborhood cleanup operations</span>
</div>
</div>
<div class="top-actions">
<div class="live-pill" id="livePill">
<span class="live-dot"></span>
<span id="liveText">Simulation live</span>
</div>
<div class="clock" id="clock">08:30</div>
<button class="button" id="playPause" type="button">Pause</button>
</div>
</header>
<main class="workspace">
<section class="stage" id="stage" aria-label="Interactive 3D cleanup park">
<div id="canvasHost"></div>
<div id="mapLabels"></div>
<div class="stats" aria-live="polite">
<div class="stat">
<span class="stat-label">Clusters cleared</span>
<span class="stat-value" id="statCleared">0 <small>/ 9</small></span>
</div>
<div class="stat">
<span class="stat-label">Area restored</span>
<span class="stat-value" id="statArea">0 <small>m²</small></span>
</div>
<div class="stat">
<span class="stat-label">Items recovered</span>
<span class="stat-value" id="statItems">0</span>
</div>
<div class="stat">
<span class="stat-label">Teams deployed</span>
<span class="stat-value" id="statTeams">0 <small>/ 3</small></span>
</div>
</div>
<div class="map-note">
<strong>Neighborhood Park · Sector 04</strong>
<span>
Drag to orbit · Shift/right-drag to pan · Scroll to zoom ·
Fictional task estimates run at one task minute per second.
</span>
</div>
<div class="map-actions">
<button class="button active" id="routeToggle" type="button">Routes on</button>
<button class="button" id="topView" type="button">Top view</button>
<button class="button" id="resetView" type="button">Reset view</button>
<button class="button" id="resetRun" type="button">Reset run</button>
</div>
</section>
<aside class="sidebar">
<section class="panel-heading">
<div class="eyebrow">Dispatch board</div>
<h1>Assign the cleanup crew</h1>
<p>
Pair each litter cluster with a team and a collection point.
Teams walk continuously from their current position to each pickup,
then onward to the selected depot.
</p>
<div class="heading-actions">
<button class="button primary" id="autoDispatch" type="button">
Auto-dispatch open jobs
</button>
</div>
</section>
<section class="materials">
<div class="section-title">
Recovered by material
<span>items</span>
</div>
<div id="materialRows"></div>
</section>
<section class="board-section">
<div class="section-title">
Litter clusters
<span id="openCount">9 open</span>
</div>
<div class="task-list" id="taskList"></div>
</section>
<section class="teams-section">
<div class="section-title">
Field teams
<span>click to focus route</span>
</div>
<div class="team-list" id="teamList"></div>
<p class="footnote">
Task areas and durations are fictional planning estimates.
Each team can hold three active assignments.
</p>
</section>
</aside>
</main>
</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 stage = $("#stage");
const canvasHost = $("#canvasHost");
const mapLabels = $("#mapLabels");
const materialMeta = {
Plastic: { color: 0x4b9eaa, css: "#4b9eaa" },
Paper: { color: 0xd7a946, css: "#d7a946" },
Glass: { color: 0x748f63, css: "#748f63" },
Mixed: { color: 0xdf7954, css: "#df7954" }
};
const collectionPoints = [
{
id: "north",
name: "North depot",
short: "N",
color: 0x557f68,
css: "#557f68",
position: new THREE.Vector3(-10, 0, -8.6),
deposited: 0
},
{
id: "east",
name: "East depot",
short: "E",
color: 0xd09035,
css: "#d09035",
position: new THREE.Vector3(13.2, 0, -0.2),
deposited: 0
},
{
id: "gate",
name: "Gate hub",
short: "G",
color: 0xc66545,
css: "#c66545",
position: new THREE.Vector3(0, 0, 9.3),
deposited: 0
}
];
const rawTasks = [
{ name: "South picnic lawn", area: 4.8, material: "Mixed", duration: 7, units: 6, x: -11.2, z: 6.2 },
{ name: "West play edge", area: 3.6, material: "Paper", duration: 5, units: 4, x: -5.8, z: 7.0 },
{ name: "East meadow", area: 5.4, material: "Plastic", duration: 9, units: 8, x: 6.0, z: 6.4 },
{ name: "East hedge line", area: 2.9, material: "Glass", duration: 6, units: 5, x: 11.4, z: 3.2 },
{ name: "Cycling corner", area: 4.1, material: "Mixed", duration: 8, units: 7, x: 10.1, z: -2.5 },
{ name: "North garden path", area: 3.3, material: "Paper", duration: 5, units: 4, x: 3.6, z: -6.1 },
{ name: "Willow bend", area: 5.0, material: "Plastic", duration: 10, units: 8, x: -4.5, z: -6.5 },
{ name: "Pond approach", area: 2.5, material: "Glass", duration: 4, units: 3, x: -11.4, z: -2.4 },
{ name: "Central crossing", area: 4.3, material: "Mixed", duration: 8, units: 7, x: -1.0, z: 0.2 }
];
const tasks = rawTasks.map((task, index) => ({
...task,
id: index + 1,
position: new THREE.Vector3(task.x, 0, task.z),
teamId: null,
collectionId: null,
cleared: false,
deposited: false,
progress: 0,
visual: null,
label: null
}));
const teams = [
{
id: "moss",
name: "Moss crew",
color: 0x2f8f68,
css: "#2f8f68",
home: new THREE.Vector3(-4.8, 0, 8.5),
capacity: 3
},
{
id: "cedar",
name: "Cedar crew",
color: 0xd0794c,
css: "#d0794c",
home: new THREE.Vector3(0, 0, 8.3),
capacity: 3
},
{
id: "sun",
name: "Sun crew",
color: 0xcf9b32,
css: "#cf9b32",
home: new THREE.Vector3(4.8, 0, 8.5),
capacity: 3
}
].map((team) => ({
...team,
current: team.home.clone(),
route: [],
routeIndex: 0,
activeTaskId: null,
serviceRemaining: 0,
clearedTasks: 0,
depositedItems: 0,
avatar: null,
routeLine: null
}));
const state = {
running: true,
routesVisible: true,
selectedTaskId: null,
selectedTeamId: null,
simMinutes: 0,
simRate: 1,
cameraDirty: true
};
function getTeam(id) {
return teams.find((team) => team.id === id);
}
function getPoint(id) {
return collectionPoints.find((point) => point.id === id);
}
function nearestPoint(task) {
return [...collectionPoints].sort(
(a, b) =>
a.position.distanceToSquared(task.position) -
b.position.distanceToSquared(task.position)
)[0];
}
tasks.forEach((task) => {
task.collectionId = nearestPoint(task).id;
});
// ---------- Three.js scene ----------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe8df);
scene.fog = new THREE.Fog(0xdbe8df, 48, 82);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 120);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Low-poly neighborhood park with cleanup teams and litter clusters"
);
canvasHost.appendChild(renderer.domElement);
const hemiLight = new THREE.HemisphereLight(0xf8f2d7, 0x607b69, 2.25);
scene.add(hemiLight);
const sunLight = new THREE.DirectionalLight(0xfff1d1, 3.2);
sunLight.position.set(-12, 25, 14);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(2048, 2048);
sunLight.shadow.camera.left = -23;
sunLight.shadow.camera.right = 23;
sunLight.shadow.camera.top = 20;
sunLight.shadow.camera.bottom = -20;
sunLight.shadow.camera.near = 1;
sunLight.shadow.camera.far = 60;
sunLight.shadow.bias = -0.0003;
scene.add(sunLight);
const cameraControls = {
target: new THREE.Vector3(0, 0, 0),
azimuth: 0.56,
polar: 0.82,
distance: 40,
dragging: false,
panning: false,
lastX: 0,
lastY: 0,
moved: 0
};
function updateCamera() {
const { target, azimuth, polar, distance } = cameraControls;
const sinPolar = Math.sin(polar);
camera.position.set(
target.x + distance * sinPolar * Math.sin(azimuth),
target.y + distance * Math.cos(polar),
target.z + distance * sinPolar * Math.cos(azimuth)
);
camera.lookAt(target);
camera.updateMatrixWorld();
}
function resetCamera(top = false) {
cameraControls.target.set(0, 0, 0);
cameraControls.azimuth = top ? 0 : 0.56;
cameraControls.polar = top ? 0.08 : 0.82;
cameraControls.distance = top ? 43 : 40;
state.cameraDirty = true;
}
const flatMaterial = (color, extra = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0,
flatShading: true,
...extra
});
function createBox(width, height, depth, material, x, y, z, castShadow = false) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
// Park base and lawn.
createBox(34, 0.75, 24, flatMaterial(0x9b8b68), 0, -0.58, 0);
createBox(32, 0.32, 22, flatMaterial(0x83ad77), 0, -0.16, 0);
function addPath(x, z, width, depth) {
createBox(
width + 0.2,
0.08,
depth + 0.2,
flatMaterial(0xb8a985),
x,
0.035,
z
);
createBox(
width,
0.08,
depth,
flatMaterial(0xdac9a8),
x,
0.07,
z
);
}
addPath(0, 1.2, 29.4, 2.15);
addPath(3.8, -1.55, 2.05, 17.2);
addPath(-1.0, -5.9, 20.8, 1.45);
addPath(0, 8.25, 2.15, 5.5);
addPath(-10.4, -2.1, 1.4, 6.1);
addPath(10.7, 2.0, 1.35, 5.2);
// Low-poly pond.
const pondBorder = new THREE.Mesh(
new THREE.CircleGeometry(3.05, 18),
flatMaterial(0xc3b98e)
);
pondBorder.rotation.x = -Math.PI / 2;
pondBorder.position.set(-7.8, 0.13, -4.25);
pondBorder.receiveShadow = true;
scene.add(pondBorder);
const pond = new THREE.Mesh(
new THREE.CircleGeometry(2.75, 18),
flatMaterial(0x6fa6a3, { roughness: 0.42 })
);
pond.rotation.x = -Math.PI / 2;
pond.position.set(-7.8, 0.15, -4.25);
scene.add(pond);
[
[-8.8, -3.6, 0.38],
[-6.9, -4.9, 0.3],
[-8.0, -5.1, 0.25]
].forEach(([x, z, radius]) => {
const lily = new THREE.Mesh(
new THREE.CircleGeometry(radius, 8),
flatMaterial(0x6e985c)
);
lily.rotation.x = -Math.PI / 2;
lily.position.set(x, 0.17, z);
scene.add(lily);
});
// Trees.
const treeLocations = [
[-14, 8.5, 1.05],
[-14, 2.2, 0.9],
[-7.1, 9.2, 0.95],
[8.6, 9.2, 1.08],
[14.2, 7.1, 1.0],
[14.3, -6.7, 1.12],
[7.3, -8.4, 0.93],
[-1.2, -8.8, 0.82],
[-14.2, -7.2, 1.13],
[1.0, -8.8, 0.72]
];
function addTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.19, 0.28, 1.65, 6),
flatMaterial(0x78563c)
);
trunk.position.y = 0.82;
trunk.castShadow = true;
group.add(trunk);
const crown = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.25, 0),
flatMaterial(0x477f51)
);
crown.position.y = 2.15;
crown.scale.set(1, 1.12, 1);
crown.castShadow = true;
group.add(crown);
const crownTop = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.75, 0),
flatMaterial(0x5f925c)
);
crownTop.position.set(0.35, 2.85, -0.08);
crownTop.castShadow = true;
group.add(crownTop);
scene.add(group);
}
treeLocations.forEach(([x, z, scale]) => addTree(x, z, scale));
// Benches.
function addBench(x, z, rotation = 0) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = rotation;
const wood = flatMaterial(0x9a6944);
const metal = flatMaterial(0x4d5c54);
const seat = new THREE.Mesh(new THREE.BoxGeometry(1.8, 0.13, 0.55), wood);
seat.position.y = 0.62;
seat.castShadow = true;
group.add(seat);
const back = new THREE.Mesh(new THREE.BoxGeometry(1.8, 0.55, 0.12), wood);
back.position.set(0, 0.93, -0.22);
back.castShadow = true;
group.add(back);
[-0.65, 0.65].forEach((legX) => {
const leg = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.62, 0.42), metal);
leg.position.set(legX, 0.31, 0);
leg.castShadow = true;
group.add(leg);
});
scene.add(group);
}
addBench(-7.2, 2.9, 0);
addBench(7.1, 2.8, Math.PI);
addBench(1.4, -4.9, Math.PI / 2);
addBench(-10.2, -0.5, Math.PI / 2);
// Boundary fence.
const fenceMaterial = flatMaterial(0xe7dfc9);
const fencePostMaterial = flatMaterial(0x697b6f);
function fenceSegment(ax, az, bx, bz) {
const length = Math.hypot(bx - ax, bz - az);
const angle = -Math.atan2(bz - az, bx - ax);
const midX = (ax + bx) / 2;
const midZ = (az + bz) / 2;
[0.65, 1.18].forEach((height) => {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.09, 0.09),
fenceMaterial
);
rail.position.set(midX, height, midZ);
rail.rotation.y = angle;
rail.castShadow = true;
scene.add(rail);
});
const count = Math.max(1, Math.ceil(length / 2.35));
for (let i = 0; i <= count; i++) {
const t = i / count;
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.07, 0.09, 1.55, 6),
fencePostMaterial
);
post.position.set(
THREE.MathUtils.lerp(ax, bx, t),
0.76,
THREE.MathUtils.lerp(az, bz, t)
);
post.castShadow = true;
scene.add(post);
}
}
fenceSegment(-16, -11, 16, -11);
fenceSegment(-16, -11, -16, 11);
fenceSegment(16, -11, 16, 11);
fenceSegment(-16, 11, -2.2, 11);
fenceSegment(2.2, 11, 16, 11);
[-2.2, 2.2].forEach((x) => {
createBox(0.36, 2.25, 0.36, fencePostMaterial, x, 1.1, 10.85, true);
});
createBox(4.7, 0.35, 0.3, flatMaterial(0x2f7057), 0, 2.05, 10.85, true);
// Small flower beds.
function addFlowerBed(x, z, color) {
createBox(2.4, 0.18, 1.05, flatMaterial(0x947d58), x, 0.09, z);
for (let i = 0; i < 7; i++) {
const flower = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.13, 0),
flatMaterial(color)
);
flower.position.set(
x - 0.9 + (i % 4) * 0.58,
0.3,
z - 0.2 + Math.floor(i / 4) * 0.4
);
scene.add(flower);
}
}
addFlowerBed(-8.3, 9.0, 0xe7a64a);
addFlowerBed(9.0, 9.0, 0xcf6654);
// ---------- Litter clusters ----------
const hitMeshes = [];
const litterMaterials = {
paper: flatMaterial(0xf0ead8),
paperWarm: flatMaterial(0xc9ab75),
bottle: flatMaterial(0x5fa4a1, { roughness: 0.5 }),
bottleBlue: flatMaterial(0x5a83b4, { roughness: 0.5 }),
can: flatMaterial(0xa8b2aa, { metalness: 0.25, roughness: 0.45 }),
wrapper: flatMaterial(0xe5a74c),
glass: flatMaterial(0x719678, {
roughness: 0.35,
transparent: true,
opacity: 0.86
})
};
function seededRandom(seed) {
const value = Math.sin(seed * 999.31) * 43758.5453;
return value - Math.floor(value);
}
function createLitterMesh(kind, index) {
let mesh;
if (kind === "paper") {
mesh = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.045, 0.46),
index % 2 ? litterMaterials.paper : litterMaterials.paperWarm
);
mesh.rotation.y = seededRandom(index + 1) * Math.PI;
} else if (kind === "bottle") {
mesh = new THREE.Mesh(
new THREE.CylinderGeometry(0.085, 0.09, 0.48, 6),
index % 2 ? litterMaterials.bottle : litterMaterials.bottleBlue
);
mesh.rotation.z = Math.PI / 2;
} else if (kind === "can") {
mesh = new THREE.Mesh(
new THREE.CylinderGeometry(0.12, 0.12, 0.3, 8),
litterMaterials.can
);
} else if (kind === "glass") {
mesh = new THREE.Mesh(
new THREE.CylinderGeometry(0.095, 0.11, 0.38, 7),
litterMaterials.glass
);
} else {
mesh = new THREE.Mesh(
new THREE.BoxGeometry(0.28, 0.05, 0.2),
litterMaterials.wrapper
);
mesh.rotation.y = seededRandom(index + 8) * Math.PI;
}
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
tasks.forEach((task) => {
const group = new THREE.Group();
group.position.copy(task.position);
const litterGroup = new THREE.Group();
const kinds =
task.material === "Plastic"
? ["bottle", "wrapper", "bottle", "can"]
: task.material === "Paper"
? ["paper", "paperWarm", "paper"]
: task.material === "Glass"
? ["glass", "can", "glass"]
: ["paper", "bottle", "wrapper", "can"];
for (let i = 0; i < task.units; i++) {
const piece = createLitterMesh(kinds[i % kinds.length], i + task.id * 10);
const angle = seededRandom(i + task.id * 21) * Math.PI * 2;
const radius = 0.18 + seededRandom(i + task.id * 37) * 0.55;
piece.position.set(
Math.cos(angle) * radius,
0.17 + (piece.geometry.type === "BoxGeometry" ? 0.02 : 0.04),
Math.sin(angle) * radius
);
litterGroup.add(piece);
}
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.72, 0.88, 28),
new THREE.MeshBasicMaterial({
color: materialMeta[task.material].color,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.92,
depthWrite: false
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.14;
ring.renderOrder = 3;
group.add(ring);
const hit = new THREE.Mesh(
new THREE.CylinderGeometry(0.92, 0.92, 1.4, 8),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
})
);
hit.position.y = 0.7;
hit.userData.taskId = task.id;
group.add(hit);
hitMeshes.push(hit);
scene.add(group);
const patch = new THREE.Mesh(
new THREE.CircleGeometry(1, 24),
new THREE.MeshBasicMaterial({
color: 0x3e9b6c,
transparent: true,
opacity: 0.22,
depthWrite: false,
side: THREE.DoubleSide
})
);
patch.rotation.x = -Math.PI / 2;
patch.position.set(task.x, 0.125, task.z);
patch.scale.setScalar(Math.sqrt(task.area) * 0.32);
patch.visible = false;
scene.add(patch);
const label = document.createElement("button");
label.className = "map-label task-label";
label.type = "button";
label.style.background = materialMeta[task.material].css;
label.textContent = String(task.id).padStart(2, "0");
label.setAttribute(
"aria-label",
`${task.name}, ${task.material}, ${task.area} square meters`
);
label.addEventListener("click", () => selectTask(task.id));
mapLabels.appendChild(label);
task.visual = { group, litterGroup, ring, patch, label };
});
// ---------- Collection points ----------
collectionPoints.forEach((point) => {
const group = new THREE.Group();
group.position.copy(point.position);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.83, 0.92, 0.18, 10),
flatMaterial(0x7b806f)
);
base.position.y = 0.09;
base.receiveShadow = true;
group.add(base);
const bin = new THREE.Mesh(
new THREE.CylinderGeometry(0.62, 0.54, 1.08, 8),
flatMaterial(point.color)
);
bin.position.y = 0.72;
bin.castShadow = true;
group.add(bin);
const lid = new THREE.Mesh(
new THREE.CylinderGeometry(0.67, 0.67, 0.13, 8),
flatMaterial(0x344e43)
);
lid.position.y = 1.3;
lid.castShadow = true;
group.add(lid);
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.18, 0),
flatMaterial(0xf2d77b)
);
marker.position.y = 1.62;
group.add(marker);
scene.add(group);
point.visual = { group, bin, lid, marker };
const label = document.createElement("div");
label.className = "map-label collection-label";
label.innerHTML = `<i style="background:${point.css}"></i>${point.name}`;
mapLabels.appendChild(label);
point.label = label;
});
// ---------- Teams and continuous routes ----------
function createTeamVisual(team) {
const group = new THREE.Group();
const torso = new THREE.Mesh(
new THREE.CylinderGeometry(0.24, 0.31, 0.64, 6),
flatMaterial(team.color)
);
torso.position.y = 0.78;
torso.castShadow = true;
group.add(torso);
const head = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.22, 0),
flatMaterial(0xd8a078)
);
head.position.y = 1.3;
head.castShadow = true;
group.add(head);
const hat = new THREE.Mesh(
new THREE.CylinderGeometry(0.25, 0.25, 0.12, 8),
flatMaterial(0xf4d26f)
);
hat.position.y = 1.48;
hat.castShadow = true;
group.add(hat);
const backpack = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.4, 0.18),
flatMaterial(0x405b4c)
);
backpack.position.set(0, 0.82, -0.25);
backpack.castShadow = true;
group.add(backpack);
[-0.13, 0.13].forEach((x) => {
const leg = new THREE.Mesh(
new THREE.BoxGeometry(0.13, 0.43, 0.16),
flatMaterial(0x34453e)
);
leg.position.set(x, 0.3, 0);
leg.castShadow = true;
group.add(leg);
const arm = new THREE.Mesh(
new THREE.BoxGeometry(0.11, 0.43, 0.13),
flatMaterial(team.color)
);
arm.position.set(x * 2.15, 0.79, 0);
arm.rotation.z = x > 0 ? -0.12 : 0.12;
arm.castShadow = true;
group.add(arm);
});
const selectionRing = new THREE.Mesh(
new THREE.RingGeometry(0.38, 0.49, 20),
new THREE.MeshBasicMaterial({
color: team.color,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.8
})
);
selectionRing.rotation.x = -Math.PI / 2;
selectionRing.position.y = 0.14;
group.add(selectionRing);
group.position.copy(team.current);
scene.add(group);
team.avatar = group;
team.selectionRing = selectionRing;
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(3), 3)
);
const line = new THREE.Line(
geometry,
new THREE.LineBasicMaterial({
color: team.color,
transparent: true,
opacity: 0.86,
depthTest: false,
depthWrite: false
})
);
line.renderOrder = 8;
line.frustumCulled = false;
scene.add(line);
team.routeLine = line;
const label = document.createElement("div");
label.className = "map-label team-map-label";
label.innerHTML = `<i style="background:${team.css}"></i>${team.name}`;
mapLabels.appendChild(label);
team.label = label;
}
teams.forEach(createTeamVisual);
function assignedTasks(team) {
return tasks
.filter((task) => task.teamId === team.id && !task.cleared)
.sort((a, b) => a.id - b.id);
}
function rebuildTeamRoute(team) {
const assigned = assignedTasks(team);
const active = assigned.find((task) => task.id === team.activeTaskId);
const ordered = active
? [active, ...assigned.filter((task) => task.id !== active.id)]
: assigned;
const route = [];
ordered.forEach((task) => {
route.push({
type: "pickup",
taskId: task.id,
position: task.position.clone()
});
route.push({
type: "dropoff",
taskId: task.id,
position: getPoint(task.collectionId).position.clone()
});
});
team.route = route;
team.routeIndex = 0;
}
function updateRouteLines() {
teams.forEach((team) => {
const points = [team.current.clone()];
for (let i = team.routeIndex; i < team.route.length; i++) {
points.push(team.route[i].position.clone());
}
points.forEach((point) => {
point.y = 0.19;
});
const geometry = team.routeLine.geometry;
const attribute = geometry.getAttribute("position");
if (attribute.count !== points.length) {
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(
points.flatMap((point) => [point.x, point.y, point.z]),
3
)
);
} else {
points.forEach((point, index) => {
attribute.setXYZ(index, point.x, point.y, point.z);
});
attribute.needsUpdate = true;
}
geometry.computeBoundingSphere();
const selected = !state.selectedTeamId || state.selectedTeamId === team.id;
team.routeLine.material.opacity = selected ? 0.92 : 0.2;
team.routeLine.visible =
state.routesVisible && points.length > 1 && team.route.length > 0;
});
}
// ---------- Simulation ----------
function completeTask(team, task) {
task.cleared = true;
task.progress = 1;
task.visual.litterGroup.visible = false;
task.visual.patch.visible = true;
team.clearedTasks += 1;
team.activeTaskId = null;
team.serviceRemaining = 0;
team.routeIndex += 1;
refreshStatuses();
updateMetrics();
updateTeamCards();
updateTaskLabels();
}
function updateTeam(team, deltaMinutes) {
if (team.activeTaskId !== null) {
const task = tasks.find((item) => item.id === team.activeTaskId);
team.serviceRemaining -= deltaMinutes;
task.progress = THREE.MathUtils.clamp(
1 - team.serviceRemaining / task.duration,
0,
1
);
if (team.serviceRemaining <= 0) {
completeTask(team, task);
}
return;
}
if (team.routeIndex >= team.route.length) {
team.avatar.position.copy(team.current);
return;
}
const waypoint = team.route[team.routeIndex];
const target = waypoint.position;
const distance = team.current.distanceTo(target);
const travel = 2.7 * deltaMinutes;
if (distance <= travel) {
team.current.copy(target);
team.avatar.position.copy(team.current);
if (waypoint.type === "pickup") {
const task = tasks.find((item) => item.id === waypoint.taskId);
team.activeTaskId = task.id;
team.serviceRemaining = task.duration;
task.progress = 0;
refreshStatuses();
} else {
const task = tasks.find((item) => item.id === waypoint.taskId);
const point = getPoint(task.collectionId);
if (!task.deposited) {
task.deposited = true;
point.deposited += task.units;
team.depositedItems += task.units;
}
team.routeIndex += 1;
}
} else {
const direction = target.clone().sub(team.current).normalize();
team.current.addScaledVector(direction, travel);
team.avatar.position.copy(team.current);
team.avatar.rotation.y = Math.atan2(direction.x, direction.z);
}
}
function updateSimulation(deltaMinutes) {
state.simMinutes += deltaMinutes;
teams.forEach((team) => updateTeam(team, deltaMinutes));
}
// ---------- UI ----------
function taskState(task) {
if (task.cleared) {
return { kind: "cleared", label: "Cleared" };
}
const team = getTeam(task.teamId);
if (team?.activeTaskId === task.id) {
return {
kind: "active",
label: `Collecting ${Math.round(task.progress * 100)}%`
};
}
if (team) {
return { kind: "queued", label: "Queued" };
}
return { kind: "open", label: "Open" };
}
function renderBoard() {
const list = $("#taskList");
list.innerHTML = "";
tasks.forEach((task) => {
const meta = materialMeta[task.material];
const card = document.createElement("article");
card.className = "task-card";
card.dataset.taskId = task.id;
card.innerHTML = `
<div class="task-top">
<div class="task-number" style="background:${meta.css}">
${String(task.id).padStart(2, "0")}
</div>
<div class="task-name">
<strong>${task.name}</strong>
<span>${task.material} litter</span>
</div>
<span class="task-status"></span>
</div>
<div class="task-meta">
<span>${task.area.toFixed(1)} m²</span>
<span>${task.duration} min</span>
<span>${task.units} items</span>
</div>
<div class="assignment-row">
<select class="team-select" aria-label="Team for ${task.name}">
<option value="">Choose team</option>
${teams
.map(
(team) =>
`<option value="${team.id}">${team.name}</option>`
)
.join("")}
</select>
<select class="point-select" aria-label="Collection point for ${task.name}">
${collectionPoints
.map(
(point) =>
`<option value="${point.id}">${point.name}</option>`
)
.join("")}
</select>
<button class="assign-button" type="button">Assign</button>
</div>
`;
const teamSelect = card.querySelector(".team-select");
const pointSelect = card.querySelector(".point-select");
const assignButton = card.querySelector(".assign-button");
teamSelect.value = task.teamId || "";
pointSelect.value = task.collectionId;
assignButton.textContent = task.teamId ? "Update" : "Assign";
assignButton.addEventListener("click", () => {
if (!teamSelect.value) {
showToast("Choose a field team before assigning this cluster.");
return;
}
assignTask(task, teamSelect.value, pointSelect.value);
});
card.addEventListener("click", (event) => {
if (
event.target !== teamSelect &&
event.target !== pointSelect &&
event.target !== assignButton
) {
selectTask(task.id);
}
});
list.appendChild(card);
});
refreshStatuses();
updateOpenCount();
}
function refreshStatuses() {
document.querySelectorAll(".task-card").forEach((card) => {
const task = tasks.find((item) => item.id === Number(card.dataset.taskId));
const status = taskState(task);
const badge = card.querySelector(".task-status");
badge.textContent = status.label;
badge.dataset.kind = status.kind;
card.classList.toggle("selected", state.selectedTaskId === task.id);
card.classList.toggle("cleared", task.cleared);
});
}
function updateOpenCount() {
const open = tasks.filter((task) => !task.teamId).length;
$("#openCount").textContent = `${open} unassigned`;
}
function renderTeamCards() {
const list = $("#teamList");
list.innerHTML = "";
teams.forEach((team) => {
const assigned = assignedTasks(team).length;
const card = document.createElement("article");
card.className = "team-card";
card.dataset.teamId = team.id;
card.style.setProperty("--team-color", team.css);
card.innerHTML = `
<div class="team-head">
<span class="team-name">${team.name}</span>
<span class="team-open">${assigned}/${team.capacity} assigned</span>
</div>
<span class="team-state"></span>
<div class="team-progress"><span></span></div>
`;
card.addEventListener("click", () => {
state.selectedTeamId =
state.selectedTeamId === team.id ? null : team.id;
renderTeamCards();
updateRouteLines();
});
list.appendChild(card);
});
updateTeamCards();
}
function updateTeamCards() {
teams.forEach((team) => {
const card = document.querySelector(
`.team-card[data-team-id="${team.id}"]`
);
if (!card) return;
card.classList.toggle("selected", state.selectedTeamId === team.id);
const assigned = assignedTasks(team).length;
card.querySelector(".team-open").textContent =
`${assigned}/${team.capacity} assigned`;
const stateElement = card.querySelector(".team-state");
const progress = card.querySelector(".team-progress span");
if (team.activeTaskId !== null) {
const task = tasks.find((item) => item.id === team.activeTaskId);
stateElement.textContent =
`Collecting ${task.name} · ${Math.max(
0,
Math.ceil(team.serviceRemaining)
)} min`;
progress.style.width = `${task.progress * 100}%`;
} else if (team.routeIndex < team.route.length) {
const next = team.route[team.routeIndex];
if (next.type === "pickup") {
const task = tasks.find((item) => item.id === next.taskId);
stateElement.textContent = `Walking to ${task.name}`;
} else {
const task = tasks.find((item) => item.id === next.taskId);
stateElement.textContent = `Hauling to ${getPoint(task.collectionId).name}`;
}
progress.style.width = "0%";
} else {
stateElement.textContent = `${team.clearedTasks} clusters cleared · Ready`;
progress.style.width = "0%";
}
});
}
function updateMetrics() {
const clearedTasks = tasks.filter((task) => task.cleared);
const clearedArea = clearedTasks.reduce((sum, task) => sum + task.area, 0);
const recoveredItems = clearedTasks.reduce((sum, task) => sum + task.units, 0);
const deployed = teams.filter((team) => assignedTasks(team).length > 0).length;
$("#statCleared").innerHTML = `${clearedTasks.length} <small>/ ${tasks.length}</small>`;
$("#statArea").innerHTML = `${clearedArea.toFixed(1)} <small>m²</small>`;
$("#statItems").textContent = recoveredItems;
$("#statTeams").innerHTML = `${deployed} <small>/ ${teams.length}</small>`;
const counts = {
Plastic: 0,
Paper: 0,
Glass: 0,
Mixed: 0
};
clearedTasks.forEach((task) => {
counts[task.material] += task.units;
});
const maximum = Math.max(1, ...Object.values(counts));
Object.entries(counts).forEach(([name, count]) => {
const row = document.querySelector(`[data-material="${name}"]`);
if (!row) return;
row.querySelector(".material-fill").style.width =
`${(count / maximum) * 100}%`;
row.querySelector(".material-count").textContent = count;
});
}
function initializeMaterialRows() {
$("#materialRows").innerHTML = Object.entries(materialMeta)
.map(
([name, meta]) => `
<div class="material-row" data-material="${name}">
<div class="material-name">
<i style="background:${meta.css}"></i>${name}
</div>
<div class="material-track">
<div class="material-fill" style="background:${meta.css}"></div>
</div>
<span class="material-count">0</span>
</div>
`
)
.join("");
}
function assignTask(task, teamId, collectionId, quiet = false) {
if (!task || task.cleared) return;
const newTeam = getTeam(teamId);
const point = getPoint(collectionId);
if (!newTeam || !point) return;
const oldTeam = getTeam(task.teamId);
const changingTeam = task.teamId !== teamId;
if (changingTeam) {
if (oldTeam?.activeTaskId === task.id) {
if (!quiet) {
showToast("That team is actively collecting this cluster. Let the pickup finish first.");
}
return;
}
if (assignedTasks(newTeam).length >= newTeam.capacity) {
if (!quiet) {
showToast(`${newTeam.name} already has ${newTeam.capacity} assigned clusters.`);
}
return;
}
}
task.teamId = teamId;
task.collectionId = collectionId;
task.progress = 0;
if (oldTeam && oldTeam.id !== teamId) {
rebuildTeamRoute(oldTeam);
}
rebuildTeamRoute(newTeam);
renderBoard();
renderTeamCards();
updateMetrics();
if (!quiet) {
showToast(
`${task.name} assigned to ${newTeam.name} · ${point.name}`
);
}
}
function autoDispatch() {
const openTasks = tasks
.filter((task) => !task.teamId)
.sort((a, b) => b.area - a.area);
let assignedCount = 0;
openTasks.forEach((task) => {
const available = teams
.filter((team) => assignedTasks(team).length < team.capacity)
.sort(
(a, b) =>
assignedTasks(a).length - assignedTasks(b).length ||
a.home.distanceToSquared(task.position) -
b.home.distanceToSquared(task.position)
);
if (!available.length) return;
const point = nearestPoint(task);
assignTask(task, available[0].id, point.id, true);
assignedCount++;
});
renderBoard();
renderTeamCards();
updateMetrics();
showToast(
assignedCount
? `${assignedCount} open clusters assigned across the field teams.`
: "All teams are at capacity. Update an existing assignment first."
);
}
function selectTask(id) {
state.selectedTaskId = id;
refreshStatuses();
updateTaskLabels();
const card = document.querySelector(`.task-card[data-task-id="${id}"]`);
card?.scrollIntoView({ behavior: "smooth", block: "nearest" });
const task = tasks.find((item) => item.id === id);
if (task) {
showToast(
`${task.name}: ${task.material}, ${task.area.toFixed(1)} m², ${task.duration} min estimate`
);
}
}
function showToast(message) {
document.querySelectorAll(".toast").forEach((node) => node.remove());
const toast = document.createElement("div");
toast.className = "toast";
toast.textContent = message;
stage.appendChild(toast);
window.setTimeout(() => toast.remove(), 2600);
}
// ---------- Map labels ----------
const projection = new THREE.Vector3();
function positionLabel(element, position, heightOffset = 0) {
projection.copy(position);
projection.y += heightOffset;
projection.project(camera);
const visible = projection.z > -1 && projection.z < 1;
element.style.display = visible ? "flex" : "none";
if (!visible) return;
const width = canvasHost.clientWidth;
const height = canvasHost.clientHeight;
element.style.left = `${(projection.x * 0.5 + 0.5) * width}px`;
element.style.top = `${(-projection.y * 0.5 + 0.5) * height}px`;
}
function updateTaskLabels() {
tasks.forEach((task) => {
const label = task.visual.label;
const status = taskState(task);
label.dataset.state = status.kind;
label.classList.toggle("active", status.kind === "active");
label.classList.toggle("cleared", task.cleared);
label.classList.toggle("selected", state.selectedTaskId === task.id);
label.title = `${task.name} · ${task.material} · ${task.area.toFixed(1)} m²`;
});
}
function updateMapLabels() {
tasks.forEach((task) => {
positionLabel(task.visual.label, task.position, 1.35);
});
collectionPoints.forEach((point) => {
positionLabel(point.label, point.position, 1.9);
});
teams.forEach((team) => {
positionLabel(team.label, team.current, 1.72);
});
}
function updateMarkers(now) {
tasks.forEach((task) => {
const status = taskState(task);
let color = materialMeta[task.material].color;
if (task.cleared) color = 0x3e9b6c;
else if (status.kind === "active") color = getTeam(task.teamId).color;
task.visual.ring.material.color.setHex(color);
const pulse =
task.cleared
? 1
: 1 + Math.sin(now * 0.003 + task.id) * 0.055;
task.visual.ring.scale.setScalar(
state.selectedTaskId === task.id ? pulse * 1.12 : pulse
);
});
collectionPoints.forEach((point) => {
const fill = Math.min(1, point.deposited / 20);
point.visual.bin.scale.y = 1 + fill * 0.12;
point.visual.lid.position.y = 1.3 + fill * 0.04;
});
}
// ---------- Custom camera controls ----------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
renderer.domElement.addEventListener("pointerdown", (event) => {
cameraControls.dragging = true;
cameraControls.panning = event.button === 2 || event.shiftKey;
cameraControls.lastX = event.clientX;
cameraControls.lastY = event.clientY;
cameraControls.moved = 0;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!cameraControls.dragging) return;
const dx = event.clientX - cameraControls.lastX;
const dy = event.clientY - cameraControls.lastY;
cameraControls.lastX = event.clientX;
cameraControls.lastY = event.clientY;
cameraControls.moved += Math.abs(dx) + Math.abs(dy);
if (cameraControls.panning) {
const azimuth = cameraControls.azimuth;
const right = new THREE.Vector3(Math.cos(azimuth), 0, -Math.sin(azimuth));
const forward = new THREE.Vector3(
-Math.sin(azimuth),
0,
-Math.cos(azimuth)
);
const scale = cameraControls.distance * 0.0014;
cameraControls.target.addScaledVector(right, -dx * scale);
cameraControls.target.addScaledVector(forward, dy * scale);
cameraControls.target.x = THREE.MathUtils.clamp(
cameraControls.target.x,
-12,
12
);
cameraControls.target.z = THREE.MathUtils.clamp(
cameraControls.target.z,
-8,
8
);
} else {
cameraControls.azimuth -= dx * 0.005;
cameraControls.polar = THREE.MathUtils.clamp(
cameraControls.polar - dy * 0.004,
0.08,
1.25
);
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
const wasClick = cameraControls.moved < 7 && event.button === 0;
cameraControls.dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (!wasClick) return;
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(hitMeshes, false);
if (hits.length) {
selectTask(hits[0].object.userData.taskId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
cameraControls.dragging = false;
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraControls.distance = THREE.MathUtils.clamp(
cameraControls.distance * Math.exp(event.deltaY * 0.001),
20,
60
);
},
{ passive: false }
);
// ---------- Buttons and keyboard ----------
function updatePlayButton() {
$("#playPause").textContent = state.running ? "Pause" : "Resume";
$("#livePill").classList.toggle("paused", !state.running);
$("#liveText").textContent = state.running ? "Simulation live" : "Simulation paused";
}
$("#playPause").addEventListener("click", () => {
state.running = !state.running;
updatePlayButton();
});
$("#routeToggle").addEventListener("click", () => {
state.routesVisible = !state.routesVisible;
$("#routeToggle").textContent = state.routesVisible ? "Routes on" : "Routes off";
$("#routeToggle").classList.toggle("active", state.routesVisible);
updateRouteLines();
});
$("#topView").addEventListener("click", () => resetCamera(true));
$("#resetView").addEventListener("click", () => resetCamera(false));
$("#autoDispatch").addEventListener("click", autoDispatch);
$("#resetRun").addEventListener("click", () => {
state.simMinutes = 0;
state.selectedTaskId = null;
state.selectedTeamId = null;
state.running = true;
tasks.forEach((task) => {
task.teamId = null;
task.collectionId = nearestPoint(task).id;
task.cleared = false;
task.deposited = false;
task.progress = 0;
task.visual.litterGroup.visible = true;
task.visual.patch.visible = false;
task.visual.ring.material.color.setHex(materialMeta[task.material].color);
});
collectionPoints.forEach((point) => {
point.deposited = 0;
});
teams.forEach((team) => {
team.current.copy(team.home);
team.avatar.position.copy(team.current);
team.route = [];
team.routeIndex = 0;
team.activeTaskId = null;
team.serviceRemaining = 0;
team.clearedTasks = 0;
team.depositedItems = 0;
});
renderBoard();
renderTeamCards();
updateMetrics();
updatePlayButton();
showToast("The cleanup run has been reset.");
});
window.addEventListener("keydown", (event) => {
const tag = event.target.tagName;
if (tag === "INPUT" || tag === "SELECT" || tag === "TEXTAREA") return;
if (event.code === "Space") {
event.preventDefault();
state.running = !state.running;
updatePlayButton();
}
if (event.key.toLowerCase() === "r") {
resetCamera(false);
}
if (event.key.toLowerCase() === "t") {
resetCamera(true);
}
});
// ---------- Resize and animation ----------
function resizeRenderer() {
const width = Math.max(1, canvasHost.clientWidth);
const height = Math.max(1, canvasHost.clientHeight);
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(canvasHost);
resizeRenderer();
function updateClock() {
const totalMinutes = 8 * 60 + 30 + Math.floor(state.simMinutes);
const hours = Math.floor(totalMinutes / 60) % 24;
const minutes = totalMinutes % 60;
$("#clock").textContent = `${String(hours).padStart(2, "0")}:${String(
minutes
).padStart(2, "0")}`;
}
initializeMaterialRows();
renderBoard();
renderTeamCards();
updateMetrics();
updatePlayButton();
resetCamera(false);
let previousTime = performance.now();
let uiAccumulator = 0;
function animate(now) {
requestAnimationFrame(animate);
const realDelta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (state.running) {
updateSimulation(realDelta * state.simRate);
}
updateCamera();
updateRouteLines();
updateMapLabels();
updateMarkers(now);
uiAccumulator += realDelta;
if (uiAccumulator >= 0.12) {
uiAccumulator = 0;
updateClock();
updateTeamCards();
refreshStatuses();
updateTaskLabels();
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```