Prompt specification
Build or customize the Three.js 3D scene "Choose a load distribution for a steep route" 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: Choose a load distribution for a steep route
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/choose-a-load-distribution-for-a-steep-route-x2632
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring mountain trade along the Tea Horse Road. Let users divide fictional cargo across pack animals with stated capacity limits. Highlight overloaded carriers and compare trip counts while treating the trade scenario as illustrative. Low-poly.
Working Three.js Starter (choose-a-load-distribution-for-a-steep-route-x2632):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#29483f">
<title>Tea Horse Road — Mountain Trade Planner</title>
<style>
:root {
--ink: #21342e;
--muted: #718079;
--paper: #f7f2e8;
--paper-deep: #eee6d7;
--jade: #356b5d;
--jade-dark: #294f45;
--rust: #b55c42;
--rust-dark: #8c3f2f;
--gold: #c99a4b;
--line: rgba(33, 52, 46, 0.13);
--shadow: 0 22px 70px rgba(25, 42, 35, 0.2);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce7df;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
cursor: pointer;
}
#app,
#scene,
#labels {
position: fixed;
inset: 0;
}
#scene {
background:
radial-gradient(circle at 45% 30%, #f4f3e9 0, transparent 35%),
#dce7df;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
#labels {
pointer-events: none;
overflow: hidden;
z-index: 3;
}
.scene-header {
position: fixed;
z-index: 5;
top: 22px;
left: 24px;
display: flex;
align-items: center;
gap: 15px;
padding: 12px 16px 12px 12px;
border: 1px solid rgba(255, 255, 255, 0.58);
border-radius: 15px;
background: rgba(247, 242, 232, 0.82);
box-shadow: 0 12px 35px rgba(37, 62, 51, 0.12);
backdrop-filter: blur(14px);
pointer-events: none;
}
.route-mark {
width: 42px;
height: 42px;
display: grid;
place-items: center;
border-radius: 12px;
background: var(--jade);
color: #fff8e8;
box-shadow: inset 0 0 0 1px rgba(255,255,255,.15);
}
.route-mark svg {
width: 27px;
height: 27px;
}
.scene-header .eyebrow {
margin: 0 0 3px;
color: var(--rust);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.scene-header h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: 18px;
font-weight: 700;
letter-spacing: -0.01em;
}
.scene-header .subtitle {
margin: 3px 0 0;
color: var(--muted);
font-size: 11px;
}
#panel {
position: fixed;
z-index: 10;
top: 18px;
right: 18px;
bottom: 18px;
width: 390px;
display: flex;
flex-direction: column;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.68);
border-radius: 22px;
background: rgba(247, 242, 232, 0.94);
box-shadow: var(--shadow);
backdrop-filter: blur(20px);
}
.panel-top {
flex: 0 0 auto;
padding: 23px 23px 17px;
border-bottom: 1px solid var(--line);
background:
linear-gradient(135deg, rgba(255,255,255,.52), transparent 70%),
var(--paper);
}
.panel-top .eyebrow {
display: flex;
align-items: center;
justify-content: space-between;
margin: 0 0 7px;
color: var(--rust);
font-size: 10px;
font-weight: 850;
letter-spacing: .15em;
text-transform: uppercase;
}
.illustrative-badge {
padding: 4px 7px;
border: 1px solid rgba(181, 92, 66, .25);
border-radius: 999px;
color: var(--rust-dark);
background: rgba(181, 92, 66, .08);
font-size: 9px;
letter-spacing: .08em;
}
.panel-top h2 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: 28px;
line-height: 1.06;
letter-spacing: -.025em;
}
.panel-top p {
margin: 10px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.panel-scroll {
flex: 1 1 auto;
overflow-y: auto;
overscroll-behavior: contain;
padding: 18px 20px 24px;
scrollbar-width: thin;
scrollbar-color: rgba(53, 107, 93, .28) transparent;
}
.panel-scroll::-webkit-scrollbar {
width: 6px;
}
.panel-scroll::-webkit-scrollbar-thumb {
border-radius: 99px;
background: rgba(53, 107, 93, .28);
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-bottom: 18px;
}
.metric {
min-height: 76px;
padding: 11px 10px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255,255,255,.42);
}
.metric-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: .08em;
text-transform: uppercase;
}
.metric-value {
display: block;
font-family: Georgia, "Times New Roman", serif;
font-size: 24px;
line-height: 1;
}
.metric-value small {
margin-left: 2px;
color: var(--muted);
font-family: inherit;
font-size: 12px;
}
.metric-note {
display: block;
margin-top: 6px;
color: var(--muted);
font-size: 9px;
line-height: 1.25;
}
.metric.alert .metric-value,
.metric.alert .metric-note {
color: var(--rust-dark);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin: 18px 2px 9px;
}
.section-heading h3 {
margin: 0;
font-size: 11px;
font-weight: 850;
letter-spacing: .11em;
text-transform: uppercase;
}
.section-heading span {
color: var(--muted);
font-size: 10px;
}
.manifest {
overflow: hidden;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255,255,255,.38);
}
.manifest-row {
display: grid;
grid-template-columns: 31px 1fr auto;
align-items: center;
gap: 10px;
min-height: 54px;
padding: 8px 11px;
border-bottom: 1px solid var(--line);
}
.manifest-row:last-child {
border-bottom: 0;
}
.cargo-icon {
width: 29px;
height: 29px;
display: grid;
place-items: center;
border-radius: 9px;
color: white;
font-family: Georgia, serif;
font-size: 15px;
font-weight: 700;
box-shadow: inset 0 0 0 1px rgba(255,255,255,.2);
}
.manifest-name {
font-size: 11px;
font-weight: 750;
}
.manifest-meta {
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.manifest-weight {
text-align: right;
font-family: Georgia, serif;
font-size: 15px;
font-weight: 700;
}
.manifest-weight small {
display: block;
margin-top: 1px;
color: var(--muted);
font-family: inherit;
font-size: 8px;
font-weight: 600;
text-transform: uppercase;
}
.inventory-track {
height: 4px;
background: var(--paper-deep);
}
.inventory-track i {
display: block;
width: 100%;
height: 100%;
background: var(--jade);
transition: width .25s ease;
}
.plan-summary {
margin: 10px 0 0;
padding: 11px 12px;
border-left: 3px solid var(--jade);
border-radius: 0 10px 10px 0;
color: var(--jade-dark);
background: rgba(53, 107, 93, .08);
font-size: 11px;
line-height: 1.45;
}
.plan-summary.warning {
border-left-color: var(--rust);
color: var(--rust-dark);
background: rgba(181, 92, 66, .09);
}
.carrier-list {
display: grid;
gap: 10px;
}
.carrier-card {
padding: 13px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(255,255,255,.43);
transition: border-color .2s ease, transform .2s ease, box-shadow .2s ease;
}
.carrier-card:hover,
.carrier-card.selected {
border-color: rgba(53, 107, 93, .42);
box-shadow: 0 8px 25px rgba(33, 52, 46, .08);
transform: translateY(-1px);
}
.carrier-card.overloaded {
border-color: rgba(181, 92, 66, .43);
background: rgba(181, 92, 66, .045);
}
.carrier-head {
display: grid;
grid-template-columns: 34px 1fr auto;
align-items: center;
gap: 9px;
}
.animal-badge {
width: 32px;
height: 32px;
display: grid;
place-items: center;
border-radius: 10px;
color: #fff9ec;
background: var(--jade);
font-family: Georgia, serif;
font-size: 15px;
font-weight: 700;
}
.animal-badge.horse {
background: var(--rust);
}
.animal-badge.mule {
background: var(--gold);
}
.carrier-name {
font-size: 12px;
font-weight: 800;
}
.carrier-type {
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.trip-chip {
padding: 4px 7px;
border-radius: 999px;
color: var(--jade-dark);
background: rgba(53, 107, 93, .1);
font-size: 9px;
font-weight: 800;
white-space: nowrap;
}
.trip-chip.overload {
color: var(--rust-dark);
background: rgba(181, 92, 66, .12);
}
.load-row {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 10px;
margin: 11px 0 10px;
}
.load-track {
height: 7px;
overflow: hidden;
border-radius: 99px;
background: rgba(33, 52, 46, .1);
}
.load-track i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--jade);
transition: width .25s ease, background .25s ease;
}
.carrier-card.overloaded .load-track i {
background: var(--rust);
}
.load-number {
min-width: 54px;
color: var(--muted);
text-align: right;
font-size: 10px;
font-weight: 750;
}
.carrier-card.overloaded .load-number {
color: var(--rust-dark);
}
.allocation-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.allocation-item {
min-width: 0;
padding: 8px;
border-radius: 10px;
background: rgba(33, 52, 46, .045);
}
.allocation-item label {
display: block;
overflow: hidden;
margin-bottom: 5px;
color: var(--muted);
font-size: 8px;
font-weight: 700;
text-overflow: ellipsis;
white-space: nowrap;
}
.number-field {
display: flex;
align-items: center;
gap: 4px;
}
.number-field input {
width: 100%;
min-width: 0;
padding: 3px 2px;
border: 0;
border-bottom: 1px solid rgba(33, 52, 46, .25);
outline: none;
color: var(--ink);
background: transparent;
font-size: 13px;
font-weight: 800;
text-align: center;
-moz-appearance: textfield;
}
.number-field input::-webkit-inner-spin-button,
.number-field input::-webkit-outer-spin-button {
margin: 0;
-webkit-appearance: none;
}
.number-field input:focus {
border-bottom-color: var(--jade);
}
.number-field span {
color: var(--muted);
font-size: 8px;
white-space: nowrap;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.action-button {
min-height: 40px;
padding: 9px 12px;
border: 1px solid rgba(53, 107, 93, .25);
border-radius: 11px;
color: var(--jade-dark);
background: rgba(53, 107, 93, .08);
font-size: 10px;
font-weight: 800;
transition: transform .15s ease, background .15s ease;
}
.action-button:hover {
transform: translateY(-1px);
background: rgba(53, 107, 93, .14);
}
.action-button.primary {
border-color: var(--jade);
color: white;
background: var(--jade);
}
.action-button.primary:hover {
background: var(--jade-dark);
}
.wide-action {
width: 100%;
margin-top: 9px;
}
.method-note {
margin: 14px 2px 0;
color: var(--muted);
font-size: 9px;
line-height: 1.55;
}
.method-note strong {
color: var(--ink);
}
.illustrative-note {
margin-top: 13px;
padding: 11px 12px;
border: 1px dashed rgba(181, 92, 66, .35);
border-radius: 11px;
color: #765b4d;
background: rgba(181, 92, 66, .05);
font-size: 9px;
line-height: 1.5;
}
.animal-label {
position: absolute;
min-width: 128px;
padding: 8px 10px;
border: 1px solid rgba(255,255,255,.74);
border-radius: 11px;
background: rgba(247, 242, 232, .9);
box-shadow: 0 8px 24px rgba(27, 46, 39, .15);
backdrop-filter: blur(9px);
transform: translate(-50%, -100%);
white-space: nowrap;
}
.animal-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -6px;
width: 10px;
height: 10px;
border-right: 1px solid rgba(255,255,255,.74);
border-bottom: 1px solid rgba(255,255,255,.74);
background: rgba(247, 242, 232, .9);
transform: translateX(-50%) rotate(45deg);
}
.animal-label strong {
display: block;
margin-bottom: 2px;
color: var(--ink);
font-size: 10px;
}
.animal-label .label-detail {
color: var(--muted);
font-size: 8px;
}
.animal-label .overload-badge {
display: inline-block;
margin-top: 5px;
padding: 3px 5px;
border-radius: 5px;
color: white;
background: var(--rust);
font-size: 7px;
font-weight: 900;
letter-spacing: .08em;
}
.animal-label.overloaded {
border-color: rgba(181, 92, 66, .6);
}
.animal-label.overloaded::after {
background: rgba(248, 235, 225, .94);
}
.camera-tools {
position: fixed;
z-index: 6;
left: 24px;
bottom: 24px;
display: flex;
align-items: center;
gap: 6px;
}
.camera-tools button {
width: 36px;
height: 36px;
border: 1px solid rgba(255,255,255,.65);
border-radius: 11px;
color: var(--ink);
background: rgba(247, 242, 232, .84);
box-shadow: 0 7px 20px rgba(27, 46, 39, .1);
backdrop-filter: blur(9px);
font-size: 17px;
font-weight: 700;
}
.camera-hint {
margin-left: 5px;
color: rgba(33, 52, 46, .72);
font-size: 9px;
font-weight: 700;
text-shadow: 0 1px 5px rgba(255,255,255,.8);
}
#toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 28px;
max-width: min(420px, calc(100vw - 32px));
padding: 10px 14px;
border-radius: 10px;
color: white;
background: rgba(33, 52, 46, .92);
box-shadow: 0 10px 35px rgba(27, 46, 39, .2);
font-size: 11px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 10px);
transition: opacity .2s ease, transform .2s ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
color: var(--paper);
background: #29483f;
transition: opacity .5s ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
.loading-content {
text-align: center;
}
.loading-content strong {
display: block;
margin-bottom: 8px;
font-family: Georgia, serif;
font-size: 24px;
}
.loading-content span {
color: rgba(255,255,255,.62);
font-size: 11px;
letter-spacing: .12em;
text-transform: uppercase;
}
@media (max-width: 760px) {
.scene-header {
top: 10px;
left: 10px;
padding: 9px 11px 9px 9px;
}
.scene-header h1 {
font-size: 14px;
}
.scene-header .subtitle {
display: none;
}
.route-mark {
width: 34px;
height: 34px;
}
#panel {
top: auto;
right: 8px;
bottom: 8px;
left: 8px;
width: auto;
max-height: 52vh;
border-radius: 18px;
}
.panel-top {
padding: 14px 16px 12px;
}
.panel-top h2 {
font-size: 21px;
}
.panel-top p {
display: none;
}
.panel-scroll {
padding: 13px 14px 20px;
}
.metrics {
margin-bottom: 12px;
}
.metric {
min-height: 61px;
padding: 8px;
}
.metric-value {
font-size: 20px;
}
.animal-label {
min-width: 105px;
padding: 6px 8px;
}
.animal-label strong {
font-size: 8px;
}
.animal-label .label-detail {
font-size: 7px;
}
.camera-tools {
top: 67px;
bottom: auto;
left: 10px;
}
.camera-hint {
display: none;
}
}
</style>
</head>
<body>
<div id="app">
<div
id="scene"
role="img"
aria-label="Interactive low-poly mountain trade scene inspired by the Tea Horse Road"
></div>
<div id="labels" aria-hidden="true"></div>
<header class="scene-header">
<div class="route-mark" aria-hidden="true">
<svg viewBox="0 0 32 32" fill="none">
<path d="M4 25L12 8l5 10 4-7 7 14H4Z"
stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
<path d="M8 25c2-5 5-7 9-7 3 0 5 2 7 7"
stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
</svg>
</div>
<div>
<p class="eyebrow">Mountain trade study</p>
<h1>Tea Horse Road</h1>
<p class="subtitle">A fictional caravan-planning vignette</p>
</div>
</header>
<aside id="panel" aria-label="Cargo allocation planner">
<div class="panel-top">
<p class="eyebrow">
Illustrative scenario
<span class="illustrative-badge">Not historical</span>
</p>
<h2>Load the caravan</h2>
<p>
Divide invented trade goods among the pack animals. Capacity is a
per-trip limit; red markers identify an overloaded carrier.
</p>
</div>
<div class="panel-scroll">
<section class="metrics" aria-label="Plan summary">
<div class="metric">
<span class="metric-label">Cargo</span>
<span class="metric-value"><span id="cargoStat">54</span><small>u</small></span>
<span class="metric-note" id="assignedStat">54 of 54 assigned</span>
</div>
<div class="metric">
<span class="metric-label">Fleet cap</span>
<span class="metric-value"><span id="fleetStat">58</span><small>u</small></span>
<span class="metric-note">one convoy pass</span>
</div>
<div class="metric" id="passMetric">
<span class="metric-label">Your passes</span>
<span class="metric-value" id="passStat">2</span>
<span class="metric-note" id="minimumStat">minimum: 1</span>
</div>
</section>
<div class="section-heading">
<h3>Cargo manifest</h3>
<span id="inventoryStatus">fully assigned</span>
</div>
<div class="manifest" id="manifest"></div>
<div class="inventory-track"><i id="inventoryBar"></i></div>
<div class="plan-summary" id="planSummary"></div>
<div class="section-heading">
<h3>Carrier allocation</h3>
<span>units per trip</span>
</div>
<div class="carrier-list" id="carrierList"></div>
<div class="actions">
<button class="action-button" id="balanceButton" type="button">
Auto-balance
</button>
<button class="action-button" id="clearButton" type="button">
Clear plan
</button>
</div>
<button class="action-button primary wide-action" id="convoyButton" type="button">
Preview convoy
</button>
<p class="method-note">
<strong>Trip comparison:</strong> “Your passes” is the longest individual
carrier schedule. “Minimum” is
<strong>ceil(total cargo ÷ total fleet capacity)</strong>, assuming cargo may
be redistributed freely.
</p>
<div class="illustrative-note">
<strong>Fictional planning model.</strong> The route, animals, cargo names,
weights, and capacities are invented for demonstration. This is not a
historical reconstruction or advice about real pack-animal logistics.
</div>
</div>
</aside>
<div class="camera-tools" aria-label="Camera controls">
<button id="zoomIn" type="button" aria-label="Zoom in">+</button>
<button id="zoomOut" type="button" aria-label="Zoom out">−</button>
<button id="resetCamera" type="button" aria-label="Reset camera">↺</button>
<span class="camera-hint">Drag to orbit · wheel to zoom · right-drag to pan</span>
</div>
<div id="toast" role="status" aria-live="polite"></div>
<div id="loading">
<div class="loading-content">
<strong>Tea Horse Road</strong>
<span>Building the mountain pass…</span>
</div>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Planning data
// ------------------------------------------------------------
const cargoTypes = [
{
id: "tea",
name: "Cloudleaf Tea",
shortName: "Cloudleaf",
unit: "bales",
quantity: 8,
weight: 4,
color: 0x8f5b40,
css: "#976044",
glyph: "茶"
},
{
id: "salt",
name: "Sun Amber Salt",
shortName: "Sun Amber",
unit: "sacks",
quantity: 6,
weight: 3,
color: 0xc58a43,
css: "#c28b49",
glyph: "◆"
},
{
id: "silk",
name: "Mooncloth Bundles",
shortName: "Mooncloth",
unit: "rolls",
quantity: 2,
weight: 2,
color: 0x536f91,
css: "#60779a",
glyph: "✦"
}
];
const carriers = [
{
id: "yak-a",
name: "Yak · Kharo",
type: "yak",
typeLabel: "Pack yak",
capacity: 18,
allocation: { tea: 4, salt: 1, silk: 1 }
},
{
id: "horse",
name: "Horse · Jinni",
type: "horse",
typeLabel: "Mountain horse",
capacity: 12,
allocation: { tea: 3, salt: 0, silk: 0 }
},
{
id: "mule",
name: "Mule · Bram",
type: "mule",
typeLabel: "Mountain mule",
capacity: 10,
allocation: { tea: 1, salt: 2, silk: 0 }
},
{
id: "yak-b",
name: "Yak · Norbu",
type: "yak",
typeLabel: "Pack yak",
capacity: 18,
allocation: { tea: 0, salt: 3, silk: 1 }
}
];
const TOTAL_CARGO = cargoTypes.reduce(
(sum, cargo) => sum + cargo.quantity * cargo.weight,
0
);
const FLEET_CAPACITY = carriers.reduce(
(sum, carrier) => sum + carrier.capacity,
0
);
const MINIMUM_PASSES = Math.ceil(TOTAL_CARGO / FLEET_CAPACITY);
let convoyRunning = false;
let convoyPhase = 0;
let selectedCarrier = null;
let toastTimer;
// ------------------------------------------------------------
// Three.js setup
// ------------------------------------------------------------
const sceneHost = document.querySelector("#scene");
const labelHost = document.querySelector("#labels");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdde8e2);
scene.fog = new THREE.Fog(0xdde8e2, 48, 118);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
220
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.13;
sceneHost.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf8f1dc, 0x657b67, 2.2);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffe3ad, 3.25);
sun.position.set(-24, 42, 18);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -58;
sun.shadow.camera.right = 58;
sun.shadow.camera.top = 48;
sun.shadow.camera.bottom = -48;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 120;
sun.shadow.bias = -0.00025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9dbbc8, 0.7);
fill.position.set(30, 15, -25);
scene.add(fill);
// A stable pseudo-random generator keeps the composition consistent.
let randomSeed = 48123;
function random() {
randomSeed |= 0;
randomSeed = (randomSeed + 0x6D2B79F5) | 0;
let t = Math.imul(randomSeed ^ (randomSeed >>> 15), 1 | randomSeed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
const routeCurve = new THREE.CatmullRomCurve3(
[
new THREE.Vector3(-43, 0.15, 7),
new THREE.Vector3(-32, 0.15, 2),
new THREE.Vector3(-22, 0.15, -3),
new THREE.Vector3(-11, 0.15, -1),
new THREE.Vector3(0, 0.15, 4),
new THREE.Vector3(11, 0.15, 3),
new THREE.Vector3(21, 0.15, -4),
new THREE.Vector3(31, 0.15, -7),
new THREE.Vector3(43, 0.15, -2)
],
false,
"catmullrom",
0.45
);
// ------------------------------------------------------------
// Terrain
// ------------------------------------------------------------
const terrainSource = new THREE.PlaneGeometry(130, 90, 18, 12);
const terrainPositions = terrainSource.attributes.position;
const terrainColors = [];
const lowColor = new THREE.Color(0x7e9472);
const highColor = new THREE.Color(0xa9b39a);
const tempColor = new THREE.Color();
for (let i = 0; i < terrainPositions.count; i++) {
const x = terrainPositions.getX(i);
const y = terrainPositions.getY(i);
const height =
-0.35 +
Math.sin(x * 0.105) * 0.25 +
Math.cos(y * 0.14) * 0.22 +
Math.sin((x + y) * 0.06) * 0.16;
terrainPositions.setZ(i, height);
const blend = THREE.MathUtils.clamp(
0.48 + height * 0.5 + Math.sin(x * 0.08) * 0.12,
0,
1
);
tempColor.copy(lowColor).lerp(highColor, blend);
terrainColors.push(tempColor.r, tempColor.g, tempColor.b);
}
terrainSource.setAttribute(
"color",
new THREE.Float32BufferAttribute(terrainColors, 3)
);
const terrainGeometry = terrainSource.toNonIndexed();
terrainGeometry.computeVertexNormals();
terrainSource.dispose();
const terrain = new THREE.Mesh(
terrainGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 1
})
);
terrain.rotation.x = -Math.PI / 2;
terrain.receiveShadow = true;
scene.add(terrain);
// Ribbon-shaped road.
const roadVertices = [];
const roadIndices = [];
const roadSamples = 130;
const roadWidth = 2.45;
for (let i = 0; i <= roadSamples; i++) {
const t = i / roadSamples;
const point = routeCurve.getPointAt(t);
const tangent = routeCurve.getTangentAt(t);
const side = new THREE.Vector3(-tangent.z, 0, tangent.x).normalize();
const left = point.clone().addScaledVector(side, roadWidth);
const right = point.clone().addScaledVector(side, -roadWidth);
roadVertices.push(left.x, left.y + 0.14, left.z);
roadVertices.push(right.x, right.y + 0.14, right.z);
if (i < roadSamples) {
const a = i * 2;
roadIndices.push(a, a + 2, a + 1, a + 1, a + 2, a + 3);
}
}
const roadGeometry = new THREE.BufferGeometry();
roadGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(roadVertices, 3)
);
roadGeometry.setIndex(roadIndices);
roadGeometry.computeVertexNormals();
const road = new THREE.Mesh(
roadGeometry,
new THREE.MeshStandardMaterial({
color: 0xc7a978,
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
})
);
road.receiveShadow = true;
scene.add(road);
// ------------------------------------------------------------
// Mountains, rocks, trees, and clouds
// ------------------------------------------------------------
const mountainPalette = [0x667c70, 0x75877b, 0x5e756c, 0x849087];
function addMountain(x, z, radius, height, index) {
const group = new THREE.Group();
group.position.set(x, -0.15, z);
const baseMaterial = new THREE.MeshStandardMaterial({
color: mountainPalette[index % mountainPalette.length],
flatShading: true,
roughness: 1
});
const mountain = new THREE.Mesh(
new THREE.ConeGeometry(radius, height, 5, 1),
baseMaterial
);
mountain.position.y = height / 2;
mountain.rotation.y = random() * Math.PI;
mountain.castShadow = true;
mountain.receiveShadow = true;
group.add(mountain);
const snow = new THREE.Mesh(
new THREE.ConeGeometry(radius * 0.34, height * 0.35, 5, 1),
new THREE.MeshStandardMaterial({
color: 0xe7e9df,
flatShading: true,
roughness: 1
})
);
snow.position.y = height * 0.825;
snow.rotation.y = mountain.rotation.y;
snow.castShadow = true;
group.add(snow);
scene.add(group);
}
[
[-47, -16, 13, 25],
[-38, 23, 16, 31],
[-20, -27, 13, 23],
[1, -30, 17, 34],
[19, 22, 15, 30],
[37, -25, 17, 36],
[49, 14, 14, 29],
[51, -11, 11, 23],
[-8, 29, 11, 21]
].forEach((mountain, index) => addMountain(...mountain, index));
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x7b8074,
flatShading: true,
roughness: 1
});
for (let i = 0; i < 46; i++) {
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.25 + random() * 0.55, 0),
rockMaterial
);
const x = -54 + random() * 108;
const z = -34 + random() * 68;
rock.position.set(x, 0.2, z);
rock.rotation.set(random(), random(), random());
rock.scale.y = 0.6 + random() * 0.6;
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x604938,
flatShading: true
});
const pineMaterials = [
new THREE.MeshStandardMaterial({ color: 0x486d5a, flatShading: true }),
new THREE.MeshStandardMaterial({ color: 0x587763, flatShading: true })
];
function addTree(x, z, scale = 1) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.12, 0.17, 1.45, 5),
trunkMaterial
);
trunk.position.y = 0.7;
trunk.castShadow = true;
tree.add(trunk);
for (let layer = 0; layer < 2; layer++) {
const foliage = new THREE.Mesh(
new THREE.ConeGeometry(
layer === 0 ? 0.92 : 0.66,
layer === 0 ? 1.8 : 1.45,
5
),
pineMaterials[layer]
);
foliage.position.y = layer === 0 ? 1.65 : 2.45;
foliage.rotation.y = random() * Math.PI;
foliage.castShadow = true;
tree.add(foliage);
}
scene.add(tree);
}
for (let i = 0; i < 24; i++) {
const x = -52 + random() * 104;
const z = -31 + random() * 62;
addTree(x, z, 0.7 + random() * 0.75);
}
const cloudMaterial = new THREE.MeshStandardMaterial({
color: 0xf2f0e5,
flatShading: true,
roughness: 1
});
const clouds = [];
for (let i = 0; i < 5; i++) {
const cloud = new THREE.Group();
cloud.position.set(-43 + i * 20, 17 + random() * 6, -28 + random() * 12);
for (let j = 0; j < 4; j++) {
const puff = new THREE.Mesh(
new THREE.DodecahedronGeometry(1.3 + random() * 0.9, 0),
cloudMaterial
);
puff.position.set(j * 1.45, Math.sin(j) * 0.45, random() * 0.7);
puff.scale.y = 0.62;
cloud.add(puff);
}
clouds.push(cloud);
scene.add(cloud);
}
// ------------------------------------------------------------
// Trading post and prayer flags
// ------------------------------------------------------------
const fort = new THREE.Group();
const fortPoint = routeCurve.getPointAt(0.12);
fort.position.copy(fortPoint);
fort.position.z += 6.8;
fort.position.y = 0;
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0xa94e3e,
flatShading: true,
roughness: 0.95
});
const roofMaterial = new THREE.MeshStandardMaterial({
color: 0x354943,
flatShading: true,
roughness: 0.9
});
const timberMaterial = new THREE.MeshStandardMaterial({
color: 0x594537,
flatShading: true
});
const building = new THREE.Mesh(
new THREE.BoxGeometry(8.4, 3.4, 5.2),
wallMaterial
);
building.position.y = 1.7;
building.castShadow = true;
building.receiveShadow = true;
fort.add(building);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(5.2, 2.5, 4),
roofMaterial
);
roof.position.y = 4.55;
roof.rotation.y = Math.PI / 4;
roof.scale.z = 0.82;
roof.castShadow = true;
fort.add(roof);
const tower = new THREE.Mesh(
new THREE.CylinderGeometry(1.35, 1.5, 6.1, 8),
wallMaterial
);
tower.position.set(-4.7, 3.05, 0.8);
tower.castShadow = true;
fort.add(tower);
const towerRoof = new THREE.Mesh(
new THREE.ConeGeometry(1.85, 1.7, 8),
roofMaterial
);
towerRoof.position.set(-4.7, 6.9, 0.8);
towerRoof.castShadow = true;
fort.add(towerRoof);
for (let i = -1; i <= 1; i++) {
const window = new THREE.Mesh(
new THREE.PlaneGeometry(0.85, 0.9),
new THREE.MeshBasicMaterial({ color: 0xf4c85f })
);
window.position.set(i * 2.25, 1.8, 2.62);
fort.add(window);
}
const door = new THREE.Mesh(
new THREE.PlaneGeometry(1.3, 2.2),
new THREE.MeshBasicMaterial({ color: 0x40332b })
);
door.position.set(0, 1.1, 2.63);
fort.add(door);
const poleMaterial = new THREE.MeshStandardMaterial({
color: 0x5d4b37,
flatShading: true
});
const flagColors = [
0x3e78a0, 0xf2f0dd, 0xd2643e, 0x4d8b62, 0xe0b44e
];
const prayerFlags = [];
for (const x of [-7, 7]) {
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.08, 0.1, 4.5, 6),
poleMaterial
);
pole.position.set(x, 2.25, 3.5);
pole.castShadow = true;
fort.add(pole);
}
for (let i = 0; i < 11; i++) {
const flag = new THREE.Mesh(
new THREE.PlaneGeometry(0.55, 0.42),
new THREE.MeshStandardMaterial({
color: flagColors[i % flagColors.length],
side: THREE.DoubleSide,
flatShading: true
})
);
flag.position.set(-6.55 + i * 1.31, 3.75 - Math.sin(i / 10 * Math.PI) * 0.35, 3.5);
flag.rotation.y = -0.25;
fort.add(flag);
prayerFlags.push(flag);
}
scene.add(fort);
// ------------------------------------------------------------
// Low-poly pack animals
// ------------------------------------------------------------
const animalMeshes = new Map();
function cylinderBetween(start, end, radius, material, radialSegments = 6) {
const direction = end.clone().sub(start);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(
radius,
radius,
length,
radialSegments
),
material
);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
return mesh;
}
function createAnimal(carrier, index) {
const group = new THREE.Group();
group.userData.carrierId = carrier.id;
const palette = {
yak: {
body: 0x4b4037,
dark: 0x302b28,
light: 0xd9c8a4
},
horse: {
body: 0x9d573d,
dark: 0x3e2c27,
light: 0xe0c5a1
},
mule: {
body: 0x9b815e,
dark: 0x4b4034,
light: 0xd6bea0
}
};
const colors = palette[carrier.type];
const bodyMaterial = new THREE.MeshStandardMaterial({
color: colors.body,
flatShading: true,
roughness: 0.95
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: colors.dark,
flatShading: true,
roughness: 1
});
const lightMaterial = new THREE.MeshStandardMaterial({
color: colors.light,
flatShading: true,
roughness: 1
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.72, 0.78, 0.76),
bodyMaterial
);
body.position.y = 1.18;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const rump = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.55, 0),
bodyMaterial
);
rump.scale.set(1.05, 0.82, 0.82);
rump.position.set(-0.55, 1.24, 0);
rump.castShadow = true;
group.add(rump);
const neck = cylinderBetween(
new THREE.Vector3(0.57, 1.28, 0),
new THREE.Vector3(1.02, 1.72, 0),
0.27,
bodyMaterial
);
group.add(neck);
const head = new THREE.Mesh(
new THREE.BoxGeometry(0.58, 0.48, 0.49),
bodyMaterial
);
head.position.set(1.24, 1.78, 0);
head.castShadow = true;
group.add(head);
const muzzle = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.23, 0.42),
darkMaterial
);
muzzle.position.set(1.57, 1.7, 0);
group.add(muzzle);
const eyeMaterial = new THREE.MeshBasicMaterial({ color: 0x171917 });
for (const z of [-0.255, 0.255]) {
const eye = new THREE.Mesh(
new THREE.SphereGeometry(0.035, 6, 4),
eyeMaterial
);
eye.position.set(1.42, 1.86, z);
group.add(eye);
}
const legMaterial = darkMaterial;
for (const x of [-0.53, 0.55]) {
for (const z of [-0.27, 0.27]) {
const leg = new THREE.Mesh(
new THREE.CylinderGeometry(0.09, 0.075, 0.92, 5),
legMaterial
);
leg.position.set(x, 0.51, z);
leg.castShadow = true;
group.add(leg);
const hoof = new THREE.Mesh(
new THREE.BoxGeometry(0.17, 0.13, 0.18),
darkMaterial
);
hoof.position.set(x + 0.02, 0.07, z);
group.add(hoof);
}
}
const tail = cylinderBetween(
new THREE.Vector3(-0.91, 1.35, 0),
new THREE.Vector3(-1.2, 0.66, 0.08),
0.065,
darkMaterial,
5
);
group.add(tail);
if (carrier.type === "yak") {
const hump = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.52, 0),
bodyMaterial
);
hump.scale.set(1.15, 0.72, 0.85);
hump.position.set(-0.04, 1.62, 0);
hump.castShadow = true;
group.add(hump);
for (const z of [-0.27, 0.27]) {
const horn = new THREE.Mesh(
new THREE.ConeGeometry(0.085, 0.48, 4),
lightMaterial
);
horn.position.set(1.28, 2.11, z);
horn.rotation.z = -0.92;
horn.rotation.x = z > 0 ? -0.25 : 0.25;
horn.castShadow = true;
group.add(horn);
}
} else {
for (const z of [-0.16, 0.16]) {
const ear = new THREE.Mesh(
new THREE.ConeGeometry(
carrier.type === "mule" ? 0.105 : 0.13,
carrier.type === "mule" ? 0.48 : 0.3,
4
),
bodyMaterial
);
ear.position.set(1.18, 2.11, z);
ear.rotation.z = -0.2;
ear.castShadow = true;
group.add(ear);
}
if (carrier.type === "horse") {
const mane = new THREE.Mesh(
new THREE.BoxGeometry(0.72, 0.22, 0.13),
darkMaterial
);
mane.position.set(0.72, 1.69, 0);
mane.rotation.z = -0.46;
group.add(mane);
}
}
const saddle = new THREE.Mesh(
new THREE.BoxGeometry(0.92, 0.16, 0.91),
new THREE.MeshStandardMaterial({
color: carrier.type === "horse" ? 0x6e3f31 : 0x43594d,
flatShading: true
})
);
saddle.position.set(-0.04, 1.64, 0);
saddle.castShadow = true;
group.add(saddle);
const packGroup = new THREE.Group();
group.add(packGroup);
const ringMaterial = new THREE.MeshStandardMaterial({
color: 0x4f8e74,
emissive: 0x1d4f3e,
emissiveIntensity: 0.22,
flatShading: true
});
const ring = new THREE.Mesh(
new THREE.TorusGeometry(1.23, 0.065, 6, 32),
ringMaterial
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.1;
ring.castShadow = true;
group.add(ring);
scene.add(group);
const label = document.createElement("div");
label.className = "animal-label";
labelHost.appendChild(label);
const data = {
group,
bodyMaterial,
packGroup,
ring,
ringMaterial,
label,
index,
baseT: [0.43, 0.49, 0.55, 0.61][index],
anchor: new THREE.Vector3()
};
animalMeshes.set(carrier.id, data);
return data;
}
carriers.forEach((carrier, index) => createAnimal(carrier, index));
const cargoMaterials = cargoTypes.map(
(cargo) =>
new THREE.MeshStandardMaterial({
color: cargo.color,
flatShading: true,
roughness: 0.88
})
);
function updateAnimalCargo(carrier, animal, load) {
while (animal.packGroup.children.length) {
const child = animal.packGroup.children.pop();
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
}
if (load <= 0) return;
const cargoPieces = [];
cargoTypes.forEach((cargo, cargoIndex) => {
for (let i = 0; i < carrier.allocation[cargo.id]; i++) {
cargoPieces.push(cargoIndex);
}
});
const boxCount = Math.min(8, Math.max(2, Math.ceil(load / 4)));
for (let i = 0; i < boxCount; i++) {
const cargoIndex =
cargoPieces[Math.floor((i / boxCount) * cargoPieces.length)] ?? 0;
const crate = new THREE.Mesh(
new THREE.BoxGeometry(0.43, 0.34, 0.39),
cargoMaterials[cargoIndex]
);
const column = i % 3;
const row = Math.floor(i / 3);
const layer = row > 1 ? 1 : 0;
crate.position.set(
-0.28 + column * 0.28,
1.92 + layer * 0.32,
row % 2 === 0 ? -0.2 : 0.2
);
crate.rotation.y = (i % 2 === 0 ? 1 : -1) * 0.08;
crate.castShadow = true;
crate.receiveShadow = true;
animal.packGroup.add(crate);
}
}
// ------------------------------------------------------------
// UI construction
// ------------------------------------------------------------
const manifestElement = document.querySelector("#manifest");
manifestElement.innerHTML = cargoTypes
.map(
(cargo) => `
<div class="manifest-row">
<div class="cargo-icon" style="background:${cargo.css}">
${cargo.glyph}
</div>
<div>
<div class="manifest-name">${cargo.name}</div>
<div class="manifest-meta">
${cargo.quantity} ${cargo.unit} × ${cargo.weight} units
</div>
</div>
<div class="manifest-weight">
${cargo.quantity * cargo.weight}
<small>units</small>
</div>
</div>
`
)
.join("");
const carrierListElement = document.querySelector("#carrierList");
carrierListElement.innerHTML = carriers
.map(
(carrier) => `
<article
class="carrier-card"
id="card-${carrier.id}"
data-carrier="${carrier.id}"
>
<div class="carrier-head">
<div class="animal-badge ${carrier.type}">
${carrier.type === "yak" ? "Y" : carrier.type === "horse" ? "H" : "M"}
</div>
<div>
<div class="carrier-name">${carrier.name}</div>
<div class="carrier-type">
${carrier.typeLabel} · capacity ${carrier.capacity} units
</div>
</div>
<div class="trip-chip" id="chip-${carrier.id}">1 trip</div>
</div>
<div class="load-row">
<div class="load-track">
<i id="bar-${carrier.id}"></i>
</div>
<span class="load-number" id="load-${carrier.id}"></span>
</div>
<div class="allocation-grid">
${cargoTypes
.map(
(cargo) => `
<div class="allocation-item">
<label title="${cargo.name}">
${cargo.shortName} ${cargo.weight}u
</label>
<div class="number-field">
<input
id="input-${carrier.id}-${cargo.id}"
type="number"
min="0"
max="${cargo.quantity}"
step="1"
value="${carrier.allocation[cargo.id]}"
data-carrier="${carrier.id}"
data-cargo="${cargo.id}"
aria-label="${cargo.name} assigned to ${carrier.name}"
>
<span>${cargo.unit}</span>
</div>
</div>
`
)
.join("")}
</div>
</article>
`
)
.join("");
const allocationInputs = Array.from(
document.querySelectorAll(".allocation-item input")
);
allocationInputs.forEach((input) => {
input.addEventListener("input", () => {
const carrier = carriers.find(
(item) => item.id === input.dataset.carrier
);
const cargo = cargoTypes.find(
(item) => item.id === input.dataset.cargo
);
const usedElsewhere = carriers.reduce((sum, item) => {
if (item.id === carrier.id) return sum;
return sum + item.allocation[cargo.id];
}, 0);
const available = Math.max(0, cargo.quantity - usedElsewhere);
const requested = Number.parseInt(input.value || "0", 10);
const safeValue = THREE.MathUtils.clamp(
Number.isFinite(requested) ? requested : 0,
0,
available
);
if (safeValue !== requested) {
input.value = safeValue;
showToast(
available === 0
? `No ${cargo.name.toLowerCase()} remains to assign.`
: `Only ${available} ${cargo.unit} remain in the manifest.`
);
}
carrier.allocation[cargo.id] = safeValue;
updatePlan();
});
});
// ------------------------------------------------------------
// Plan calculations and UI updates
// ------------------------------------------------------------
function calculatePlan() {
const details = carriers.map((carrier) => {
const load = cargoTypes.reduce(
(sum, cargo) =>
sum + carrier.allocation[cargo.id] * cargo.weight,
0
);
const trips = load === 0 ? 0 : Math.ceil(load / carrier.capacity);
return {
carrier,
load,
trips,
overloaded: load > carrier.capacity
};
});
const assignedByCargo = Object.fromEntries(
cargoTypes.map((cargo) => [
cargo.id,
carriers.reduce(
(sum, carrier) => sum + carrier.allocation[cargo.id],
0
)
])
);
const assignedTotal = details.reduce(
(sum, detail) => sum + detail.load,
0
);
const passes = details.reduce(
(maximum, detail) => Math.max(maximum, detail.trips),
0
);
const carrierTrips = details.reduce(
(sum, detail) => sum + detail.trips,
0
);
const overloadedCount = details.filter(
(detail) => detail.overloaded
).length;
return {
details,
assignedByCargo,
assignedTotal,
passes,
carrierTrips,
overloadedCount
};
}
function updatePlan() {
const plan = calculatePlan();
document.querySelector("#cargoStat").textContent = TOTAL_CARGO;
document.querySelector("#fleetStat").textContent = FLEET_CAPACITY;
document.querySelector("#passStat").textContent = plan.passes;
document.querySelector("#minimumStat").textContent =
`minimum: ${MINIMUM_PASSES}`;
document.querySelector("#assignedStat").textContent =
`${plan.assignedTotal} of ${TOTAL_CARGO} assigned`;
document.querySelector("#passMetric").classList.toggle(
"alert",
plan.passes > MINIMUM_PASSES || plan.overloadedCount > 0
);
const assignedCrates = cargoTypes.reduce(
(sum, cargo) => sum + plan.assignedByCargo[cargo.id],
0
);
const totalCrates = cargoTypes.reduce(
(sum, cargo) => sum + cargo.quantity,
0
);
document.querySelector("#inventoryStatus").textContent =
assignedCrates === totalCrates
? "fully assigned"
: `${assignedCrates}/${totalCrates} pieces placed`;
document.querySelector("#inventoryBar").style.width =
`${(assignedCrates / totalCrates) * 100}%`;
const summary = document.querySelector("#planSummary");
summary.classList.toggle(
"warning",
plan.overloadedCount > 0 || plan.assignedTotal < TOTAL_CARGO
);
if (plan.overloadedCount > 0) {
const names = plan.details
.filter((detail) => detail.overloaded)
.map((detail) => detail.carrier.name)
.join(", ");
summary.textContent =
`${plan.overloadedCount} carrier${plan.overloadedCount === 1 ? " is" : "s are"} over the one-trip capacity limit: ${names}. ` +
`The longest schedule requires ${plan.passes} passes.`;
} else if (plan.assignedTotal < TOTAL_CARGO) {
summary.textContent =
`${TOTAL_CARGO - plan.assignedTotal} cargo units remain unassigned. ` +
`Auto-balance can distribute the complete manifest within the fleet’s combined capacity.`;
} else {
summary.textContent =
`Every carrier is within its capacity. The complete ${TOTAL_CARGO}-unit manifest can move in ${plan.passes} convoy pass${plan.passes === 1 ? "" : "es"}, matching the fleet minimum.`;
}
for (const detail of plan.details) {
const { carrier, load, trips, overloaded } = detail;
const card = document.querySelector(`#card-${carrier.id}`);
const chip = document.querySelector(`#chip-${carrier.id}`);
const bar = document.querySelector(`#bar-${carrier.id}`);
const loadText = document.querySelector(`#load-${carrier.id}`);
const animal = animalMeshes.get(carrier.id);
card.classList.toggle("overloaded", overloaded);
card.classList.toggle(
"selected",
selectedCarrier === carrier.id
);
chip.textContent = `${trips} trip${trips === 1 ? "" : "s"}`;
chip.classList.toggle("overload", overloaded);
bar.style.width = `${Math.min(100, (load / carrier.capacity) * 100)}%`;
loadText.textContent = `${load}/${carrier.capacity} u`;
animal.ringMaterial.color.set(overloaded ? 0xb84f3b : 0x4f8e74);
animal.ringMaterial.emissive.set(overloaded ? 0x7e2118 : 0x1d4f3e);
animal.bodyMaterial.emissive.set(overloaded ? 0x5b100b : 0x000000);
animal.bodyMaterial.emissiveIntensity = overloaded ? 0.3 : 0;
animal.label.classList.toggle("overloaded", overloaded);
animal.label.innerHTML = `
<strong>${carrier.name}</strong>
<span class="label-detail">
${load}/${carrier.capacity} units · ${trips} trip${trips === 1 ? "" : "s"}
</span>
${overloaded ? `<span class="overload-badge">OVERLOADED</span>` : ""}
`;
updateAnimalCargo(carrier, animal, load);
}
allocationInputs.forEach((input) => {
if (document.activeElement !== input) {
const carrier = carriers.find(
(item) => item.id === input.dataset.carrier
);
input.value = carrier.allocation[input.dataset.cargo];
}
});
}
// ------------------------------------------------------------
// Planner actions
// ------------------------------------------------------------
document.querySelector("#balanceButton").addEventListener("click", () => {
const remaining = carriers.map(
(carrier) => carrier.capacity
);
const items = [];
cargoTypes.forEach((cargo) => {
for (let i = 0; i < cargo.quantity; i++) {
items.push({ cargoId: cargo.id, weight: cargo.weight });
}
});
items.sort((a, b) => b.weight - a.weight);
const allocations = Object.fromEntries(
carriers.map((carrier) => [
carrier.id,
{ tea: 0, salt: 0, silk: 0 }
])
);
for (const item of items) {
const candidates = carriers
.map((carrier, index) => ({
carrier,
index,
remaining: remaining[index]
}))
.filter((candidate) => candidate.remaining >= item.weight)
.sort((a, b) => a.remaining - b.remaining);
if (candidates.length === 0) continue;
const chosen = candidates[0];
allocations[chosen.carrier.id][item.cargoId]++;
remaining[chosen.index] -= item.weight;
}
carriers.forEach((carrier) => {
carrier.allocation = { ...allocations[carrier.id] };
});
updatePlan();
showToast("Manifest balanced across all four carriers.");
});
document.querySelector("#clearButton").addEventListener("click", () => {
carriers.forEach((carrier) => {
carrier.allocation = { tea: 0, salt: 0, silk: 0 };
});
updatePlan();
showToast("Allocation cleared.");
});
document.querySelector("#convoyButton").addEventListener("click", () => {
convoyRunning = !convoyRunning;
document.querySelector("#convoyButton").textContent = convoyRunning
? "Pause convoy"
: "Preview convoy";
});
function showToast(message) {
const toast = document.querySelector("#toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2200);
}
// ------------------------------------------------------------
// Direct camera controls: orbit, pan, wheel zoom, and pinch
// ------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 1.3, 0);
const spherical = new THREE.Spherical(47, 1.08, 0.58);
const initialSpherical = new THREE.Spherical(47, 1.08, 0.58);
const initialTarget = cameraTarget.clone();
const pointers = new Map();
let gestureMoved = false;
let previousPinchDistance = 0;
const canvas = renderer.domElement;
function updateCamera() {
spherical.phi = THREE.MathUtils.clamp(spherical.phi, 0.28, 1.46);
spherical.radius = THREE.MathUtils.clamp(spherical.radius, 20, 88);
cameraTarget.x = THREE.MathUtils.clamp(cameraTarget.x, -24, 24);
cameraTarget.y = THREE.MathUtils.clamp(cameraTarget.y, -1, 8);
cameraTarget.z = THREE.MathUtils.clamp(cameraTarget.z, -18, 18);
const offset = new THREE.Vector3().setFromSpherical(spherical);
camera.position.copy(cameraTarget).add(offset);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY,
mode:
event.button === 2 || event.shiftKey ? "pan" : "orbit"
});
gestureMoved = false;
if (pointers.size === 2) {
const [a, b] = Array.from(pointers.values());
previousPinchDistance = Math.hypot(a.x - b.x, a.y - b.y);
}
});
canvas.addEventListener("pointermove", (event) => {
const pointer = pointers.get(event.pointerId);
if (!pointer) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
if (Math.abs(dx) + Math.abs(dy) > 2) gestureMoved = true;
if (pointers.size === 1) {
if (pointer.mode === "pan") {
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 0)
.normalize();
const up = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 1)
.normalize();
const scale = spherical.radius * 0.00135;
cameraTarget.addScaledVector(right, -dx * scale);
cameraTarget.addScaledVector(up, dy * scale);
} else {
spherical.theta -= dx * 0.006;
spherical.phi -= dy * 0.005;
}
} else if (pointers.size === 2) {
const [a, b] = Array.from(pointers.values());
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (previousPinchDistance > 0 && distance > 0) {
spherical.radius *= previousPinchDistance / distance;
}
previousPinchDistance = distance;
}
updateCamera();
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) {
previousPinchDistance = 0;
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
spherical.radius *= Math.exp(event.deltaY * 0.001);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
spherical.copy(initialSpherical);
cameraTarget.copy(initialTarget);
updateCamera();
});
document.querySelector("#zoomIn").addEventListener("click", () => {
spherical.radius *= 0.86;
updateCamera();
});
document.querySelector("#zoomOut").addEventListener("click", () => {
spherical.radius *= 1.16;
updateCamera();
});
document.querySelector("#resetCamera").addEventListener("click", () => {
spherical.copy(initialSpherical);
cameraTarget.copy(initialTarget);
updateCamera();
});
// Clicking an animal focuses its planning card.
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
canvas.addEventListener("pointerup", (event) => {
if (gestureMoved || event.button !== 0) return;
pointerNDC.x = (event.clientX / window.innerWidth) * 2 - 1;
pointerNDC.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const intersections = raycaster.intersectObjects(
Array.from(animalMeshes.values()).map((animal) => animal.group),
true
);
if (!intersections.length) return;
let object = intersections[0].object;
while (object && !object.userData.carrierId) {
object = object.parent;
}
if (!object) return;
selectedCarrier = object.userData.carrierId;
updatePlan();
const card = document.querySelector(`#card-${selectedCarrier}`);
card.scrollIntoView({
behavior: "smooth",
block: "nearest"
});
});
// ------------------------------------------------------------
// Animation
// ------------------------------------------------------------
const clock = new THREE.Clock();
function positionAnimal(animal, t) {
const point = routeCurve.getPointAt(t);
const tangent = routeCurve.getTangentAt(t);
animal.group.position.copy(point);
animal.group.position.y = 0.43;
animal.group.rotation.y = Math.atan2(-tangent.z, tangent.x);
animal.anchor.copy(animal.group.position);
animal.anchor.y += carrierTypeLabelHeight(animal);
}
function carrierTypeLabelHeight(animal) {
return animal.group.userData.carrierId === "yak-a" ? 3.15 : 3.05;
}
function updateLabels() {
for (const animal of animalMeshes.values()) {
const projected = animal.anchor.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.2 &&
projected.x < 1.2 &&
projected.y > -1.2 &&
projected.y < 1.2;
animal.label.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
animal.label.style.left = `${x}px`;
animal.label.style.top = `${y}px`;
}
}
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (convoyRunning) {
convoyPhase += delta * 0.48;
}
for (const animal of animalMeshes.values()) {
let t = animal.baseT;
if (convoyRunning) {
const travel =
(1 - Math.cos(convoyPhase - animal.index * 0.17)) * 0.5;
t = 0.39 + travel * 0.25;
}
positionAnimal(animal, t);
const overloaded =
animal.ringMaterial.color.getHex() === 0xb84f3b;
if (overloaded) {
const pulse = 1 + Math.sin(clock.elapsedTime * 4.5 + animal.index) * 0.065;
animal.ring.scale.setScalar(pulse);
animal.ringMaterial.emissiveIntensity =
0.45 + Math.sin(clock.elapsedTime * 4.5 + animal.index) * 0.2;
} else {
animal.ring.scale.setScalar(1);
animal.ringMaterial.emissiveIntensity = 0.22;
}
}
prayerFlags.forEach((flag, index) => {
flag.rotation.z =
Math.sin(clock.elapsedTime * 2.2 + index * 0.55) * 0.08;
});
clouds.forEach((cloud, index) => {
cloud.position.x += delta * (0.12 + index * 0.018);
if (cloud.position.x > 58) cloud.position.x = -58;
});
updateCamera();
updateLabels();
renderer.render(scene, camera);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", resize);
// Initial state.
updatePlan();
updateCamera();
animate();
requestAnimationFrame(() => {
document.querySelector("#loading").classList.add("hidden");
setTimeout(() => {
document.querySelector("#loading").remove();
}, 550);
});
</script>
</body>
</html>
```