Prompt specification
Build or customize the Three.js 3D scene "Market Exchange Cycle" 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: Market Exchange Cycle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/market-exchange-cycle-x3123
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts a four-stall voxel barter market. Place the stalls around an open square: one offers grain and wants cloth, another offers cloth and wants pottery, the third offers pottery and wants fruit, and the last offers fruit and wants grain. Put separate offer and want trays on every counter. First show why none of the neighboring direct swaps satisfies both participants. Then animate a coordinated four-way exchange, moving the actual goods simultaneously around the square. Each stall ends with the item it requested, and all token counts remain visible through the transaction.
Working Three.js Starter (market-exchange-cycle-x3123):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The Four-Stall Barter Loop</title>
<style>
:root {
--ink: #18312e;
--panel: rgba(250, 247, 235, 0.93);
--line: rgba(24, 49, 46, 0.18);
--grain: #e8b94f;
--cloth: #4da5dc;
--pottery: #d77749;
--fruit: #e45559;
--danger: #b9403f;
--success: #287a58;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #c9d9d3;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
button {
font: inherit;
}
.panel {
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.62);
box-shadow: 0 14px 40px rgba(28, 49, 45, 0.18);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
#title-card {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
width: 330px;
padding: 17px 18px 15px;
border-radius: 18px;
}
.eyebrow {
margin: 0 0 5px;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.18em;
text-transform: uppercase;
opacity: 0.62;
}
h1 {
margin: 0;
font-size: clamp(22px, 2.2vw, 32px);
line-height: 1;
letter-spacing: -0.04em;
}
.subtitle {
margin: 8px 0 12px;
font-size: 12px;
line-height: 1.45;
opacity: 0.76;
}
.title-actions {
display: flex;
gap: 8px;
align-items: center;
}
.small-button,
.action-button {
border: 0;
border-radius: 10px;
cursor: pointer;
font-weight: 800;
transition: transform 150ms ease, background 150ms ease, opacity 150ms ease;
}
.small-button {
padding: 7px 10px;
color: var(--ink);
background: rgba(24, 49, 46, 0.08);
font-size: 11px;
}
.small-button:hover,
.action-button:hover:not(:disabled) {
transform: translateY(-1px);
}
#inventory {
position: fixed;
z-index: 10;
top: 18px;
right: 18px;
width: 286px;
padding: 13px;
border-radius: 18px;
}
.inventory-heading {
display: flex;
justify-content: space-between;
align-items: center;
margin: 0 2px 9px;
}
.inventory-heading strong {
font-size: 12px;
letter-spacing: 0.04em;
}
.live-dot {
display: inline-flex;
align-items: center;
gap: 5px;
font-size: 10px;
font-weight: 800;
opacity: 0.66;
}
.live-dot::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: #45a375;
box-shadow: 0 0 0 3px rgba(69, 163, 117, 0.16);
}
.stock-card {
--accent: #888;
padding: 9px 10px;
margin-top: 7px;
border: 1px solid var(--line);
border-left: 4px solid var(--accent);
border-radius: 11px;
background: rgba(255, 255, 255, 0.44);
}
.stock-title {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 6px;
}
.stock-title b {
font-size: 12px;
}
.stock-title span {
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
opacity: 0.55;
}
.stock-line {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-top: 3px;
font-size: 11px;
}
.stock-line span:first-child {
opacity: 0.68;
}
.stock-line b {
font-variant-numeric: tabular-nums;
}
.stock-progress {
height: 4px;
margin-top: 7px;
overflow: hidden;
border-radius: 10px;
background: rgba(24, 49, 46, 0.1);
}
.stock-progress > div {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--accent);
transition: width 180ms ease;
}
#story {
position: fixed;
z-index: 11;
left: 50%;
bottom: 18px;
width: min(760px, calc(100vw - 36px));
transform: translateX(-50%);
padding: 15px 17px;
border-radius: 18px;
}
#story-top {
display: grid;
grid-template-columns: auto 1fr auto;
gap: 12px;
align-items: start;
}
#phase-badge {
min-width: 92px;
padding: 7px 9px;
border-radius: 9px;
background: var(--ink);
color: #fff;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.12em;
text-align: center;
text-transform: uppercase;
}
#headline {
margin: 0;
font-size: 17px;
line-height: 1.2;
letter-spacing: -0.02em;
}
#detail {
margin: 4px 0 0;
font-size: 11px;
line-height: 1.45;
opacity: 0.72;
}
.action-button {
padding: 10px 13px;
color: #fff;
background: var(--ink);
white-space: nowrap;
font-size: 11px;
}
.action-button:disabled {
cursor: default;
opacity: 0.48;
}
#proof-matrix {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
margin-top: 11px;
}
.proof-row {
min-height: 44px;
padding: 7px 8px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.42);
transition: background 180ms ease, border-color 180ms ease;
}
.proof-row b {
display: block;
margin-bottom: 3px;
font-size: 10px;
}
.proof-row span {
display: block;
font-size: 9px;
line-height: 1.35;
opacity: 0.63;
}
.proof-row.fail {
border-color: rgba(185, 64, 63, 0.35);
background: rgba(185, 64, 63, 0.08);
}
.proof-row.fail span {
color: var(--danger);
opacity: 1;
font-weight: 750;
}
#proof-summary {
margin: 8px 1px 0;
font-size: 10px;
font-weight: 850;
opacity: 0.7;
}
#labels {
position: fixed;
inset: 0;
z-index: 5;
overflow: hidden;
pointer-events: none;
}
.tray-label,
.shipment-label,
#verdict {
position: absolute;
left: 0;
top: 0;
transform: translate(-50%, -50%);
white-space: nowrap;
border-radius: 9px;
box-shadow: 0 6px 18px rgba(24, 49, 46, 0.18);
}
.tray-label {
padding: 5px 7px;
border: 1px solid rgba(255, 255, 255, 0.65);
background: rgba(250, 247, 235, 0.9);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.01em;
}
.tray-label .tag {
margin-right: 3px;
font-size: 7px;
font-weight: 950;
letter-spacing: 0.08em;
opacity: 0.56;
}
.tray-label small {
display: block;
margin-top: 2px;
font-size: 7px;
font-weight: 750;
opacity: 0.62;
text-align: center;
}
.shipment-label {
padding: 5px 8px;
border: 2px solid currentColor;
background: rgba(250, 247, 235, 0.94);
font-size: 9px;
font-weight: 950;
letter-spacing: 0.06em;
text-transform: uppercase;
}
#verdict {
display: none;
max-width: 250px;
padding: 9px 11px;
border: 1px solid rgba(185, 64, 63, 0.28);
background: rgba(255, 241, 235, 0.96);
color: var(--danger);
font-size: 10px;
font-weight: 800;
line-height: 1.35;
text-align: center;
}
#loading {
position: fixed;
z-index: 30;
inset: 0;
display: grid;
place-items: center;
background: #d9e4de;
font-size: 13px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
@media (max-width: 820px) {
#title-card {
width: 260px;
padding: 13px;
}
#inventory {
width: 235px;
padding: 10px;
}
#story-top {
grid-template-columns: auto 1fr;
}
#exchange-button {
grid-column: 1 / -1;
width: 100%;
}
#proof-matrix {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 560px) {
#title-card {
top: 8px;
left: 8px;
width: 190px;
}
#title-card .subtitle,
#title-card .eyebrow {
display: none;
}
#inventory {
top: 8px;
right: 8px;
width: 175px;
}
.stock-card {
padding: 6px 7px;
}
.stock-line {
font-size: 9px;
}
#story {
bottom: 8px;
width: calc(100vw - 16px);
padding: 11px;
}
#headline {
font-size: 14px;
}
#detail {
font-size: 9px;
}
#proof-matrix {
display: none;
}
}
</style>
</head>
<body>
<div id="loading">Building the barter square…</div>
<header id="title-card" class="panel">
<p class="eyebrow">A voxel exchange study</p>
<h1>The Four-Stall Loop</h1>
<p class="subtitle">
Every neighboring trade leaves one trader disappointed.
Follow the missing links to reveal the coordinated four-way exchange.
</p>
<div class="title-actions">
<button id="camera-button" class="small-button">Reset camera</button>
<button id="proof-button" class="small-button">Replay direct-swap proof</button>
</div>
</header>
<aside id="inventory" class="panel" aria-label="Live inventory">
<div class="inventory-heading">
<strong>LIVE TOKEN COUNTS</strong>
<span class="live-dot">visible</span>
</div>
<div id="stock-cards"></div>
</aside>
<div id="labels" aria-hidden="true"></div>
<section id="story" class="panel" aria-live="polite">
<div id="story-top">
<div id="phase-badge">Proof</div>
<div>
<h2 id="headline">Testing the neighboring trades</h2>
<p id="detail">Each trial swaps only two adjacent stalls.</p>
</div>
<button id="exchange-button" class="action-button">Skip to four-way exchange</button>
</div>
<div id="proof-matrix"></div>
<div id="proof-summary">Testing whether any adjacent swap satisfies both participants…</div>
</section>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and shared data
// -------------------------------------------------------------------------
const phaseBadge = document.querySelector("#phase-badge");
const headline = document.querySelector("#headline");
const detail = document.querySelector("#detail");
const proofMatrix = document.querySelector("#proof-matrix");
const proofSummary = document.querySelector("#proof-summary");
const exchangeButton = document.querySelector("#exchange-button");
const proofButton = document.querySelector("#proof-button");
const cameraButton = document.querySelector("#camera-button");
const stockCards = document.querySelector("#stock-cards");
const labelsRoot = document.querySelector("#labels");
const loading = document.querySelector("#loading");
const verdict = document.createElement("div");
verdict.id = "verdict";
labelsRoot.appendChild(verdict);
const goods = {
grain: {
name: "Grain",
color: 0xe8b94f,
css: "#e8b94f",
glyph: "▦"
},
cloth: {
name: "Cloth",
color: 0x4da5dc,
css: "#4da5dc",
glyph: "▤"
},
pottery: {
name: "Pottery",
color: 0xd77749,
css: "#d77749",
glyph: "▣"
},
fruit: {
name: "Fruit",
color: 0xe45559,
css: "#e45559",
glyph: "●"
}
};
const stalls = [
{
letter: "A",
name: "Grain stall",
offer: "grain",
want: "cloth",
qty: 3,
wantQty: 2,
position: new THREE.Vector3(0, 0, 4.25),
rotation: Math.PI
},
{
letter: "B",
name: "Cloth stall",
offer: "cloth",
want: "pottery",
qty: 2,
wantQty: 4,
position: new THREE.Vector3(4.25, 0, 0),
rotation: -Math.PI / 2
},
{
letter: "C",
name: "Pottery stall",
offer: "pottery",
want: "fruit",
qty: 4,
wantQty: 3,
position: new THREE.Vector3(0, 0, -4.25),
rotation: 0
},
{
letter: "D",
name: "Fruit stall",
offer: "fruit",
want: "grain",
qty: 3,
wantQty: 3,
position: new THREE.Vector3(-4.25, 0, 0),
rotation: Math.PI / 2
}
];
// The desired exchange is a complete cycle around the square.
// A's grain goes to D, B's cloth to A, C's pottery to B, D's fruit to C.
const transferTarget = [3, 0, 1, 2];
const directPairs = [
{
i: 0,
j: 1,
result: "A gets cloth ✓ · B gets grain ✗",
explanation:
"A receives the cloth it wants, but B receives grain instead of pottery."
},
{
i: 1,
j: 2,
result: "B gets pottery ✓ · C gets cloth ✗",
explanation:
"B receives the pottery it wants, but C receives cloth instead of fruit."
},
{
i: 2,
j: 3,
result: "C gets fruit ✓ · D gets pottery ✗",
explanation:
"C receives the fruit it wants, but D receives pottery instead of grain."
},
{
i: 3,
j: 0,
result: "D gets grain ✓ · A gets fruit ✗",
explanation:
"D receives the grain it wants, but A receives fruit instead of cloth."
}
];
// -------------------------------------------------------------------------
// Renderer, scene, lighting, and direct camera controls
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xc9d9d3);
scene.fog = new THREE.Fog(0xc9d9d3, 18, 32);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
document.body.prepend(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const orbit = {
theta: 0.72,
phi: 0.91,
radius: 13.8,
target: new THREE.Vector3(0, 1.15, 0)
};
const defaultOrbit = { ...orbit, target: orbit.target.clone() };
function updateCamera() {
const spherical = new THREE.Spherical(
orbit.radius,
orbit.phi,
orbit.theta
);
camera.position.setFromSpherical(spherical).add(orbit.target);
camera.lookAt(orbit.target);
}
function resetCamera() {
orbit.theta = defaultOrbit.theta;
orbit.phi = defaultOrbit.phi;
orbit.radius = defaultOrbit.radius;
orbit.target.copy(defaultOrbit.target);
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi + dy * 0.005, 0.38, 1.34);
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.008,
9,
20
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
cameraButton.addEventListener("click", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") resetCamera();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
const hemi = new THREE.HemisphereLight(0xf5fbff, 0x80705b, 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff2d8, 3.1);
sun.position.set(8, 13, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0008;
scene.add(sun);
// -------------------------------------------------------------------------
// Procedural voxel helpers
// -------------------------------------------------------------------------
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
function material(color, opacity = 1) {
const key = `${color}_${opacity}`;
if (!materialCache.has(key)) {
materialCache.set(
key,
new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0,
transparent: opacity < 1,
opacity,
depthWrite: opacity >= 1
})
);
}
return materialCache.get(key);
}
function box(
parent,
width,
height,
depth,
color,
x = 0,
y = 0,
z = 0,
opacity = 1
) {
const mesh = new THREE.Mesh(cubeGeometry, material(color, opacity));
mesh.scale.set(width, height, depth);
mesh.position.set(x, y, z);
mesh.castShadow = opacity >= 1;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeSignTexture(title, subtitle, accent) {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 192;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#faf5e6";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = accent;
ctx.fillRect(0, 0, 18, canvas.height);
ctx.fillRect(0, canvas.height - 12, canvas.width, 12);
ctx.fillStyle = "#18312e";
ctx.font = "900 62px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.fillText(title, canvas.width / 2, 88);
ctx.fillStyle = "#53625f";
ctx.font = "700 27px system-ui, sans-serif";
ctx.fillText(subtitle, canvas.width / 2, 139);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
return texture;
}
function makeToken(type, mode = "solid") {
const group = new THREE.Group();
const opacity = mode === "ghost" ? 0.23 : mode === "trial" ? 0.62 : 1;
function part(w, h, d, color, x, y, z) {
return box(group, w, h, d, color, x, y, z, opacity);
}
if (type === "grain") {
part(0.23, 0.28, 0.20, 0xe8b94f, 0, 0.14, 0);
part(0.16, 0.09, 0.15, 0xf3d77c, 0, 0.32, 0);
part(0.035, 0.24, 0.205, 0xc08d27, 0, 0.14, 0);
} else if (type === "cloth") {
part(0.29, 0.07, 0.23, 0x4da5dc, 0, 0.055, 0);
part(0.25, 0.07, 0.21, 0x69b7e7, 0.01, 0.125, 0);
part(0.21, 0.07, 0.18, 0x388fc8, -0.01, 0.195, 0);
part(0.08, 0.075, 0.235, 0xe6f3f7, 0.10, 0.13, 0);
} else if (type === "pottery") {
part(0.22, 0.23, 0.20, 0xd77749, 0, 0.115, 0);
part(0.28, 0.08, 0.25, 0xe18b5f, 0, 0.25, 0);
part(0.12, 0.13, 0.12, 0xc96138, 0, 0.35, 0);
part(0.15, 0.025, 0.15, 0x9e472c, 0, 0.42, 0);
} else {
part(0.25, 0.24, 0.25, 0xe45559, 0, 0.13, 0);
part(0.20, 0.19, 0.22, 0xf06d6e, -0.015, 0.17, -0.01);
part(0.055, 0.09, 0.055, 0x467b48, 0, 0.29, 0);
part(0.10, 0.035, 0.05, 0x5f934b, 0.035, 0.32, 0);
}
group.traverse((object) => {
if (object.isMesh) {
object.castShadow = mode === "solid";
object.receiveShadow = true;
}
});
return group;
}
function slotFor(qty, index) {
if (qty === 1) return new THREE.Vector3(0, 0.07, 0);
if (qty === 2) {
return new THREE.Vector3(index === 0 ? -0.19 : 0.19, 0.07, 0);
}
if (qty === 3) {
const positions = [
[-0.19, -0.13],
[0.19, -0.13],
[0, 0.17]
];
return new THREE.Vector3(positions[index][0], 0.07, positions[index][1]);
}
const positions = [
[-0.19, -0.13],
[0.19, -0.13],
[-0.19, 0.17],
[0.19, 0.17]
];
return new THREE.Vector3(positions[index][0], 0.07, positions[index][1]);
}
// -------------------------------------------------------------------------
// Floor and voxel market
// -------------------------------------------------------------------------
box(scene, 13.2, 0.22, 13.2, 0xa99978, 0, -0.17, 0);
const tileColors = [0xd8c9a7, 0xe5d8b8, 0xcdbf9f];
for (let x = -5.5; x <= 5.5; x += 1) {
for (let z = -5.5; z <= 5.5; z += 1) {
const inCenter = Math.abs(x) <= 2.5 && Math.abs(z) <= 2.5;
const color = inCenter
? (Math.round(x + z) % 2 === 0 ? 0xf0dfb8 : 0xe6d3a8)
: tileColors[Math.abs(Math.round(x + z)) % tileColors.length];
box(scene, 0.96, 0.055, 0.96, color, x, -0.045, z);
}
}
// Center border, leaving the square open.
box(scene, 5.5, 0.07, 0.12, 0xa89772, 0, 0.015, 2.7);
box(scene, 5.5, 0.07, 0.12, 0xa89772, 0, 0.015, -2.7);
box(scene, 0.12, 0.07, 5.5, 0xa89772, 2.7, 0.015, 0);
box(scene, 0.12, 0.07, 5.5, 0xa89772, -2.7, 0.015, 0);
// Small colored center markers.
box(scene, 0.58, 0.055, 0.58, goods.grain.color, -0.72, 0.02, -0.72);
box(scene, 0.58, 0.055, 0.58, goods.cloth.color, 0.72, 0.02, -0.72);
box(scene, 0.58, 0.055, 0.58, goods.pottery.color, 0.72, 0.02, 0.72);
box(scene, 0.58, 0.055, 0.58, goods.fruit.color, -0.72, 0.02, 0.72);
function buildStall(stall, index) {
const group = new THREE.Group();
group.position.copy(stall.position);
group.rotation.y = stall.rotation;
scene.add(group);
stall.group = group;
const accent = goods[stall.offer].color;
// Booth base, back wall, counter, and uprights.
box(group, 3.25, 0.22, 2.15, 0x8d704e, 0, 0.12, -0.08);
box(group, 3.05, 1.42, 0.16, 0xd2b987, 0, 1.83, -0.78);
box(group, 2.95, 0.22, 0.88, 0xb38755, 0, 0.98, 0.92);
box(group, 2.86, 0.13, 0.79, 0xe0bd82, 0, 1.115, 0.92);
box(group, 2.70, 0.57, 0.08, accent, 0, 0.68, 1.39);
for (const x of [-1.48, 1.48]) {
box(group, 0.16, 3.08, 0.16, 0x8f6e48, x, 1.58, 0.72);
box(group, 0.16, 3.08, 0.16, 0x8f6e48, x, 1.58, -0.72);
}
// Striped voxel canopy.
const stripColors = [accent, 0xf5e6c5];
for (let strip = 0; strip < 8; strip++) {
box(
group,
0.405,
0.20,
1.92,
stripColors[strip % 2],
-1.4175 + strip * 0.405,
3.18,
-0.05
);
}
box(group, 3.35, 0.13, 0.16, 0x7e6043, 0, 3.13, 0.88);
box(group, 3.35, 0.13, 0.16, 0x7e6043, 0, 3.13, -0.98);
// Blocky vendor.
box(group, 0.48, 0.66, 0.36, accent, 0, 1.72, -0.36);
box(group, 0.38, 0.38, 0.35, 0xdca77c, 0, 2.28, -0.34);
box(group, 0.42, 0.10, 0.38, 0x59483b, 0, 2.50, -0.34);
box(group, 0.08, 0.08, 0.025, 0x263c39, -0.09, 2.30, -0.155);
box(group, 0.08, 0.08, 0.025, 0x263c39, 0.09, 2.30, -0.155);
// Two physically separate trays.
function makeTray(x, isWant) {
const tray = new THREE.Group();
tray.position.set(x, 1.23, 1.03);
group.add(tray);
box(tray, 0.96, 0.08, 0.63, 0x6c5138, 0, 0, 0);
box(tray, 0.96, 0.12, 0.07, 0x9d7649, 0, 0.06, -0.28);
box(tray, 0.96, 0.12, 0.07, 0x9d7649, 0, 0.06, 0.28);
box(tray, 0.07, 0.12, 0.56, 0x9d7649, -0.445, 0.06, 0);
box(tray, 0.07, 0.12, 0.56, 0x9d7649, 0.445, 0.06, 0);
if (isWant) {
const outline = new THREE.Mesh(
new THREE.BoxGeometry(0.83, 0.035, 0.48),
new THREE.MeshBasicMaterial({
color: goods[stall.want].color,
transparent: true,
opacity: 0.18
})
);
outline.position.y = 0.055;
tray.add(outline);
}
return tray;
}
stall.offerRoot = makeTray(-0.73, false);
stall.wantRoot = makeTray(0.73, true);
stall.offerTokens = [];
stall.ghostTokens = [];
stall.remaining = stall.qty;
stall.received = 0;
// World-facing sign.
const signTexture = makeSignTexture(
`${stall.letter} · ${goods[stall.offer].name.toUpperCase()} STALL`,
`OFFERS ${goods[stall.offer].name.toUpperCase()} · WANTS ${goods[stall.want].name.toUpperCase()}`,
goods[stall.offer].css
);
const sign = new THREE.Mesh(
new THREE.PlaneGeometry(2.95, 0.74),
new THREE.MeshBasicMaterial({
map: signTexture,
side: THREE.DoubleSide,
transparent: true
})
);
sign.position.set(0, 3.80, 0.02);
group.add(sign);
// Two projected count labels, one over each tray.
const offerLabel = document.createElement("div");
offerLabel.className = "tray-label";
labelsRoot.appendChild(offerLabel);
const wantLabel = document.createElement("div");
wantLabel.className = "tray-label";
labelsRoot.appendChild(wantLabel);
stall.labels = {
offer: offerLabel,
want: wantLabel,
offerPosition: new THREE.Vector3(-0.73, 1.64, 1.03),
wantPosition: new THREE.Vector3(0.73, 1.64, 1.03)
};
}
stalls.forEach(buildStall);
function buildArrow(x, z, dx, dz, color) {
const group = new THREE.Group();
group.position.set(x, 0.07, z);
group.rotation.y = Math.atan2(-dz, dx);
scene.add(group);
box(group, 0.62, 0.055, 0.15, color, 0.08, 0, 0);
const upper = box(group, 0.31, 0.06, 0.12, color, 0.48, 0, 0.10);
upper.rotation.y = Math.PI / 4;
const lower = box(group, 0.31, 0.06, 0.12, color, 0.48, 0, -0.10);
lower.rotation.y = -Math.PI / 4;
}
scene.updateMatrixWorld(true);
const routeCorners = [
new THREE.Vector3(-3.3, 0, 3.3),
new THREE.Vector3(3.3, 0, 3.3),
new THREE.Vector3(3.3, 0, -3.3),
new THREE.Vector3(-3.3, 0, -3.3)
];
for (let source = 0; source < stalls.length; source++) {
const target = transferTarget[source];
const start = stalls[source].group.localToWorld(
new THREE.Vector3(0, 0, 0.96)
);
const end = stalls[target].group.localToWorld(
new THREE.Vector3(0, 0, 0.96)
);
const corner = routeCorners[source];
const firstMid = start.clone().lerp(corner, 0.5);
const firstDir = corner.clone().sub(start);
buildArrow(
firstMid.x,
firstMid.z,
firstDir.x,
firstDir.z,
goods[stalls[source].offer].color
);
const secondMid = corner.clone().lerp(end, 0.5);
const secondDir = end.clone().sub(corner);
buildArrow(
secondMid.x,
secondMid.z,
secondDir.x,
secondDir.z,
goods[stalls[source].offer].color
);
}
// -------------------------------------------------------------------------
// Inventory UI
// -------------------------------------------------------------------------
for (const stall of stalls) {
const card = document.createElement("div");
card.className = "stock-card";
card.style.setProperty("--accent", goods[stall.offer].css);
card.innerHTML = `
<div class="stock-title">
<b>${stall.letter} · ${goods[stall.offer].name}</b>
<span>${goods[stall.want].name} wanted</span>
</div>
<div class="stock-line">
<span>Offer · ${goods[stall.offer].name}</span>
<b class="offer-count"></b>
</div>
<div class="stock-line">
<span>Want · ${goods[stall.want].name}</span>
<b class="want-count"></b>
</div>
<div class="stock-progress"><div></div></div>
`;
stockCards.appendChild(card);
stall.ui = {
offer: card.querySelector(".offer-count"),
want: card.querySelector(".want-count"),
progress: card.querySelector(".stock-progress > div")
};
}
for (let i = 0; i < directPairs.length; i++) {
const pair = directPairs[i];
const row = document.createElement("div");
row.className = "proof-row";
row.innerHTML = `
<b>${stalls[pair.i].letter} ↔ ${stalls[pair.j].letter}</b>
<span>not yet tested</span>
`;
proofMatrix.appendChild(row);
pair.row = row;
}
function refreshCounts() {
for (const stall of stalls) {
stall.ui.offer.textContent = `${stall.remaining} / ${stall.qty}`;
stall.ui.want.textContent = `${stall.received} / ${stall.wantQty}`;
stall.ui.progress.style.width = `${
(stall.received / stall.wantQty) * 100
}%`;
stall.labels.offer.innerHTML = `
<span class="tag">OFFER</span>
${goods[stall.offer].name} <b>×${stall.remaining}</b>
`;
stall.labels.want.innerHTML = `
<span class="tag">WANT</span>
${goods[stall.want].name} <b>×${stall.wantQty}</b>
<small>${stall.received}/${stall.wantQty} received</small>
`;
}
}
function setStatus(phase, title, description) {
phaseBadge.textContent = phase;
headline.textContent = title;
detail.textContent = description;
}
// -------------------------------------------------------------------------
// Market reset and physical token creation
// -------------------------------------------------------------------------
let shipmentLabels = [];
function resetMarket() {
for (const label of shipmentLabels) label.remove();
shipmentLabels = [];
for (const stall of stalls) {
for (const token of stall.offerTokens) {
token.removeFromParent();
}
for (const ghost of stall.ghostTokens) {
ghost.removeFromParent();
}
stall.offerTokens = [];
stall.ghostTokens = [];
stall.remaining = stall.qty;
stall.received = 0;
for (let i = 0; i < stall.qty; i++) {
const token = makeToken(stall.offer, "solid");
token.position.copy(slotFor(stall.qty, i));
stall.offerRoot.add(token);
stall.offerTokens.push(token);
}
// The want tray starts with translucent request markers, not duplicate
// physical stock. Solid delivered tokens replace them one by one.
for (let i = 0; i < stall.wantQty; i++) {
const ghost = makeToken(stall.want, "ghost");
ghost.position.copy(slotFor(stall.wantQty, i));
stall.wantRoot.add(ghost);
stall.ghostTokens.push(ghost);
}
}
refreshCounts();
}
// -------------------------------------------------------------------------
// Direct-swap proof
// -------------------------------------------------------------------------
let phase = "proof";
let proofIndex = -1;
let proofNextAt = 0;
let currentAttempt = null;
let autoExchangeAt = Infinity;
function clearAttempt() {
if (!currentAttempt) return;
for (const token of currentAttempt.tokens) token.removeFromParent();
currentAttempt = null;
verdict.style.display = "none";
}
function beginAttempt(now) {
const pair = directPairs[proofIndex];
const tokenA = makeToken(stalls[pair.i].offer, "trial");
const tokenB = makeToken(stalls[pair.j].offer, "trial");
scene.add(tokenA, tokenB);
scene.updateMatrixWorld(true);
const startA = stalls[pair.i].offerRoot.getWorldPosition(
new THREE.Vector3()
);
const startB = stalls[pair.j].offerRoot.getWorldPosition(
new THREE.Vector3()
);
const endA = stalls[pair.j].offerRoot.getWorldPosition(
new THREE.Vector3()
);
const endB = stalls[pair.i].offerRoot.getWorldPosition(
new THREE.Vector3()
);
currentAttempt = {
pair,
tokens: [tokenA, tokenB],
starts: [startA, startB],
ends: [endA, endB],
startTime: now,
duration: 2050,
done: false,
removeAt: Infinity,
verdictShown: false,
midpoint: startA.clone().add(startB).multiplyScalar(0.5)
};
verdict.textContent = "";
verdict.style.display = "none";
setStatus(
"Direct test",
`Trying ${stalls[pair.i].letter} ↔ ${stalls[pair.j].letter}`,
pair.explanation
);
}
function updateProof(now) {
if (proofIndex < 0) {
if (now >= proofNextAt) {
proofIndex = 0;
beginAttempt(now);
}
return;
}
if (!currentAttempt) {
if (proofIndex >= directPairs.length) {
phase = "proofDone";
autoExchangeAt = now + 1350;
proofSummary.textContent =
"0 of 4 neighboring swaps satisfy both participants. The missing requests form one continuous four-way cycle.";
setStatus(
"Proof complete",
"No neighboring direct swap works",
"Each adjacent trade satisfies only one trader. The four unmatched requests must be fulfilled together."
);
exchangeButton.textContent = "Start four-way exchange";
return;
}
if (now >= proofNextAt) {
beginAttempt(now);
}
return;
}
const attempt = currentAttempt;
const progress = THREE.MathUtils.clamp(
(now - attempt.startTime) / attempt.duration,
0,
1
);
const moveProgress = smoothstep(Math.min(progress / 0.76, 1));
for (let i = 0; i < 2; i++) {
const token = attempt.tokens[i];
token.position.lerpVectors(
attempt.starts[i],
attempt.ends[i],
moveProgress
);
token.position.y += Math.sin(moveProgress * Math.PI) * 0.7;
token.rotation.y = moveProgress * Math.PI * 1.4;
}
if (progress > 0.56 && !attempt.verdictShown) {
attempt.verdictShown = true;
verdict.innerHTML = `
<strong>DIRECT SWAP FAILS</strong><br>
${attempt.pair.result}
`;
verdict.style.display = "block";
}
if (progress >= 1 && !attempt.done) {
attempt.done = true;
attempt.removeAt = now + 420;
attempt.pair.row.classList.add("fail");
attempt.pair.row.querySelector("span").textContent =
attempt.pair.result;
proofSummary.textContent =
`${proofIndex + 1} of 4 neighboring pairs tested. So far, 0 satisfy both participants.`;
}
if (attempt.done && now >= attempt.removeAt) {
for (const token of attempt.tokens) token.removeFromParent();
currentAttempt = null;
verdict.style.display = "none";
proofIndex++;
proofNextAt = now + 280;
}
}
function startProof() {
resetMarket();
clearAttempt();
phase = "proof";
proofIndex = -1;
proofNextAt = performance.now() + 450;
autoExchangeAt = Infinity;
exchangeButton.disabled = false;
exchangeButton.textContent = "Skip to four-way exchange";
for (const pair of directPairs) {
pair.row.classList.remove("fail");
pair.row.querySelector("span").textContent = "not yet tested";
}
proofSummary.textContent =
"Testing whether any adjacent swap satisfies both participants…";
setStatus(
"Proof",
"Testing the neighboring trades",
"Each trial swaps only two adjacent stalls; both participants must be satisfied."
);
}
// -------------------------------------------------------------------------
// Coordinated four-way exchange
// -------------------------------------------------------------------------
let exchangeStart = 0;
const exchangeDuration = 4300;
let shipments = [];
function prepareExchange() {
scene.updateMatrixWorld(true);
shipments = [];
for (let source = 0; source < stalls.length; source++) {
const targetIndex = transferTarget[source];
const target = stalls[targetIndex];
const sourceStall = stalls[source];
const tokens = sourceStall.offerTokens.slice();
const shipment = {
source,
target: targetIndex,
type: sourceStall.offer,
qty: tokens.length,
records: [],
label: null
};
const label = document.createElement("div");
label.className = "shipment-label";
label.style.color = goods[sourceStall.offer].css;
label.textContent = `${goods[sourceStall.offer].name} ×${
tokens.length
} → ${goods[target.want].name}`;
labelsRoot.appendChild(label);
shipment.label = label;
shipmentLabels.push(label);
const offerCenter = sourceStall.offerRoot.getWorldPosition(
new THREE.Vector3()
);
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
scene.attach(token);
const start = token.getWorldPosition(new THREE.Vector3());
const targetSlot = slotFor(target.wantQty, i);
const end = target.wantRoot.localToWorld(targetSlot.clone());
const formationOffset = start.clone().sub(offerCenter);
const corner = routeCorners[source].clone().add(formationOffset);
corner.y = 1.55;
shipment.records.push({
token,
start,
end,
corner,
targetSlot,
targetIndex: i,
arrived: false
});
}
sourceStall.remaining -= tokens.length;
shipments.push(shipment);
}
refreshCounts();
}
function startExchange() {
if (phase === "exchange") return;
if (phase === "complete") resetMarket();
clearAttempt();
verdict.style.display = "none";
phase = "exchange";
exchangeStart = performance.now();
exchangeButton.disabled = true;
exchangeButton.textContent = "Exchange in progress…";
prepareExchange();
setStatus(
"Four-way exchange",
"All four shipments are moving simultaneously",
"Grain → Fruit stall · Cloth → Grain stall · Pottery → Cloth stall · Fruit → Pottery stall."
);
}
function routePoint(record, t, out) {
let a;
let b;
let localT;
if (t < 0.5) {
a = record.start;
b = record.corner;
localT = smoothstep(t * 2);
} else {
a = record.corner;
b = record.end;
localT = smoothstep((t - 0.5) * 2);
}
out.lerpVectors(a, b, localT);
out.y += Math.sin(t * Math.PI) * 0.48;
return out;
}
function updateExchange(now) {
const progress = THREE.MathUtils.clamp(
(now - exchangeStart) / exchangeDuration,
0,
1
);
const point = new THREE.Vector3();
for (const shipment of shipments) {
const average = new THREE.Vector3();
for (const record of shipment.records) {
routePoint(record, progress, point);
record.token.position.copy(point);
record.token.rotation.y = progress * Math.PI * 2;
record.token.rotation.z = Math.sin(progress * Math.PI * 8) * 0.08;
average.add(record.token.position);
if (progress >= 1 && !record.arrived) {
record.arrived = true;
const target = stalls[shipment.target];
target.wantRoot.attach(record.token);
record.token.position.copy(record.targetSlot);
record.token.rotation.set(0, 0, 0);
target.received++;
const ghost = target.ghostTokens[record.targetIndex];
if (ghost) {
ghost.removeFromParent();
target.ghostTokens[record.targetIndex] = null;
}
refreshCounts();
}
}
average.multiplyScalar(1 / shipment.records.length);
projectElement(shipment.label, average);
}
if (progress >= 1 && phase === "exchange") {
phase = "complete";
exchangeButton.disabled = false;
exchangeButton.textContent = "Replay four-way exchange";
for (const label of shipmentLabels) {
label.style.transition = "opacity 300ms ease";
label.style.opacity = "0";
}
setTimeout(() => {
for (const label of shipmentLabels) label.remove();
shipmentLabels = [];
}, 320);
proofSummary.textContent =
"All four requests are satisfied: every offer tray is empty and every want tray holds the requested item.";
setStatus(
"Exchange complete",
"All four traders received exactly what they requested",
"Grain → Fruit · Cloth → Grain · Pottery → Cloth · Fruit → Pottery. Every token has a final owner."
);
}
}
// -------------------------------------------------------------------------
// Projected DOM labels
// -------------------------------------------------------------------------
function projectElement(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.25 &&
projected.x < 1.25 &&
projected.y > -1.25 &&
projected.y < 1.25;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateLabels() {
for (const stall of stalls) {
const offerWorld = stall.group.localToWorld(
stall.labels.offerPosition.clone()
);
const wantWorld = stall.group.localToWorld(
stall.labels.wantPosition.clone()
);
projectElement(stall.labels.offer, offerWorld);
projectElement(stall.labels.want, wantWorld);
}
if (currentAttempt && currentAttempt.verdictShown) {
projectElement(verdict, currentAttempt.midpoint);
}
}
// -------------------------------------------------------------------------
// UI wiring and animation loop
// -------------------------------------------------------------------------
proofButton.addEventListener("click", startProof);
exchangeButton.addEventListener("click", startExchange);
function smoothstep(value) {
const t = THREE.MathUtils.clamp(value, 0, 1);
return t * t * (3 - 2 * t);
}
function animate(now) {
requestAnimationFrame(animate);
if (phase === "proof") {
updateProof(now);
} else if (phase === "proofDone" && now >= autoExchangeAt) {
startExchange();
} else if (phase === "exchange") {
updateExchange(now);
}
updateLabels();
renderer.render(scene, camera);
}
resetMarket();
startProof();
updateCamera();
renderer.render(scene, camera);
loading.remove();
requestAnimationFrame(animate);
</script>
</body>
</html>
```