Prompt specification
Build or customize the Three.js 3D scene "Nonviolent Island Settlement Strategy" 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: Nonviolent Island Settlement Strategy
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/nonviolent-island-settlement-strategy-x3587
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows connected territory and vulnerable links. Build an original island board where communities expand paths and shared services. Use fictional cooperative rules and make access, water, and terrain constraints visible. Voxel style.
Working Three.js Starter (nonviolent-island-settlement-strategy-x3587):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tideglass Commons — Cooperative Territory Board</title>
<style>
:root {
--ink: #18333b;
--muted: #667b80;
--cream: #fff9eb;
--paper: rgba(255, 251, 239, 0.94);
--line: rgba(24, 51, 59, 0.12);
--teal: #168b88;
--teal-dark: #0f6768;
--coral: #e96e58;
--gold: #e5aa43;
--danger: #d64b45;
--shadow: 0 18px 50px rgba(9, 35, 42, 0.2);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #15343c;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, select { font: inherit; }
button {
border: 0;
cursor: pointer;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#labels {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
overflow: hidden;
}
.world-label {
position: absolute;
transform: translate(-50%, -100%);
padding: 6px 9px 6px 7px;
border-radius: 8px;
background: rgba(255, 250, 238, 0.94);
border: 1px solid rgba(24, 51, 59, 0.15);
box-shadow: 0 5px 14px rgba(7, 28, 34, 0.18);
color: var(--ink);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.04em;
white-space: nowrap;
display: flex;
align-items: center;
gap: 6px;
}
.world-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -5px;
width: 8px;
height: 8px;
background: rgba(255, 250, 238, 0.94);
border-right: 1px solid rgba(24, 51, 59, 0.15);
border-bottom: 1px solid rgba(24, 51, 59, 0.15);
transform: translateX(-50%) rotate(45deg);
}
.world-label .dot {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--dot, var(--teal));
box-shadow: 0 0 0 2px color-mix(in srgb, var(--dot, var(--teal)) 18%, transparent);
}
.world-label.service-label {
padding: 4px 7px;
font-size: 8px;
letter-spacing: 0.1em;
background: rgba(20, 50, 57, 0.86);
color: #fff8e7;
border-color: rgba(255,255,255,.15);
}
.world-label.service-label::after { background: rgba(20, 50, 57, 0.86); }
.topbar {
position: fixed;
z-index: 10;
top: 14px;
left: 14px;
right: 14px;
height: 66px;
padding: 0 14px 0 16px;
display: flex;
align-items: center;
gap: 18px;
color: #fff9eb;
background: rgba(12, 39, 46, 0.9);
border: 1px solid rgba(255,255,255,.13);
border-radius: 15px;
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.brand {
display: flex;
align-items: center;
gap: 11px;
min-width: 255px;
}
.brand-mark {
width: 38px;
height: 38px;
position: relative;
transform: rotate(-2deg);
}
.brand-mark i {
position: absolute;
display: block;
background: #62d0bf;
box-shadow: inset -5px -5px 0 rgba(10, 73, 72, .25);
}
.brand-mark i:nth-child(1) { width: 24px; height: 24px; left: 0; top: 11px; }
.brand-mark i:nth-child(2) { width: 17px; height: 17px; left: 16px; top: 0; background: #f0b858; }
.brand-mark i:nth-child(3) { width: 15px; height: 15px; left: 25px; top: 18px; background: #e96e58; }
.brand h1 {
margin: 0;
font-size: 18px;
line-height: 1.05;
letter-spacing: -0.02em;
}
.brand p {
margin: 4px 0 0;
color: rgba(255,249,235,.62);
font-size: 10px;
font-weight: 650;
letter-spacing: .09em;
text-transform: uppercase;
}
.stats {
display: flex;
align-items: stretch;
gap: 8px;
margin-left: auto;
}
.stat {
min-width: 82px;
padding: 8px 11px;
border-left: 1px solid rgba(255,255,255,.11);
}
.stat span {
display: block;
color: rgba(255,249,235,.52);
font-size: 8px;
font-weight: 800;
letter-spacing: .12em;
text-transform: uppercase;
}
.stat strong {
display: block;
margin-top: 2px;
font-size: 16px;
line-height: 1;
}
.stat.risk strong { color: #ff9182; }
.stat.labor strong { color: #ffd17e; }
.top-actions { display: flex; gap: 7px; }
.icon-button {
height: 36px;
padding: 0 12px;
border-radius: 9px;
color: #fff9eb;
background: rgba(255,255,255,.09);
border: 1px solid rgba(255,255,255,.11);
font-size: 11px;
font-weight: 750;
}
.icon-button:hover { background: rgba(255,255,255,.16); }
.panel {
position: fixed;
z-index: 8;
top: 94px;
bottom: 16px;
padding: 16px;
border-radius: 17px;
background: var(--paper);
border: 1px solid rgba(255,255,255,.68);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
overflow: auto;
scrollbar-width: thin;
scrollbar-color: rgba(24,51,59,.2) transparent;
}
.left-panel {
left: 14px;
width: 248px;
}
.right-panel {
right: 14px;
width: 310px;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 13px;
}
.eyebrow {
margin: 0 0 4px;
color: var(--teal-dark);
font-size: 9px;
font-weight: 850;
letter-spacing: .14em;
text-transform: uppercase;
}
.panel-heading h2 {
margin: 0;
font-size: 17px;
letter-spacing: -.02em;
}
.tiny-badge {
padding: 5px 7px;
border-radius: 6px;
color: var(--teal-dark);
background: rgba(22,139,136,.1);
font-size: 9px;
font-weight: 850;
text-transform: uppercase;
letter-spacing: .06em;
}
.community-list {
display: grid;
gap: 8px;
}
.community-card {
position: relative;
width: 100%;
padding: 10px 10px 10px 12px;
text-align: left;
color: var(--ink);
background: rgba(255,255,255,.55);
border: 1px solid var(--line);
border-radius: 11px;
transition: transform .15s ease, border-color .15s ease, background .15s ease;
}
.community-card:hover {
transform: translateY(-1px);
border-color: rgba(24,51,59,.25);
background: rgba(255,255,255,.88);
}
.community-card.active {
background: #fffef9;
border-color: var(--accent);
box-shadow: inset 3px 0 0 var(--accent), 0 5px 14px rgba(24,51,59,.07);
}
.community-row {
display: flex;
align-items: center;
gap: 9px;
}
.community-swatch {
width: 13px;
height: 13px;
flex: 0 0 auto;
border-radius: 3px;
background: var(--accent);
box-shadow: inset -3px -3px 0 rgba(0,0,0,.12);
}
.community-name {
font-size: 12px;
font-weight: 850;
}
.focus-label {
margin-left: auto;
color: var(--accent);
font-size: 8px;
font-weight: 850;
letter-spacing: .08em;
text-transform: uppercase;
}
.community-meta {
display: flex;
align-items: center;
gap: 5px;
margin: 7px 0 0 22px;
color: var(--muted);
font-size: 9px;
}
.service-pip {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 18px;
height: 18px;
padding: 0 4px;
border-radius: 5px;
color: #fff;
background: var(--teal);
font-size: 8px;
font-weight: 850;
}
.service-pip.care { background: var(--coral); }
.service-pip.build { background: var(--gold); }
.isolated {
color: #a55a4d;
}
.legend {
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
.legend-title {
margin-bottom: 8px;
color: var(--muted);
font-size: 8px;
font-weight: 850;
letter-spacing: .12em;
text-transform: uppercase;
}
.legend-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px 5px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
color: #52696e;
font-size: 9px;
font-weight: 650;
}
.legend-block {
width: 12px;
height: 12px;
border-radius: 2px;
background: var(--block);
box-shadow: inset -3px -3px rgba(0,0,0,.1);
}
.legend-line {
width: 17px;
height: 4px;
border-radius: 1px;
background: var(--block);
}
.labor-card {
padding: 13px;
border-radius: 12px;
color: #fff9eb;
background: linear-gradient(135deg, #17595d, #123e47);
box-shadow: 0 8px 20px rgba(17,65,71,.18);
}
.labor-top {
display: flex;
align-items: flex-end;
justify-content: space-between;
}
.labor-top span {
color: rgba(255,255,255,.6);
font-size: 9px;
font-weight: 800;
letter-spacing: .09em;
text-transform: uppercase;
}
.labor-top strong {
font-size: 24px;
line-height: 1;
color: #ffd17e;
}
.labor-track {
height: 5px;
margin-top: 10px;
overflow: hidden;
border-radius: 10px;
background: rgba(255,255,255,.13);
}
.labor-fill {
height: 100%;
width: 50%;
border-radius: inherit;
background: #f2bd62;
transition: width .3s ease;
}
.labor-note {
margin: 8px 0 0;
color: rgba(255,255,255,.55);
font-size: 9px;
line-height: 1.4;
}
.mode-tabs {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 14px;
}
.mode-tab {
min-height: 52px;
padding: 7px 4px;
border-radius: 10px;
color: #607378;
background: rgba(24,51,59,.055);
border: 1px solid transparent;
font-size: 9px;
font-weight: 850;
letter-spacing: .04em;
text-transform: uppercase;
}
.mode-tab b {
display: block;
margin-bottom: 3px;
color: var(--ink);
font-size: 17px;
}
.mode-tab.active {
color: var(--teal-dark);
background: rgba(22,139,136,.11);
border-color: rgba(22,139,136,.28);
}
.mode-help {
min-height: 56px;
margin: 10px 0;
padding: 10px 11px;
border-left: 3px solid var(--teal);
border-radius: 0 8px 8px 0;
color: #536c70;
background: rgba(22,139,136,.065);
font-size: 10px;
line-height: 1.45;
}
.service-picker {
display: grid;
gap: 6px;
margin-bottom: 11px;
}
.service-option {
display: flex;
align-items: center;
gap: 9px;
padding: 8px 9px;
border-radius: 9px;
color: var(--ink);
background: rgba(255,255,255,.55);
border: 1px solid var(--line);
text-align: left;
}
.service-option.active {
background: #fff;
border-color: var(--teal);
box-shadow: 0 4px 12px rgba(24,51,59,.08);
}
.service-icon {
display: grid;
place-items: center;
width: 27px;
height: 27px;
flex: 0 0 auto;
border-radius: 7px;
color: #fff;
background: var(--teal);
font-size: 12px;
font-weight: 900;
}
.service-option.care .service-icon { background: var(--coral); }
.service-option.build .service-icon { background: var(--gold); }
.service-option strong {
display: block;
font-size: 10px;
}
.service-option small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
}
.service-option .cost {
margin-left: auto;
color: #9a6a1d;
font-size: 9px;
font-weight: 850;
}
.link-card {
margin-top: 12px;
padding: 11px;
border-radius: 10px;
background: rgba(214,75,69,.075);
border: 1px solid rgba(214,75,69,.18);
}
.link-card.safe {
background: rgba(22,139,136,.07);
border-color: rgba(22,139,136,.18);
}
.link-title {
display: flex;
align-items: center;
gap: 7px;
font-size: 10px;
font-weight: 850;
}
.risk-dot {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--danger);
box-shadow: 0 0 0 4px rgba(214,75,69,.1);
animation: riskPulse 1.6s ease-in-out infinite;
}
.safe .risk-dot {
background: var(--teal);
box-shadow: 0 0 0 4px rgba(22,139,136,.1);
animation: none;
}
.link-card p {
margin: 7px 0 0;
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.activity {
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
.activity h3 {
margin: 0 0 8px;
font-size: 10px;
letter-spacing: .04em;
}
.log-entry {
position: relative;
padding: 0 0 8px 13px;
color: var(--muted);
font-size: 9px;
line-height: 1.4;
}
.log-entry::before {
content: "";
position: absolute;
left: 0;
top: 4px;
width: 5px;
height: 5px;
border-radius: 1px;
background: var(--teal);
}
.primary-button {
width: 100%;
margin-top: 13px;
padding: 11px 12px;
border-radius: 10px;
color: #17383e;
background: #f0bc61;
box-shadow: inset 0 -3px 0 rgba(112,72,12,.12), 0 6px 14px rgba(229,170,67,.22);
font-size: 10px;
font-weight: 900;
letter-spacing: .04em;
text-transform: uppercase;
}
.primary-button:hover { background: #f6c979; }
.secondary-button {
width: 100%;
margin-top: 8px;
padding: 9px;
border-radius: 9px;
color: #617479;
background: rgba(24,51,59,.05);
font-size: 9px;
font-weight: 800;
}
.board-hint {
position: fixed;
z-index: 5;
left: 50%;
bottom: 17px;
transform: translateX(-50%);
padding: 8px 12px;
border-radius: 20px;
color: rgba(255,249,235,.72);
background: rgba(12,39,46,.72);
border: 1px solid rgba(255,255,255,.11);
backdrop-filter: blur(10px);
font-size: 9px;
font-weight: 650;
white-space: nowrap;
pointer-events: none;
}
.view-tools {
position: fixed;
z-index: 7;
left: 276px;
bottom: 16px;
display: flex;
gap: 6px;
}
.view-tools button {
padding: 8px 10px;
border-radius: 8px;
color: #fff9eb;
background: rgba(12,39,46,.74);
border: 1px solid rgba(255,255,255,.12);
font-size: 9px;
font-weight: 800;
}
#tooltip {
position: fixed;
z-index: 12;
display: none;
min-width: 170px;
max-width: 230px;
padding: 10px 11px;
border-radius: 10px;
color: #fff9eb;
background: rgba(12,39,46,.94);
border: 1px solid rgba(255,255,255,.13);
box-shadow: 0 10px 30px rgba(0,0,0,.24);
pointer-events: none;
}
#tooltip strong {
display: block;
font-size: 10px;
letter-spacing: .03em;
}
#tooltip span {
display: block;
margin-top: 4px;
color: rgba(255,249,235,.68);
font-size: 9px;
line-height: 1.4;
}
#toast {
position: fixed;
z-index: 20;
left: 50%;
top: 94px;
transform: translate(-50%, -12px);
max-width: 380px;
padding: 10px 15px;
border-radius: 10px;
color: #fff9eb;
background: rgba(12,39,46,.94);
border: 1px solid rgba(255,255,255,.15);
box-shadow: 0 12px 32px rgba(0,0,0,.25);
font-size: 10px;
font-weight: 750;
text-align: center;
opacity: 0;
pointer-events: none;
transition: opacity .2s ease, transform .2s ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error { background: rgba(129,47,43,.96); }
#toast.success { background: rgba(20,103,86,.96); }
.rules-backdrop {
position: fixed;
z-index: 29;
inset: 0;
display: none;
background: rgba(7,28,34,.4);
backdrop-filter: blur(4px);
}
.rules-backdrop.open { display: block; }
.rules-drawer {
position: absolute;
top: 0;
right: 0;
width: min(430px, 94vw);
height: 100%;
padding: 26px;
overflow: auto;
color: var(--ink);
background: var(--cream);
box-shadow: -20px 0 60px rgba(0,0,0,.22);
}
.rules-close {
position: absolute;
top: 18px;
right: 18px;
width: 32px;
height: 32px;
border-radius: 8px;
color: var(--ink);
background: rgba(24,51,59,.07);
font-size: 18px;
}
.rules-drawer h2 {
margin: 0;
font-size: 26px;
letter-spacing: -.04em;
}
.rules-drawer .intro {
color: var(--muted);
font-size: 12px;
line-height: 1.6;
}
.rule {
display: grid;
grid-template-columns: 34px 1fr;
gap: 12px;
padding: 15px 0;
border-top: 1px solid var(--line);
}
.rule-number {
display: grid;
place-items: center;
width: 30px;
height: 30px;
border-radius: 8px;
color: #fff;
background: var(--teal);
font-size: 11px;
font-weight: 900;
}
.rule h3 {
margin: 1px 0 4px;
font-size: 12px;
}
.rule p {
margin: 0;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
@keyframes riskPulse {
0%, 100% { opacity: 1; }
50% { opacity: .45; }
}
@media (max-width: 1050px) {
.brand { min-width: 210px; }
.stat { min-width: 67px; padding-inline: 8px; }
.left-panel { width: 220px; }
.right-panel { width: 282px; }
.view-tools { left: 248px; }
}
@media (max-width: 780px) {
.topbar {
top: 8px;
left: 8px;
right: 8px;
height: 58px;
padding-inline: 10px;
}
.brand { min-width: 0; }
.brand h1 { font-size: 14px; }
.brand p { display: none; }
.brand-mark { width: 31px; height: 31px; transform: scale(.8); }
.stats { display: none; }
.icon-button { padding-inline: 9px; }
.left-panel {
top: 74px;
left: 8px;
right: 8px;
width: auto;
bottom: auto;
height: 112px;
padding: 10px;
}
.left-panel .panel-heading,
.left-panel .legend { display: none; }
.community-list {
display: flex;
overflow-x: auto;
gap: 7px;
padding-bottom: 3px;
}
.community-card { min-width: 155px; }
.right-panel {
top: auto;
left: 8px;
right: 8px;
bottom: 8px;
width: auto;
height: 235px;
padding: 11px;
}
.right-panel .activity { display: none; }
.labor-card { padding: 9px 11px; }
.labor-note { display: none; }
.mode-tabs { margin-top: 8px; }
.mode-tab { min-height: 40px; }
.mode-help { min-height: 0; margin: 7px 0; padding: 7px 9px; }
.service-picker { grid-template-columns: repeat(3, 1fr); }
.service-option { padding: 6px; }
.service-option small, .service-option .cost { display: none; }
.link-card { margin-top: 7px; padding: 7px 9px; }
.link-card p { display: none; }
.primary-button { margin-top: 7px; padding: 8px; }
.view-tools { left: 10px; bottom: 250px; }
.board-hint { display: none; }
#tooltip { display: none !important; }
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div id="labels"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"><i></i><i></i><i></i></div>
<div>
<h1>Tideglass Commons</h1>
<p>Cooperative territory board</p>
</div>
</div>
<div class="stats">
<div class="stat"><span>Round</span><strong id="roundStat">01</strong></div>
<div class="stat labor"><span>Labor</span><strong id="laborStat">12</strong></div>
<div class="stat"><span>Linked</span><strong id="linkedStat">3 / 5</strong></div>
<div class="stat risk"><span>Fragile</span><strong id="riskStat">2</strong></div>
</div>
<div class="top-actions">
<button class="icon-button" id="rulesButton">The Accord</button>
<button class="icon-button" id="resetButton">Reset</button>
</div>
</header>
<aside class="panel left-panel">
<div class="panel-heading">
<div>
<p class="eyebrow">Shared island</p>
<h2>Five Commons</h2>
</div>
<span class="tiny-badge" id="districtBadge">2 districts</span>
</div>
<div class="community-list" id="communityList"></div>
<div class="legend">
<div class="legend-title">Terrain & route language</div>
<div class="legend-grid">
<div class="legend-item"><span class="legend-block" style="--block:#76aa66"></span>Meadow</div>
<div class="legend-item"><span class="legend-block" style="--block:#4d9180"></span>Fen</div>
<div class="legend-item"><span class="legend-block" style="--block:#8b7862"></span>Ridge</div>
<div class="legend-item"><span class="legend-block" style="--block:#4aa6b5"></span>Water</div>
<div class="legend-item"><span class="legend-line" style="--block:#f0d69a"></span>Trail</div>
<div class="legend-item"><span class="legend-line" style="--block:#b87a43"></span>Causeway</div>
<div class="legend-item"><span class="legend-line" style="--block:#df554d"></span>Fragile link</div>
<div class="legend-item"><span class="legend-block" style="--block:#f3bb4f"></span>Access</div>
</div>
</div>
</aside>
<aside class="panel right-panel">
<div class="labor-card">
<div class="labor-top">
<span>Commons labor</span>
<strong id="laborValue">12</strong>
</div>
<div class="labor-track"><div class="labor-fill" id="laborFill"></div></div>
<p class="labor-note">Labor is shared by every settlement. Each council round restores 8.</p>
</div>
<div class="mode-tabs" role="tablist" aria-label="Council action">
<button class="mode-tab active" data-mode="trail"><b>+</b>Trail</button>
<button class="mode-tab" data-mode="service"><b>◇</b>Service</button>
<button class="mode-tab" data-mode="reinforce"><b>▣</b>Brace</button>
</div>
<div class="mode-help" id="modeHelp"></div>
<div class="service-picker" id="servicePicker" hidden>
<button class="service-option active" data-service="water">
<span class="service-icon">W</span>
<span><strong>Rain Cistern</strong><small>Shared water</small></span>
<span class="cost">4</span>
</button>
<button class="service-option care" data-service="care">
<span class="service-icon">+</span>
<span><strong>Care Hut</strong><small>Shared care</small></span>
<span class="cost">5</span>
</button>
<button class="service-option build" data-service="build">
<span class="service-icon">T</span>
<span><strong>Tinker Yard</strong><small>Extends reach</small></span>
<span class="cost">4</span>
</button>
</div>
<div class="link-card" id="linkCard">
<div class="link-title"><span class="risk-dot"></span><span id="linkTitle">Fragile east crossing</span></div>
<p id="linkDescription">A single causeway joins two districts.</p>
</div>
<div class="activity">
<h3>Council record</h3>
<div id="activityLog"></div>
</div>
<button class="primary-button" id="nextRound">Next council · +8 labor</button>
<button class="secondary-button" id="howToPlay">How to play</button>
</aside>
<div class="view-tools">
<button id="topView">Top view</button>
<button id="resetView">Reset view</button>
</div>
<div class="board-hint">Drag to orbit · Shift-drag to pan · Scroll to zoom · Click a tile</div>
<div id="tooltip"></div>
<div id="toast"></div>
<div class="rules-backdrop" id="rulesBackdrop">
<section class="rules-drawer">
<button class="rules-close" id="rulesClose" aria-label="Close">×</button>
<p class="eyebrow">The Tideglass Accord</p>
<h2>Fictional rules for shared land</h2>
<p class="intro">Tideglass is governed as one commons. Settlements may grow their own routes, but water, labor, and fragile crossings remain shared responsibilities.</p>
<article class="rule">
<div class="rule-number">1</div>
<div>
<h3>Shared labor</h3>
<p>All construction draws from one labor pool. Every council round restores 8 labor, even when a district is isolated.</p>
</div>
</article>
<article class="rule">
<div class="rule-number">2</div>
<div>
<h3>Access follows connection</h3>
<p>A new trail must touch a route or settlement already reachable by the focused commons. The standard working reach is five path steps; a Tinker Yard adds one.</p>
</div>
</article>
<article class="rule">
<div class="rule-number">3</div>
<div>
<h3>Water must be bridged</h3>
<p>Trails cannot cross open water. Building a trail on water creates a timber causeway costing 3 labor. Wider crossings require more than one deck.</p>
</div>
</article>
<article class="rule">
<div class="rule-number">4</div>
<div>
<h3>Terrain has a voice</h3>
<p>Meadow costs 1 labor, fen costs 2, and ridge costs 3. Ridges cannot host a shared service. Fen absorbs paths but slows travel.</p>
</div>
</article>
<article class="rule">
<div class="rule-number">5</div>
<div>
<h3>Services belong to the commons</h3>
<p>A service must touch connected territory and sit within two steps of the focused settlement. Its benefits travel three route steps to linked settlements.</p>
</div>
</article>
<article class="rule">
<div class="rule-number">6</div>
<div>
<h3>Fragile links are marked</h3>
<p>Red-framed causeway decks become a single point of failure between communities. Spend 2 labor to brace one deck. A second crossing removes the monopoly of either crossing.</p>
</div>
</article>
</section>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ------------------------------------------------------------
GAME STATE
------------------------------------------------------------ */
const GRID = 17;
const HALF = Math.floor(GRID / 2);
const key = (x, z) => `${x},${z}`;
const communities = [
{ id: 'alder', name: 'Alder Commons', x: -4, z: 3, color: '#e96e58', glyph: 'A' },
{ id: 'reedward', name: 'Reedward', x: 4, z: -1, color: '#35a6b1', glyph: 'R' },
{ id: 'tideglass', name: 'Tideglass', x: 5, z: 4, color: '#e5aa43', glyph: 'T' },
{ id: 'stonecrest',name: 'Stonecrest', x: -4, z: -5, color: '#8b76b0', glyph: 'S' },
{ id: 'sunmoss', name: 'Sunmoss', x: -6, z: -2, color: '#70ad68', glyph: 'M' }
];
const communityById = Object.fromEntries(communities.map(c => [c.id, c]));
const initialPaths = [
'-3,3','-2,3','-1,3','0,3','1,3','2,3','3,3','4,3',
'3,2','3,1','3,0','4,0','5,3','4,4',
'-4,-4','-5,-4','-5,-3','-6,-3'
];
const state = {
round: 1,
labor: 12,
activeId: 'alder',
mode: 'trail',
serviceType: 'water',
paths: new Set(initialPaths),
reinforced: new Set(),
services: [
{ owner: 'alder', type: 'water', x: -4, z: 4 },
{ owner: 'reedward', type: 'care', x: 5, z: -1 },
{ owner: 'stonecrest', type: 'build', x: -5, z: -5 }
],
log: [
'The east causeway is the only open crossing.',
'Three shared services remain in operation.'
]
};
const serviceInfo = {
water: { name: 'Rain Cistern', cost: 4, glyph: 'W', className: 'water' },
care: { name: 'Care Hut', cost: 5, glyph: '+', className: 'care' },
build: { name: 'Tinker Yard', cost: 4, glyph: 'T', className: 'build' }
};
const terrainInfo = {
meadow: { name: 'Meadow', cost: 1, top: 0.38, color: 0x78a968, dark: 0x526f52 },
fen: { name: 'Fen', cost: 2, top: 0.23, color: 0x4f9181, dark: 0x356c62 },
ridge: { name: 'Ridge', cost: 3, top: 0.88, color: 0x8b7862, dark: 0x635647 },
water: { name: 'Water', cost: 3, top: -0.04, color: 0x4aa6b5, dark: 0x327a8c }
};
/* ------------------------------------------------------------
DOM
------------------------------------------------------------ */
const canvas = document.getElementById('scene');
const labelLayer = document.getElementById('labels');
const communityList = document.getElementById('communityList');
const modeHelp = document.getElementById('modeHelp');
const servicePicker = document.getElementById('servicePicker');
const activityLog = document.getElementById('activityLog');
const tooltip = document.getElementById('tooltip');
const toast = document.getElementById('toast');
const rulesBackdrop = document.getElementById('rulesBackdrop');
const ui = {
round: document.getElementById('roundStat'),
labor: document.getElementById('laborStat'),
laborValue: document.getElementById('laborValue'),
laborFill: document.getElementById('laborFill'),
linked: document.getElementById('linkedStat'),
risk: document.getElementById('riskStat'),
district: document.getElementById('districtBadge'),
linkCard: document.getElementById('linkCard'),
linkTitle: document.getElementById('linkTitle'),
linkDescription: document.getElementById('linkDescription')
};
/* ------------------------------------------------------------
THREE.JS SCENE
------------------------------------------------------------ */
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
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.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x15343c);
scene.fog = new THREE.Fog(0x15343c, 30, 62);
const camera = new THREE.OrthographicCamera(-10, 10, 10, -10, 0.1, 100);
const cameraState = {
theta: 0.69,
phi: 0.86,
zoom: 1,
target: new THREE.Vector3(0, 0, 0),
radius: 30
};
const hemi = new THREE.HemisphereLight(0xc8f1e5, 0x30454b, 2.2);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffe2ae, 3.0);
sun.position.set(-9, 18, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -14;
sun.shadow.camera.right = 14;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 50;
sun.shadow.bias = -0.0008;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x75d9d3, 1.25);
rimLight.position.set(10, 8, -12);
scene.add(rimLight);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
function materialFor(color) {
if (!materialCache.has(color)) {
materialCache.set(color, new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0.02
}));
}
return materialCache.get(color);
}
function voxel(parent, color, w, h, d, x, y, z) {
const mesh = new THREE.Mesh(unitBox, materialFor(color));
mesh.scale.set(w, h, d);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const terrainGroup = new THREE.Group();
const territoryGroup = new THREE.Group();
const pathGroup = new THREE.Group();
const serviceGroup = new THREE.Group();
const communityGroup = new THREE.Group();
const decorGroup = new THREE.Group();
const accessGroup = new THREE.Group();
scene.add(terrainGroup, territoryGroup, pathGroup, serviceGroup, communityGroup, decorGroup, accessGroup);
const tiles = new Map();
/* ------------------------------------------------------------
TERRAIN GENERATION
------------------------------------------------------------ */
function riverX(z) {
const table = {
'-6': -1, '-5': -1, '-4': -0.5, '-3': -0.5,
'-2': 0, '-1': 0, '0': 0, '1': 0,
'2': 0.5, '3': 0.5, '4': 0.5, '5': 0
};
return table[String(z)] ?? 10;
}
function isLand(x, z) {
const edge = (x * x) / (7.7 * 7.7) + (z * z) / (6.8 * 6.8);
const wobble = 0.055 * Math.sin(x * 1.7 + z * 0.8) + 0.035 * Math.cos(z * 2.2 - x);
if (edge > 1 + wobble) return false;
if (z >= -6 && z <= 5 && Math.abs(x - riverX(z)) <= 0.55) return false;
return true;
}
function terrainType(x, z) {
if (!isLand(x, z)) return 'water';
const ridgeA = ((x + 3) ** 2) / 10 + ((z + 4) ** 2) / 5 < 1;
const ridgeB = ((x - 5) ** 2) / 4 + ((z + 2) ** 2) / 3 < 1;
if (ridgeA || ridgeB) return 'ridge';
const fenA = ((x + 5) ** 2) / 5 + ((z - 0.5) ** 2) / 4 < 1;
const fenB = ((x - 2) ** 2) / 3 + ((z + 4) ** 2) / 3 < 1;
const fenC = ((x - 5) ** 2) / 3 + ((z - 1) ** 2) / 3 < 1;
if (fenA || fenB || fenC) return 'fen';
return 'meadow';
}
for (let z = -HALF; z <= HALF; z++) {
for (let x = -HALF; x <= HALF; x++) {
const type = terrainType(x, z);
tiles.set(key(x, z), {
x, z, type,
top: terrainInfo[type].top,
land: type !== 'water'
});
}
}
function buildTerrain() {
const landTiles = [...tiles.values()].filter(t => t.land);
const waterTiles = [...tiles.values()].filter(t => !t.land);
const foundation = new THREE.InstancedMesh(
unitBox,
new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 1 }),
landTiles.length
);
foundation.castShadow = true;
foundation.receiveShadow = true;
const caps = new THREE.InstancedMesh(
unitBox,
new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: .9 }),
landTiles.length
);
caps.castShadow = true;
caps.receiveShadow = true;
const matrix = new THREE.Matrix4();
const quat = new THREE.Quaternion();
landTiles.forEach((tile, i) => {
const info = terrainInfo[tile.type];
const foundationHeight = tile.top + 0.23;
matrix.compose(
new THREE.Vector3(tile.x, (tile.top - 0.23) / 2, tile.z),
quat,
new THREE.Vector3(.98, foundationHeight, .98)
);
foundation.setMatrixAt(i, matrix);
foundation.setColorAt(i, new THREE.Color(info.dark));
matrix.compose(
new THREE.Vector3(tile.x, tile.top - .015, tile.z),
quat,
new THREE.Vector3(.985, .12, .985)
);
caps.setMatrixAt(i, matrix);
caps.setColorAt(i, new THREE.Color(info.color));
});
foundation.instanceMatrix.needsUpdate = true;
caps.instanceMatrix.needsUpdate = true;
if (foundation.instanceColor) foundation.instanceColor.needsUpdate = true;
if (caps.instanceColor) caps.instanceColor.needsUpdate = true;
terrainGroup.add(foundation, caps);
const water = new THREE.InstancedMesh(
unitBox,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: .3,
metalness: .08,
transparent: true,
opacity: .93
}),
waterTiles.length
);
water.receiveShadow = true;
waterTiles.forEach((tile, i) => {
const wave = ((tile.x * 13 + tile.z * 7) % 5) * 0.006;
matrix.compose(
new THREE.Vector3(tile.x, -0.13 + wave, tile.z),
quat,
new THREE.Vector3(.985, .14, .985)
);
water.setMatrixAt(i, matrix);
const color = new THREE.Color(0x4aa6b5).offsetHSL(0, 0, ((i * 7) % 5 - 2) * .018);
water.setColorAt(i, color);
});
water.instanceMatrix.needsUpdate = true;
if (water.instanceColor) water.instanceColor.needsUpdate = true;
terrainGroup.add(water);
const sea = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({ color: 0x327b88, roughness: .32, metalness: .06 })
);
sea.rotation.x = -Math.PI / 2;
sea.position.y = -.22;
sea.receiveShadow = true;
scene.add(sea);
// Small voxel markers around the outer water.
for (let i = 0; i < 22; i++) {
const angle = i / 22 * Math.PI * 2;
const radius = 11.5 + (i % 3) * .55;
const x = Math.cos(angle) * radius;
const z = Math.sin(angle) * radius;
const buoy = voxel(decorGroup, i % 2 ? 0xe9ba58 : 0xe06d59, .16, .28, .16, x, .02, z);
buoy.castShadow = false;
}
}
function seededRandom(seed) {
let s = seed >>> 0;
return () => {
s = (s * 1664525 + 1013904223) >>> 0;
return s / 4294967296;
};
}
const decorByCell = new Map();
function buildDecor() {
const random = seededRandom(12481);
const occupied = new Set([
...state.paths,
...communities.map(c => key(c.x, c.z)),
...state.services.map(s => key(s.x, s.z))
]);
for (const tile of tiles.values()) {
if (!tile.land || occupied.has(key(tile.x, tile.z))) continue;
const roll = random();
if ((tile.type === 'meadow' || tile.type === 'fen') && roll < .13) {
const group = new THREE.Group();
const height = .45 + random() * .3;
voxel(group, 0x765840, .12, height, .12, tile.x, tile.top + height / 2, tile.z);
voxel(group, tile.type === 'fen' ? 0x3f7f68 : 0x3e7e4e, .48, .3, .48, tile.x, tile.top + height + .08, tile.z);
voxel(group, tile.type === 'fen' ? 0x4e9275 : 0x4f945d, .32, .25, .32, tile.x, tile.top + height + .32, tile.z);
group.userData.baseScale = .9 + random() * .16;
group.scale.setScalar(group.userData.baseScale);
decorGroup.add(group);
decorByCell.set(key(tile.x, tile.z), group);
} else if (tile.type === 'ridge' && roll < .28) {
const group = new THREE.Group();
voxel(group, 0x786957, .34, .25, .28, tile.x, tile.top + .1, tile.z);
voxel(group, 0x958269, .2, .18, .17, tile.x + .08, tile.top + .29, tile.z - .03);
decorGroup.add(group);
decorByCell.set(key(tile.x, tile.z), group);
}
}
}
/* ------------------------------------------------------------
COMMUNITY AND SERVICE STRUCTURES
------------------------------------------------------------ */
function buildCommunities() {
for (const community of communities) {
const tile = tiles.get(key(community.x, community.z));
const group = new THREE.Group();
voxel(group, 0xd7ceb1, 1.18, .16, 1.18, 0, .08, 0);
voxel(group, 0xf0e3c5, .72, .58, .68, 0, .45, 0);
voxel(group, community.color, .82, .25, .78, 0, .84, 0);
voxel(group, community.color, .57, .28, .53, 0, 1.08, 0);
voxel(group, 0x41626a, .22, .22, .025, 0, .49, -.351);
voxel(group, 0xffe6a5, .13, .15, .03, .18, .7, -.351);
voxel(group, 0x5b5048, .13, .95, .13, .3, .55, .28);
voxel(group, community.color, .38, .2, .035, .48, .96, .28);
group.position.set(community.x, tile.top + .13, community.z);
communityGroup.add(group);
// Colored territory plates make each settlement's home district visible.
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
if (Math.abs(dx) + Math.abs(dz) > 1) continue;
const x = community.x + dx;
const z = community.z + dz;
const t = tiles.get(key(x, z));
if (!t?.land || state.paths.has(key(x, z))) continue;
const plate = new THREE.Mesh(
unitBox,
new THREE.MeshBasicMaterial({
color: community.color,
transparent: true,
opacity: .14,
depthWrite: false
})
);
plate.scale.set(.91, .025, .91);
plate.position.set(x, t.top + .072, z);
territoryGroup.add(plate);
}
}
}
}
function buildServiceStructure(service) {
const tile = tiles.get(key(service.x, service.z));
const group = new THREE.Group();
voxel(group, 0xe3d7b9, .88, .12, .88, 0, .06, 0);
if (service.type === 'water') {
voxel(group, 0x2d8fa1, .56, .56, .56, 0, .4, 0);
voxel(group, 0x58c5cd, .64, .12, .64, 0, .73, 0);
voxel(group, 0xd8f5e9, .16, .16, .16, 0, .86, 0);
voxel(group, 0x246e7d, .68, .12, .12, 0, .32, 0);
} else if (service.type === 'care') {
voxel(group, 0xf4ead3, .68, .48, .62, 0, .36, 0);
voxel(group, 0xe75d50, .38, .1, .1, 0, .64, 0);
voxel(group, 0xe75d50, .1, .1, .38, 0, .64, 0);
voxel(group, 0xe75d50, .08, .32, .08, .25, .36, .1);
} else {
voxel(group, 0xe7a73f, .64, .35, .58, 0, .29, 0);
voxel(group, 0xf1c566, .28, .32, .26, -.16, .62, -.04);
voxel(group, 0x486d70, .16, .16, .55, .25, .36, 0);
voxel(group, 0xf3e5c2, .2, .12, .2, -.16, .84, -.04);
}
group.position.set(service.x, tile.top + .1, service.z);
serviceGroup.add(group);
}
/* ------------------------------------------------------------
PICKING, HOVER, AND ACCESS MARKERS
------------------------------------------------------------ */
const pickMesh = new THREE.InstancedMesh(
unitBox,
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
}),
tiles.size
);
{
const matrix = new THREE.Matrix4();
const quat = new THREE.Quaternion();
let i = 0;
for (const tile of tiles.values()) {
matrix.compose(
new THREE.Vector3(tile.x, tile.top + .19, tile.z),
quat,
new THREE.Vector3(.96, .16, .96)
);
pickMesh.setMatrixAt(i++, matrix);
}
pickMesh.instanceMatrix.needsUpdate = true;
pickMesh.computeBoundingSphere();
scene.add(pickMesh);
}
const hoverBox = new THREE.Mesh(
unitBox,
new THREE.MeshBasicMaterial({
color: 0xffed9d,
transparent: true,
opacity: .78,
depthWrite: false
})
);
hoverBox.scale.set(1.035, .1, 1.035);
hoverBox.visible = false;
scene.add(hoverBox);
const accessMaterial = new THREE.MeshBasicMaterial({
color: 0xf4c45d,
transparent: true,
opacity: .9,
depthWrite: false
});
const vulnerableMaterial = new THREE.LineBasicMaterial({
color: 0xe34f47,
transparent: true,
opacity: .95
});
const reinforcedMaterial = new THREE.LineBasicMaterial({
color: 0x54d1bd,
transparent: true,
opacity: .95
});
const frameGeometry = new THREE.EdgesGeometry(new THREE.BoxGeometry(1.02, .18, 1.02));
function clearGroup(group) {
while (group.children.length) group.remove(group.children[group.children.length - 1]);
}
function rebuildAccessMarkers() {
clearGroup(accessGroup);
for (const tile of tiles.values()) {
const info = getBuildInfo(tile);
if (!info.ok) continue;
const marker = new THREE.Mesh(unitBox, accessMaterial);
marker.scale.set(.13, .13, .13);
marker.position.set(tile.x + .34, tile.top + .32, tile.z + .34);
accessGroup.add(marker);
}
}
/* ------------------------------------------------------------
GRAPH AND GAME LOGIC
------------------------------------------------------------ */
function buildPathGraph(excludeKey = null) {
const nodes = new Map();
for (const c of communities) {
nodes.set(key(c.x, c.z), { x: c.x, z: c.z, kind: 'community', id: c.id });
}
for (const pathKey of state.paths) {
if (pathKey === excludeKey) continue;
const [x, z] = pathKey.split(',').map(Number);
nodes.set(pathKey, { x, z, kind: 'path' });
}
const adjacency = new Map();
for (const nodeKey of nodes.keys()) adjacency.set(nodeKey, []);
for (const [nodeKey, node] of nodes) {
for (const [dx, dz] of [[1,0],[-1,0],[0,1],[0,-1]]) {
const neighborKey = key(node.x + dx, node.z + dz);
if (nodes.has(neighborKey)) adjacency.get(nodeKey).push(neighborKey);
}
}
return { nodes, adjacency };
}
function buildFullGraph() {
const graph = buildPathGraph();
for (const service of state.services) {
const serviceKey = key(service.x, service.z);
graph.nodes.set(serviceKey, { x: service.x, z: service.z, kind: 'service' });
graph.adjacency.set(serviceKey, []);
for (const [dx, dz] of [[1,0],[-1,0],[0,1],[0,-1]]) {
const neighborKey = key(service.x + dx, service.z + dz);
if (graph.nodes.has(neighborKey)) {
graph.adjacency.get(serviceKey).push(neighborKey);
graph.adjacency.get(neighborKey).push(serviceKey);
}
}
}
return graph;
}
function distancesFrom(graph, startKey) {
const distances = new Map([[startKey, 0]]);
const queue = [startKey];
for (let i = 0; i < queue.length; i++) {
const current = queue[i];
for (const neighbor of graph.adjacency.get(current) || []) {
if (!distances.has(neighbor)) {
distances.set(neighbor, distances.get(current) + 1);
queue.push(neighbor);
}
}
}
return distances;
}
function componentFrom(graph, startKey) {
const distances = distancesFrom(graph, startKey);
return new Set(distances.keys());
}
function communitiesIn(component, graph) {
return communities.filter(c => component.has(key(c.x, c.z)));
}
function activeCommunity() {
return communityById[state.activeId];
}
function activeComponent() {
const active = activeCommunity();
const graph = buildPathGraph();
return componentFrom(graph, key(active.x, active.z));
}
function isCauseway(pathKey) {
const [x, z] = pathKey.split(',').map(Number);
return tiles.get(pathKey)?.type === 'water';
}
function computeVulnerableCauseways() {
const graph = buildPathGraph();
const vulnerable = new Set();
for (const pathKey of state.paths) {
if (!isCauseway(pathKey)) continue;
const originalDistances = distancesFrom(graph, pathKey);
const relevantCommunities = communities.filter(c =>
originalDistances.has(key(c.x, c.z))
);
if (relevantCommunities.length < 2) continue;
const reduced = buildPathGraph(pathKey);
const unseen = new Set(reduced.nodes.keys());
const groups = [];
while (unseen.size) {
const start = unseen.values().next().value;
const component = componentFrom(reduced, start);
for (const k of component) unseen.delete(k);
const groupCount = relevantCommunities.filter(c =>
component.has(key(c.x, c.z))
).length;
if (groupCount > 0) groups.push(groupCount);
}
if (groups.length > 1) vulnerable.add(pathKey);
}
return vulnerable;
}
let vulnerableCauseways = new Set();
function serviceCoverage() {
const graph = buildFullGraph();
const coverage = Object.fromEntries(communities.map(c => [c.id, { water: false, care: false, build: false }]));
for (const service of state.services) {
const distances = distancesFrom(graph, key(service.x, service.z));
for (const community of communities) {
const distance = distances.get(key(community.x, community.z));
if (distance !== undefined && distance <= 3) {
coverage[community.id][service.type] = true;
}
}
}
return coverage;
}
function activeReach() {
const active = activeCommunity();
const graph = buildFullGraph();
const distances = distancesFrom(graph, key(active.x, active.z));
let workshops = 0;
for (const service of state.services.filter(s => s.type === 'build')) {
const distance = distances.get(key(service.x, service.z));
if (distance !== undefined && distance <= 3) workshops++;
}
return 5 + workshops;
}
function occupied(cellKey) {
return state.paths.has(cellKey) ||
communities.some(c => key(c.x, c.z) === cellKey) ||
state.services.some(s => key(s.x, s.z) === cellKey);
}
function getBuildInfo(tile) {
const cellKey = key(tile.x, tile.z);
const active = activeCommunity();
const graph = buildPathGraph();
const distances = distancesFrom(graph, key(active.x, active.z));
if (state.mode === 'trail') {
if (occupied(cellKey)) return { ok: false, reason: 'This tile is already occupied.', cost: 0 };
let best = Infinity;
for (const [dx, dz] of [[1,0],[-1,0],[0,1],[0,-1]]) {
const neighborKey = key(tile.x + dx, tile.z + dz);
if (distances.has(neighborKey)) best = Math.min(best, distances.get(neighborKey));
}
if (!Number.isFinite(best)) {
return { ok: false, reason: 'A trail must touch connected territory.', cost: 0 };
}
const reach = activeReach();
if (best + 1 > reach) {
return { ok: false, reason: `Beyond this district’s ${reach}-step access reach.`, cost: 0 };
}
const cost = terrainInfo[tile.type].cost;
if (state.labor < cost) {
return { ok: false, reason: `Needs ${cost} labor; only ${state.labor} remains.`, cost };
}
return {
ok: true,
reason: tile.type === 'water'
? 'Build a timber causeway across open water.'
: `Accessible in ${best + 1} path steps.`,
cost
};
}
if (state.mode === 'service') {
if (tile.type === 'water') return { ok: false, reason: 'Shared services cannot float on water.', cost: 0 };
if (tile.type === 'ridge') return { ok: false, reason: 'The ridge is too exposed for a shared service.', cost: 0 };
if (occupied(cellKey)) return { ok: false, reason: 'This tile is already occupied.', cost: 0 };
const adjacent = [[1,0],[-1,0],[0,1],[0,-1]].some(([dx,dz]) =>
distances.has(key(tile.x + dx, tile.z + dz))
);
if (!adjacent) return { ok: false, reason: 'A service must touch connected territory.', cost: 0 };
const localDistance = Math.abs(tile.x - active.x) + Math.abs(tile.z - active.z);
if (localDistance > 2) {
return { ok: false, reason: 'A service must be within two local steps of this commons.', cost: 0 };
}
const cost = serviceInfo[state.serviceType].cost;
if (state.labor < cost) {
return { ok: false, reason: `Needs ${cost} labor; only ${state.labor} remains.`, cost };
}
return { ok: true, reason: 'A shared service here can serve linked districts.', cost };
}
if (state.mode === 'reinforce') {
if (!state.paths.has(cellKey)) return { ok: false, reason: 'Only an existing causeway can be braced.', cost: 0 };
if (!isCauseway(cellKey)) return { ok: false, reason: 'Only timber causeway decks need bracing.', cost: 0 };
if (state.reinforced.has(cellKey)) return { ok: false, reason: 'This deck is already braced.', cost: 0 };
if (!vulnerableCauseways.has(cellKey)) return { ok: false, reason: 'This deck is not currently a fragile link.', cost: 0 };
if (state.labor < 2) return { ok: false, reason: 'Bracing needs 2 labor.', cost: 2 };
return { ok: true, reason: 'Brace this fragile causeway deck.', cost: 2 };
}
return { ok: false, reason: 'Choose a council action.', cost: 0 };
}
/* ------------------------------------------------------------
PATH AND LABEL VISUALS
------------------------------------------------------------ */
function rebuildPaths() {
clearGroup(pathGroup);
const activeSet = activeComponent();
for (const pathKey of state.paths) {
const [x, z] = pathKey.split(',').map(Number);
const tile = tiles.get(pathKey);
const water = tile.type === 'water';
const y = water ? .14 : tile.top + .115;
const activeConnected = activeSet.has(pathKey);
voxel(pathGroup, water ? 0xb97942 : 0xefd69b, .88, .13, .88, x, y, z);
if (water) {
voxel(pathGroup, 0x805535, .08, .2, .94, x - .39, y + .02, z);
voxel(pathGroup, 0x805535, .08, .2, .94, x + .39, y + .02, z);
voxel(pathGroup, 0xdba969, .82, .035, .08, x, y + .085, z);
} else {
voxel(pathGroup, activeConnected ? 0x4db9ad : 0xc59c55, .1, .035, .68, x, y + .08, z);
}
if (vulnerableCauseways.has(pathKey) && !state.reinforced.has(pathKey)) {
const frame = new THREE.LineSegments(frameGeometry, vulnerableMaterial);
frame.position.set(x, y + .105, z);
pathGroup.add(frame);
}
if (state.reinforced.has(pathKey)) {
const frame = new THREE.LineSegments(frameGeometry, reinforcedMaterial);
frame.position.set(x, y + .105, z);
pathGroup.add(frame);
voxel(pathGroup, 0x45b9a8, .16, .16, .16, x - .27, y + .13, z + .27);
voxel(pathGroup, 0x45b9a8, .16, .16, .16, x + .27, y + .13, z + .27);
}
}
}
function rebuildServices() {
clearGroup(serviceGroup);
for (const service of state.services) buildServiceStructure(service);
}
const labels = [];
function rebuildLabels() {
labelLayer.innerHTML = '';
labels.length = 0;
for (const community of communities) {
const tile = tiles.get(key(community.x, community.z));
const el = document.createElement('div');
el.className = 'world-label';
el.style.setProperty('--dot', community.color);
el.innerHTML = `<span class="dot"></span>${community.name}`;
labelLayer.appendChild(el);
labels.push({
el,
position: new THREE.Vector3(community.x, tile.top + 1.9, community.z)
});
}
for (const service of state.services) {
const tile = tiles.get(key(service.x, service.z));
const info = serviceInfo[service.type];
const el = document.createElement('div');
el.className = 'world-label service-label';
el.textContent = info.name.toUpperCase();
labelLayer.appendChild(el);
labels.push({
el,
position: new THREE.Vector3(service.x, tile.top + 1.25, service.z)
});
}
}
/* ------------------------------------------------------------
UI
------------------------------------------------------------ */
function addLog(message) {
state.log.unshift(message);
state.log = state.log.slice(0, 5);
activityLog.innerHTML = state.log.map(entry => `<div class="log-entry">${entry}</div>`).join('');
}
function showToast(message, type = '') {
toast.textContent = message;
toast.className = `show ${type}`;
clearTimeout(showToast.timer);
showToast.timer = setTimeout(() => toast.className = '', 2600);
}
function updateModeUI() {
document.querySelectorAll('.mode-tab').forEach(button => {
button.classList.toggle('active', button.dataset.mode === state.mode);
});
document.querySelectorAll('.service-option').forEach(button => {
button.classList.toggle('active', button.dataset.service === state.serviceType);
});
servicePicker.hidden = state.mode !== 'service';
if (state.mode === 'trail') {
modeHelp.innerHTML = `Grow a trail from connected territory within <strong>${activeReach()} steps</strong>. Meadow 1, fen 2, ridge 3, and water causeway 3 labor.`;
} else if (state.mode === 'service') {
modeHelp.innerHTML = `Place a shared service beside connected territory and within <strong>2 local steps</strong>. Benefits reach linked settlements three route steps away.`;
} else {
modeHelp.innerHTML = `Brace one fragile causeway deck for <strong>2 labor</strong>. Red frames mark crossings whose failure would divide the commons.`;
}
}
function updateUI() {
const active = activeCommunity();
const component = activeComponent();
const linked = communitiesIn(component, buildPathGraph());
const coverage = serviceCoverage();
const graph = buildPathGraph();
const districtCount = new Set();
for (const community of communities) {
const comp = componentFrom(graph, key(community.x, community.z));
districtCount.add([...comp].sort().join('|'));
}
ui.round.textContent = String(state.round).padStart(2, '0');
ui.labor.textContent = state.labor;
ui.laborValue.textContent = state.labor;
ui.laborFill.style.width = `${Math.min(100, state.labor / 24 * 100)}%`;
ui.linked.textContent = `${linked.length} / ${communities.length}`;
ui.risk.textContent = vulnerableCauseways.size;
ui.district.textContent = `${districtCount.size} district${districtCount.size === 1 ? '' : 's'}`;
communityList.innerHTML = communities.map(community => {
const services = coverage[community.id];
const pips = [
services.water ? '<span class="service-pip" title="Water service">W</span>' : '',
services.care ? '<span class="service-pip care" title="Care service">+</span>' : '',
services.build ? '<span class="service-pip build" title="Build service">T</span>' : ''
].join('');
const connected = component.has(key(community.x, community.z));
const isActive = community.id === state.activeId;
return `
<button class="community-card ${isActive ? 'active' : ''}"
data-community="${community.id}"
style="--accent:${community.color}">
<div class="community-row">
<span class="community-swatch"></span>
<span class="community-name">${community.name}</span>
${isActive ? '<span class="focus-label">Focus</span>' : ''}
</div>
<div class="community-meta ${connected ? '' : 'isolated'}">
${connected ? '● Linked district' : '○ Separate route'}
${pips}
</div>
</button>
`;
}).join('');
if (vulnerableCauseways.size) {
ui.linkCard.classList.remove('safe');
ui.linkTitle.textContent = `${vulnerableCauseways.size} fragile causeway deck${vulnerableCauseways.size === 1 ? '' : 's'}`;
ui.linkDescription.textContent = 'The east crossing can divide linked districts. Brace a red-framed deck or create a second crossing.';
} else {
ui.linkCard.classList.add('safe');
ui.linkTitle.textContent = 'No fragile crossings';
ui.linkDescription.textContent = 'Current routes have no single causeway deck dividing the linked commons.';
}
activityLog.innerHTML = state.log.map(entry => `<div class="log-entry">${entry}</div>`).join('');
updateModeUI();
}
function refreshWorld() {
vulnerableCauseways = computeVulnerableCauseways();
rebuildPaths();
rebuildServices();
rebuildLabels();
for (const [cellKey, decor] of decorByCell) {
decor.visible = !state.paths.has(cellKey) &&
!state.services.some(s => key(s.x, s.z) === cellKey);
}
rebuildAccessMarkers();
updateUI();
}
/* ------------------------------------------------------------
ACTIONS
------------------------------------------------------------ */
function buildTrail(tile) {
const info = getBuildInfo(tile);
if (!info.ok) {
showToast(info.reason, 'error');
return;
}
state.labor -= info.cost;
state.paths.add(key(tile.x, tile.z));
const active = activeCommunity();
const crossing = tile.type === 'water';
addLog(`${active.name} opened ${crossing ? 'a causeway deck' : 'a trail'} at ${tile.x}, ${tile.z}.`);
showToast(crossing ? 'Timber causeway raised across the channel.' : 'Trail joined to the commons.', 'success');
refreshWorld();
}
function buildService(tile) {
const info = getBuildInfo(tile);
if (!info.ok) {
showToast(info.reason, 'error');
return;
}
const service = serviceInfo[state.serviceType];
state.labor -= service.cost;
state.services.push({
owner: state.activeId,
type: state.serviceType,
x: tile.x,
z: tile.z
});
addLog(`${activeCommunity().name} established a ${service.name.toLowerCase()} at ${tile.x}, ${tile.z}.`);
showToast(`${service.name} added to the shared commons.`, 'success');
refreshWorld();
}
function reinforce(tile) {
const info = getBuildInfo(tile);
if (!info.ok) {
showToast(info.reason, 'error');
return;
}
state.labor -= 2;
state.reinforced.add(key(tile.x, tile.z));
addLog(`${activeCommunity().name} braced the causeway at ${tile.x}, ${tile.z}.`);
showToast('Causeway deck braced against storm and decay.', 'success');
refreshWorld();
}
function handleTile(tile) {
if (!tile) return;
if (state.mode === 'trail') buildTrail(tile);
else if (state.mode === 'service') buildService(tile);
else reinforce(tile);
}
function nextRound() {
state.round++;
state.labor += 8;
addLog(`Council round ${state.round}: 8 shared labor restored.`);
showToast('The council reconvenes. Eight labor restored.', 'success');
refreshWorld();
}
function setMode(mode) {
state.mode = mode;
rebuildAccessMarkers();
updateModeUI();
hideTooltip();
}
function setActiveCommunity(id) {
if (!communityById[id]) return;
state.activeId = id;
addLog(`${communityById[id].name} became the council focus.`);
refreshWorld();
}
/* ------------------------------------------------------------
CAMERA CONTROLS
------------------------------------------------------------ */
function updateCamera() {
const { theta, phi, radius, target } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
const aspect = window.innerWidth / window.innerHeight;
const halfHeight = 7.25 / cameraState.zoom;
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
}
function resetCamera() {
cameraState.theta = .69;
cameraState.phi = .86;
cameraState.zoom = 1;
cameraState.target.set(0, 0, 0);
updateCamera();
}
function topCamera() {
cameraState.theta = 0;
cameraState.phi = .08;
cameraState.zoom = 1.06;
cameraState.target.set(0, 0, 0);
updateCamera();
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = false;
let dragMoved = false;
let dragButton = 0;
let lastPointer = { x: 0, y: 0 };
function updatePointer(event) {
pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
}
function pickTile(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObject(pickMesh, false);
if (!hits.length || hits[0].instanceId === undefined) return null;
const tileList = [...tiles.values()];
return tileList[hits[0].instanceId] || null;
}
canvas.addEventListener('pointerdown', event => {
pointerDown = true;
dragMoved = false;
dragButton = event.button;
lastPointer = { x: event.clientX, y: event.clientY };
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener('pointermove', event => {
updatePointer(event);
if (pointerDown) {
const dx = event.clientX - lastPointer.x;
const dy = event.clientY - lastPointer.y;
if (Math.abs(dx) + Math.abs(dy) > 2) dragMoved = true;
if (dragMoved) {
if (event.shiftKey || dragButton === 2) {
const worldPerPixel = (14.5 / cameraState.zoom) / window.innerHeight;
const right = new THREE.Vector3();
const forward = new THREE.Vector3();
camera.matrixWorld.extractBasis(right, forward, new THREE.Vector3());
right.y = 0;
forward.y = 0;
right.normalize();
forward.normalize();
cameraState.target.addScaledVector(right, -dx * worldPerPixel);
cameraState.target.addScaledVector(forward, -dy * worldPerPixel);
} else {
cameraState.theta -= dx * .006;
cameraState.phi = THREE.MathUtils.clamp(cameraState.phi - dy * .005, .08, 1.38);
}
lastPointer = { x: event.clientX, y: event.clientY };
updateCamera();
hoverBox.visible = false;
hideTooltip();
return;
}
}
const tile = pickTile(event);
if (tile) {
hoverBox.visible = true;
hoverBox.position.set(tile.x, tile.top + .27, tile.z);
showTooltip(tile, event.clientX, event.clientY);
} else {
hoverBox.visible = false;
hideTooltip();
}
});
canvas.addEventListener('pointerup', event => {
if (pointerDown && !dragMoved && event.button === 0) {
const tile = pickTile(event);
handleTile(tile);
}
pointerDown = false;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
});
canvas.addEventListener('pointerleave', () => {
if (!pointerDown) {
hoverBox.visible = false;
hideTooltip();
}
});
canvas.addEventListener('contextmenu', event => event.preventDefault());
canvas.addEventListener('wheel', event => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * .001),
.65,
2.15
);
updateCamera();
}, { passive: false });
function showTooltip(tile, clientX, clientY) {
const info = getBuildInfo(tile);
const path = state.paths.has(key(tile.x, tile.z));
const service = state.services.find(s => key(s.x, s.z) === key(tile.x, tile.z));
const terrain = terrainInfo[tile.type];
let title = terrain.name;
let detail = info.reason;
if (path) {
title = isCauseway(key(tile.x, tile.z)) ? 'Timber causeway' : 'Shared trail';
if (state.reinforced.has(key(tile.x, tile.z))) {
detail = 'This deck is braced and no longer counted as fragile.';
} else if (vulnerableCauseways.has(key(tile.x, tile.z))) {
detail = 'Fragile link: this deck divides linked districts.';
} else {
detail = 'Part of the connected route network.';
}
} else if (service) {
title = serviceInfo[service.type].name;
detail = 'Shared service. Its benefit travels three route steps.';
} else if (info.ok) {
detail = `${info.reason} Cost: ${info.cost} labor.`;
} else {
detail = info.reason;
}
tooltip.innerHTML = `<strong>${title} · ${tile.x}, ${tile.z}</strong><span>${detail}</span>`;
tooltip.style.display = 'block';
const width = 220;
const left = Math.min(window.innerWidth - width - 10, Math.max(10, clientX + 16));
const top = Math.min(window.innerHeight - 78, Math.max(82, clientY + 16));
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top}px`;
}
function hideTooltip() {
tooltip.style.display = 'none';
}
/* ------------------------------------------------------------
UI EVENTS
------------------------------------------------------------ */
communityList.addEventListener('click', event => {
const button = event.target.closest('[data-community]');
if (button) setActiveCommunity(button.dataset.community);
});
document.querySelectorAll('.mode-tab').forEach(button => {
button.addEventListener('click', () => setMode(button.dataset.mode));
});
document.querySelectorAll('.service-option').forEach(button => {
button.addEventListener('click', () => {
state.serviceType = button.dataset.service;
rebuildAccessMarkers();
updateModeUI();
});
});
document.getElementById('nextRound').addEventListener('click', nextRound);
document.getElementById('topView').addEventListener('click', topCamera);
document.getElementById('resetView').addEventListener('click', resetCamera);
document.getElementById('rulesButton').addEventListener('click', () => {
rulesBackdrop.classList.add('open');
});
document.getElementById('howToPlay').addEventListener('click', () => {
rulesBackdrop.classList.add('open');
});
document.getElementById('rulesClose').addEventListener('click', () => {
rulesBackdrop.classList.remove('open');
});
rulesBackdrop.addEventListener('click', event => {
if (event.target === rulesBackdrop) rulesBackdrop.classList.remove('open');
});
document.getElementById('resetButton').addEventListener('click', () => {
if (confirm('Reset the island and return to the opening council?')) location.reload();
});
window.addEventListener('keydown', event => {
if (event.key === '1') setMode('trail');
if (event.key === '2') setMode('service');
if (event.key === '3') setMode('reinforce');
if (event.key === 'Escape') {
rulesBackdrop.classList.remove('open');
hideTooltip();
}
});
window.addEventListener('resize', () => {
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
updateCamera();
});
/* ------------------------------------------------------------
INITIALIZATION AND RENDER LOOP
------------------------------------------------------------ */
buildTerrain();
buildDecor();
buildCommunities();
updateCamera();
refreshWorld();
const projected = new THREE.Vector3();
function animate(time) {
requestAnimationFrame(animate);
const pulse = .68 + Math.sin(time * .0035) * .22;
accessMaterial.opacity = pulse;
vulnerableMaterial.opacity = .68 + Math.sin(time * .006) * .28;
for (const label of labels) {
projected.copy(label.position).project(camera);
const visible = projected.z > -1 && projected.z < 1;
label.el.style.display = visible ? 'flex' : 'none';
if (visible) {
label.el.style.left = `${(projected.x * .5 + .5) * window.innerWidth}px`;
label.el.style.top = `${(-projected.y * .5 + .5) * window.innerHeight}px`;
}
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```