Prompt specification
Build or customize the Three.js 3D scene "Barter Network Search Puzzle" 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: Barter Network Search Puzzle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/barter-network-search-puzzle-x3124
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows matching offers and wants in barter. Create a small fictional trading square with six agents and bounded inventories. Let players discover exchange cycles, compare them with pairwise swaps, and reset all holdings. Voxel style.
Working Three.js Starter (barter-network-search-puzzle-x3124):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Exchange — Barter Trading Square</title>
<style>
:root {
--ink: #17242a;
--muted: #66777b;
--paper: #f6f1e7;
--panel: #fffaf0;
--line: #d9d2c3;
--gold: #f1bd4d;
--gold-dark: #b87912;
--teal: #287d7d;
--teal-dark: #175858;
--red: #bc5148;
--green: #34795a;
--shadow: 0 5px 0 rgba(23, 36, 42, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
min-height: 100%;
margin: 0;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
border: 0;
cursor: pointer;
}
button:disabled {
cursor: not-allowed;
opacity: 0.45;
}
button:focus-visible,
select:focus-visible {
outline: 3px solid rgba(40, 125, 125, 0.35);
outline-offset: 2px;
}
#app {
display: grid;
grid-template-rows: 66px minmax(0, 1fr) 94px;
width: 100%;
height: 100vh;
}
header {
z-index: 20;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 10px 18px;
border-bottom: 3px solid var(--ink);
background: var(--panel);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
display: grid;
grid-template-columns: repeat(3, 9px);
grid-template-rows: repeat(3, 9px);
gap: 2px;
transform: rotate(-2deg);
}
.brand-mark i {
display: block;
background: var(--ink);
}
.brand-mark i:nth-child(2),
.brand-mark i:nth-child(4),
.brand-mark i:nth-child(8) {
background: var(--gold);
}
.brand-mark i:nth-child(5) {
background: var(--teal);
}
.brand h1 {
margin: 0;
font-size: clamp(17px, 2vw, 24px);
line-height: 1;
letter-spacing: -0.04em;
white-space: nowrap;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.header-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
flex-wrap: wrap;
}
.market-status {
display: flex;
align-items: center;
gap: 7px;
margin-right: 4px;
padding: 7px 10px;
border: 1px solid #c8d8c9;
border-radius: 7px;
background: #eef6e9;
color: var(--green);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.market-status::before {
width: 8px;
height: 8px;
content: "";
background: #55a66f;
box-shadow: 0 0 0 3px rgba(85, 166, 111, 0.15);
}
.btn {
min-height: 36px;
padding: 8px 12px;
border: 2px solid var(--ink);
border-radius: 5px;
background: #fff;
color: var(--ink);
box-shadow: 0 3px 0 var(--ink);
font-size: 12px;
font-weight: 850;
transition: transform 100ms ease, box-shadow 100ms ease, background 100ms ease;
}
.btn:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 4px 0 var(--ink);
}
.btn:active:not(:disabled) {
transform: translateY(3px);
box-shadow: 0 0 0 var(--ink);
}
.btn.primary {
background: var(--gold);
}
.btn.teal {
border-color: var(--teal-dark);
background: var(--teal);
color: white;
box-shadow: 0 3px 0 var(--teal-dark);
}
.btn.small {
min-height: 30px;
padding: 6px 9px;
font-size: 11px;
}
.btn.subtle {
border-color: #aaa393;
background: #f3eee4;
box-shadow: 0 3px 0 #aaa393;
}
main {
display: grid;
grid-template-columns: 258px minmax(320px, 1fr) 348px;
min-height: 0;
overflow: hidden;
}
aside {
z-index: 5;
min-height: 0;
overflow: auto;
background: var(--panel);
scrollbar-width: thin;
scrollbar-color: #bdb6a8 transparent;
}
.left-panel {
border-right: 3px solid var(--ink);
}
.right-panel {
border-left: 3px solid var(--ink);
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 15px 15px 11px;
}
.panel-heading h2,
.card h2,
.card h3 {
margin: 0;
letter-spacing: -0.025em;
}
.panel-heading h2,
.card h2 {
font-size: 15px;
}
.eyebrow {
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.unit-badge {
padding: 4px 6px;
border: 1px solid #cfc7b8;
border-radius: 4px;
background: #eee8dc;
color: var(--muted);
font-size: 9px;
font-weight: 900;
text-transform: uppercase;
}
#agentList {
display: grid;
gap: 7px;
padding: 0 11px 14px;
}
.agent-card {
position: relative;
width: 100%;
padding: 10px 10px 9px 13px;
border: 2px solid #d4cdbf;
border-radius: 6px;
background: #fffdf7;
color: var(--ink);
text-align: left;
box-shadow: 0 3px 0 #ddd5c6;
transition: transform 100ms ease, border-color 100ms ease, background 100ms ease;
}
.agent-card::before {
position: absolute;
top: 8px;
bottom: 8px;
left: 5px;
width: 4px;
border-radius: 2px;
background: var(--agent-color);
content: "";
}
.agent-card:hover {
transform: translateX(2px);
border-color: #9d9587;
}
.agent-card.active {
border-color: var(--ink);
background: #fff5d7;
box-shadow: 0 3px 0 var(--ink);
}
.agent-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.agent-name {
font-size: 13px;
font-weight: 900;
}
.agent-role {
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.stock-total {
flex: 0 0 auto;
padding: 3px 5px;
border-radius: 3px;
background: #ece6da;
color: #57676b;
font-size: 9px;
font-weight: 900;
}
.trade-badges {
display: flex;
align-items: center;
gap: 5px;
margin-top: 8px;
overflow: hidden;
font-size: 9px;
font-weight: 850;
white-space: nowrap;
}
.trade-badge {
overflow: hidden;
max-width: 95px;
padding: 3px 5px;
border-radius: 3px;
text-overflow: ellipsis;
}
.trade-badge.offer {
background: color-mix(in srgb, var(--good-color) 24%, white);
color: #28373a;
}
.trade-badge.want {
border: 1px dashed color-mix(in srgb, var(--good-color) 70%, #555);
color: #526164;
}
.trade-arrow {
color: #8c918e;
}
.conservation-note {
margin: 0 12px 16px;
padding: 11px;
border: 1px dashed #bfb7a8;
border-radius: 6px;
background: #f2ede3;
color: #667276;
font-size: 10px;
line-height: 1.45;
}
.conservation-note strong {
color: var(--green);
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #dce7df;
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
#labels {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
min-width: 92px;
padding: 6px 8px;
border: 2px solid rgba(23, 36, 42, 0.85);
border-radius: 5px;
background: rgba(255, 250, 240, 0.94);
box-shadow: 0 3px 0 rgba(23, 36, 42, 0.22);
color: var(--ink);
text-align: left;
transform: translate(-50%, -100%);
pointer-events: auto;
backdrop-filter: blur(3px);
}
.world-label.active {
border-color: var(--gold-dark);
background: #fff3ca;
}
.world-label strong {
display: block;
font-size: 10px;
line-height: 1;
}
.world-label span {
display: block;
margin-top: 4px;
color: #617074;
font-size: 8px;
font-weight: 800;
}
.stage-top {
position: absolute;
top: 12px;
left: 12px;
display: flex;
align-items: center;
gap: 7px;
pointer-events: none;
}
.stage-chip {
padding: 6px 8px;
border: 1px solid rgba(23, 36, 42, 0.35);
border-radius: 4px;
background: rgba(255, 250, 240, 0.86);
color: #435358;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.04em;
text-transform: uppercase;
backdrop-filter: blur(4px);
}
.stage-help {
position: absolute;
right: 12px;
bottom: 12px;
padding: 7px 9px;
border: 1px solid rgba(23, 36, 42, 0.25);
border-radius: 4px;
background: rgba(255, 250, 240, 0.82);
color: #4b5d61;
font-size: 9px;
font-weight: 750;
pointer-events: none;
backdrop-filter: blur(4px);
}
#toast {
position: absolute;
bottom: 48px;
left: 50%;
max-width: min(420px, 90%);
padding: 10px 13px;
border: 2px solid var(--ink);
border-radius: 5px;
background: var(--ink);
box-shadow: 0 4px 0 rgba(23, 36, 42, 0.24);
color: white;
font-size: 11px;
font-weight: 800;
text-align: center;
opacity: 0;
transform: translate(-50%, 12px);
transition: opacity 160ms ease, transform 160ms ease;
pointer-events: none;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.good {
background: #27694f;
}
#toast.warn {
background: #a44840;
}
.right-panel > * + * {
border-top: 1px solid #ddd5c7;
}
.card {
padding: 14px;
}
.card-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
margin-bottom: 11px;
}
.selected-name {
margin: 0;
font-size: 18px;
letter-spacing: -0.04em;
}
.selected-role {
margin: 3px 0 0;
color: var(--muted);
font-size: 10px;
}
.selected-avatar {
display: grid;
place-items: center;
width: 36px;
height: 36px;
border: 2px solid var(--ink);
border-radius: 4px;
background: var(--agent-color);
box-shadow: 0 3px 0 var(--ink);
color: var(--ink);
font-size: 14px;
font-weight: 950;
}
.field-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.field label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
select {
width: 100%;
height: 35px;
padding: 0 26px 0 8px;
border: 2px solid #aaa394;
border-radius: 4px;
background-color: #fffdf7;
color: var(--ink);
font-size: 11px;
font-weight: 800;
}
.posting-status {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 9px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
}
.posting-status .ready {
color: var(--green);
font-weight: 900;
}
.posting-status .invalid {
color: var(--red);
font-weight: 900;
}
.inventory-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 12px;
}
.inventory-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 4px;
min-width: 0;
padding: 7px 6px;
border: 1px solid #d6cebf;
border-radius: 4px;
background: #f7f2e8;
}
.inventory-item.empty {
opacity: 0.48;
}
.inventory-name {
overflow: hidden;
font-size: 9px;
font-weight: 850;
text-overflow: ellipsis;
white-space: nowrap;
}
.inventory-swatch {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 4px;
border: 1px solid rgba(0, 0, 0, 0.18);
background: var(--good-color);
}
.inventory-count {
flex: 0 0 auto;
color: var(--muted);
font-size: 9px;
font-weight: 900;
}
.pair-card {
background: #f3eee3;
}
.pair-row {
display: grid;
grid-template-columns: 1fr 34px 1fr;
align-items: center;
gap: 7px;
}
.pair-person {
min-width: 0;
padding: 8px;
border: 1px solid #cfc7b8;
border-radius: 4px;
background: #fffdf7;
text-align: center;
}
.pair-person strong {
display: block;
overflow: hidden;
font-size: 11px;
text-overflow: ellipsis;
}
.pair-person span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
}
.pair-symbol {
color: var(--gold-dark);
font-size: 19px;
font-weight: 950;
text-align: center;
}
#pairStatus {
margin: 9px 0;
color: var(--muted);
font-size: 9px;
font-weight: 750;
line-height: 1.4;
}
#pairStatus.match {
color: var(--green);
}
.wide-button {
width: 100%;
}
.cycle-card {
background: #fffaf0;
}
#graph {
display: block;
width: 100%;
height: 190px;
margin: 3px 0 6px;
border: 1px solid #ded6c8;
border-radius: 6px;
background:
linear-gradient(rgba(40, 125, 125, 0.04) 1px, transparent 1px),
linear-gradient(90deg, rgba(40, 125, 125, 0.04) 1px, transparent 1px),
#f8f4ea;
background-size: 16px 16px;
}
.graph-edge {
fill: none;
stroke: #9aabaa;
stroke-width: 1.7;
marker-end: url(#arrow);
}
.graph-edge.highlight {
stroke: var(--gold-dark);
stroke-width: 3.5;
}
.graph-node {
fill: #fff;
stroke: var(--ink);
stroke-width: 2;
}
.graph-node.selected {
stroke: var(--gold-dark);
stroke-width: 4;
}
.graph-label {
fill: var(--ink);
font-size: 10px;
font-weight: 900;
text-anchor: middle;
dominant-baseline: middle;
pointer-events: none;
}
.cycle-list {
display: grid;
gap: 7px;
margin-top: 9px;
}
.cycle-option {
padding: 8px;
border: 1px solid #d8d0c2;
border-radius: 5px;
background: #fffdf7;
}
.cycle-option.active {
border-color: var(--gold-dark);
background: #fff4d3;
}
.cycle-route {
overflow: hidden;
margin-bottom: 7px;
font-size: 10px;
font-weight: 900;
line-height: 1.4;
text-overflow: ellipsis;
white-space: nowrap;
}
.cycle-meta {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
}
.cycle-empty {
padding: 12px;
border: 1px dashed #bdb5a6;
border-radius: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
text-align: center;
}
footer {
z-index: 15;
display: grid;
grid-template-columns: 155px 1fr 1fr 210px;
align-items: stretch;
border-top: 3px solid var(--ink);
background: var(--panel);
}
.footer-title,
.route-card,
.balance-card {
display: flex;
align-items: center;
padding: 12px 15px;
}
.footer-title {
border-right: 1px solid #d9d1c3;
}
.footer-title strong {
display: block;
font-size: 12px;
}
.footer-title span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 9px;
}
.route-card {
gap: 12px;
border-right: 1px solid #d9d1c3;
}
.route-icon {
display: grid;
flex: 0 0 auto;
place-items: center;
width: 37px;
height: 37px;
border: 2px solid var(--ink);
border-radius: 4px;
background: #ece6d9;
color: var(--ink);
font-size: 17px;
font-weight: 950;
box-shadow: 0 3px 0 #c3baaa;
}
.route-card.cycle .route-icon {
background: #f7d876;
}
.route-card strong {
display: block;
font-size: 11px;
}
.route-card span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 9px;
line-height: 1.35;
}
.balance-card {
justify-content: center;
gap: 10px;
background: #eef5e9;
}
.balance-number {
font-size: 25px;
font-weight: 950;
letter-spacing: -0.05em;
}
.balance-card span {
color: var(--green);
font-size: 9px;
font-weight: 900;
line-height: 1.4;
text-transform: uppercase;
}
@media (max-width: 1120px) {
main {
grid-template-columns: 220px minmax(300px, 1fr) 320px;
}
.market-status {
display: none;
}
footer {
grid-template-columns: 125px 1fr 1fr 175px;
}
}
@media (max-width: 850px) {
html,
body {
overflow: auto;
}
#app {
display: block;
height: auto;
min-height: 100vh;
}
header {
position: sticky;
top: 0;
min-height: 66px;
}
.brand p {
display: none;
}
.header-actions .btn {
padding: 7px 8px;
font-size: 10px;
}
main {
display: grid;
grid-template-columns: 1fr;
overflow: visible;
}
#stage {
grid-row: 1;
height: 58vh;
min-height: 430px;
border-bottom: 3px solid var(--ink);
}
.left-panel {
grid-row: 2;
overflow: visible;
border-right: 0;
border-bottom: 3px solid var(--ink);
}
.right-panel {
grid-row: 3;
overflow: visible;
border-left: 0;
}
#agentList {
grid-template-columns: repeat(2, 1fr);
}
aside {
overflow: visible;
}
footer {
grid-template-columns: 1fr 1fr;
}
.footer-title {
display: none;
}
.balance-card {
grid-column: 1 / -1;
border-top: 1px solid #d9d1c3;
}
}
@media (max-width: 520px) {
header {
align-items: flex-start;
flex-direction: column;
gap: 8px;
}
.header-actions {
justify-content: flex-start;
}
#agentList {
grid-template-columns: 1fr;
}
footer {
grid-template-columns: 1fr;
}
.route-card {
border-right: 0;
border-bottom: 1px solid #d9d1c3;
}
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i>
<i></i><i></i><i></i>
<i></i><i></i><i></i>
</div>
<div>
<h1>Voxel Exchange</h1>
<p>Barter trading square</p>
</div>
</div>
<div class="header-actions">
<div class="market-status" id="marketStatus">Market balanced</div>
<button class="btn teal" id="findCyclesBtn">Find Cycles</button>
<button class="btn" id="resetHoldingsBtn">Reset Holdings</button>
<button class="btn subtle" id="resetViewBtn">Reset View</button>
</div>
</header>
<main>
<aside class="left-panel">
<div class="panel-heading">
<div>
<div class="eyebrow">Six participants</div>
<h2>Trading Agents</h2>
</div>
<span class="unit-badge">30 units</span>
</div>
<div id="agentList"></div>
<div class="conservation-note">
<strong>Closed economy.</strong> Every exchange conserves all 30 units.
Each trader may hold at most 5 of one good and 6 units in total.
</div>
</aside>
<section id="stage" aria-label="Interactive 3D trading square">
<canvas id="scene"></canvas>
<div id="labels"></div>
<div class="stage-top">
<div class="stage-chip">Drag to rotate</div>
<div class="stage-chip">Scroll to zoom</div>
</div>
<div class="stage-help">Click a voxel trader or their name card to inspect them.</div>
<div id="toast" role="status" aria-live="polite"></div>
</section>
<aside class="right-panel">
<section class="card">
<div class="card-header">
<div>
<div class="eyebrow">Market posting</div>
<h2 class="selected-name" id="selectedName">Ada</h2>
<p class="selected-role" id="selectedRole">Bread maker</p>
</div>
<div class="selected-avatar" id="selectedAvatar">A</div>
</div>
<div class="field-grid">
<div class="field">
<label for="offerSelect">Offers one</label>
<select id="offerSelect"></select>
</div>
<div class="field">
<label for="wantSelect">Wants one</label>
<select id="wantSelect"></select>
</div>
</div>
<div class="posting-status">
<span id="postingStatus"></span>
<button class="btn small subtle" id="resetPostingBtn">Reset posting</button>
</div>
<div class="inventory-grid" id="inventoryGrid"></div>
</section>
<section class="card pair-card">
<div class="card-header">
<div>
<div class="eyebrow">Direct negotiation</div>
<h3>Pairwise swap</h3>
</div>
</div>
<div class="pair-row">
<div class="pair-person">
<strong id="pairSourceName">Ada</strong>
<span id="pairSourceOffer">Bread</span>
</div>
<div class="pair-symbol">↔</div>
<div class="pair-person">
<strong id="pairTargetName">Bram</strong>
<span id="pairTargetOffer">Ore</span>
</div>
</div>
<div class="field" style="margin-top: 10px;">
<label for="pairTargetSelect">Swap with</label>
<select id="pairTargetSelect"></select>
</div>
<div id="pairStatus"></div>
<button class="btn primary wide-button" id="executePairBtn">Execute Swap</button>
</section>
<section class="card cycle-card">
<div class="card-header">
<div>
<div class="eyebrow">Exchange graph</div>
<h3>Discover Cycles</h3>
</div>
<button class="btn small teal" id="discoverBtn">Trace</button>
</div>
<div id="graph"></div>
<div class="cycle-list" id="cycleList"></div>
</section>
</aside>
</main>
<footer>
<div class="footer-title">
<div>
<strong>Route comparison</strong>
<span>Same units, different coordination</span>
</div>
</div>
<div class="route-card" id="pairComparison">
<div class="route-icon">↔</div>
<div>
<strong>Pairwise swap</strong>
<span id="pairComparisonText">Looking for a reciprocal offer…</span>
</div>
</div>
<div class="route-card cycle" id="cycleComparison">
<div class="route-icon">↻</div>
<div>
<strong>Exchange cycle</strong>
<span id="cycleComparisonText">Looking for an exchange cycle…</span>
</div>
</div>
<div class="balance-card">
<div class="balance-number" id="totalUnits">30</div>
<span id="balanceText">Units conserved<br />Market balanced</span>
</div>
</footer>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const GOODS = [
{ name: "Bread", short: "Br", color: 0xe4b35b },
{ name: "Ore", short: "Or", color: 0x8094a8 },
{ name: "Herbs", short: "He", color: 0x66b878 },
{ name: "Tools", short: "To", color: 0xd9795b },
{ name: "Potions", short: "Po", color: 0xae79d4 },
{ name: "Runes", short: "Ru", color: 0x53b8c5 }
];
const AGENT_DEFS = [
{
name: "Ada",
role: "Bread maker",
color: 0xd76b59,
position: [-5.8, 0, -4.5],
initial: [4, 1, 0, 0, 0, 0],
offer: 0,
want: 1
},
{
name: "Bram",
role: "Ore smith",
color: 0x557fa2,
position: [0, 0, -6.4],
initial: [1, 4, 0, 0, 0, 0],
offer: 1,
want: 0
},
{
name: "Cleo",
role: "Herb keeper",
color: 0x5ca56d,
position: [5.8, 0, -4.5],
initial: [0, 1, 4, 0, 0, 0],
offer: 2,
want: 1
},
{
name: "Dax",
role: "Tool smith",
color: 0xbf7c42,
position: [5.8, 0, 4.5],
initial: [0, 0, 1, 4, 0, 0],
offer: 3,
want: 2
},
{
name: "Elle",
role: "Potion brewer",
color: 0x8d67ad,
position: [0, 0, 6.4],
initial: [0, 0, 0, 1, 4, 0],
offer: 4,
want: 3
},
{
name: "Finn",
role: "Rune reader",
color: 0x3c929e,
position: [-5.8, 0, 4.5],
initial: [1, 3, 0, 0, 1, 0],
offer: 1,
want: 4
}
];
const state = {
agents: AGENT_DEFS.map((agent) => ({
...agent,
initial: [...agent.initial],
inventory: [...agent.initial]
})),
selected: 0,
cycles: [],
cycleOptions: [],
selectedCycle: null,
target: 1
};
const sceneHost = $("#stage");
const canvas = $("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
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 scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce7df);
scene.fog = new THREE.Fog(0xdce7df, 27, 48);
const camera = new THREE.OrthographicCamera(-10, 10, 10, -10, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0.5, 0);
let cameraYaw = 0.67;
let cameraPitch = 0.72;
let cameraZoom = 1;
function updateCamera() {
const radius = 30;
camera.position.set(
Math.sin(cameraYaw) * Math.cos(cameraPitch) * radius,
Math.sin(cameraPitch) * radius,
Math.cos(cameraYaw) * Math.cos(cameraPitch) * radius
);
camera.lookAt(cameraTarget);
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xfff8df, 0x718b7d, 2.15);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff3d2, 3.1);
sun.position.set(-10, 18, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -14;
sun.shadow.camera.right = 14;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x9dd7dc, 0.8);
rim.position.set(12, 8, -10);
scene.add(rim);
function box(w, h, d, color, x = 0, y = 0, z = 0, parent = scene, options = {}) {
const geometry = new THREE.BoxGeometry(w, h, d);
const material = options.material || new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.88,
metalness: options.metalness ?? 0,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
parent.add(mesh);
return mesh;
}
function makeGround() {
box(19.4, 0.5, 19.4, 0x8d9a82, 0, -0.48, 0, scene, {
castShadow: false
});
const tileGeometry = new THREE.BoxGeometry(0.98, 0.14, 0.98);
const tileMaterial = new THREE.MeshLambertMaterial({
color: 0xffffff,
vertexColors: true
});
const gridSize = 17;
const tiles = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
gridSize * gridSize
);
tiles.receiveShadow = true;
const dummy = new THREE.Object3D();
const color = new THREE.Color();
let index = 0;
for (let x = 0; x < gridSize; x++) {
for (let z = 0; z < gridSize; z++) {
const px = (x - (gridSize - 1) / 2) * 1.05;
const pz = (z - (gridSize - 1) / 2) * 1.05;
dummy.position.set(px, -0.07, pz);
dummy.updateMatrix();
tiles.setMatrixAt(index, dummy.matrix);
const centerDistance = Math.hypot(px, pz);
if (centerDistance < 2.6) {
color.setHex(0xd7c894);
} else if ((x + z) % 2 === 0) {
color.setHex(0xbec9b1);
} else {
color.setHex(0xcdd3bd);
}
const variation = ((x * 17 + z * 31) % 7) * 0.008;
color.offsetHSL(0, 0, variation);
tiles.setColorAt(index, color);
index++;
}
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
scene.add(tiles);
box(19.2, 0.28, 0.35, 0x806342, 0, -0.08, -9.35);
box(19.2, 0.28, 0.35, 0x806342, 0, -0.08, 9.35);
box(0.35, 0.28, 19.2, 0x806342, -9.35, -0.08, 0);
box(0.35, 0.28, 19.2, 0x806342, 9.35, -0.08, 0);
}
makeGround();
function makeCentralMonument() {
box(4.8, 0.25, 4.8, 0x9a8d71, 0, 0.1, 0);
box(4.1, 0.35, 4.1, 0xb7a687, 0, 0.34, 0);
box(3.45, 0.3, 3.45, 0x827963, 0, 0.66, 0);
box(2.85, 0.28, 2.85, 0xd0bf93, 0, 0.94, 0);
const centralMaterial = new THREE.MeshStandardMaterial({
color: 0xf1bd4d,
roughness: 0.62,
metalness: 0.08,
emissive: 0x4a2f00,
emissiveIntensity: 0.16
});
const centralToken = box(
1.15,
1.15,
1.15,
0xf1bd4d,
0,
1.72,
0,
scene,
{ material: centralMaterial }
);
centralToken.name = "centralToken";
box(0.32, 1.5, 0.32, 0x6f6758, 0, 1.25, 0);
box(1.55, 0.2, 0.2, 0xf3e3b6, 0, 2.45, 0);
box(0.2, 0.2, 1.55, 0xf3e3b6, 0, 2.45, 0);
}
makeCentralMonument();
const agentVisuals = [];
function makeAgent(agent, index) {
const group = new THREE.Group();
group.position.set(...agent.position);
group.lookAt(0, 0, 0);
group.userData.agentId = index;
scene.add(group);
const clothMaterial = new THREE.MeshStandardMaterial({
color: agent.color,
roughness: 0.86
});
const skinMaterial = new THREE.MeshStandardMaterial({
color: index % 2 === 0 ? 0xe7b58d : 0xc98f68,
roughness: 0.9
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x29363b,
roughness: 0.9
});
box(1.55, 0.22, 1.55, 0x6f756b, 0, 0.12, 0, group);
box(1.25, 0.12, 1.25, 0xd1c7ae, 0, 0.28, 0, group);
box(0.28, 0.62, 0.34, darkMaterial, -0.19, 0.62, 0, group);
box(0.28, 0.62, 0.34, darkMaterial, 0.19, 0.62, 0, group);
box(0.76, 0.86, 0.48, clothMaterial, 0, 1.23, 0, group);
box(0.26, 0.75, 0.3, clothMaterial, -0.49, 1.2, 0, group);
box(0.26, 0.75, 0.3, clothMaterial, 0.49, 1.2, 0, group);
box(0.62, 0.58, 0.56, skinMaterial, 0, 1.98, 0, group);
box(0.73, 0.2, 0.67, darkMaterial, 0, 2.3, 0, group);
box(0.73, 0.16, 0.3, clothMaterial, 0, 2.42, -0.18, group);
box(0.08, 0.08, 0.08, 0x17242a, -0.14, 2.03, -0.291, group);
box(0.08, 0.08, 0.08, 0x17242a, 0.14, 2.03, -0.291, group);
const offerMaterial = new THREE.MeshStandardMaterial({
color: GOODS[agent.offer].color,
roughness: 0.62,
emissive: GOODS[agent.offer].color,
emissiveIntensity: 0.12
});
const offerToken = box(
0.44,
0.44,
0.44,
GOODS[agent.offer].color,
0,
2.78,
0,
group,
{ material: offerMaterial }
);
const wantMaterial = new THREE.MeshBasicMaterial({
color: GOODS[agent.want].color,
wireframe: true
});
const wantToken = box(
0.35,
0.35,
0.35,
GOODS[agent.want].color,
0.95,
1.62,
-0.12,
group,
{
material: wantMaterial,
castShadow: false,
receiveShadow: false
}
);
const cargo = [];
for (let i = 0; i < GOODS.length; i++) {
const cargoMaterial = new THREE.MeshStandardMaterial({
color: GOODS[i].color,
roughness: 0.9
});
const cargoBlock = box(
0.19,
1,
0.22,
GOODS[i].color,
(i - 2.5) * 0.23,
0.3,
0.91,
group,
{ material: cargoMaterial }
);
cargo.push(cargoBlock);
}
const post = box(
0.12,
1.15,
0.12,
0x6c5940,
-0.98,
0.78,
-0.95,
group
);
box(
0.64,
0.38,
0.12,
0xf3e7c9,
-0.7,
1.39,
-0.95,
group
);
group.traverse((child) => {
if (child.isMesh) child.userData.agentId = index;
});
agentVisuals.push({
group,
offerToken,
offerMaterial,
wantToken,
wantMaterial,
cargo
});
}
state.agents.forEach(makeAgent);
const selectionMaterial = new THREE.MeshBasicMaterial({
color: 0xf1bd4d,
transparent: true,
opacity: 0.95
});
const selectionFrame = new THREE.Group();
box(1.9, 0.07, 0.09, 0xf1bd4d, 0, 0.34, -0.95, selectionFrame, {
material: selectionMaterial,
castShadow: false,
receiveShadow: false
});
box(1.9, 0.07, 0.09, 0xf1bd4d, 0, 0.34, 0.95, selectionFrame, {
material: selectionMaterial,
castShadow: false,
receiveShadow: false
});
box(0.09, 0.07, 1.9, 0xf1bd4d, -0.95, 0.34, 0, selectionFrame, {
material: selectionMaterial,
castShadow: false,
receiveShadow: false
});
box(0.09, 0.07, 1.9, 0xf1bd4d, 0.95, 0.34, 0, selectionFrame, {
material: selectionMaterial,
castShadow: false,
receiveShadow: false
});
scene.add(selectionFrame);
let routeGroup = new THREE.Group();
scene.add(routeGroup);
const flyingTokens = [];
function clearRoute() {
routeGroup.traverse((child) => {
if (child.isMesh) {
child.geometry.dispose();
if (Array.isArray(child.material)) {
child.material.forEach((material) => material.dispose());
} else {
child.material.dispose();
}
}
});
routeGroup.clear();
}
function buildRoute(cycle) {
clearRoute();
if (!cycle || cycle.length < 2) return;
const routeMaterial = new THREE.MeshStandardMaterial({
color: 0xf1bd4d,
roughness: 0.55,
emissive: 0x704400,
emissiveIntensity: 0.2
});
for (let i = 0; i < cycle.length; i++) {
const from = state.agents[cycle[i]].position;
const to = state.agents[cycle[(i + 1) % cycle.length]].position;
const fromV = new THREE.Vector3(from[0], 0.25, from[2]);
const toV = new THREE.Vector3(to[0], 0.25, to[2]);
for (let s = 1; s <= 5; s++) {
const t = s / 6;
const point = fromV.clone().lerp(toV, t);
const marker = box(
0.18,
0.12,
0.18,
0xf1bd4d,
point.x,
point.y,
point.z,
routeGroup,
{
material: routeMaterial,
castShadow: false,
receiveShadow: false
}
);
marker.scale.setScalar(0.8 + Math.sin(t * Math.PI) * 0.55);
}
}
}
function launchTransferAnimations(cycle) {
if (!cycle || cycle.length < 2) return;
cycle.forEach((agentIndex, i) => {
const nextIndex = cycle[(i + 1) % cycle.length];
const from = state.agents[agentIndex].position;
const to = state.agents[nextIndex].position;
const material = new THREE.MeshStandardMaterial({
color: GOODS[state.agents[agentIndex].offer].color,
roughness: 0.55,
emissive: GOODS[state.agents[agentIndex].offer].color,
emissiveIntensity: 0.2
});
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(0.35, 0.35, 0.35),
material
);
mesh.position.set(from[0], 1.55, from[2]);
mesh.castShadow = true;
scene.add(mesh);
flyingTokens.push({
mesh,
from: new THREE.Vector3(from[0], 1.55, from[2]),
to: new THREE.Vector3(to[0], 1.55, to[2]),
start: performance.now(),
duration: 800 + i * 35
});
});
}
function updateSceneInventory() {
state.agents.forEach((agent, agentIndex) => {
const visual = agentVisuals[agentIndex];
visual.offerMaterial.color.setHex(GOODS[agent.offer].color);
visual.offerMaterial.emissive.setHex(GOODS[agent.offer].color);
visual.wantMaterial.color.setHex(GOODS[agent.want].color);
visual.cargo.forEach((block, goodIndex) => {
const count = agent.inventory[goodIndex];
block.visible = count > 0;
block.scale.y = Math.max(0.12, count * 0.18);
block.position.y = 0.2 + block.scale.y * 0.5;
});
});
const selected = state.agents[state.selected];
selectionFrame.position.set(selected.position[0], 0, selected.position[2]);
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragging = false;
let dragMoved = false;
let pointerStart = { x: 0, y: 0 };
let lastPointer = { x: 0, y: 0 };
function pickAgent(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(scene.children, true);
for (const hit of intersections) {
let object = hit.object;
while (object) {
if (Number.isInteger(object.userData.agentId)) {
selectAgent(object.userData.agentId);
break;
}
object = object.parent;
}
if (Number.isInteger(object?.userData.agentId)) break;
}
}
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
dragMoved = false;
pointerStart = { x: event.clientX, y: event.clientY };
lastPointer = { x: event.clientX, y: event.clientY };
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointer.x;
const dy = event.clientY - lastPointer.y;
if (
Math.abs(event.clientX - pointerStart.x) +
Math.abs(event.clientY - pointerStart.y) > 5
) {
dragMoved = true;
}
cameraYaw -= dx * 0.006;
cameraPitch = THREE.MathUtils.clamp(cameraPitch + dy * 0.004, 0.38, 1.08);
lastPointer = { x: event.clientX, y: event.clientY };
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
dragging = false;
canvas.releasePointerCapture(event.pointerId);
if (!dragMoved) pickAgent(event);
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(
cameraZoom - event.deltaY * 0.001,
0.72,
1.75
);
updateCamera();
},
{ passive: false }
);
function resizeRenderer() {
const width = sceneHost.clientWidth;
const height = sceneHost.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
const aspect = width / height;
const halfHeight = aspect < 1 ? 10.5 / aspect : 10.5;
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
}
new ResizeObserver(resizeRenderer).observe(sceneHost);
resizeRenderer();
const labelElements = state.agents.map((agent, index) => {
const element = document.createElement("button");
element.className = "world-label";
element.type = "button";
element.addEventListener("click", (event) => {
event.stopPropagation();
selectAgent(index);
});
$("#labels").appendChild(element);
return element;
});
function inventorySummary(inventory) {
return GOODS
.map((good, i) => inventory[i] > 0 ? `${good.short}${inventory[i]}` : null)
.filter(Boolean)
.join(" · ");
}
function updateLabels() {
state.agents.forEach((agent, index) => {
const world = new THREE.Vector3(
agent.position[0],
3.25,
agent.position[2]
).project(camera);
const label = labelElements[index];
const visible = world.z > -1 && world.z < 1;
label.style.display = visible ? "block" : "none";
label.style.left = `${(world.x * 0.5 + 0.5) * sceneHost.clientWidth}px`;
label.style.top = `${(-world.y * 0.5 + 0.5) * sceneHost.clientHeight}px`;
label.classList.toggle("active", index === state.selected);
label.innerHTML = `
<strong>${agent.name}</strong>
<span>${inventorySummary(agent.inventory) || "Empty"}</span>
`;
});
}
function renderAgents() {
$("#agentList").innerHTML = state.agents
.map((agent, index) => `
<button
class="agent-card ${index === state.selected ? "active" : ""}"
style="--agent-color:#${agent.color.toString(16).padStart(6, "0")}"
data-agent="${index}"
>
<div class="agent-top">
<div>
<div class="agent-name">${agent.name}</div>
<div class="agent-role">${agent.role}</div>
</div>
<span class="stock-total">${agent.inventory.reduce((a, b) => a + b, 0)}/6</span>
</div>
<div class="trade-badges">
<span
class="trade-badge offer"
style="--good-color:#${GOODS[agent.offer].color.toString(16).padStart(6, "0")}"
>▲ ${GOODS[agent.offer].name}</span>
<span class="trade-arrow">for</span>
<span
class="trade-badge want"
style="--good-color:#${GOODS[agent.want].color.toString(16).padStart(6, "0")}"
>▼ ${GOODS[agent.want].name}</span>
</div>
</button>
`)
.join("");
}
function renderEditor() {
const agent = state.agents[state.selected];
$("#selectedName").textContent = agent.name;
$("#selectedRole").textContent = agent.role;
$("#selectedAvatar").textContent = agent.name.charAt(0);
$("#selectedAvatar").style.setProperty(
"--agent-color",
`#${agent.color.toString(16).padStart(6, "0")}`
);
const options = GOODS.map(
(good, index) =>
`<option value="${index}">${good.name}</option>`
).join("");
$("#offerSelect").innerHTML = options;
$("#wantSelect").innerHTML = options;
$("#offerSelect").value = agent.offer;
$("#wantSelect").value = agent.want;
const hasStock = agent.inventory[agent.offer] > 0;
$("#postingStatus").className = hasStock ? "ready" : "invalid";
$("#postingStatus").textContent = hasStock
? "Ready · one unit offered"
: "No stock for this offer";
$("#inventoryGrid").innerHTML = GOODS.map((good, index) => {
const count = agent.inventory[index];
return `
<div class="inventory-item ${count === 0 ? "empty" : ""}">
<span class="inventory-name">
<i class="inventory-swatch" style="--good-color:#${good.color.toString(16).padStart(6, "0")}"></i>
${good.name}
</span>
<span class="inventory-count">${count}/5</span>
</div>
`;
}).join("");
}
function isDirectPair(a, b) {
return (
a.offer === b.want &&
b.offer === a.want &&
a.inventory[a.offer] > 0 &&
b.inventory[b.offer] > 0
);
}
function renderPair() {
const source = state.agents[state.selected];
const target = state.agents[state.target];
$("#pairSourceName").textContent = source.name;
$("#pairSourceOffer").textContent = `Offers ${GOODS[source.offer].name}`;
$("#pairTargetName").textContent = target.name;
$("#pairTargetOffer").textContent = `Offers ${GOODS[target.offer].name}`;
const matches = isDirectPair(source, target);
const pairStatus = $("#pairStatus");
pairStatus.classList.toggle("match", matches);
if (matches) {
pairStatus.textContent =
`Ready: ${source.name} gives ${GOODS[source.offer].name}; ` +
`${target.name} gives ${GOODS[target.offer].name}.`;
} else {
const sourceOffered = GOODS[source.offer].name;
const targetOffered = GOODS[target.offer].name;
pairStatus.textContent =
`Not reciprocal. ${source.name} wants ${GOODS[source.want].name}, not ${targetOffered}; ` +
`${target.name} wants ${GOODS[target.want].name}, not ${sourceOffered}.`;
}
$("#executePairBtn").disabled = !matches;
}
function getGraphEdges() {
const edges = [];
state.agents.forEach((source, sourceIndex) => {
state.agents.forEach((target, targetIndex) => {
if (
sourceIndex !== targetIndex &&
target.want === source.offer &&
source.inventory[source.offer] > 0
) {
edges.push({ from: sourceIndex, to: targetIndex });
}
});
});
return edges;
}
function detectCycles() {
const edges = getGraphEdges();
const adjacency = state.agents.map(() => []);
edges.forEach((edge) => adjacency[edge.from].push(edge.to));
const cycles = [];
function visit(start, current, path, visited) {
for (const next of adjacency[current]) {
if (next === start && path.length >= 2) {
cycles.push([...path]);
continue;
}
if (next < start || visited.has(next)) continue;
visited.add(next);
path.push(next);
visit(start, next, path, visited);
path.pop();
visited.delete(next);
}
}
for (let start = 0; start < state.agents.length; start++) {
visit(start, start, [start], new Set([start]));
}
return cycles.sort((a, b) => b.length - a.length);
}
function graphPositions() {
const centerX = 150;
const centerY = 94;
const radiusX = 101;
const radiusY = 69;
return state.agents.map((_, index) => {
const angle = -Math.PI / 2 + (index / state.agents.length) * Math.PI * 2;
return {
x: centerX + Math.cos(angle) * radiusX,
y: centerY + Math.sin(angle) * radiusY
};
});
}
function renderGraph() {
const positions = graphPositions();
const edges = getGraphEdges();
const selectedCycle = state.selectedCycle;
const cycleEdges = new Set();
if (selectedCycle) {
selectedCycle.forEach((from, index) => {
cycleEdges.add(`${from}-${selectedCycle[(index + 1) % selectedCycle.length]}`);
});
}
const edgePaths = edges.map((edge) => {
const a = positions[edge.from];
const b = positions[edge.to];
const reverseExists = edges.some(
(other) => other.from === edge.to && other.to === edge.from
);
let controlX = (a.x + b.x) / 2;
let controlY = (a.y + b.y) / 2;
if (reverseExists) {
const dx = b.x - a.x;
const dy = b.y - a.y;
const length = Math.hypot(dx, dy) || 1;
const side = edge.from < edge.to ? 1 : -1;
controlX += (-dy / length) * 12 * side;
controlY += (dx / length) * 12 * side;
}
const highlighted = cycleEdges.has(`${edge.from}-${edge.to}`);
const className = highlighted
? "graph-edge highlight"
: "graph-edge";
return `
<path
class="${className}"
d="M ${a.x} ${a.y} Q ${controlX} ${controlY} ${b.x} ${b.y}"
marker-end="url(#arrow)"
>
<title>${state.agents[edge.from].name} → ${state.agents[edge.to].name}</title>
</path>
`;
}).join("");
const nodes = state.agents.map((agent, index) => {
const point = positions[index];
const selectedClass = index === state.selected ? " selected" : "";
return `
<g>
<circle
class="graph-node${selectedClass}"
cx="${point.x}"
cy="${point.y}"
r="15"
fill="#${agent.color.toString(16).padStart(6, "0")}"
/>
<text class="graph-label" x="${point.x}" y="${point.y + 0.5}">
${agent.name.charAt(0)}
</text>
<text
x="${point.x}"
y="${point.y + 27}"
fill="#17242a"
font-size="8"
font-weight="900"
text-anchor="middle"
>${agent.name}</text>
</g>
`;
}).join("");
$("#graph").innerHTML = `
<svg viewBox="0 0 300 188" role="img" aria-label="Directed barter exchange graph">
<defs>
<marker
id="arrow"
markerWidth="7"
markerHeight="7"
refX="6"
refY="3.5"
orient="auto"
>
<path d="M0,0 L7,3.5 L0,7 Z" fill="#809795"></path>
</marker>
</defs>
${edgePaths}
${nodes}
</svg>
`;
}
function renderCycleList() {
state.cycleOptions = state.cycles;
if (!state.cycles.length) {
$("#cycleList").innerHTML = `
<div class="cycle-empty">
No executable exchange cycle was found.
Change an offer or want, then trace the graph again.
</div>
`;
return;
}
$("#cycleList").innerHTML = state.cycles.map((cycle, optionIndex) => {
const route = cycle
.map((index) => state.agents[index].name)
.join(" → ") + ` → ${state.agents[cycle[0]].name}`;
const active =
state.selectedCycle &&
cycle.length === state.selectedCycle.length &&
cycle.every((index, i) => index === state.selectedCycle[i]);
const label = cycle.length === 2 ? "Run pairwise swap" : "Run multilateral cycle";
return `
<div class="cycle-option ${active ? "active" : ""}">
<div class="cycle-route">${route}</div>
<div class="cycle-meta">
<span>${cycle.length} traders · ${cycle.length} transfers</span>
<button
class="btn small ${cycle.length === 2 ? "primary" : "teal"}"
data-cycle-option="${optionIndex}"
>${label}</button>
</div>
</div>
`;
}).join("");
}
function renderComparison() {
const pair = state.cycles.find((cycle) => cycle.length === 2);
const longCycle = state.cycles.find((cycle) => cycle.length > 2);
if (pair) {
const names = pair.map((index) => state.agents[index].name);
$("#pairComparisonText").textContent =
`${names[0]} ↔ ${names[1]} · one direct reciprocal trade`;
} else {
$("#pairComparisonText").textContent =
"No reciprocal pair in the current postings";
}
if (longCycle) {
const names = longCycle.map((index) => state.agents[index].name);
$("#cycleComparisonText").textContent =
`${names.join(" → ")} → ${names[0]} · simultaneous clearing`;
} else {
$("#cycleComparisonText").textContent =
"No multilateral exchange cycle found";
}
const total = state.agents.reduce(
(sum, agent) => sum + agent.inventory.reduce((a, b) => a + b, 0),
0
);
$("#totalUnits").textContent = total;
$("#balanceText").innerHTML =
"Units conserved<br />Market balanced";
$("#marketStatus").textContent = total === 30 ? "Market balanced" : "Check inventory";
}
function renderAll() {
renderAgents();
renderEditor();
renderPair();
renderGraph();
renderCycleList();
renderComparison();
updateSceneInventory();
}
function selectAgent(index) {
state.selected = index;
const possibleTarget = state.agents.findIndex(
(agent, agentIndex) =>
agentIndex !== index &&
isDirectPair(state.agents[index], agent)
);
if (possibleTarget >= 0) {
state.target = possibleTarget;
}
renderAll();
}
function populateTargetSelect() {
$("#pairTargetSelect").innerHTML = state.agents
.map(
(agent, index) =>
`<option value="${index}" ${index === state.target ? "selected" : ""}>
${agent.name} — ${agent.role}
</option>`
)
.join("");
if (state.target === state.selected) {
state.target = (state.selected + 1) % state.agents.length;
$("#pairTargetSelect").value = state.target;
}
}
function announce(message, tone = "") {
const toast = $("#toast");
toast.textContent = message;
toast.className = `show ${tone}`;
clearTimeout(announce.timeout);
announce.timeout = setTimeout(() => {
toast.className = "";
}, 2600);
}
function discoverCycles(notify = false) {
state.cycles = detectCycles();
const longCycle = state.cycles.find((cycle) => cycle.length > 2);
state.selectedCycle = longCycle || state.cycles[0] || null;
buildRoute(state.selectedCycle);
renderAll();
if (notify) {
if (longCycle) {
announce(
`Found a ${longCycle.length}-trader exchange cycle and a direct pairwise swap.`,
"good"
);
} else if (state.cycles.length) {
announce("Found a reciprocal pairwise swap, but no longer cycle.", "good");
} else {
announce("No exchange cycle exists with these postings.", "warn");
}
}
}
function simulateCycle(cycle) {
if (!cycle || cycle.length < 2) {
return { valid: false, reason: "The cycle is empty." };
}
const next = state.agents.map((agent) => [...agent.inventory]);
for (let i = 0; i < cycle.length; i++) {
const sourceIndex = cycle[i];
const recipientIndex = cycle[(i + 1) % cycle.length];
const source = state.agents[sourceIndex];
const recipient = state.agents[recipientIndex];
if (recipient.want !== source.offer) {
return {
valid: false,
reason: `${recipient.name} no longer wants ${GOODS[source.offer].name}.`
};
}
if (next[sourceIndex][source.offer] < 1) {
return {
valid: false,
reason: `${source.name} has no ${GOODS[source.offer].name} to offer.`
};
}
next[sourceIndex][source.offer] -= 1;
next[recipientIndex][source.offer] += 1;
}
for (let i = 0; i < next.length; i++) {
const total = next[i].reduce((sum, count) => sum + count, 0);
if (total > 6) {
return {
valid: false,
reason: `${state.agents[i].name} would exceed the 6-unit inventory limit.`
};
}
if (next[i].some((count) => count > 5)) {
return {
valid: false,
reason: `${state.agents[i].name} would exceed the 5-unit per-good limit.`
};
}
}
return { valid: true, next };
}
function executeCycle(cycle, label) {
const simulation = simulateCycle(cycle);
if (!simulation.valid) {
announce(simulation.reason, "warn");
return;
}
state.agents.forEach((agent, index) => {
agent.inventory = simulation.next[index];
});
launchTransferAnimations(cycle);
renderAll();
announce(`${label} completed. All units were conserved.`, "good");
}
$("#agentList").addEventListener("click", (event) => {
const card = event.target.closest("[data-agent]");
if (card) selectAgent(Number(card.dataset.agent));
});
$("#offerSelect").addEventListener("change", (event) => {
state.agents[state.selected].offer = Number(event.target.value);
discoverCycles(false);
announce(`${state.agents[state.selected].name} now offers ${GOODS[state.agents[state.selected].offer].name}.`);
});
$("#wantSelect").addEventListener("change", (event) => {
state.agents[state.selected].want = Number(event.target.value);
discoverCycles(false);
announce(`${state.agents[state.selected].name} now wants ${GOODS[state.agents[state.selected].want].name}.`);
});
$("#resetPostingBtn").addEventListener("click", () => {
const agent = state.agents[state.selected];
agent.offer = AGENT_DEFS[state.selected].offer;
agent.want = AGENT_DEFS[state.selected].want;
discoverCycles(false);
announce(`${agent.name}'s posting was restored.`);
});
$("#pairTargetSelect").addEventListener("change", (event) => {
state.target = Number(event.target.value);
renderPair();
});
$("#executePairBtn").addEventListener("click", () => {
const source = state.agents[state.selected];
const target = state.agents[state.target];
if (!isDirectPair(source, target)) {
announce("That pair does not have reciprocal offers.", "warn");
return;
}
executeCycle(
[state.selected, state.target],
`${source.name} ↔ ${target.name} pairwise swap`
);
});
$("#cycleList").addEventListener("click", (event) => {
const button = event.target.closest("[data-cycle-option]");
if (!button) return;
const cycle = state.cycleOptions[Number(button.dataset.cycleOption)];
state.selectedCycle = cycle;
buildRoute(cycle);
renderAll();
});
$("#findCyclesBtn").addEventListener("click", () => discoverCycles(true));
$("#discoverBtn").addEventListener("click", () => discoverCycles(true));
$("#resetHoldingsBtn").addEventListener("click", () => {
state.agents.forEach((agent, index) => {
agent.inventory = [...AGENT_DEFS[index].initial];
});
renderAll();
announce("All 30 holdings were restored. Market postings were preserved.", "good");
});
$("#resetViewBtn").addEventListener("click", () => {
cameraYaw = 0.67;
cameraPitch = 0.72;
cameraZoom = 1;
updateCamera();
announce("Camera view reset.");
});
populateTargetSelect();
discoverCycles(false);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const time = clock.getElapsedTime();
agentVisuals.forEach((visual, index) => {
const phase = index * 0.75;
visual.offerToken.position.y = 2.78 + Math.sin(time * 2.1 + phase) * 0.09;
visual.offerToken.rotation.y = Math.sin(time * 0.8 + phase) * 0.16;
visual.wantToken.rotation.y = time * 0.55 + phase;
visual.wantToken.rotation.x = Math.sin(time * 0.7 + phase) * 0.12;
});
const centralToken = scene.getObjectByName("centralToken");
if (centralToken) {
centralToken.rotation.y = Math.sin(time * 0.7) * 0.18;
centralToken.position.y = 1.72 + Math.sin(time * 1.8) * 0.06;
}
selectionMaterial.opacity = 0.78 + Math.sin(time * 3.4) * 0.18;
const now = performance.now();
for (let i = flyingTokens.length - 1; i >= 0; i--) {
const flight = flyingTokens[i];
const progress = (now - flight.start) / flight.duration;
if (progress >= 1) {
scene.remove(flight.mesh);
flight.mesh.geometry.dispose();
flight.mesh.material.dispose();
flyingTokens.splice(i, 1);
continue;
}
const eased = progress * progress * (3 - 2 * progress);
flight.mesh.position.lerpVectors(flight.from, flight.to, eased);
flight.mesh.position.y += Math.sin(eased * Math.PI) * 1.4;
flight.mesh.rotation.x += 0.08;
flight.mesh.rotation.y += 0.11;
}
updateLabels();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```