Prompt specification
Build or customize the Three.js 3D scene "One Household Daily Resource Balance" 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: One Household Daily Resource Balance
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/one-household-daily-resource-balance-x3946
Scene Description Prompt:
Make a cutaway Three.js scene in a self-contained HTML file using cdnjs: one household daily resource balance. Animate a synthetic daily schedule for one household with explicit input, use, storage, and output accounts. Show unmet requests and losses rather than silently balancing missing quantities.
Working Three.js Starter (one-household-daily-resource-balance-x3946):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Household Daily Resource Balance</title>
<style>
:root {
color-scheme: dark;
--bg: #07111d;
--panel: rgba(10, 22, 35, 0.92);
--panel2: rgba(18, 35, 52, 0.82);
--line: rgba(170, 210, 230, 0.16);
--text: #edf7fb;
--muted: #91a9b8;
--water: #38c6ff;
--power: #ffc857;
--food: #71e08f;
--bad: #ff5e73;
--warn: #ff9b52;
--good: #62dfa0;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, select, input { font: inherit; }
button, select {
color: var(--text);
background: #142a3c;
border: 1px solid rgba(170, 220, 240, 0.2);
border-radius: 8px;
}
button {
cursor: pointer;
padding: 8px 11px;
transition: background 150ms, border-color 150ms, transform 150ms;
}
button:hover {
background: #1d3b51;
border-color: rgba(170, 220, 240, 0.42);
}
button:active { transform: translateY(1px); }
select { padding: 7px 9px; }
#viewport {
position: fixed;
inset: 0 370px 0 0;
overflow: hidden;
}
#sceneCanvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#labelLayer {
position: absolute;
inset: 0;
pointer-events: none;
overflow: hidden;
}
.room-label {
padding: 5px 8px;
border: 1px solid rgba(196, 228, 242, 0.22);
border-radius: 6px;
background: rgba(5, 15, 24, 0.72);
color: #d9edf5;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
white-space: nowrap;
backdrop-filter: blur(6px);
}
.world-badge {
padding: 4px 7px;
border-radius: 5px;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.04em;
white-space: nowrap;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35);
}
.world-badge.unmet {
color: #fff;
background: rgba(218, 48, 69, 0.94);
border: 1px solid #ff8090;
}
.world-badge.loss {
color: #fff;
background: rgba(209, 100, 29, 0.94);
border: 1px solid #ffb261;
}
#topbar {
position: absolute;
top: 15px;
left: 16px;
right: 16px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.title-block, .controls {
pointer-events: auto;
border: 1px solid var(--line);
background: rgba(7, 18, 29, 0.82);
backdrop-filter: blur(12px);
border-radius: 12px;
box-shadow: 0 10px 35px rgba(0, 0, 0, 0.22);
}
.title-block { padding: 12px 15px; }
.eyebrow {
color: #8eb4c6;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 3px 0 2px;
font-size: clamp(17px, 2vw, 25px);
line-height: 1.08;
letter-spacing: -0.035em;
}
.subtitle {
color: var(--muted);
font-size: 11px;
}
.controls {
display: flex;
align-items: center;
gap: 8px;
padding: 8px;
}
#clock {
min-width: 70px;
padding: 0 4px;
font-size: 20px;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
#timelinePanel {
position: absolute;
left: 16px;
right: 16px;
bottom: 15px;
padding: 11px 13px 10px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(7, 18, 29, 0.87);
backdrop-filter: blur(12px);
box-shadow: 0 10px 35px rgba(0, 0, 0, 0.25);
}
.timeline-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-bottom: 6px;
}
#nowLabel {
color: #c7dce6;
font-size: 11px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.timeline-legend {
display: flex;
gap: 10px;
color: var(--muted);
font-size: 10px;
white-space: nowrap;
}
.legend-dot {
display: inline-block;
width: 7px;
height: 7px;
border-radius: 50%;
margin-right: 4px;
}
#timelineVisual {
position: relative;
height: 25px;
}
#timelineVisual::before {
content: "";
position: absolute;
left: 0;
right: 0;
top: 11px;
height: 3px;
border-radius: 3px;
background: rgba(175, 210, 225, 0.18);
}
#nowLine {
position: absolute;
top: 3px;
width: 2px;
height: 19px;
background: white;
box-shadow: 0 0 12px white;
transform: translateX(-1px);
pointer-events: none;
}
.tick {
position: absolute;
top: 7px;
width: 11px;
height: 11px;
padding: 0;
border: 2px solid var(--c);
border-radius: 50%;
background: #091724;
transform: translateX(-50%);
box-shadow: 0 0 0 2px rgba(7, 17, 29, 0.9);
}
.tick.done {
background: var(--c);
box-shadow: 0 0 10px color-mix(in srgb, var(--c) 65%, transparent);
}
.tick.unmet-event { border-color: var(--bad); }
#scrub {
display: block;
width: 100%;
height: 13px;
margin: -1px 0 0;
accent-color: white;
cursor: pointer;
}
#viewHelp {
position: absolute;
left: 18px;
bottom: 91px;
color: rgba(222, 240, 248, 0.72);
font-size: 10px;
text-shadow: 0 2px 8px #000;
pointer-events: none;
}
#ledger {
position: fixed;
z-index: 5;
top: 12px;
right: 12px;
bottom: 12px;
width: 346px;
overflow: auto;
padding: 15px;
border: 1px solid var(--line);
border-radius: 15px;
background: var(--panel);
backdrop-filter: blur(16px);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.36);
scrollbar-width: thin;
scrollbar-color: #29485e transparent;
}
.ledger-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 4px;
}
.ledger-title h2 {
margin: 0;
font-size: 16px;
letter-spacing: -0.02em;
}
.live {
display: inline-flex;
align-items: center;
gap: 6px;
color: #a8d8c0;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.12em;
}
.live::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--good);
box-shadow: 0 0 10px var(--good);
}
.ledger-sub {
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
#summary {
margin: 12px 0;
padding: 10px 11px;
border: 1px solid rgba(255, 94, 115, 0.25);
border-radius: 10px;
background: rgba(255, 94, 115, 0.08);
font-size: 11px;
line-height: 1.45;
}
#summary.good {
border-color: rgba(98, 223, 160, 0.25);
background: rgba(98, 223, 160, 0.08);
}
.resource-card {
margin-top: 10px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: linear-gradient(145deg, rgba(24, 45, 63, 0.78), rgba(10, 24, 37, 0.7));
}
.resource-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
}
.resource-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
font-weight: 850;
}
.resource-name i {
display: block;
width: 10px;
height: 10px;
border-radius: 3px;
background: var(--c);
box-shadow: 0 0 12px var(--c);
}
.resource-unit {
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-width: 0;
padding: 7px 8px;
border-radius: 7px;
background: rgba(3, 12, 20, 0.34);
}
.metric label {
display: block;
margin-bottom: 3px;
color: #83a0b1;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.11em;
}
.metric strong {
display: block;
overflow: hidden;
color: #eaf7fb;
font-size: 13px;
font-variant-numeric: tabular-nums;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric strong.bad { color: var(--bad); }
.metric strong.warn { color: var(--warn); }
.metric strong.good { color: var(--good); }
.storage-track {
height: 4px;
margin-top: 8px;
overflow: hidden;
border-radius: 4px;
background: rgba(255, 255, 255, 0.08);
}
.storage-track i {
display: block;
height: 100%;
width: 0;
border-radius: inherit;
background: var(--c);
box-shadow: 0 0 8px var(--c);
transition: width 180ms ease;
}
.equation {
margin-top: 10px;
padding-top: 8px;
border-top: 1px solid var(--line);
color: #aac0cd;
font-size: 9px;
line-height: 1.6;
}
.equation .check {
color: var(--good);
font-weight: 850;
}
.equation b {
color: #e9f7fb;
font-variant-numeric: tabular-nums;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 16px 0 8px;
color: #c9dde7;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.06em;
text-transform: uppercase;
}
#eventLog {
border: 1px solid var(--line);
border-radius: 9px;
overflow: hidden;
}
.log-row {
display: grid;
grid-template-columns: 42px 1fr;
gap: 8px;
padding: 8px 9px;
border-bottom: 1px solid rgba(170, 210, 230, 0.09);
background: rgba(18, 35, 52, 0.42);
font-size: 10px;
}
.log-row:last-child { border-bottom: 0; }
.log-time { color: #7f9ead; font-variant-numeric: tabular-nums; }
.log-name { color: #dcecf2; font-weight: 750; }
.log-detail { margin-top: 2px; color: #8fa9b8; line-height: 1.35; }
.log-detail.bad { color: #ff8796; }
.log-detail.loss { color: #ffb66f; }
.method {
margin-top: 12px;
padding: 10px;
border-left: 3px solid #5ca3bd;
background: rgba(92, 163, 189, 0.08);
color: #9eb6c3;
font-size: 10px;
line-height: 1.5;
}
@media (max-width: 900px) {
#viewport { inset: 0 0 300px 0; }
#ledger {
top: auto;
left: 10px;
right: 10px;
bottom: 10px;
width: auto;
height: 280px;
}
#topbar { flex-direction: column; }
.controls { align-self: flex-start; }
#viewHelp { display: none; }
.timeline-legend { display: none; }
}
@media (max-width: 560px) {
.title-block { max-width: calc(100vw - 32px); }
.controls { flex-wrap: wrap; }
#timelinePanel { left: 8px; right: 8px; bottom: 8px; }
}
</style>
</head>
<body>
<main id="viewport" aria-label="Interactive cutaway household resource scene">
<canvas id="sceneCanvas"></canvas>
<div id="labelLayer"></div>
<header id="topbar">
<div class="title-block">
<div class="eyebrow">One household · synthetic 24-hour boundary</div>
<h1>Daily Resource Balance</h1>
<div class="subtitle">Cutaway meter-to-use view · native units remain separate</div>
</div>
<div class="controls">
<button id="play" title="Play or pause">Pause</button>
<div id="clock">00:00</div>
<select id="speed" aria-label="Playback speed">
<option value="0.25">1×</option>
<option value="0.5" selected>2×</option>
<option value="1">4×</option>
</select>
<button id="resetView" title="Reset camera">Reset view</button>
</div>
</header>
<div id="viewHelp">Drag to orbit · wheel to zoom · double-click to reset · space to play/pause</div>
<section id="timelinePanel" aria-label="Synthetic daily timeline">
<div class="timeline-head">
<div id="nowLabel">Waiting for the first scheduled transaction…</div>
<div class="timeline-legend">
<span><i class="legend-dot" style="background:var(--water)"></i>Water</span>
<span><i class="legend-dot" style="background:var(--power)"></i>Power</span>
<span><i class="legend-dot" style="background:var(--food)"></i>Food</span>
</div>
</div>
<div id="timelineVisual">
<div id="ticks"></div>
<div id="nowLine"></div>
</div>
<input id="scrub" type="range" min="0" max="24" step="0.01" value="0" aria-label="Time of day" />
</section>
</main>
<aside id="ledger" aria-label="Explicit resource accounts">
<div class="ledger-title">
<h2>Boundary accounts</h2>
<div class="live">LIVE SYNTHETIC DAY</div>
</div>
<div class="ledger-sub">
Inputs, requested use, storage, output losses, and unmet demand are explicit.
Missing quantities are never inserted as a balancing plug.
</div>
<div id="summary">No unmet requests yet.</div>
<div id="resourceCards"></div>
<div class="section-title">
<span>Transaction log</span>
<span id="logCount">0 events</span>
</div>
<div id="eventLog"></div>
<div class="method">
<b>Balance rule:</b> input + opening storage = fulfilled use + closing storage + output loss.
Unmet requests are shown separately and are not counted as fulfilled use.
Resources are not summed across incompatible units.
</div>
</aside>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const viewport = $("#viewport");
const canvas = $("#sceneCanvas");
const labelLayer = $("#labelLayer");
const COLORS = {
water: 0x38c6ff,
power: 0xffc857,
food: 0x71e08f,
bad: 0xff5e73,
loss: 0xff9b52
};
const CSS_COLORS = {
water: "#38c6ff",
power: "#ffc857",
food: "#71e08f",
bad: "#ff5e73",
loss: "#ff9b52"
};
const resourceDefs = {
water: {
name: "Water",
unit: "L",
decimals: 0,
color: COLORS.water,
css: CSS_COLORS.water,
opening: 20,
capacity: 300,
lossAnchor: new THREE.Vector3(-7.55, 0.55, 3.05),
events: [
{ time: 6.0, type: "input", amount: 330, label: "Mains delivery", path: "w_in", node: "w_input" },
{ time: 6.2, type: "use", amount: 80, label: "Morning shower", path: "w_shower", node: "w_shower" },
{ time: 6.5, type: "use", amount: 20, label: "Toilet flush", path: "w_toilet", node: "w_toilet" },
{ time: 10.0, type: "use", amount: 110, label: "Laundry", path: "w_laundry", node: "w_laundry" },
{ time: 13.0, type: "use", amount: 45, label: "Dishwashing", path: "w_dish", node: "w_dish" },
{ time: 16.0, type: "loss", amount: 10, label: "Pipe leak", path: "w_loss", node: "w_storage", reason: "Leak" },
{ time: 18.5, type: "use", amount: 50, label: "Cooking water", path: "w_cook", node: "w_cook" },
{ time: 21.0, type: "use", amount: 15, label: "Evening toilet flush", path: "w_toilet2", node: "w_toilet2" }
]
},
power: {
name: "Electricity",
unit: "kWh",
decimals: 1,
color: COLORS.power,
css: CSS_COLORS.power,
opening: 1,
capacity: 12,
lossAnchor: new THREE.Vector3(7.65, 0.55, -0.75),
events: [
{ time: 0.5, type: "use", amount: 1.0, label: "Refrigeration", path: "e_fridge", node: "e_fridge" },
{ time: 6.5, type: "use", amount: 5.0, label: "Space heating", path: "e_heat", node: "e_heat" },
{ time: 7.0, type: "use", amount: 0.8, label: "Kettle", path: "e_kettle", node: "e_kettle" },
{ time: 9.5, type: "use", amount: 1.5, label: "Laptop charging", path: "e_laptop", node: "e_laptop" },
{ time: 12.0, type: "input", amount: 5.0, label: "Solar generation", path: "e_solar", node: "e_solar" },
{ time: 15.0, type: "loss", amount: 0.5, label: "Inverter / standby heat", path: "e_loss", node: "e_storage", reason: "Conversion loss" },
{ time: 17.0, type: "input", amount: 12.0, label: "Grid delivery", path: "e_grid", node: "e_grid" },
{ time: 18.0, type: "use", amount: 3.0, label: "Electric cooking", path: "e_cook", node: "e_cook" },
{ time: 19.5, type: "use", amount: 1.2, label: "Lighting", path: "e_lamp", node: "e_lamp" },
{ time: 20.5, type: "use", amount: 2.8, label: "Clothes dryer", path: "e_washer", node: "e_washer" }
]
},
food: {
name: "Food",
unit: "kg",
decimals: 1,
color: COLORS.food,
css: CSS_COLORS.food,
opening: 0.3,
capacity: 8,
lossAnchor: new THREE.Vector3(7.75, 0.55, 3.05),
events: [
{ time: 7.0, type: "use", amount: 0.5, label: "Breakfast", path: "f_table", node: "f_breakfast" },
{ time: 8.0, type: "input", amount: 4.5, label: "Grocery delivery", path: "f_input", node: "f_input" },
{ time: 12.5, type: "use", amount: 0.8, label: "Lunch", path: "f_table", node: "f_lunch" },
{ time: 18.0, type: "use", amount: 1.2, label: "Dinner", path: "f_table", node: "f_dinner" },
{ time: 19.0, type: "input", amount: 3.0, label: "Evening grocery delivery", path: "f_input", node: "f_input" },
{ time: 21.0, type: "loss", amount: 0.6, label: "Spoilage", path: "f_loss", node: "f_storage", reason: "Spoilage" }
]
}
};
const allEvents = Object.entries(resourceDefs)
.flatMap(([resource, def]) => def.events.map(event => ({ ...event, resource })))
.sort((a, b) => a.time - b.time);
function formatTime(value) {
const totalMinutes = Math.round(value * 60);
const h = Math.floor(totalMinutes / 60) % 24;
const m = totalMinutes % 60;
if (totalMinutes === 1440) return "24:00";
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
}
function formatAmount(value, decimals = 1) {
return Number(value).toLocaleString(undefined, {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals
});
}
function resourceFormat(def, value) {
return `${formatAmount(value, def.decimals)} ${def.unit}`;
}
// -----------------------------------------------------------------------------
// Three.js scene
// -----------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x102233);
scene.fog = new THREE.Fog(0x102233, 25, 52);
const camera = new THREE.PerspectiveCamera(40, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const ambient = new THREE.HemisphereLight(0xcbeaff, 0x26343b, 1.55);
scene.add(ambient);
const sunLight = new THREE.DirectionalLight(0xfff0cf, 2.1);
sunLight.position.set(8, 13, 8);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(2048, 2048);
sunLight.shadow.camera.left = -15;
sunLight.shadow.camera.right = 15;
sunLight.shadow.camera.top = 15;
sunLight.shadow.camera.bottom = -15;
sunLight.shadow.camera.near = 1;
sunLight.shadow.camera.far = 45;
sunLight.shadow.bias = -0.00025;
scene.add(sunLight);
const fillLight = new THREE.DirectionalLight(0x76bfff, 0.65);
fillLight.position.set(-10, 8, 2);
scene.add(fillLight);
const materials = {
ground: new THREE.MeshStandardMaterial({ color: 0x0b1821, roughness: 1 }),
slab: new THREE.MeshStandardMaterial({ color: 0x34444c, roughness: 0.9 }),
floor: new THREE.MeshStandardMaterial({ color: 0xaeb9b5, roughness: 0.85 }),
wall: new THREE.MeshStandardMaterial({ color: 0xc7d7d8, roughness: 0.85 }),
partition: new THREE.MeshStandardMaterial({ color: 0x91a9ad, roughness: 0.9 }),
cut: new THREE.MeshStandardMaterial({ color: 0xf0a35b, roughness: 0.55 }),
cabinet: new THREE.MeshStandardMaterial({ color: 0x54787c, roughness: 0.65 }),
cabinetDark: new THREE.MeshStandardMaterial({ color: 0x315258, roughness: 0.65 }),
white: new THREE.MeshStandardMaterial({ color: 0xf1f4ef, roughness: 0.5 }),
metal: new THREE.MeshStandardMaterial({ color: 0x8fa5ac, metalness: 0.65, roughness: 0.35 }),
dark: new THREE.MeshStandardMaterial({ color: 0x172930, roughness: 0.65 }),
wood: new THREE.MeshStandardMaterial({ color: 0x986c4c, roughness: 0.85 }),
glass: new THREE.MeshStandardMaterial({
color: 0xa8e8ff,
transparent: true,
opacity: 0.22,
roughness: 0.12,
metalness: 0.05,
depthWrite: false
}),
window: new THREE.MeshStandardMaterial({
color: 0x74b9df,
emissive: 0x173e59,
emissiveIntensity: 0.4,
transparent: true,
opacity: 0.72,
roughness: 0.2
})
};
function addBox(w, h, d, x, y, z, material, parent = scene, outlined = false) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
if (outlined) addEdges(mesh, 0x344b54, 0.55);
return mesh;
}
function addCylinder(radius, height, x, y, z, material, parent = scene, segments = 24) {
const mesh = new THREE.Mesh(new THREE.CylinderGeometry(radius, radius, height, segments), material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addEdges(mesh, color = 0x29424c, opacity = 0.5) {
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
new THREE.LineBasicMaterial({ color, transparent: true, opacity })
);
mesh.add(edges);
return edges;
}
const ground = new THREE.Mesh(new THREE.PlaneGeometry(70, 70), materials.ground);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.43;
ground.receiveShadow = true;
scene.add(ground);
// House shell: front wall and most of the roof are deliberately removed.
addBox(14.5, 0.34, 8.5, 0, -0.25, 0, materials.slab, scene, true);
addBox(14, 0.12, 8, 0, -0.02, 0, materials.floor, scene, true);
addBox(14, 5, 0.22, 0, 2.5, -4, materials.wall, scene, true);
addBox(0.22, 5, 8, -7, 2.5, 0, materials.wall, scene, true);
addBox(0.22, 1.15, 8, 7, 0.56, 0, materials.partition, scene, true);
addBox(14.25, 0.18, 1.75, 0, 5.05, -3.15, materials.dark, scene, true);
addBox(14.25, 0.12, 0.16, 0, 5.02, -2.26, materials.cut, scene);
// Low cutaway room partitions.
addBox(0.14, 1.25, 3.7, -3.55, 0.63, -2.1, materials.partition, scene, true);
addBox(0.14, 1.25, 3.7, 0.15, 0.63, -2.1, materials.partition, scene, true);
addBox(6.7, 0.12, 0.14, 3.65, 0.75, -0.15, materials.partition, scene, true);
// Window cutouts on the rear wall.
for (const x of [-5.35, 0.25, 5.15]) {
addBox(1.75, 1.45, 0.06, x, 2.65, -3.86, materials.window, scene, true);
addBox(0.07, 1.55, 0.08, x, 2.65, -3.81, materials.white);
addBox(1.85, 0.07, 0.08, x, 2.65, -3.81, materials.white);
}
// Floor tile grid.
const tilePositions = [];
for (let x = -6.5; x <= 6.5; x += 0.5) {
tilePositions.push(x, 0.055, -3.95, x, 0.055, 3.95);
}
for (let z = -3.5; z <= 3.5; z += 0.5) {
tilePositions.push(-6.95, 0.055, z, 6.95, 0.055, z);
}
const tileGeometry = new THREE.BufferGeometry();
tileGeometry.setAttribute("position", new THREE.Float32BufferAttribute(tilePositions, 3));
scene.add(new THREE.LineSegments(
tileGeometry,
new THREE.LineBasicMaterial({ color: 0x647d80, transparent: true, opacity: 0.28 })
));
// Bathroom.
addBox(1.85, 0.12, 1.75, -5.95, 0.12, -2.75, materials.white, scene, true);
addBox(0.05, 2.15, 1.75, -6.86, 1.15, -2.75, materials.glass, scene);
addBox(1.85, 2.15, 0.05, -5.95, 1.15, -3.62, materials.glass, scene);
addCylinder(0.045, 2.0, -6.72, 1.1, -3.45, materials.metal);
const showerHead = addCylinder(0.18, 0.06, -6.55, 2.05, -3.25, materials.metal);
showerHead.rotation.z = Math.PI / 2;
addBox(0.65, 0.85, 0.28, -4.55, 0.52, -3.18, materials.white, scene, true);
const toiletBowl = new THREE.Mesh(new THREE.SphereGeometry(0.4, 24, 16), materials.white);
toiletBowl.scale.set(1, 0.62, 1.28);
toiletBowl.position.set(-4.55, 0.38, -2.72);
toiletBowl.castShadow = true;
scene.add(toiletBowl);
// Laundry.
const washer = addBox(1.15, 1.22, 1.0, -2.55, 0.67, -2.85, materials.white, scene, true);
const washerDoor = addCylinder(0.34, 0.07, -2.55, 0.73, -2.32, materials.dark);
washerDoor.rotation.x = Math.PI / 2;
const washerGlass = addCylinder(0.24, 0.08, -2.55, 0.73, -2.275, materials.glass);
washerGlass.rotation.x = Math.PI / 2;
// Battery enclosure.
addBox(1.35, 1.75, 0.9, -1.45, 0.94, -2.85, materials.dark, scene, true);
addBox(1.48, 0.12, 1.02, -1.45, 1.86, -2.85, materials.metal, scene, true);
for (let i = 0; i < 4; i++) {
addBox(0.94, 0.06, 0.04, -1.45, 0.45 + i * 0.34, -2.38, materials.cabinetDark);
}
// Kitchen counters, sink, hob, refrigerator and pantry.
addBox(3.3, 1.05, 0.95, 1.65, 0.58, -3.0, materials.cabinet, scene, true);
addBox(3.45, 0.12, 1.04, 1.65, 1.16, -3.0, materials.white, scene, true);
addBox(0.75, 0.08, 0.55, 0.55, 1.26, -3.0, materials.metal, scene, true);
addBox(0.85, 0.07, 0.65, 2.25, 1.27, -3.0, materials.dark, scene, true);
for (const x of [2.02, 2.48]) {
const burner = addCylinder(0.14, 0.025, x, 1.32, -3.0, materials.metal);
burner.castShadow = false;
}
addBox(0.95, 2.25, 0.9, 3.72, 1.18, -3.0, materials.white, scene, true);
addBox(0.035, 0.72, 0.035, 4.04, 1.05, -2.53, materials.metal);
addBox(0.65, 1.75, 0.65, 5.45, 0.93, -3.0, materials.cabinetDark, scene, true);
// Dining area.
addBox(2.2, 0.16, 1.15, 5.3, 1.02, 1.2, materials.wood, scene, true);
addBox(0.18, 0.9, 0.18, 5.3, 0.5, 1.2, materials.dark);
addBox(1.45, 0.14, 0.55, 5.3, 0.55, 0.05, materials.wood, scene, true);
addBox(1.45, 0.14, 0.55, 5.3, 0.55, 2.35, materials.wood, scene, true);
addBox(0.12, 1.2, 0.12, 6.55, 0.7, 1.2, materials.dark);
const lamp = addCylinder(0.42, 0.16, 6.55, 1.34, 1.2, materials.cut);
lamp.castShadow = true;
// Exterior source objects.
addCylinder(0.5, 1.2, -7.75, 0.25, 1.35,
new THREE.MeshStandardMaterial({ color: COLORS.water, roughness: 0.4 }));
addBox(0.55, 1.2, 0.55, 7.75, 0.65, -3.45,
new THREE.MeshStandardMaterial({ color: COLORS.power, roughness: 0.45 }), scene, true);
addBox(1.15, 0.65, 0.8, 7.75, 0.35, 1.6,
new THREE.MeshStandardMaterial({ color: 0x4c9a5b, roughness: 0.85 }), scene, true);
for (let i = 0; i < 3; i++) {
addBox(0.8, 0.12, 0.55, 7.75, 0.55 + i * 0.16, 1.6, materials.wood);
}
addBox(0.65, 0.65, 0.65, 7.75, 0.3, 3.05, materials.dark, scene, true);
// Solar panel on the retained rear roof strip.
const solarPanel = addBox(2.2, 0.09, 1.25, -3.15, 5.25, -3.15,
new THREE.MeshStandardMaterial({ color: 0x173e64, metalness: 0.35, roughness: 0.3 }), scene, true);
solarPanel.rotation.x = -0.12;
for (let i = 1; i < 5; i++) {
const line = addBox(0.025, 0.012, 1.1, -4.05 + i * 0.45, 5.33, -3.15, materials.metal);
line.rotation.x = -0.12;
}
// Storage fill volumes.
const tankOuter = addCylinder(0.58, 1.85, -5.0, 1.04, -2.9, materials.glass);
tankOuter.renderOrder = 2;
const tankRimMaterial = new THREE.MeshStandardMaterial({ color: 0x779aa4, metalness: 0.55, roughness: 0.4 });
addCylinder(0.62, 0.08, -5.0, 1.98, -2.9, tankRimMaterial);
addCylinder(0.62, 0.08, -5.0, 0.14, -2.9, tankRimMaterial);
const waterFillGeometry = new THREE.CylinderGeometry(0.51, 0.51, 1, 28);
waterFillGeometry.translate(0, 0.5, 0);
const waterFill = new THREE.Mesh(
waterFillGeometry,
new THREE.MeshStandardMaterial({
color: COLORS.water,
emissive: COLORS.water,
emissiveIntensity: 0.32,
transparent: true,
opacity: 0.72,
roughness: 0.3
})
);
waterFill.position.set(-5.0, 0.18, -2.9);
scene.add(waterFill);
const batteryFill = addBox(
1.02, 1, 0.08, -1.45, 0.14, -2.375,
new THREE.MeshStandardMaterial({
color: COLORS.power,
emissive: COLORS.power,
emissiveIntensity: 0.25,
transparent: true,
opacity: 0.78
})
);
const foodFill = addBox(
0.54, 1, 0.55, 5.45, 0.12, -2.98,
new THREE.MeshStandardMaterial({
color: COLORS.food,
emissive: COLORS.food,
emissiveIntensity: 0.22,
transparent: true,
opacity: 0.72
})
);
// -----------------------------------------------------------------------------
// Resource paths and endpoint nodes
// -----------------------------------------------------------------------------
const pathDefs = {
w_in: {
resource: "water",
points: [[-7.75, 0.7, 1.35], [-7.15, 0.18, -0.8], [-6.4, 0.18, -3.15], [-5.0, 1.0, -2.9]]
},
w_shower: {
resource: "water",
points: [[-5.0, 1.0, -2.9], [-5.55, 0.18, -1.9], [-6.15, 0.55, -2.75]]
},
w_toilet: {
resource: "water",
points: [[-5.0, 1.0, -2.9], [-4.55, 0.18, -2.25], [-4.55, 0.68, -2.72]]
},
w_laundry: {
resource: "water",
points: [[-5.0, 1.0, -2.9], [-4.0, 0.18, -3.35], [-3.2, 0.18, -3.35], [-2.55, 0.78, -2.85]]
},
w_dish: {
resource: "water",
points: [[-5.0, 1.0, -2.9], [-2.0, 0.18, -3.4], [0.0, 0.18, -3.4], [0.55, 1.22, -3.0]]
},
w_cook: {
resource: "water",
points: [[-5.0, 1.0, -2.9], [-1.0, 0.18, -3.4], [1.8, 0.18, -3.4], [2.25, 1.28, -3.0]]
},
w_toilet2: {
resource: "water",
points: [[-5.0, 1.0, -2.9], [-4.55, 0.18, -2.2], [-4.55, 0.68, -2.72]]
},
w_loss: {
resource: "water",
points: [[-5.0, 0.9, -2.9], [-6.1, 0.12, -0.8], [-7.45, 0.12, 2.85]]
},
e_grid: {
resource: "power",
points: [[7.75, 1.0, -3.45], [6.0, 0.18, -3.45], [0.0, 0.18, -3.48], [-1.45, 0.92, -2.85]]
},
e_solar: {
resource: "power",
points: [[-3.15, 5.4, -3.15], [-2.8, 4.7, -3.15], [-1.45, 4.3, -3.15], [-1.45, 1.75, -2.85]]
},
e_fridge: {
resource: "power",
points: [[-1.45, 0.92, -2.85], [0.0, 0.18, -3.5], [3.72, 0.18, -3.48], [3.72, 1.2, -2.95]]
},
e_cook: {
resource: "power",
points: [[-1.45, 0.92, -2.85], [0.0, 0.18, -3.5], [2.25, 0.18, -3.5], [2.25, 1.3, -3.0]]
},
e_heat: {
resource: "power",
points: [[-1.45, 0.92, -2.85], [0.0, 0.18, -3.5], [4.8, 0.18, -3.5], [5.8, 0.18, 1.2], [6.55, 1.35, 1.2]]
},
e_kettle: {
resource: "power",
points: [[-1.45, 0.92, -2.85], [0.0, 0.18, -3.5], [1.35, 0.18, -3.5], [1.35, 1.3, -3.0]]
},
e_laptop: {
resource: "power",
points: [[-1.45, 0.92, -2.85], [0.0, 0.18, -3.5], [4.8, 0.18, -2.5], [5.55, 1.08, 1.1]]
},
e_lamp: {
resource: "power",
points: [[-1.45, 0.92, -2.85], [0.0, 0.18, -3.5], [5.0, 0.18, -1.0], [6.55, 1.3, 1.2]]
},
e_washer: {
resource: "power",
points: [[-1.45, 0.92, -2.85], [-2.0, 0.18, -3.42], [-2.55, 0.72, -2.82]]
},
e_loss: {
resource: "power",
points: [[-1.45, 0.92, -2.85], [0.0, 0.18, -3.5], [6.0, 0.18, -3.5], [7.55, 0.2, -0.85]]
},
f_input: {
resource: "food",
points: [[7.75, 0.7, 1.6], [7.2, 0.18, -0.3], [6.4, 0.18, -3.35], [5.45, 0.95, -3.0]]
},
f_table: {
resource: "food",
points: [[5.45, 0.95, -3.0], [6.1, 0.18, -2.7], [6.1, 0.18, 1.2], [5.45, 1.1, 1.2]]
},
f_loss: {
resource: "food",
points: [[5.45, 0.95, -3.0], [6.2, 0.18, -2.2], [7.2, 0.18, 1.8], [7.75, 0.2, 3.05]]
}
};
const pathObjects = {};
for (const [id, definition] of Object.entries(pathDefs)) {
const resource = resourceDefs[definition.resource];
const points = definition.points.map(p => new THREE.Vector3(...p));
const curve = new THREE.CatmullRomCurve3(points, false, "catmullrom", 0.12);
const geometry = new THREE.TubeGeometry(curve, 72, 0.035, 8, false);
const material = new THREE.MeshStandardMaterial({
color: resource.color,
emissive: resource.color,
emissiveIntensity: 0.26,
transparent: true,
opacity: 0.36,
roughness: 0.45,
depthWrite: false
});
const tube = new THREE.Mesh(geometry, material);
tube.renderOrder = 1;
scene.add(tube);
pathObjects[id] = { curve, tube };
}
const nodePositions = {
w_input: new THREE.Vector3(-7.75, 1.0, 1.35),
w_storage: new THREE.Vector3(-5.0, 1.85, -2.9),
w_shower: new THREE.Vector3(-6.15, 0.72, -2.75),
w_toilet: new THREE.Vector3(-4.55, 0.82, -2.72),
w_laundry: new THREE.Vector3(-2.55, 0.92, -2.82),
w_dish: new THREE.Vector3(0.55, 1.38, -3.0),
w_cook: new THREE.Vector3(2.25, 1.42, -3.0),
w_toilet2: new THREE.Vector3(-4.38, 0.82, -2.72),
e_grid: new THREE.Vector3(7.75, 1.3, -3.45),
e_solar: new THREE.Vector3(-3.15, 5.48, -3.15),
e_storage: new THREE.Vector3(-1.45, 1.92, -2.82),
e_fridge: new THREE.Vector3(3.72, 1.32, -2.93),
e_cook: new THREE.Vector3(2.25, 1.46, -3.0),
e_heat: new THREE.Vector3(6.55, 1.52, 1.2),
e_kettle: new THREE.Vector3(1.35, 1.46, -3.0),
e_laptop: new THREE.Vector3(5.55, 1.25, 1.1),
e_lamp: new THREE.Vector3(6.55, 1.52, 1.2),
e_washer: new THREE.Vector3(-2.55, 0.88, -2.75),
f_input: new THREE.Vector3(7.75, 0.9, 1.6),
f_storage: new THREE.Vector3(5.45, 1.85, -3.0),
f_breakfast: new THREE.Vector3(5.05, 1.2, 1.2),
f_lunch: new THREE.Vector3(5.3, 1.2, 1.2),
f_dinner: new THREE.Vector3(5.55, 1.2, 1.2)
};
const nodes = {};
function nodeResource(id) {
if (id.startsWith("w_")) return "water";
if (id.startsWith("e_")) return "power";
return "food";
}
for (const [id, position] of Object.entries(nodePositions)) {
const resource = resourceDefs[nodeResource(id)];
const mesh = new THREE.Mesh(
new THREE.SphereGeometry(0.115, 18, 12),
new THREE.MeshStandardMaterial({
color: resource.color,
emissive: resource.color,
emissiveIntensity: 0.5,
roughness: 0.28
})
);
mesh.position.copy(position);
mesh.castShadow = true;
scene.add(mesh);
nodes[id] = { mesh, baseColor: resource.color, flashUntil: 0, flashColor: resource.color };
}
// Room labels.
const worldItems = [];
function addWorldLabel(text, position, className = "room-label") {
const element = document.createElement("div");
element.className = className;
element.textContent = text;
labelLayer.appendChild(element);
worldItems.push({ element, position: position.clone(), visible: true });
return element;
}
addWorldLabel("BATH / LAUNDRY", new THREE.Vector3(-4.75, 4.35, -3.35));
addWorldLabel("UTILITY / STORAGE", new THREE.Vector3(-1.2, 4.35, -3.35));
addWorldLabel("KITCHEN", new THREE.Vector3(2.05, 4.35, -3.35));
addWorldLabel("LIVING / DINING", new THREE.Vector3(5.1, 4.35, 2.45));
// Sun and its daily orbit.
const sun = new THREE.Mesh(
new THREE.SphereGeometry(0.28, 20, 14),
new THREE.MeshBasicMaterial({ color: 0xffd977, toneMapped: false })
);
scene.add(sun);
const orbitPoints = [];
for (let i = 0; i < 96; i++) {
const angle = (i / 96) * Math.PI * 2;
orbitPoints.push(new THREE.Vector3(
Math.cos(angle) * 10,
4.2 + Math.sin(angle) * 5.2,
-1.5 + Math.sin(angle) * 2.5
));
}
const orbit = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(orbitPoints),
new THREE.LineBasicMaterial({ color: 0xffd977, transparent: true, opacity: 0.3 })
);
scene.add(orbit);
// -----------------------------------------------------------------------------
// Explicit simulation
// -----------------------------------------------------------------------------
let clock = 0;
let eventCursor = 0;
let playing = true;
let playbackSpeed = 0.5;
let eventResults = [];
let nodeUnmet = {};
let lastLogLength = -1;
function makeInitialState(def) {
return {
opening: def.opening,
stock: def.opening,
input: 0,
requested: 0,
fulfilled: 0,
unmet: 0,
loss: 0,
lossByReason: {},
lossRecords: 0,
unmetRequests: 0
};
}
const states = Object.fromEntries(
Object.entries(resourceDefs).map(([key, def]) => [key, makeInitialState(def)])
);
const pulseGeometry = new THREE.SphereGeometry(0.105, 14, 10);
const pulses = [];
function spawnPulse(pathId, color, delay = 0) {
if (!pathObjects[pathId]) return;
const material = new THREE.MeshBasicMaterial({ color, toneMapped: false });
const mesh = new THREE.Mesh(pulseGeometry, material);
scene.add(mesh);
pulses.push({ mesh, pathId, age: -delay, duration: 1.05 });
}
function flashNode(nodeId, color) {
const node = nodes[nodeId];
if (!node) return;
node.flashUntil = performance.now() + 1250;
node.flashColor = color;
}
function applyEvent(event, animate = true) {
const def = resourceDefs[event.resource];
const state = states[event.resource];
let detail = "";
let status = "normal";
if (event.type === "input") {
const room = Math.max(0, def.capacity - state.stock);
const accepted = Math.min(event.amount, room);
const overflow = event.amount - accepted;
state.input += event.amount;
state.stock += accepted;
if (overflow > 0) {
state.loss += overflow;
state.lossByReason.overflow = (state.lossByReason.overflow || 0) + overflow;
state.lossRecords++;
}
detail = `${resourceFormat(def, event.amount)} delivered` +
(overflow > 0 ? ` · ${resourceFormat(def, overflow)} overflow` : "");
if (animate) {
spawnPulse(event.path, def.color);
flashNode(event.node, overflow > 0 ? COLORS.loss : def.color);
if (overflow > 0) {
spawnPulse(def === resourceDefs.water ? "w_loss" :
def === resourceDefs.power ? "e_loss" : "f_loss", COLORS.loss, 0.35);
}
}
} else if (event.type === "use") {
const met = Math.min(state.stock, event.amount);
const unmet = event.amount - met;
state.requested += event.amount;
state.fulfilled += met;
state.unmet += unmet;
state.stock -= met;
if (unmet > 0) {
state.unmetRequests++;
nodeUnmet[event.node] = (nodeUnmet[event.node] || 0) + unmet;
status = "bad";
}
detail = `${resourceFormat(def, event.amount)} requested · ` +
`${resourceFormat(def, met)} met` +
(unmet > 0 ? ` · ${resourceFormat(def, unmet)} unmet` : "");
if (animate) {
spawnPulse(event.path, unmet > 0 ? COLORS.bad : def.color);
flashNode(event.node, unmet > 0 ? COLORS.bad : def.color);
}
} else if (event.type === "loss") {
const actual = Math.min(state.stock, event.amount);
state.stock -= actual;
state.loss += actual;
state.lossByReason[event.reason] = (state.lossByReason[event.reason] || 0) + actual;
state.lossRecords++;
detail = `${resourceFormat(def, actual)} recorded as ${event.reason.toLowerCase()}`;
status = "loss";
if (animate) {
spawnPulse(event.path, COLORS.loss);
flashNode(event.node, COLORS.loss);
}
}
eventResults.push({ event, detail, status });
}
function resetSimulation(targetTime, animate = false) {
for (const [key, def] of Object.entries(resourceDefs)) {
Object.assign(states[key], makeInitialState(def));
}
eventResults = [];
nodeUnmet = {};
eventCursor = 0;
clock = THREE.MathUtils.clamp(targetTime, 0, 24);
while (eventCursor < allEvents.length && allEvents[eventCursor].time <= clock) {
applyEvent(allEvents[eventCursor], animate);
eventCursor++;
}
}
// -----------------------------------------------------------------------------
// Account cards
// -----------------------------------------------------------------------------
const cardMarkup = Object.entries(resourceDefs).map(([key, def]) => `
<article class="resource-card" style="--c:${def.css}">
<div class="resource-head">
<div class="resource-name"><i></i>${def.name}</div>
<div class="resource-unit">${def.unit}</div>
</div>
<div class="metrics">
<div class="metric"><label>INPUT</label><strong id="${key}-input"></strong></div>
<div class="metric"><label>USE REQUESTED</label><strong id="${key}-requested"></strong></div>
<div class="metric"><label>FULFILLED USE</label><strong id="${key}-fulfilled" class="good"></strong></div>
<div class="metric"><label>UNMET</label><strong id="${key}-unmet"></strong></div>
<div class="metric"><label>STORAGE: OPEN → CURRENT</label><strong id="${key}-storage"></strong></div>
<div class="metric"><label>OUTPUT / LOSS</label><strong id="${key}-loss" class="warn"></strong></div>
</div>
<div class="storage-track"><i id="${key}-bar"></i></div>
<div class="equation" id="${key}-equation"></div>
</article>
`).join("");
$("#resourceCards").innerHTML = cardMarkup;
function updateAccountCards() {
let unmetRequests = 0;
let lossRecords = 0;
for (const [key, def] of Object.entries(resourceDefs)) {
const state = states[key];
$(`#${key}-input`).textContent = resourceFormat(def, state.input);
$(`#${key}-requested`).textContent = resourceFormat(def, state.requested);
$(`#${key}-fulfilled`).textContent = resourceFormat(def, state.fulfilled);
$(`#${key}-unmet`).textContent = resourceFormat(def, state.unmet);
$(`#${key}-unmet`).className = state.unmet > 0 ? "bad" : "";
$(`#${key}-storage`).textContent =
`${formatAmount(state.opening, def.decimals)} → ${formatAmount(state.stock, def.decimals)} / ${formatAmount(def.capacity, def.decimals)}`;
$(`#${key}-loss`).textContent = resourceFormat(def, state.loss);
$(`#${key}-bar`).style.width =
`${THREE.MathUtils.clamp(state.stock / def.capacity * 100, 0, 100)}%`;
const lhs = state.input + state.opening;
const rhs = state.fulfilled + state.stock + state.loss;
const balanced = Math.abs(lhs - rhs) < 0.0001;
$(`#${key}-equation`).innerHTML = `
<span class="check">${balanced ? "✓ BALANCE" : "⚠ CHECK"}</span><br>
IN <b>${formatAmount(lhs, def.decimals)}</b> =
MET <b>${formatAmount(state.fulfilled, def.decimals)}</b> +
STOCK <b>${formatAmount(state.stock, def.decimals)}</b> +
LOSS <b>${formatAmount(state.loss, def.decimals)}</b> ${def.unit}
`;
unmetRequests += state.unmetRequests;
lossRecords += state.lossRecords;
}
const summary = $("#summary");
if (unmetRequests === 0 && lossRecords === 0) {
summary.className = "good";
summary.textContent = "No unmet requests or output losses have occurred yet.";
} else {
summary.className = "";
summary.innerHTML =
`<b>${unmetRequests} unmet request${unmetRequests === 1 ? "" : "s"}</b> and ` +
`<b>${lossRecords} output-loss record${lossRecords === 1 ? "" : "s"}</b> ` +
`are visible in the accounts. Unmet quantities are excluded from fulfilled use.`;
}
}
function renderLog() {
if (eventResults.length === lastLogLength) return;
lastLogLength = eventResults.length;
$("#logCount").textContent = `${eventResults.length} event${eventResults.length === 1 ? "" : "s"}`;
if (!eventResults.length) {
$("#eventLog").innerHTML = `<div class="log-row"><div class="log-time">00:00</div><div class="log-name">No transactions yet</div></div>`;
return;
}
$("#eventLog").innerHTML = eventResults.slice(-6).reverse().map(({ event, detail, status }) => `
<div class="log-row">
<div class="log-time">${formatTime(event.time)}</div>
<div>
<div class="log-name">${event.label}</div>
<div class="log-detail ${status}">${detail}</div>
</div>
</div>
`).join("");
}
// -----------------------------------------------------------------------------
// Timeline
// -----------------------------------------------------------------------------
const tickElements = [];
for (const [index, event] of allEvents.entries()) {
const tick = document.createElement("button");
tick.className = "tick";
tick.style.left = `${event.time / 24 * 100}%`;
tick.style.setProperty("--c", resourceDefs[event.resource].css);
tick.title = `${formatTime(event.time)} — ${event.label}`;
tick.setAttribute("aria-label", tick.title);
tick.addEventListener("click", () => {
resetSimulation(event.time, false);
updateUI();
});
$("#ticks").appendChild(tick);
tickElements.push(tick);
}
function updateTimeline() {
$("#clock").textContent = formatTime(clock);
$("#scrub").value = clock;
$("#nowLine").style.left = `${clock / 24 * 100}%`;
const latest = eventResults[eventResults.length - 1];
$("#nowLabel").textContent = latest
? `${formatTime(latest.event.time)} · ${latest.event.label} — ${latest.detail}`
: "Waiting for the first scheduled transaction…";
tickElements.forEach((tick, index) => {
tick.classList.toggle("done", index < eventCursor);
const event = allEvents[index];
const willBeUnmet = event.type === "use" && event.amount > (
resourceDefs[event.resource].opening +
resourceDefs[event.resource].events
.filter(e => e.type === "input" && e.time <= event.time)
.reduce((sum, e) => sum + e.amount, 0) -
resourceDefs[event.resource].events
.filter(e => e.type === "use" && e.time < event.time)
.reduce((sum, e) => sum + e.amount, 0)
);
tick.classList.toggle("unmet-event", Boolean(willBeUnmet));
});
}
// -----------------------------------------------------------------------------
// World badges for persistent unmet demand and loss quantities
// -----------------------------------------------------------------------------
const badges = new Map();
function ensureBadge(id, text, type, anchor) {
let badge = badges.get(id);
if (!badge) {
const element = document.createElement("div");
element.className = `world-badge ${type}`;
labelLayer.appendChild(element);
badge = { element, anchor: anchor.clone(), type };
badges.set(id, badge);
worldItems.push(badge);
}
badge.element.textContent = text;
}
function updateBadges() {
for (const [id, amount] of Object.entries(nodeUnmet)) {
if (amount <= 0) continue;
const resourceKey = nodeResource(id);
const def = resourceDefs[resourceKey];
ensureBadge(
`unmet-${id}`,
`${resourceFormat(def, amount)} UNMET`,
"unmet",
nodePositions[id].clone().add(new THREE.Vector3(0, 0.42, 0))
);
}
for (const [key, def] of Object.entries(resourceDefs)) {
const state = states[key];
if (state.loss > 0) {
ensureBadge(
`loss-${key}`,
`${resourceFormat(def, state.loss)} OUTPUT`,
"loss",
def.lossAnchor.clone().add(new THREE.Vector3(0, 0.35, 0))
);
}
}
}
function updateWorldLabels() {
camera.updateMatrixWorld();
const width = viewport.clientWidth;
const height = viewport.clientHeight;
for (const item of worldItems) {
const projected = item.position.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1 &&
Math.abs(projected.x) < 1.15 && Math.abs(projected.y) < 1.15;
item.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
item.element.style.left = `${x}px`;
item.element.style.top = `${y}px`;
item.element.style.transform = "translate(-50%, -100%)";
}
}
// -----------------------------------------------------------------------------
// Dynamic scene state
// -----------------------------------------------------------------------------
function updateStorageVisuals() {
const water = states.water;
const waterRatio = THREE.MathUtils.clamp(water.stock / resourceDefs.water.capacity, 0, 1);
waterFill.scale.y = Math.max(0.001, waterRatio * 1.62);
const power = states.power;
const powerRatio = THREE.MathUtils.clamp(power.stock / resourceDefs.power.capacity, 0, 1);
batteryFill.scale.y = Math.max(0.001, powerRatio * 1.48);
batteryFill.position.y = 0.14 + batteryFill.scale.y / 2;
const food = states.food;
const foodRatio = THREE.MathUtils.clamp(food.stock / resourceDefs.food.capacity, 0, 1);
foodFill.scale.y = Math.max(0.001, foodRatio * 1.48);
foodFill.position.y = 0.12 + foodFill.scale.y / 2;
}
function updateNodes(now) {
for (const [id, node] of Object.entries(nodes)) {
const material = node.mesh.material;
material.color.setHex(node.baseColor);
material.emissive.setHex(node.baseColor);
material.emissiveIntensity = 0.42;
const unmet = nodeUnmet[id] || 0;
if (unmet > 0) {
material.color.setHex(COLORS.bad);
material.emissive.setHex(COLORS.bad);
material.emissiveIntensity = 0.75;
}
if (now < node.flashUntil) {
material.color.setHex(node.flashColor);
material.emissive.setHex(node.flashColor);
material.emissiveIntensity = 1.25;
const pulse = 1 + Math.sin(now * 0.018) * 0.22;
node.mesh.scale.setScalar(pulse);
} else {
node.mesh.scale.setScalar(1);
}
}
}
function updatePulses(delta) {
for (let i = pulses.length - 1; i >= 0; i--) {
const pulse = pulses[i];
pulse.age += delta;
if (pulse.age < 0) {
pulse.mesh.visible = false;
continue;
}
pulse.mesh.visible = true;
const t = THREE.MathUtils.clamp(pulse.age / pulse.duration, 0, 1);
const path = pathObjects[pulse.pathId];
const point = path.curve.getPointAt(t);
pulse.mesh.position.copy(point);
pulse.mesh.scale.setScalar(0.85 + Math.sin(t * Math.PI) * 0.45);
pulse.mesh.material.opacity = 1 - t;
if (t >= 1) {
scene.remove(pulse.mesh);
pulse.mesh.material.dispose();
pulses.splice(i, 1);
}
}
}
function updateDayLight() {
const angle = (clock / 24) * Math.PI * 2 - Math.PI / 2;
const daylight = Math.max(0, Math.sin(angle));
const easedDay = daylight * daylight;
sun.position.set(
Math.cos(angle) * 10,
2.3 + easedDay * 6.2,
-1.5 + Math.sin(angle) * 2.5
);
sunLight.position.copy(sun.position).multiplyScalar(1.25);
sunLight.intensity = 0.45 + easedDay * 2.15;
fillLight.intensity = 0.52 + (1 - easedDay) * 0.28;
const nightColor = new THREE.Color(0x07131f);
const dayColor = new THREE.Color(0x7ea9b8);
scene.background.copy(nightColor).lerp(dayColor, easedDay * 0.82);
scene.fog.color.copy(scene.background);
renderer.toneMappingExposure = 0.9 + easedDay * 0.22;
}
// -----------------------------------------------------------------------------
// Custom camera controls — no external controls module
// -----------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 1.5, -0.25);
const cameraState = {
yaw: 0.58,
pitch: 0.47,
distance: 22,
dragging: false,
pointerX: 0,
pointerY: 0
};
function resetCamera() {
cameraState.yaw = 0.58;
cameraState.pitch = 0.47;
cameraState.distance = 22;
}
function updateCamera() {
const { yaw, pitch, distance } = cameraState;
camera.position.set(
cameraTarget.x + Math.sin(yaw) * Math.cos(pitch) * distance,
cameraTarget.y + Math.sin(pitch) * distance,
cameraTarget.z + Math.cos(yaw) * Math.cos(pitch) * distance
);
camera.lookAt(cameraTarget);
}
canvas.addEventListener("pointerdown", (event) => {
cameraState.dragging = true;
cameraState.pointerX = event.clientX;
cameraState.pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!cameraState.dragging) return;
const dx = event.clientX - cameraState.pointerX;
const dy = event.clientY - cameraState.pointerY;
cameraState.pointerX = event.clientX;
cameraState.pointerY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch + dy * 0.005, 0.16, 1.22);
});
function endDrag(event) {
cameraState.dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("dblclick", resetCamera);
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
12,
31
);
}, { passive: false });
// -----------------------------------------------------------------------------
// UI controls
// -----------------------------------------------------------------------------
function setPlaying(value) {
if (value && clock >= 24) resetSimulation(0, false);
playing = value;
$("#play").textContent = playing ? "Pause" : "Play";
}
$("#play").addEventListener("click", () => setPlaying(!playing));
$("#resetView").addEventListener("click", resetCamera);
$("#speed").addEventListener("change", event => {
playbackSpeed = Number(event.target.value);
});
$("#scrub").addEventListener("input", event => {
resetSimulation(Number(event.target.value), false);
updateUI();
});
window.addEventListener("keydown", event => {
if (event.code === "Space" && event.target.tagName !== "INPUT" && event.target.tagName !== "SELECT") {
event.preventDefault();
setPlaying(!playing);
}
});
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(1, height);
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(viewport);
resize();
function updateUI() {
updateAccountCards();
updateTimeline();
renderLog();
updateBadges();
}
// -----------------------------------------------------------------------------
// Main animation loop
// -----------------------------------------------------------------------------
resetSimulation(0, false);
updateUI();
let previousTime = performance.now();
let uiAccumulator = 0;
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
if (playing) {
const nextClock = Math.min(24, clock + delta * playbackSpeed);
while (eventCursor < allEvents.length && allEvents[eventCursor].time <= nextClock) {
applyEvent(allEvents[eventCursor], true);
eventCursor++;
}
clock = nextClock;
if (clock >= 24) setPlaying(false);
}
updateCamera();
updateDayLight();
updateStorageVisuals();
updateNodes(now);
updatePulses(delta);
uiAccumulator += delta;
if (uiAccumulator > 0.09) {
updateUI();
uiAccumulator = 0;
}
updateWorldLabels();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```