Prompt specification
Build or customize the Three.js 3D scene "Village Reserve During Independent Shocks" 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: Village Reserve During Independent Shocks
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/village-reserve-during-independent-shocks-x3191
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows pooled reserves for uncertain losses. Build a village and repair depot with transparent contribution rules. Show reserve balances and unmet repairs across repeated events, labeling the probabilities as fictional assumptions. Voxel style.
Working Three.js Starter (village-reserve-during-independent-shocks-x3191):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Common Repair Pool — Voxel Village</title>
<style>
:root {
--ink: #18313a;
--muted: #5c7379;
--paper: rgba(250, 248, 238, 0.94);
--paper-solid: #faf8ee;
--line: rgba(24, 49, 58, 0.14);
--teal: #087f83;
--teal-light: #58c3bd;
--amber: #e49532;
--red: #c85b45;
--navy: #18313a;
--shadow: 0 16px 42px rgba(24, 49, 58, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9d7cf;
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;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
pointer-events: auto;
background: var(--paper);
border: 1px solid rgba(255, 255, 255, 0.65);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.brand {
position: absolute;
top: 22px;
left: 24px;
width: 420px;
pointer-events: none;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.45);
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 7px;
padding: 6px 9px;
border-radius: 6px;
background: var(--navy);
color: #f8f1d6;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.eyebrow::before {
width: 7px;
height: 7px;
content: "";
border-radius: 2px;
background: var(--teal-light);
}
.brand h1 {
margin: 0;
font-size: clamp(24px, 3vw, 39px);
font-weight: 850;
line-height: 0.98;
letter-spacing: -0.045em;
}
.brand p {
width: 390px;
margin: 9px 0 0;
color: #36565b;
font-size: 13px;
line-height: 1.45;
}
.stats {
position: absolute;
top: 22px;
right: 24px;
display: flex;
gap: 9px;
}
.stat {
width: 132px;
padding: 12px 14px;
border-radius: 10px;
background: var(--paper);
border: 1px solid rgba(255, 255, 255, 0.7);
box-shadow: 0 10px 28px rgba(24, 49, 58, 0.13);
backdrop-filter: blur(12px);
}
.stat-label {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.stat-value {
display: flex;
align-items: baseline;
gap: 5px;
margin-top: 3px;
font-size: 26px;
font-weight: 850;
line-height: 1;
letter-spacing: -0.04em;
}
.stat-value small {
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0;
}
.stat.reserve .stat-value {
color: var(--teal);
}
.stat.unmet .stat-value {
color: var(--red);
}
.controls {
position: absolute;
top: 151px;
left: 24px;
width: 342px;
max-height: calc(100vh - 175px);
overflow: auto;
border-radius: 13px;
scrollbar-width: thin;
}
.control-inner {
padding: 17px;
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.section-head h2 {
margin: 0;
font-size: 16px;
letter-spacing: -0.02em;
}
.fiction-badge {
padding: 5px 7px;
border: 1px solid rgba(200, 91, 69, 0.25);
border-radius: 5px;
background: rgba(200, 91, 69, 0.09);
color: #9d4938;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.08em;
white-space: nowrap;
text-transform: uppercase;
}
.intro {
margin: 0 0 13px;
color: var(--muted);
font-size: 11.5px;
line-height: 1.48;
}
.assumption {
margin: 12px 0;
padding: 11px 12px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.5);
}
.assumption-top {
display: flex;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
font-size: 11px;
font-weight: 750;
}
.assumption output {
color: var(--teal);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 7px 0 3px;
border-radius: 999px;
outline: none;
appearance: none;
background: linear-gradient(
90deg,
var(--teal) 0 var(--range-fill, 50%),
rgba(24, 49, 58, 0.13) var(--range-fill, 50%) 100%
);
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
border: 3px solid var(--paper-solid);
border-radius: 4px;
appearance: none;
background: var(--teal);
box-shadow: 0 2px 7px rgba(24, 49, 58, 0.25);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid var(--paper-solid);
border-radius: 4px;
background: var(--teal);
box-shadow: 0 2px 7px rgba(24, 49, 58, 0.25);
}
.rule-title {
margin: 15px 0 8px;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.rules {
display: grid;
gap: 7px;
margin: 0;
padding: 0;
list-style: none;
}
.rules li {
display: grid;
grid-template-columns: 22px 1fr;
gap: 8px;
color: #496267;
font-size: 10.8px;
line-height: 1.42;
}
.rule-number {
display: grid;
width: 21px;
height: 21px;
place-items: center;
border-radius: 5px;
background: rgba(8, 127, 131, 0.11);
color: var(--teal);
font-size: 9px;
font-weight: 850;
}
.formula {
margin: 10px 0 0;
padding: 9px 10px;
border-left: 3px solid var(--teal);
background: rgba(8, 127, 131, 0.075);
color: #315a5e;
font-size: 11px;
line-height: 1.45;
}
.formula strong {
color: var(--teal);
}
.severity {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 9px;
}
.severity-item {
padding: 7px;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(255, 255, 255, 0.45);
}
.severity-item span {
display: block;
color: var(--muted);
font-size: 8.5px;
font-weight: 750;
text-transform: uppercase;
}
.severity-item strong {
display: block;
margin-top: 2px;
font-size: 12px;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
.button {
min-height: 38px;
border: 0;
border-radius: 7px;
font-size: 11px;
font-weight: 850;
transition:
transform 120ms ease,
background 120ms ease,
opacity 120ms ease;
}
.button:hover:not(:disabled) {
transform: translateY(-1px);
}
.button:active:not(:disabled) {
transform: translateY(0);
}
.button:disabled {
cursor: wait;
opacity: 0.55;
}
.button.primary {
background: var(--teal);
color: white;
box-shadow: 0 5px 12px rgba(8, 127, 131, 0.2);
}
.button.secondary {
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.7);
color: var(--ink);
}
.button.ghost {
grid-column: 1 / -1;
min-height: 32px;
background: transparent;
color: var(--muted);
border: 1px dashed rgba(24, 49, 58, 0.18);
}
.log {
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
.log-list {
display: grid;
gap: 5px;
max-height: 139px;
overflow: auto;
scrollbar-width: thin;
}
.log-row {
display: grid;
grid-template-columns: 30px 1fr auto;
align-items: center;
gap: 8px;
padding: 7px 8px;
border-radius: 6px;
background: rgba(24, 49, 58, 0.045);
font-size: 9.8px;
}
.log-row b {
color: var(--teal);
font-variant-numeric: tabular-nums;
}
.log-row span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.log-row em {
color: var(--muted);
font-style: normal;
font-variant-numeric: tabular-nums;
}
.empty-log {
padding: 10px;
color: var(--muted);
font-size: 10px;
text-align: center;
}
.chart-panel {
position: absolute;
right: 24px;
bottom: 24px;
width: min(570px, calc(100vw - 410px));
min-width: 430px;
padding: 15px 16px 12px;
border-radius: 13px;
}
.chart-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.chart-head h2 {
margin: 0;
font-size: 15px;
letter-spacing: -0.02em;
}
.chart-head p {
margin: 4px 0 0;
color: var(--muted);
font-size: 9.5px;
}
.legend {
display: flex;
gap: 11px;
margin-top: 9px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.legend-swatch {
width: 15px;
height: 3px;
border-radius: 3px;
background: var(--teal);
}
.legend-swatch.unmet {
background: var(--amber);
}
#chart {
display: block;
width: 100%;
height: 165px;
margin-top: 3px;
}
.chart-note {
color: var(--muted);
font-size: 8.8px;
line-height: 1.35;
}
.camera-tools {
position: absolute;
right: 24px;
bottom: 247px;
display: flex;
gap: 6px;
pointer-events: auto;
}
.camera-tools button {
width: 35px;
height: 35px;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 7px;
background: var(--paper);
color: var(--ink);
box-shadow: 0 8px 18px rgba(24, 49, 58, 0.13);
font-size: 16px;
font-weight: 800;
}
#labels {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
top: 0;
left: 0;
min-width: 62px;
padding: 5px 7px;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 6px;
background: rgba(250, 248, 238, 0.9);
box-shadow: 0 5px 14px rgba(24, 49, 58, 0.13);
color: var(--ink);
font-size: 9px;
font-weight: 850;
text-align: center;
white-space: nowrap;
will-change: transform;
}
.world-label.depot {
background: rgba(24, 49, 58, 0.92);
color: white;
}
.world-label small {
display: block;
margin-top: 2px;
color: var(--red);
font-size: 8px;
}
#tooltip {
position: fixed;
z-index: 20;
display: none;
max-width: 220px;
padding: 8px 10px;
border-radius: 6px;
background: rgba(24, 49, 58, 0.94);
color: white;
box-shadow: 0 8px 20px rgba(24, 49, 58, 0.2);
font-size: 10px;
line-height: 1.35;
pointer-events: none;
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
background: #b9d7cf;
color: var(--ink);
font-size: 13px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#loading.hidden {
display: none;
}
@media (max-width: 980px) {
.brand {
top: 12px;
left: 12px;
width: calc(100% - 24px);
}
.brand h1 {
font-size: 26px;
}
.brand p {
display: none;
}
.stats {
top: 91px;
right: 12px;
left: 12px;
}
.stat {
flex: 1;
width: auto;
padding: 9px 11px;
}
.stat-value {
font-size: 21px;
}
.controls {
top: 157px;
left: 12px;
width: min(335px, calc(100% - 24px));
max-height: 45vh;
}
.chart-panel {
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
min-width: 0;
}
.camera-tools {
right: 12px;
bottom: 221px;
}
#chart {
height: 135px;
}
}
@media (max-width: 620px) {
.eyebrow {
font-size: 8px;
}
.brand h1 {
font-size: 22px;
}
.stats {
gap: 5px;
}
.stat {
padding: 8px;
}
.stat-label {
font-size: 8px;
}
.stat-value {
font-size: 18px;
}
.controls {
top: 149px;
width: calc(100% - 24px);
max-height: 38vh;
}
.control-inner {
padding: 13px;
}
.chart-panel {
padding: 11px 12px 9px;
}
.chart-head p,
.chart-note {
display: none;
}
.camera-tools {
bottom: 183px;
}
}
</style>
</head>
<body>
<div id="loading">Building voxel village…</div>
<div id="scene" aria-label="Interactive 3D voxel village"></div>
<div id="labels" aria-hidden="true"></div>
<main id="ui">
<header class="brand">
<div class="eyebrow">Common repair pool</div>
<h1>One village. One shared buffer.</h1>
<p>
Watch four households pool contributions, encounter uncertain repair
costs, and share the burden when the reserve runs short.
</p>
</header>
<section class="stats" aria-label="Pool status">
<div class="stat reserve">
<div class="stat-label">Reserve</div>
<div class="stat-value">
<span id="reserveValue">12</span><small>coins</small>
</div>
</div>
<div class="stat unmet">
<div class="stat-label">Unmet</div>
<div class="stat-value">
<span id="unmetValue">0</span><small>coins</small>
</div>
</div>
<div class="stat">
<div class="stat-label">Events</div>
<div class="stat-value">
<span id="eventValue">0</span><small>rounds</small>
</div>
</div>
</section>
<aside class="controls panel" aria-label="Simulation controls and assumptions">
<div class="control-inner">
<div class="section-head">
<h2>Transparent assumptions</h2>
<span class="fiction-badge">Fictional assumptions</span>
</div>
<p class="intro">
These probabilities and repair costs are invented for illustration.
They are not estimates, forecasts, or an actuarial model.
</p>
<div class="assumption">
<div class="assumption-top">
<label for="contribution">Contribution per household</label>
<output id="contributionOutput" for="contribution">5 coins</output>
</div>
<input
id="contribution"
type="range"
min="1"
max="10"
step="1"
value="5"
/>
</div>
<div class="assumption">
<div class="assumption-top">
<label for="probability">Chance of a loss event</label>
<output id="probabilityOutput" for="probability">40%</output>
</div>
<input
id="probability"
type="range"
min="0"
max="70"
step="1"
value="40"
/>
</div>
<div class="formula" id="poolFormula">
<strong>4 homes × 5 coins = 20 coins</strong> enter the pool each round.
</div>
<div class="rule-title">Repair cost if a loss occurs</div>
<div class="severity">
<div class="severity-item">
<span>Minor · 30%</span>
<strong>30 coins</strong>
</div>
<div class="severity-item">
<span>Moderate · 45%</span>
<strong>60 coins</strong>
</div>
<div class="severity-item">
<span>Severe · 25%</span>
<strong>100 coins</strong>
</div>
</div>
<div class="rule-title">Pool rules</div>
<ol class="rules">
<li>
<span class="rule-number">1</span>
<span>Every modeled household contributes the same amount before each event.</span>
</li>
<li>
<span class="rule-number">2</span>
<span>A loss receives a fictional repair cost from the severity table above.</span>
</li>
<li>
<span class="rule-number">3</span>
<span>The depot can pay only from the shared reserve; payouts cannot exceed available coins.</span>
</li>
<li>
<span class="rule-number">4</span>
<span>The oldest unpaid repair is settled before a new claim. Unused coins carry forward.</span>
</li>
<li>
<span class="rule-number">5</span>
<span>The pool begins with 12 seed coins and retains a 12-coin opening balance.</span>
</li>
</ol>
<div class="buttons">
<button class="button primary" id="stepButton">Step one event</button>
<button class="button secondary" id="runButton">Add 12 events</button>
<button class="button ghost" id="resetButton">
Reset ledger and village
</button>
</div>
<section class="log" aria-live="polite">
<div class="rule-title">Recent event ledger</div>
<div id="eventLog" class="log-list">
<div class="empty-log">No events yet.</div>
</div>
</section>
</div>
</aside>
<section class="chart-panel panel" aria-label="Reserve history chart">
<div class="chart-head">
<div>
<h2>Reserve and unmet repairs</h2>
<p>Balances shown immediately after each fictional event</p>
</div>
<div class="legend">
<span class="legend-item">
<span class="legend-swatch"></span>Reserve
</span>
<span class="legend-item">
<span class="legend-swatch unmet"></span>Unmet
</span>
</div>
</div>
<canvas id="chart"></canvas>
<div class="chart-note">
Each point represents one repeated event. The amber series is the total
repair cost still waiting for payment.
</div>
</section>
<div class="camera-tools" aria-label="Camera controls">
<button id="zoomIn" title="Zoom in" aria-label="Zoom in">+</button>
<button id="zoomOut" title="Zoom out" aria-label="Zoom out">−</button>
<button id="cameraReset" title="Reset camera" aria-label="Reset camera">⌂</button>
</div>
</main>
<div id="tooltip"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const palette = {
ink: 0x18313a,
ground: 0x9fbf83,
groundDark: 0x789d69,
path: 0xd8c59a,
pathDark: 0xbca77d,
depot: 0x2b7080,
depotDark: 0x173f49,
roof: 0xd77a42,
roofDark: 0xa94d32,
wood: 0x7b5639,
cream: 0xf4e5bc,
white: 0xf7f4e8,
gold: 0xe7ad3d,
goldDark: 0xb97924,
window: 0x8dd1d0,
damage: 0x4b3833,
scaffold: 0xe18a2d,
water: 0x5ba9b1
};
const houseColors = [
0xe8c987,
0x9ccbb8,
0xdca69a,
0xc8b7d8
];
const houseRoofColors = [
0xc95d42,
0x347b83,
0xd78745,
0x655d91
];
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d7cf);
scene.fog = new THREE.Fog(0xb9d7cf, 27, 47);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
$("scene").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xe7f8f5, 0x60775a, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2d0, 3.2);
sun.position.set(10, 18, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 18;
sun.shadow.camera.bottom = -18;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0007;
scene.add(sun);
const world = new THREE.Group();
scene.add(world);
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.84,
metalness: 0,
flatShading: true,
...options
});
}
const mat = {
ground: material(palette.ground),
groundDark: material(palette.groundDark),
path: material(palette.path),
pathDark: material(palette.pathDark),
cream: material(palette.cream),
white: material(palette.white),
wood: material(palette.wood),
dark: material(palette.ink),
damage: material(palette.damage),
scaffold: material(palette.scaffold),
gold: material(palette.gold, { roughness: 0.55 }),
goldDark: material(palette.goldDark),
window: material(palette.window, {
roughness: 0.45,
metalness: 0.08
})
};
function addBox(parent, width, height, depth, color, x, y, z, options = {}) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
color?.isMaterial ? color : material(color, options)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addSign(parent, text, width, height, x, y, z) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#173f49";
ctx.fillRect(0, 0, 512, 128);
ctx.fillStyle = "#f4e5bc";
ctx.fillRect(9, 9, 494, 110);
ctx.strokeStyle = "#e4a33b";
ctx.lineWidth = 8;
ctx.strokeRect(13, 13, 486, 102);
ctx.fillStyle = "#173f49";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "900 46px system-ui";
ctx.fillText(text, 256, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sign = new THREE.Mesh(
new THREE.PlaneGeometry(width, height),
new THREE.MeshBasicMaterial({ map: texture })
);
sign.position.set(x, y, z);
parent.add(sign);
return sign;
}
// Ground and paths.
addBox(world, 22, 0.7, 18, mat.ground, 0, -0.48, 0);
addBox(world, 22.2, 0.25, 0.35, mat.groundDark, 0, -0.08, 8.85);
addBox(world, 22.2, 0.25, 0.35, mat.groundDark, 0, -0.08, -8.85);
addBox(world, 0.35, 0.25, 18, mat.groundDark, -10.85, -0.08, 0);
addBox(world, 0.35, 0.25, 18, mat.groundDark, 10.85, -0.08, 0);
for (let x = -10; x <= 10; x += 1.05) {
addBox(world, 0.91, 0.12, 1.18, mat.path, x, -0.07, 0);
addBox(world, 0.91, 0.12, 0.95, mat.pathDark, x, -0.075, 0.08);
}
for (let z = -7; z <= 7; z += 1.05) {
if (Math.abs(z) > 1.3) {
addBox(world, 1.15, 0.12, 0.9, mat.path, 0, -0.07, z);
}
}
// Patchwork grass voxels.
const grassPatches = [
[-9.5, -4.6, 1.4, 1.1],
[9.2, 2.7, 1.7, 1.3],
[-3.4, 7.2, 1.5, 0.9],
[3.8, -7.2, 1.8, 1.0],
[-9.1, 6.5, 1.2, 0.9],
[9.5, -6.1, 1.1, 1.4]
];
for (const [x, z, w, d] of grassPatches) {
addBox(world, w, 0.12, d, mat.groundDark, x, 0.01, z);
}
function makeTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
addBox(group, 0.45, 1.8, 0.45, mat.wood, 0, 0.9, 0);
addBox(group, 1.7, 0.8, 1.5, material(0x477f5f), 0, 1.75, 0);
addBox(group, 1.25, 0.75, 1.15, material(0x5c9568), -0.18, 2.35, 0.03);
addBox(group, 0.8, 0.55, 0.8, material(0x70a776), 0.2, 2.8, -0.05);
world.add(group);
}
[
[-9.3, -6.8, 1.05],
[-9.4, 6.8, 0.95],
[9.3, -6.9, 1.0],
[9.5, 6.7, 0.9],
[-3.7, -7.2, 0.85],
[3.8, 7.1, 0.9],
[8.9, -2.9, 0.72],
[-8.8, 2.3, 0.68]
].forEach((args) => makeTree(...args));
function makeFence() {
const fenceMat = mat.cream;
const postPositions = [];
for (let x = -10; x <= 10; x += 2) {
postPositions.push([x, -8.25]);
postPositions.push([x, 8.25]);
}
for (let z = -7; z <= 7; z += 2) {
postPositions.push([-10.25, z]);
postPositions.push([10.25, z]);
}
for (const [x, z] of postPositions) {
addBox(world, 0.18, 0.85, 0.18, fenceMat, x, 0.42, z);
}
for (let x = -10; x <= 10; x += 2) {
addBox(world, 2, 0.13, 0.12, fenceMat, x, 0.55, -8.25);
addBox(world, 2, 0.13, 0.12, fenceMat, x, 0.55, 8.25);
}
for (let z = -7; z <= 7; z += 2) {
addBox(world, 0.12, 0.13, 2, fenceMat, -10.25, 0.55, z);
addBox(world, 0.12, 0.13, 2, fenceMat, 10.25, 0.55, z);
}
}
makeFence();
// Small voxel well.
const well = new THREE.Group();
well.position.set(-3.2, 0, 2.5);
addBox(well, 1.55, 0.75, 1.55, material(0x8f9185), 0, 0.38, 0);
addBox(well, 1.15, 0.1, 1.15, material(palette.water), 0, 0.79, 0);
addBox(well, 0.16, 1.7, 0.16, mat.wood, -0.65, 1.2, 0);
addBox(well, 0.16, 1.7, 0.16, mat.wood, 0.65, 1.2, 0);
addBox(well, 1.65, 0.18, 0.22, mat.wood, 0, 2.0, 0);
addBox(well, 1.65, 0.16, 0.18, material(0xb65b40), 0, 2.12, 0);
world.add(well);
const houses = [];
const houseLabels = [];
function createHouse(index, x, z) {
const group = new THREE.Group();
group.position.set(x, 0, z);
const bodyMaterial = material(houseColors[index]);
const roofMaterial = material(houseRoofColors[index]);
addBox(group, 3.8, 0.28, 3.55, material(0x9b927d), 0, 0.14, 0);
const body = addBox(
group,
3.25,
2.35,
2.85,
bodyMaterial,
0,
1.42,
0
);
// Stacked roof blocks create a stepped voxel roof.
addBox(group, 3.75, 0.38, 3.4, roofMaterial, 0, 2.77, 0);
addBox(group, 2.85, 0.38, 2.8, roofMaterial, 0, 3.13, 0);
addBox(group, 1.95, 0.38, 2.2, roofMaterial, 0, 3.49, 0);
addBox(group, 1.05, 0.38, 1.6, roofMaterial, 0, 3.85, 0);
addBox(group, 0.28, 0.65, 0.32, material(0x6d6256), 0.55, 4.25, -0.25);
// Door.
addBox(group, 0.78, 1.55, 0.12, material(0x7a5137), -0.65, 1.05, 1.47);
addBox(group, 0.08, 0.08, 0.08, mat.gold, -0.34, 1.08, 1.55);
// Windows.
for (const wx of [-1.15, 1.05]) {
addBox(group, 0.63, 0.63, 0.11, mat.cream, wx, 1.58, 1.48);
addBox(group, 0.43, 0.43, 0.13, mat.window, wx, 1.58, 1.55);
addBox(group, 0.045, 0.45, 0.15, mat.cream, wx, 1.58, 1.58);
}
// Damage group appears only while that home has an unmet repair.
const damage = new THREE.Group();
addBox(damage, 0.75, 0.82, 0.13, mat.damage, 0.72, 1.42, 1.54);
addBox(damage, 0.17, 0.9, 0.15, mat.damage, 0.45, 2.38, 1.1);
addBox(damage, 0.7, 0.16, 0.16, mat.damage, 0.45, 2.82, 0.65);
addBox(damage, 0.52, 0.08, 0.08, mat.goldDark, 0.72, 1.38, 1.63);
damage.visible = false;
group.add(damage);
// Simple repair scaffolding.
const scaffolding = new THREE.Group();
addBox(scaffolding, 0.11, 2.6, 0.11, mat.scaffold, 1.68, 1.45, 1.72);
addBox(scaffolding, 0.11, 2.6, 0.11, mat.scaffold, 0.02, 1.45, 1.72);
addBox(scaffolding, 1.95, 0.11, 0.11, mat.scaffold, 0.85, 2.25, 1.72);
addBox(scaffolding, 1.95, 0.11, 0.11, mat.scaffold, 0.85, 0.95, 1.72);
scaffolding.visible = false;
group.add(scaffolding);
group.userData = {
type: "house",
index,
body,
damage,
scaffolding,
originalColor: new THREE.Color(houseColors[index])
};
group.traverse((child) => {
if (child.isMesh) {
child.userData.pick = { type: "house", index };
}
});
world.add(group);
houses.push(group);
const label = document.createElement("div");
label.className = "world-label";
label.innerHTML = `HOME ${index + 1}`;
$("labels").appendChild(label);
houseLabels.push(label);
}
createHouse(0, -6.1, 4.4);
createHouse(1, 6.1, 4.4);
createHouse(2, -6.1, -4.5);
createHouse(3, 6.1, -4.5);
// Central repair depot.
const depot = new THREE.Group();
depot.position.set(0, 0, 0);
const depotBody = addBox(
depot,
4.9,
2.65,
3.6,
material(palette.depot),
0,
1.45,
0
);
addBox(depot, 5.35, 0.35, 4.05, material(0x244f59), 0, 2.95, 0);
addBox(depot, 4.25, 0.38, 3.45, material(0xe2a23a), 0, 3.3, 0);
addBox(depot, 3.1, 0.38, 2.8, material(0xe2a23a), 0, 3.67, 0);
addBox(depot, 1.85, 0.38, 2.1, material(0xe2a23a), 0, 4.04, 0);
// Open repair bay.
addBox(depot, 2.55, 2.15, 0.13, material(0x142d33), -0.4, 1.18, 1.84);
addBox(depot, 0.16, 2.4, 0.18, material(0x8cc8c4), -1.7, 1.35, 1.9);
addBox(depot, 0.16, 2.4, 0.18, material(0x8cc8c4), 0.9, 1.35, 1.9);
addBox(depot, 2.7, 0.18, 0.2, material(0x8cc8c4), -0.4, 2.55, 1.9);
addSign(depot, "REPAIR DEPOT", 3.7, 0.75, 0, 3.0, 1.88);
// Depot side window and chimney.
addBox(depot, 0.12, 0.78, 1.05, mat.window, 2.5, 1.65, -0.4);
addBox(depot, 0.55, 1.2, 0.55, material(0x7b6653), -1.55, 4.25, -0.65);
// Workbench and tool blocks.
addBox(depot, 1.65, 0.18, 0.85, mat.wood, 3.6, 1.1, -0.7);
addBox(depot, 0.16, 1.05, 0.16, mat.wood, 2.9, 0.55, -0.7);
addBox(depot, 0.16, 1.05, 0.16, mat.wood, 4.3, 0.55, -0.7);
addBox(depot, 0.13, 0.9, 0.13, material(0xd9d3c1), 3.4, 1.58, -0.7);
addBox(depot, 0.62, 0.22, 0.22, material(0x9c5e43), 3.85, 1.43, -0.7);
// Reserve vault and visible coin stacks.
const vault = new THREE.Group();
vault.position.set(-3.45, 0, 1.55);
addBox(vault, 1.9, 1.25, 1.45, material(0x506b70), 0, 0.65, 0);
addBox(vault, 2.05, 0.28, 1.6, material(0x304b50), 0, 1.38, 0);
addBox(vault, 0.5, 0.66, 0.12, mat.gold, 0, 0.72, 0.78);
addBox(vault, 0.12, 0.12, 0.12, mat.cream, 0, 0.72, 0.87);
depot.add(vault);
const coinBlocks = [];
for (let stack = 0; stack < 10; stack++) {
const x = -3.45 + (stack % 5) * 0.31 - 0.62;
const z = 0.5 + Math.floor(stack / 5) * 0.42;
for (let level = 0; level < 3; level++) {
const coin = addBox(
depot,
0.23,
0.09,
0.23,
level === 0 ? mat.gold : mat.goldDark,
x,
1.57 + level * 0.095,
z
);
coin.visible = false;
coinBlocks.push({ mesh: coin, stack, level });
}
}
depot.traverse((child) => {
if (child.isMesh) {
child.userData.pick = { type: "depot" };
}
});
world.add(depot);
const depotLabel = document.createElement("div");
depotLabel.className = "world-label depot";
depotLabel.textContent = "REPAIR DEPOT";
$("labels").appendChild(depotLabel);
// A few bench and crate details.
function makeBench(x, z, rotation = 0) {
const bench = new THREE.Group();
bench.position.set(x, 0, z);
bench.rotation.y = rotation;
addBox(bench, 1.7, 0.16, 0.48, mat.wood, 0, 0.7, 0);
addBox(bench, 0.16, 0.65, 0.42, mat.wood, -0.58, 0.34, 0);
addBox(bench, 0.16, 0.65, 0.42, mat.wood, 0.58, 0.34, 0);
addBox(bench, 1.7, 0.36, 0.12, mat.wood, 0, 1.05, -0.22);
world.add(bench);
}
makeBench(3.3, 4.7, -Math.PI / 2);
makeBench(-3.7, -3.7, Math.PI / 2);
// Pixel-like clouds.
const clouds = [];
function makeCloud(x, y, z, scale = 1) {
const cloud = new THREE.Group();
cloud.position.set(x, y, z);
cloud.scale.setScalar(scale);
addBox(cloud, 2.2, 0.5, 0.8, mat.white, 0, 0, 0);
addBox(cloud, 1.3, 0.8, 0.8, mat.white, -0.45, 0.35, 0);
addBox(cloud, 1.5, 0.75, 0.8, mat.white, 0.55, 0.3, 0);
addBox(cloud, 0.8, 0.5, 0.8, mat.white, 1.2, 0, 0);
cloud.userData.speed = 0.11 + Math.random() * 0.07;
world.add(cloud);
clouds.push(cloud);
}
makeCloud(-9, 9, -9, 1.2);
makeCloud(9, 7.5, -4, 0.85);
makeCloud(-3, 11, 4, 0.72);
// -------------------------------------------------------------------------
// Simulation ledger
// -------------------------------------------------------------------------
const HOUSE_COUNT = 4;
const OPENING_RESERVE = 12;
const severityTable = [
{ name: "Minor", amount: 30, weight: 0.30 },
{ name: "Moderate", amount: 60, weight: 0.45 },
{ name: "Severe", amount: 100, weight: 0.25 }
];
let simulation;
let runTimer = null;
let resetTimer = null;
function random() {
// Mulberry32-like deterministic generator for reproducible examples.
simulation.seed |= 0;
simulation.seed = (simulation.seed + 0x6d2b79f5) | 0;
let t = Math.imul(simulation.seed ^ (simulation.seed >>> 15), 1 | simulation.seed);
t ^= t + Math.imul(t ^ (t >>> 7), 61 | t);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
function chooseSeverity() {
const value = random();
let cumulative = 0;
for (const severity of severityTable) {
cumulative += severity.weight;
if (value <= cumulative) return severity;
}
return severityTable[severityTable.length - 1];
}
function resetSimulation() {
if (runTimer) {
clearInterval(runTimer);
runTimer = null;
}
simulation = {
seed: 0x5eed123,
reserve: OPENING_RESERVE,
debts: [],
history: [],
totalContributed: 0,
totalClaimed: 0,
totalPaid: 0
};
$("runButton").disabled = false;
$("stepButton").disabled = false;
updateUI();
}
function stepSimulation() {
const contribution = Number($("contribution").value);
const probability = Number($("probability").value) / 100;
const contributed = contribution * HOUSE_COUNT;
simulation.reserve += contributed;
simulation.totalContributed += contributed;
// Oldest outstanding repair gets priority.
let backlogPaid = 0;
while (simulation.debts.length && simulation.reserve > 0.001) {
const debt = simulation.debts[0];
const payment = Math.min(simulation.reserve, debt.amount);
debt.amount -= payment;
simulation.reserve -= payment;
backlogPaid += payment;
simulation.totalPaid += payment;
if (debt.amount <= 0.001) {
simulation.debts.shift();
} else {
break;
}
}
let claimed = 0;
let currentPaid = 0;
let severity = null;
let affectedHouse = -1;
if (random() < probability) {
severity = chooseSeverity();
claimed = severity.amount;
affectedHouse = Math.floor(random() * HOUSE_COUNT);
simulation.totalClaimed += claimed;
currentPaid = Math.min(simulation.reserve, claimed);
simulation.reserve -= currentPaid;
simulation.totalPaid += currentPaid;
if (claimed - currentPaid > 0.001) {
simulation.debts.push({
house: affectedHouse,
amount: claimed - currentPaid
});
}
}
const outstanding = simulation.debts.reduce(
(sum, debt) => sum + debt.amount,
0
);
simulation.history.push({
round: simulation.history.length + 1,
contributed,
claimed,
paid: currentPaid + backlogPaid,
currentPaid,
backlogPaid,
reserve: simulation.reserve,
outstanding,
severity,
affectedHouse,
loss: Boolean(severity)
});
}
function updateHouseVisuals() {
const debtByHouse = Array(HOUSE_COUNT).fill(0);
for (const debt of simulation.debts) {
debtByHouse[debt.house] += debt.amount;
}
houses.forEach((house, index) => {
const debt = debtByHouse[index];
const hasDamage = debt > 0.001;
house.userData.damage.visible = hasDamage;
house.userData.scaffolding.visible = hasDamage;
if (hasDamage) {
const damagedColor = new THREE.Color(house.userData.originalColor);
damagedColor.lerp(new THREE.Color(0xb56f58), 0.34);
house.userData.body.material.color.copy(damagedColor);
} else {
house.userData.body.material.color.copy(house.userData.originalColor);
}
houseLabels[index].innerHTML =
`HOME ${index + 1}` +
(hasDamage ? `<small>${Math.round(debt)} coins due</small>` : "");
});
}
function updateCoinStack() {
const visibleStacks = Math.min(
10,
Math.max(0, Math.ceil(simulation.reserve / 15))
);
for (const coin of coinBlocks) {
coin.mesh.visible =
coin.stack < visibleStacks &&
coin.level < Math.min(3, 1 + Math.floor(coin.stack / 3));
}
}
function updateUI() {
const outstanding = simulation.debts.reduce(
(sum, debt) => sum + debt.amount,
0
);
$("reserveValue").textContent = Math.round(simulation.reserve);
$("unmetValue").textContent = Math.round(outstanding);
$("eventValue").textContent = simulation.history.length;
updateHouseVisuals();
updateCoinStack();
updateEventLog();
drawChart();
}
function updateEventLog() {
const log = $("eventLog");
if (!simulation.history.length) {
log.innerHTML = '<div class="empty-log">No events yet.</div>';
return;
}
const recent = simulation.history.slice(-7).reverse();
log.innerHTML = recent
.map((event) => {
if (!event.loss) {
return `
<div class="log-row">
<b>E${event.round}</b>
<span>No loss · pool grew</span>
<em>+${event.contributed}</em>
</div>
`;
}
const paidText =
event.paid >= event.claimed
? `${event.claimed} paid`
: `${Math.round(event.paid)}/${event.claimed} paid`;
return `
<div class="log-row">
<b>E${event.round}</b>
<span>Home ${event.affectedHouse + 1} · ${event.severity.name}</span>
<em>${paidText}</em>
</div>
`;
})
.join("");
}
function drawChart() {
const canvas = $("chart");
const rect = canvas.getBoundingClientRect();
const cssWidth = Math.max(100, rect.width);
const cssHeight = Math.max(100, rect.height);
const dpr = Math.min(devicePixelRatio, 2);
canvas.width = Math.round(cssWidth * dpr);
canvas.height = Math.round(cssHeight * dpr);
const ctx = canvas.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, cssWidth, cssHeight);
const history = simulation.history;
const pad = {
top: 13,
right: 12,
bottom: 25,
left: 38
};
const width = cssWidth - pad.left - pad.right;
const height = cssHeight - pad.top - pad.bottom;
if (!history.length) {
ctx.fillStyle = "#6c8184";
ctx.font = "600 10px system-ui";
ctx.textAlign = "center";
ctx.fillText(
"Step or add events to build the ledger",
cssWidth / 2,
cssHeight / 2
);
return;
}
const maxValue = Math.max(
20,
...history.map((event) =>
Math.max(event.reserve, event.outstanding)
)
);
const scaleMax = Math.ceil(maxValue / 20) * 20;
const xAt = (index) => {
if (history.length === 1) return pad.left + width / 2;
return (
pad.left + (index / (history.length - 1)) * width
);
};
const yAt = (value) =>
pad.top + height - (value / scaleMax) * height;
// Grid and y-axis labels.
ctx.lineWidth = 1;
ctx.font = "8px system-ui";
ctx.textAlign = "right";
ctx.textBaseline = "middle";
for (let i = 0; i <= 4; i++) {
const value = (scaleMax / 4) * i;
const y = yAt(value);
ctx.strokeStyle = "rgba(24,49,58,0.09)";
ctx.beginPath();
ctx.moveTo(pad.left, y);
ctx.lineTo(cssWidth - pad.right, y);
ctx.stroke();
ctx.fillStyle = "#718487";
ctx.fillText(String(Math.round(value)), pad.left - 7, y);
}
// Reserve area and line.
const reserveGradient = ctx.createLinearGradient(
0,
pad.top,
0,
pad.top + height
);
reserveGradient.addColorStop(0, "rgba(8,127,131,0.24)");
reserveGradient.addColorStop(1, "rgba(8,127,131,0.015)");
ctx.beginPath();
history.forEach((event, index) => {
const x = xAt(index);
const y = yAt(event.reserve);
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.lineTo(xAt(history.length - 1), pad.top + height);
ctx.lineTo(xAt(0), pad.top + height);
ctx.closePath();
ctx.fillStyle = reserveGradient;
ctx.fill();
ctx.beginPath();
history.forEach((event, index) => {
const x = xAt(index);
const y = yAt(event.reserve);
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.strokeStyle = "#087f83";
ctx.lineWidth = 2.3;
ctx.stroke();
// Unmet line.
ctx.beginPath();
history.forEach((event, index) => {
const x = xAt(index);
const y = yAt(event.outstanding);
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.strokeStyle = "#e49532";
ctx.lineWidth = 2;
ctx.setLineDash([5, 4]);
ctx.stroke();
ctx.setLineDash([]);
// Points.
history.forEach((event, index) => {
ctx.beginPath();
ctx.arc(xAt(index), yAt(event.reserve), 2.7, 0, Math.PI * 2);
ctx.fillStyle = "#087f83";
ctx.fill();
ctx.beginPath();
ctx.arc(xAt(index), yAt(event.outstanding), 2.5, 0, Math.PI * 2);
ctx.fillStyle = "#e49532";
ctx.fill();
});
// X-axis labels.
ctx.fillStyle = "#718487";
ctx.textBaseline = "bottom";
ctx.textAlign = "left";
ctx.fillText("Event 1", pad.left, cssHeight - 3);
if (history.length > 1) {
ctx.textAlign = "right";
ctx.fillText(
`Event ${history.length}`,
cssWidth - pad.right,
cssHeight - 3
);
}
}
// -------------------------------------------------------------------------
// Camera controls implemented directly, without Three.js add-ons.
// -------------------------------------------------------------------------
const cameraState = {
yaw: 0.72,
pitch: 0.61,
radius: 23.5,
target: new THREE.Vector3(0, 1.1, 0)
};
const defaultCamera = {
yaw: 0.72,
pitch: 0.61,
radius: 23.5
};
function updateCamera() {
const horizontal = Math.cos(cameraState.pitch) * cameraState.radius;
camera.position.set(
cameraState.target.x + Math.sin(cameraState.yaw) * horizontal,
cameraState.target.y + Math.sin(cameraState.pitch) * cameraState.radius,
cameraState.target.z + Math.cos(cameraState.yaw) * horizontal
);
camera.lookAt(cameraState.target);
}
updateCamera();
let pointerDown = false;
let pointerMoved = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDown = true;
pointerMoved = false;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
if (Math.abs(dx) + Math.abs(dy) > 2) {
pointerMoved = true;
}
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.0045,
0.28,
1.22
);
previousX = event.clientX;
previousY = event.clientY;
updateCamera();
} else {
updateHover(event);
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
pointerDown = false;
if (!pointerMoved) inspectAt(event.clientX, event.clientY);
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
12,
34
);
updateCamera();
},
{ passive: false }
);
$("zoomIn").addEventListener("click", () => {
cameraState.radius = Math.max(12, cameraState.radius - 2);
updateCamera();
});
$("zoomOut").addEventListener("click", () => {
cameraState.radius = Math.min(34, cameraState.radius + 2);
updateCamera();
});
$("cameraReset").addEventListener("click", () => {
cameraState.yaw = defaultCamera.yaw;
cameraState.pitch = defaultCamera.pitch;
cameraState.radius = defaultCamera.radius;
updateCamera();
});
// Scene picking.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pickAt(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(world.children, true);
for (const hit of hits) {
if (hit.object.userData.pick) return hit.object.userData.pick;
}
return null;
}
function updateHover(event) {
const pick = pickAt(event.clientX, event.clientY);
const tooltip = $("tooltip");
if (!pick) {
tooltip.style.display = "none";
renderer.domElement.style.cursor = "grab";
return;
}
renderer.domElement.style.cursor = "pointer";
if (pick.type === "depot") {
tooltip.innerHTML =
`<strong>Shared Repair Depot</strong><br>` +
`Available pool: ${Math.round(simulation.reserve)} coins`;
} else {
const debt = simulation.debts
.filter((item) => item.house === pick.index)
.reduce((sum, item) => sum + item.amount, 0);
tooltip.innerHTML =
`<strong>Home ${pick.index + 1}</strong><br>` +
(debt > 0
? `Unmet repair: ${Math.round(debt)} coins`
: "Contributes to the shared repair pool");
}
tooltip.style.display = "block";
tooltip.style.left = `${Math.min(innerWidth - 230, event.clientX + 13)}px`;
tooltip.style.top = `${Math.min(innerHeight - 80, event.clientY + 13)}px`;
}
function inspectAt(clientX, clientY) {
const pick = pickAt(clientX, clientY);
if (!pick) return;
if (pick.type === "depot") {
$("eventLog").insertAdjacentHTML(
"beforeend",
`<div class="log-row">
<b>INFO</b>
<span>Shared reserve</span>
<em>${Math.round(simulation.reserve)}</em>
</div>`
);
} else {
const debt = simulation.debts
.filter((item) => item.house === pick.index)
.reduce((sum, item) => sum + item.amount, 0);
$("eventLog").insertAdjacentHTML(
"beforeend",
`<div class="log-row">
<b>H${pick.index + 1}</b>
<span>Household inspection</span>
<em>${Math.round(debt)} due</em>
</div>`
);
}
}
// -------------------------------------------------------------------------
// UI interactions
// -------------------------------------------------------------------------
function updateAssumptionLabels() {
const contribution = Number($("contribution").value);
const probability = Number($("probability").value);
$("contributionOutput").textContent = `${contribution} coins`;
$("probabilityOutput").textContent = `${probability}%`;
$("poolFormula").innerHTML =
`<strong>4 homes × ${contribution} coins = ` +
`${contribution * HOUSE_COUNT} coins</strong> enter the pool each round.`;
for (const id of ["contribution", "probability"]) {
const input = $(id);
const percent =
((Number(input.value) - Number(input.min)) /
(Number(input.max) - Number(input.min))) *
100;
input.style.setProperty("--range-fill", `${percent}%`);
}
}
$("contribution").addEventListener("input", updateAssumptionLabels);
$("probability").addEventListener("input", updateAssumptionLabels);
for (const id of ["contribution", "probability"]) {
$(id).addEventListener("change", () => {
clearTimeout(resetTimer);
resetTimer = setTimeout(resetSimulation, 120);
});
}
$("stepButton").addEventListener("click", () => {
stepSimulation();
updateUI();
});
$("runButton").addEventListener("click", () => {
if (runTimer) return;
$("runButton").disabled = true;
$("stepButton").disabled = true;
let remaining = 12;
runTimer = setInterval(() => {
stepSimulation();
updateUI();
remaining -= 1;
if (remaining <= 0) {
clearInterval(runTimer);
runTimer = null;
$("runButton").disabled = false;
$("stepButton").disabled = false;
}
}, 190);
});
$("resetButton").addEventListener("click", resetSimulation);
// -------------------------------------------------------------------------
// Labels, resize, and render loop
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
function positionLabel(label, position, verticalOffset = 0) {
projected.copy(position);
projected.y += verticalOffset;
projected.project(camera);
const visible = projected.z > -1 && projected.z < 1;
if (!visible) {
label.style.display = "none";
return;
}
label.style.display = "";
const x = (projected.x * 0.5 + 0.5) * innerWidth;
const y = (-projected.y * 0.5 + 0.5) * innerHeight;
label.style.transform = `translate(${x}px, ${y}px) translate(-50%, -50%)`;
}
const houseWorldPositions = houses.map(
(house) => new THREE.Vector3(house.position.x, 4.55, house.position.z)
);
const depotWorldPosition = new THREE.Vector3(0, 4.65, 0);
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
drawChart();
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
for (const cloud of clouds) {
cloud.position.x += cloud.userData.speed * 0.008;
if (cloud.position.x > 13) cloud.position.x = -13;
}
for (let i = 0; i < houses.length; i++) {
positionLabel(houseLabels[i], houseWorldPositions[i], 0);
}
positionLabel(depotLabel, depotWorldPosition, 0);
renderer.render(scene, camera);
}
updateAssumptionLabels();
resetSimulation();
// Open with eight repeated events so the pooled pattern is immediately visible.
for (let i = 0; i < 8; i++) {
stepSimulation();
}
updateUI();
$("loading").classList.add("hidden");
animate();
</script>
</body>
</html>
```