Prompt specification
Build or customize the Three.js 3D scene "Arrange a temporary performance in the square" 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: Arrange a temporary performance in the square
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/arrange-a-temporary-performance-in-the-square-x2672
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring Largo de São Sebastião and the Teatro Amazonas in Manaus. Let users place a small stage and audience area in a schematic plaza layout. Keep routes to surrounding entrances open and show how seating changes circulation. Voxel style.
Working Three.js Starter (arrange-a-temporary-performance-in-the-square-x2672):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Largo de São Sebastião · Circulation Studio</title>
<style>
:root {
--ink: #18333a;
--muted: #62777c;
--panel: rgba(250, 249, 243, 0.94);
--line: rgba(24, 51, 58, 0.12);
--teal: #167f78;
--teal-soft: #d8eee7;
--coral: #df684c;
--gold: #d29a37;
--blue: #3979a5;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #c8dfe1;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active { cursor: grabbing; }
.panel {
position: fixed;
z-index: 10;
top: 16px;
left: 16px;
width: 330px;
max-height: calc(100vh - 32px);
overflow: auto;
padding: 18px;
border: 1px solid rgba(255,255,255,0.7);
border-radius: 20px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(28, 54, 58, 0.18);
backdrop-filter: blur(16px);
scrollbar-width: thin;
}
.eyebrow {
margin-bottom: 6px;
color: var(--teal);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 23px;
line-height: 1.12;
letter-spacing: -0.035em;
}
.subtitle {
margin: 8px 0 16px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.section {
padding: 14px 0;
border-top: 1px solid var(--line);
}
.section:first-of-type { padding-top: 12px; }
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section-title small {
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.04em;
}
.tool-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
button {
appearance: none;
border: 1px solid var(--line);
border-radius: 11px;
padding: 9px 10px;
background: rgba(255,255,255,0.72);
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition: 140ms ease;
}
button:hover {
border-color: rgba(22,127,120,0.4);
background: #fff;
transform: translateY(-1px);
}
button.active {
border-color: var(--teal);
background: var(--teal);
color: white;
}
button.wide {
width: 100%;
margin-top: 8px;
}
.hint {
margin-top: 9px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.control {
margin: 11px 0;
}
.control-head {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 6px;
font-size: 11px;
font-weight: 700;
}
.control-head output {
color: var(--teal);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
accent-color: var(--teal);
cursor: pointer;
}
.check-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 9px 0;
color: var(--ink);
font-size: 11px;
font-weight: 650;
}
.switch {
position: relative;
width: 34px;
height: 19px;
flex: 0 0 auto;
}
.switch input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.switch span {
position: absolute;
inset: 0;
border-radius: 20px;
background: #bcc9c8;
transition: 150ms;
cursor: pointer;
}
.switch span::after {
content: "";
position: absolute;
width: 15px;
height: 15px;
top: 2px;
left: 2px;
border-radius: 50%;
background: white;
box-shadow: 0 1px 4px rgba(0,0,0,0.2);
transition: 150ms;
}
.switch input:checked + span { background: var(--teal); }
.switch input:checked + span::after { transform: translateX(15px); }
.legend {
display: flex;
flex-wrap: wrap;
gap: 10px 14px;
margin-top: 10px;
color: var(--muted);
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 3px;
}
.stats {
position: fixed;
z-index: 8;
top: 16px;
right: 16px;
width: 274px;
padding: 15px;
border: 1px solid rgba(255,255,255,0.68);
border-radius: 17px;
background: rgba(250,249,243,0.9);
box-shadow: 0 12px 36px rgba(28,54,58,0.14);
backdrop-filter: blur(14px);
}
.stat-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.stat {
min-height: 67px;
padding: 10px;
border-radius: 12px;
background: rgba(255,255,255,0.7);
border: 1px solid rgba(24,51,58,0.07);
}
.stat-label {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.stat-value {
margin-top: 5px;
font-size: 20px;
font-weight: 800;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.status {
display: flex;
align-items: center;
gap: 7px;
margin-top: 9px;
color: var(--teal);
font-size: 11px;
font-weight: 750;
}
.status::before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 0 4px color-mix(in srgb, currentColor 15%, transparent);
}
.status.warn { color: var(--coral); }
.controls-help {
position: fixed;
z-index: 8;
right: 16px;
bottom: 16px;
max-width: 320px;
padding: 11px 14px;
border-radius: 13px;
background: rgba(27,53,58,0.86);
color: rgba(255,255,255,0.9);
font-size: 10px;
line-height: 1.55;
box-shadow: 0 10px 28px rgba(0,0,0,0.15);
pointer-events: none;
}
kbd {
display: inline-block;
padding: 1px 5px;
border: 1px solid rgba(255,255,255,0.25);
border-radius: 4px;
background: rgba(255,255,255,0.1);
font: inherit;
color: white;
}
#toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 24px;
max-width: min(460px, calc(100vw - 30px));
padding: 11px 15px;
border-radius: 12px;
background: #183b40;
color: white;
font-size: 12px;
font-weight: 650;
box-shadow: 0 12px 32px rgba(0,0,0,0.22);
opacity: 0;
transform: translate(-50%, 12px);
transition: 180ms ease;
pointer-events: none;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error { background: #9c4536; }
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
background: #d8e6e4;
color: var(--ink);
font-size: 13px;
font-weight: 750;
letter-spacing: 0.06em;
}
.disclaimer {
margin-top: 12px;
padding: 9px 10px;
border-radius: 10px;
background: rgba(22,127,120,0.07);
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
@media (max-width: 760px) {
.panel {
top: 10px;
left: 10px;
width: min(310px, calc(100vw - 20px));
max-height: 52vh;
padding: 14px;
}
.stats {
top: auto;
right: 10px;
bottom: 10px;
width: min(270px, calc(100vw - 20px));
}
.controls-help { display: none; }
h1 { font-size: 20px; }
}
</style>
</head>
<body>
<div id="scene"></div>
<aside class="panel">
<div class="eyebrow">Manaus · Schematic planning model</div>
<h1>Largo de São Sebastião</h1>
<p class="subtitle">
Place a compact performance stage and audience, then test how seating
redirects circulation around the Teatro Amazonas.
</p>
<section class="section">
<div class="section-title">
Placement
<small id="selectionLabel">Stage selected</small>
</div>
<div class="tool-grid">
<button class="active" data-tool="inspect">Inspect</button>
<button data-tool="stage">Place stage</button>
<button data-tool="audience">Place audience</button>
<button id="rotateButton">Rotate 15°</button>
</div>
<button class="wide" id="faceButton">Face stage and audience</button>
<p class="hint" id="toolHint">
Choose a placement tool, then click an open area of the plaza.
Entrance aprons are protected and cannot be blocked.
</p>
</section>
<section class="section">
<div class="section-title">
Audience configuration
<small>Live circulation update</small>
</div>
<div class="control">
<div class="control-head">
<label for="rows">Rows</label>
<output id="rowsOutput">6</output>
</div>
<input id="rows" type="range" min="3" max="9" step="1" value="6">
</div>
<div class="control">
<div class="control-head">
<label for="seats">Seats per row</label>
<output id="seatsOutput">10</output>
</div>
<input id="seats" type="range" min="6" max="14" step="1" value="10">
</div>
<div class="control">
<div class="control-head">
<label for="aisle">Center aisle width</label>
<output id="aisleOutput">2.2 m</output>
</div>
<input id="aisle" type="range" min="0.8" max="3.6" step="0.1" value="2.2">
</div>
<p class="hint">
A wider aisle can become a useful through-route. Narrow seating may
create longer pedestrian detours around the audience block.
</p>
</section>
<section class="section">
<div class="section-title">Analysis layers</div>
<label class="check-row">
<span>Pedestrian routes</span>
<span class="switch">
<input id="routesToggle" type="checkbox" checked>
<span></span>
</span>
</label>
<label class="check-row">
<span>Circulation pressure</span>
<span class="switch">
<input id="pressureToggle" type="checkbox" checked>
<span></span>
</span>
</label>
<label class="check-row">
<span>Landmark labels</span>
<span class="switch">
<input id="labelsToggle" type="checkbox" checked>
<span></span>
</span>
</label>
<div class="legend">
<div class="legend-item">
<span class="swatch" style="background:#45a9a0"></span>Low flow
</div>
<div class="legend-item">
<span class="swatch" style="background:#e2b54b"></span>Medium
</div>
<div class="legend-item">
<span class="swatch" style="background:#df684c"></span>Concentrated
</div>
</div>
</section>
<section class="section">
<div class="section-title">
Layout
<small>Reset</small>
</div>
<button class="wide" id="resetButton">Restore example layout</button>
</section>
<div class="disclaimer">
Conceptual voxel model, not a surveyed reconstruction. Distances and
entrances are diagrammatic and intended for circulation studies.
</div>
</aside>
<section class="stats">
<div class="stat-grid">
<div class="stat">
<div class="stat-label">Connected entrances</div>
<div class="stat-value" id="connectedStat">4 / 4</div>
</div>
<div class="stat">
<div class="stat-label">Route length</div>
<div class="stat-value" id="lengthStat">—</div>
</div>
<div class="stat">
<div class="stat-label">Extra detour</div>
<div class="stat-value" id="detourStat">—</div>
</div>
<div class="stat">
<div class="stat-label">Flow pressure</div>
<div class="stat-value" id="pressureStat">—</div>
</div>
</div>
<div class="status" id="flowStatus">Calculating circulation…</div>
</section>
<div class="controls-help">
<strong>Controls:</strong> drag to orbit · right-drag to pan · wheel to zoom<br>
<kbd>R</kbd> rotate selected · arrow keys nudge · click seating tools to place
</div>
<div id="toast"></div>
<div id="loading">Loading Largo de São Sebastião…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const container = document.getElementById("scene");
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;
container.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xc7dfe1);
scene.fog = new THREE.Fog(0xc7dfe1, 95, 170);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
260
);
const hemisphere = new THREE.HemisphereLight(0xeafcff, 0x86745d, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1d4, 3.1);
sun.position.set(28, 58, 31);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -62;
sun.shadow.camera.right = 62;
sun.shadow.camera.top = 62;
sun.shadow.camera.bottom = -62;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 140;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x93c9df, 0.8);
fill.position.set(-45, 24, -25);
scene.add(fill);
const materials = {
grass: new THREE.MeshStandardMaterial({ color: 0x87a778, roughness: 1 }),
grassDark: new THREE.MeshStandardMaterial({ color: 0x65865f, roughness: 1 }),
paving: new THREE.MeshStandardMaterial({ color: 0xd6c6a6, roughness: 0.95 }),
pavingA: new THREE.MeshStandardMaterial({ color: 0xe1d2b5, roughness: 0.95 }),
pavingB: new THREE.MeshStandardMaterial({ color: 0xcdbd9d, roughness: 0.95 }),
curb: new THREE.MeshStandardMaterial({ color: 0xe8dfcb, roughness: 0.9 }),
cream: new THREE.MeshStandardMaterial({ color: 0xf0dfbb, roughness: 0.86 }),
white: new THREE.MeshStandardMaterial({ color: 0xfff1d2, roughness: 0.8 }),
terracotta: new THREE.MeshStandardMaterial({ color: 0xc76c3c, roughness: 0.88 }),
roof: new THREE.MeshStandardMaterial({ color: 0xbe6138, roughness: 0.9 }),
window: new THREE.MeshStandardMaterial({
color: 0x264f5c,
roughness: 0.28,
metalness: 0.08
}),
wood: new THREE.MeshStandardMaterial({ color: 0x865b3d, roughness: 0.9 }),
trunk: new THREE.MeshStandardMaterial({ color: 0x72543d, roughness: 1 }),
leafA: new THREE.MeshStandardMaterial({ color: 0x4f8057, roughness: 1 }),
leafB: new THREE.MeshStandardMaterial({ color: 0x628d5d, roughness: 1 }),
seat: new THREE.MeshStandardMaterial({ color: 0x287c86, roughness: 0.78 }),
stage: new THREE.MeshStandardMaterial({ color: 0x9b563b, roughness: 0.87 }),
stageTop: new THREE.MeshStandardMaterial({ color: 0xb86f4c, roughness: 0.85 }),
dark: new THREE.MeshStandardMaterial({ color: 0x273f42, roughness: 0.8 }),
metal: new THREE.MeshStandardMaterial({
color: 0x4e6262,
roughness: 0.55,
metalness: 0.28
})
};
function box(w, h, d, material, x, y, z, parent = scene, cast = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = cast;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Plaza and protected entrance aprons
// -------------------------------------------------------------------------
box(108, 0.7, 88, materials.grass, 0, -0.52, 0, scene, false);
box(75, 0.22, 41, materials.curb, 0, -0.12, 8, scene, false);
box(72, 0.18, 38, materials.paving, 0, -0.01, 8, scene, false);
const tileCountX = 36;
const tileCountZ = 19;
const tileGeometry = new THREE.BoxGeometry(1.91, 0.07, 1.91);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.95
});
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileCountX * tileCountZ);
tiles.receiveShadow = true;
const tileMatrix = new THREE.Matrix4();
let tileIndex = 0;
for (let iz = 0; iz < tileCountZ; iz++) {
for (let ix = 0; ix < tileCountX; ix++) {
const x = -35 + ix * 2;
const z = -10 + iz * 2;
tileMatrix.makeTranslation(x, 0.07, z);
tiles.setMatrixAt(tileIndex, tileMatrix);
const alternate = (ix + iz) % 3;
tiles.setColorAt(
tileIndex,
new THREE.Color(
alternate === 0 ? 0xd8c7a7 :
alternate === 1 ? 0xe1d1b2 : 0xcfbd9e
)
);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
scene.add(tiles);
const entranceAprons = [
{ id: "west", x: -33, z: 7, w: 8, d: 8, label: "Entrada Oeste" },
{ id: "south", x: 0, z: 25, w: 8, d: 6, label: "Entrada Sul" },
{ id: "east", x: 33, z: 7, w: 8, d: 8, label: "Entrada Leste" },
{ id: "north", x: 13, z: -8, w: 8, d: 6, label: "Entrada Norte" }
];
const apronMaterial = new THREE.MeshBasicMaterial({
color: 0x39a29a,
transparent: true,
opacity: 0.11,
depthWrite: false
});
for (const apron of entranceAprons) {
box(
apron.w,
0.035,
apron.d,
apronMaterial,
apron.x,
0.125,
apron.z,
scene,
false
);
const stripe = new THREE.Mesh(
new THREE.BoxGeometry(Math.min(apron.w, 2.5), 0.05, 0.22),
new THREE.MeshStandardMaterial({ color: 0x278e86, roughness: 0.8 })
);
stripe.position.set(apron.x, 0.17, apron.z);
scene.add(stripe);
}
// -------------------------------------------------------------------------
// Labels made from local canvas textures
// -------------------------------------------------------------------------
const labels = [];
function makeLabel(text, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 180;
const ctx = canvas.getContext("2d");
ctx.fillStyle = options.background || "rgba(25,55,60,0.92)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = options.border || "rgba(255,255,255,0.32)";
ctx.lineWidth = 8;
ctx.strokeRect(5, 5, canvas.width - 10, canvas.height - 10);
ctx.fillStyle = options.color || "#ffffff";
ctx.font = `800 ${options.fontSize || 58}px system-ui, sans-serif`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, canvas.width / 2, canvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: options.depthTest !== false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
const width = options.width || 18;
sprite.scale.set(width, width * 180 / 1024, 1);
sprite.userData.isLabel = true;
labels.push(sprite);
scene.add(sprite);
return sprite;
}
// -------------------------------------------------------------------------
// Teatro Amazonas — procedural voxel landmark
// -------------------------------------------------------------------------
box(26, 1.2, 18, materials.curb, -10, 0.6, -19.5);
box(23.5, 8.3, 14.5, materials.cream, -10, 5.15, -19.5);
box(24.2, 0.55, 15, materials.white, -10, 8.9, -19.5);
// Front steps
for (let i = 0; i < 4; i++) {
box(
15 - i * 0.8,
0.32,
1.05,
materials.curb,
-10,
0.15 + i * 0.32,
-10.8 - i * 0.95
);
}
// Façade columns and windows
for (let i = 0; i < 8; i++) {
const x = -19.2 + i * 2.65;
box(0.72, 5.7, 0.72, materials.white, x, 4.2, -11.95);
box(1.65, 3.25, 0.18, materials.window, x, 4.3, -12.12);
box(1.85, 0.28, 0.42, materials.white, x, 6.1, -12.05);
}
box(4.1, 4.4, 0.3, materials.wood, -10, 3.55, -12.12);
box(3.4, 3.5, 0.12, materials.window, -10, 3.7, -12.32);
box(10.5, 1.0, 0.5, materials.white, -10, 7.35, -11.9);
box(12.0, 0.45, 0.55, materials.white, -10, 8.05, -11.9);
// Dome drum
box(13.5, 2.2, 13.5, materials.cream, -10, 10.05, -19.5);
// Voxel dome shell
const domeCells = [];
const domeSize = 0.86;
for (let layer = 0; layer < 9; layer++) {
const y = layer * 0.82;
const normalized = layer / 8;
const radius = 6.4 * Math.sqrt(Math.max(0, 1 - normalized * normalized));
for (let gx = -7; gx <= 7; gx++) {
for (let gz = -7; gz <= 7; gz++) {
const x = gx * domeSize;
const z = gz * domeSize;
const r = Math.hypot(x, z);
if (r <= radius + 0.1 && r >= radius - 0.95) {
domeCells.push([x, y, z]);
}
}
}
}
const domeMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(domeSize, domeSize, domeSize),
materials.roof,
domeCells.length
);
domeCells.forEach((p, i) => {
tileMatrix.makeTranslation(p[0] + -10, 11.15 + p[1], p[2] - 19.5);
domeMesh.setMatrixAt(i, tileMatrix);
});
domeMesh.instanceMatrix.needsUpdate = true;
domeMesh.castShadow = true;
domeMesh.receiveShadow = true;
scene.add(domeMesh);
box(2.0, 1.2, 2.0, materials.roof, -10, 18.4, -19.5);
box(0.22, 2.2, 0.22, materials.metal, -10, 19.8, -19.5);
box(1.1, 0.18, 0.18, materials.metal, -10, 20.55, -19.5);
const theaterLabel = makeLabel("TEATRO AMAZONAS", {
width: 20,
background: "rgba(117,57,36,0.93)",
border: "rgba(255,217,173,0.55)"
});
theaterLabel.position.set(-10, 22.1, -19.5);
// -------------------------------------------------------------------------
// Igreja de São Sebastião — simplified voxel landmark
// -------------------------------------------------------------------------
box(11.5, 0.75, 20.5, materials.curb, 27.3, 0.35, 4);
box(10.5, 7.0, 18.5, materials.cream, 27.3, 4.2, 4);
box(11.2, 0.55, 19.2, materials.white, 27.3, 8.0, 4);
// Stepped terracotta roof
for (let i = 0; i < 5; i++) {
box(
10.7 - i * 1.65,
0.55,
18.8,
materials.roof,
27.3,
8.35 + i * 0.5,
4
);
}
// Front towers face the plaza
for (const z of [-3.8, 11.8]) {
box(3.1, 12.4, 3.1, materials.cream, 27.3, 6.2, z);
box(3.55, 0.55, 3.55, materials.white, 27.3, 12.6, z);
box(2.5, 2.6, 2.5, materials.roof, 27.3, 13.9, z);
const arch = box(1.1, 3.1, 0.16, materials.window, 25.72, 5.7, z);
arch.rotation.y = Math.PI / 2;
}
// Side windows and west-facing entrance
for (let i = 0; i < 5; i++) {
const z = -3 + i * 3.5;
const window = box(0.18, 3.3, 1.65, materials.window, 22.0, 4.9, z);
window.rotation.y = Math.PI / 2;
}
box(0.25, 4.2, 3.3, materials.wood, 22.0, 2.75, 4);
box(0.12, 3.5, 2.6, materials.window, 21.82, 2.9, 4);
box(0.22, 2.8, 0.22, materials.metal, 27.3, 16.5, 4);
box(1.25, 0.2, 0.2, materials.metal, 27.3, 17.5, 4);
const churchLabel = makeLabel("IGREJA SÃO SEBASTIÃO", {
width: 18,
background: "rgba(42,86,91,0.93)",
border: "rgba(202,238,230,0.5)"
});
churchLabel.position.set(27.3, 19.2, 4);
for (const apron of entranceAprons) {
const label = makeLabel(apron.label, {
width: 9,
background: "rgba(25,55,60,0.80)",
fontSize: 43
});
label.position.set(apron.x, 2.4, apron.z);
}
// -------------------------------------------------------------------------
// Trees, lamps, benches, and street edges
// -------------------------------------------------------------------------
function seededRandom(seed) {
let value = seed % 2147483647;
return () => {
value = value * 16807 % 2147483647;
return (value - 1) / 2147483646;
};
}
const random = seededRandom(19);
const treeLocations = [];
for (let i = 0; i < 13; i++) {
treeLocations.push([-43 + i * 7.2, 25 + random() * 8]);
}
for (let i = 0; i < 8; i++) {
treeLocations.push([-43 + random() * 6, -25 + i * 7]);
}
for (let i = 0; i < 7; i++) {
treeLocations.push([38 + random() * 6, -20 + i * 7]);
}
for (const [x, z] of treeLocations) {
box(0.75, 3.4, 0.75, materials.trunk, x, 1.45, z);
box(3.4, 2.6, 3.4, random() > 0.5 ? materials.leafA : materials.leafB, x, 4.0, z);
box(2.5, 2.2, 2.6, materials.leafB, x + 0.4, 5.6, z - 0.25);
box(2.7, 1.8, 2.5, materials.leafA, x - 0.45, 5.3, z + 0.25);
}
for (const [x, z] of [[-30, 21], [-21, 23], [16, 22], [30, 20], [-31, -5]]) {
box(3.4, 0.28, 0.85, materials.wood, x, 0.8, z);
box(3.4, 0.85, 0.2, materials.wood, x, 1.25, z - 0.34);
box(0.24, 0.8, 0.24, materials.dark, x - 1.2, 0.4, z);
box(0.24, 0.8, 0.24, materials.dark, x + 1.2, 0.4, z);
}
for (const [x, z] of [[-28, 4], [-28, 18], [17, 17], [18, -4], [6, 23]]) {
box(0.18, 4.2, 0.18, materials.dark, x, 2.1, z);
box(0.75, 0.75, 0.75, materials.white, x, 4.3, z);
box(0.5, 0.12, 0.5, materials.terracotta, x, 4.75, z);
}
// -------------------------------------------------------------------------
// Stage and audience
// -------------------------------------------------------------------------
const stageGroup = new THREE.Group();
stageGroup.userData.part = "stage";
scene.add(stageGroup);
box(7, 0.42, 5, materials.stage, 0, 0.25, 0, stageGroup);
box(6.7, 0.16, 4.7, materials.stageTop, 0, 0.52, 0, stageGroup);
box(7, 3.3, 0.3, materials.stage, 0, 2.05, -2.25, stageGroup);
box(8.2, 0.22, 5.6, materials.terracotta, 0, 4.15, 0, stageGroup);
for (const x of [-3.7, 3.7]) {
for (const z of [-2.5, 2.5]) {
box(0.22, 3.9, 0.22, materials.metal, x, 2.25, z, stageGroup);
}
}
for (let i = 0; i < 3; i++) {
box(5.5, 0.2, 0.65, materials.stageTop, 0, 0.12 + i * 0.08, 2.7 + i * 0.48, stageGroup);
}
const stageLabel = makeLabel("STAGE", {
width: 6.5,
background: "rgba(129,67,48,0.91)",
fontSize: 50
});
stageLabel.position.set(0, 5.2, 0);
stageGroup.add(stageLabel);
const audienceGroup = new THREE.Group();
audienceGroup.userData.part = "audience";
scene.add(audienceGroup);
const seatMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.76, 0.2, 0.72),
materials.seat,
126
);
const backMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.76, 0.65, 0.13),
materials.seat,
126
);
const bodyMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.28, 0.43, 0.28),
materials.dark,
126
);
const headMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.24, 0.24, 0.24),
materials.cream,
126
);
for (const mesh of [seatMesh, backMesh, bodyMesh, headMesh]) {
mesh.castShadow = true;
mesh.receiveShadow = true;
audienceGroup.add(mesh);
}
const audienceLabel = makeLabel("AUDIENCE", {
width: 7.5,
background: "rgba(28,92,102,0.92)",
fontSize: 50
});
audienceLabel.position.set(0, 3.4, 0);
audienceGroup.add(audienceLabel);
const state = {
mode: "inspect",
selected: "stage",
rows: 6,
seats: 10,
aisle: 2.2,
stage: { x: -10, z: 3, rot: 0.86 },
audience: { x: 5, z: 16, rot: -2.28 },
showRoutes: true,
showPressure: true,
showLabels: true
};
function localSeatPositions() {
const positions = [];
const leftCount = Math.ceil(state.seats / 2);
const rightCount = Math.floor(state.seats / 2);
const spacingX = 1.2;
const spacingZ = 1.35;
const depth = (state.rows - 1) * spacingZ;
for (let row = 0; row < state.rows; row++) {
const z = -depth / 2 + row * spacingZ;
for (let i = 0; i < leftCount; i++) {
positions.push({
x: -(state.aisle / 2 + 0.48 + i * spacingX),
z
});
}
for (let i = 0; i < rightCount; i++) {
positions.push({
x: state.aisle / 2 + 0.48 + i * spacingX,
z
});
}
}
return positions;
}
function worldSeatPositions(audience = state.audience, locals = localSeatPositions()) {
const c = Math.cos(audience.rot);
const s = Math.sin(audience.rot);
return locals.map(p => ({
x: audience.x + p.x * c + p.z * s,
z: audience.z - p.x * s + p.z * c,
localX: p.x,
localZ: p.z
}));
}
const audienceMatrix = new THREE.Matrix4();
function buildAudience() {
const locals = localSeatPositions();
const count = locals.length;
seatMesh.count = count;
backMesh.count = count;
const bodyCount = Math.floor(count * 0.58);
bodyMesh.count = bodyCount;
headMesh.count = bodyCount;
locals.forEach((p, i) => {
audienceMatrix.makeTranslation(p.x, 0.23, p.z);
seatMesh.setMatrixAt(i, audienceMatrix);
audienceMatrix.makeTranslation(p.x, 0.56, p.z - 0.29);
backMesh.setMatrixAt(i, audienceMatrix);
seatMesh.setColorAt(
i,
new THREE.Color(i % 3 === 0 ? 0x337f8b : 0x246d79)
);
backMesh.setColorAt(
i,
new THREE.Color(i % 3 === 0 ? 0x337f8b : 0x246d79)
);
});
const skinColors = [0xb66f50, 0x744938, 0xd5a27d, 0x8d5941];
for (let i = 0; i < bodyCount; i++) {
const p = locals[(i * 5 + 1) % locals.length];
audienceMatrix.makeTranslation(p.x, 0.65, p.z + 0.02);
bodyMesh.setMatrixAt(i, audienceMatrix);
audienceMatrix.makeTranslation(p.x, 0.97, p.z + 0.02);
headMesh.setMatrixAt(i, audienceMatrix);
bodyMesh.setColorAt(
i,
new THREE.Color([0x456d76, 0xb06b4c, 0x586b53, 0x7a596d][i % 4])
);
headMesh.setColorAt(i, new THREE.Color(skinColors[i % skinColors.length]));
}
for (const mesh of [seatMesh, backMesh, bodyMesh, headMesh]) {
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
}
audienceGroup.position.set(state.audience.x, 0, state.audience.z);
audienceGroup.rotation.y = state.audience.rot;
}
function updateStageTransform() {
stageGroup.position.set(state.stage.x, 0, state.stage.z);
stageGroup.rotation.y = state.stage.rot;
}
buildAudience();
updateStageTransform();
// -------------------------------------------------------------------------
// Placement validation
// -------------------------------------------------------------------------
const buildingRects = [
{ x1: -23, x2: 3, z1: -29, z2: -11.1 },
{ x1: 21.7, x2: 33.1, z1: -6.4, z2: 14.4 }
];
function pointInRect(x, z, rect, padding = 0) {
return (
x >= rect.x - padding && x <= rect.x + rect.w + padding &&
z >= rect.z - padding && z <= rect.z + rect.d + padding
);
}
function pointInBuilding(x, z, padding = 0) {
return buildingRects.some(r =>
x >= r.x1 - padding && x <= r.x2 + padding &&
z >= r.z1 - padding && z <= r.z2 + padding
);
}
function inProtectedApron(x, z, padding = 0) {
return entranceAprons.some(a => pointInRect(x, z, a, padding));
}
function stageContainsPoint(stage, x, z, padding = 0) {
const dx = x - stage.x;
const dz = z - stage.z;
const c = Math.cos(stage.rot);
const s = Math.sin(stage.rot);
const localX = c * dx - s * dz;
const localZ = s * dx + c * dz;
return Math.abs(localX) <= 3.5 + padding &&
Math.abs(localZ) <= 2.5 + padding;
}
function stageCorners(stage) {
const c = Math.cos(stage.rot);
const s = Math.sin(stage.rot);
return [
[-3.5, -2.5], [3.5, -2.5], [3.5, 2.5], [-3.5, 2.5]
].map(([x, z]) => ({
x: stage.x + x * c + z * s,
z: stage.z - x * s + z * c
}));
}
function validateStage(stage) {
for (const p of stageCorners(stage)) {
if (p.x < -34 || p.x > 34 || p.z < -8.7 || p.z > 25.5) {
return "The stage must remain inside the open plaza.";
}
if (pointInBuilding(p.x, p.z, 0.25)) {
return "The stage overlaps a landmark building.";
}
if (inProtectedApron(p.x, p.z, 0.2)) {
return "Keep the entrance approach aprons clear.";
}
}
for (const seat of worldSeatPositions()) {
if (stageContainsPoint(stage, seat.x, seat.z, 0.42)) {
return "The stage overlaps the audience seating.";
}
}
return null;
}
function validateAudience(audience, locals = localSeatPositions()) {
const seats = worldSeatPositions(audience, locals);
for (const seat of seats) {
if (seat.x < -34 || seat.x > 34 || seat.z < -8.7 || seat.z > 25.5) {
return "All seats must remain inside the open plaza.";
}
if (pointInBuilding(seat.x, seat.z, 0.35)) {
return "The audience overlaps a landmark building.";
}
if (inProtectedApron(seat.x, seat.z, 0.3)) {
return "Keep the entrance approach aprons clear.";
}
if (stageContainsPoint(state.stage, seat.x, seat.z, 0.42)) {
return "The audience overlaps the stage.";
}
}
return null;
}
// -------------------------------------------------------------------------
// Grid and A* pedestrian routing
// -------------------------------------------------------------------------
const GRID = {
minX: -34,
minZ: -9,
maxX: 34,
maxZ: 26,
cell: 1.25
};
GRID.cols = Math.floor((GRID.maxX - GRID.minX) / GRID.cell) + 1;
GRID.rows = Math.floor((GRID.maxZ - GRID.minZ) / GRID.cell) + 1;
GRID.size = GRID.cols * GRID.rows;
function gridCenter(index) {
const x = index % GRID.cols;
const z = Math.floor(index / GRID.cols);
return {
x: GRID.minX + x * GRID.cell,
z: GRID.minZ + z * GRID.cell
};
}
function nearestGridIndex(x, z) {
const gx = Math.round((x - GRID.minX) / GRID.cell);
const gz = Math.round((z - GRID.minZ) / GRID.cell);
for (let radius = 0; radius < 12; radius++) {
for (let dz = -radius; dz <= radius; dz++) {
for (let dx = -radius; dx <= radius; dx++) {
if (Math.max(Math.abs(dx), Math.abs(dz)) !== radius) continue;
const ix = gx + dx;
const iz = gz + dz;
if (ix < 0 || iz < 0 || ix >= GRID.cols || iz >= GRID.rows) continue;
const index = ix + iz * GRID.cols;
if (!blockedCache[index]) return index;
}
}
}
return gz * GRID.cols + gx;
}
let blockedCache = new Uint8Array(GRID.size);
function buildBlockedGrid(seatPositions, stage) {
const blocked = new Uint8Array(GRID.size);
for (let i = 0; i < GRID.size; i++) {
const p = gridCenter(i);
if (pointInBuilding(p.x, p.z, 0.25)) {
blocked[i] = 1;
continue;
}
if (stage && stageContainsPoint(stage, p.x, p.z, 0.24)) {
blocked[i] = 1;
continue;
}
for (const seat of seatPositions) {
if (Math.hypot(p.x - seat.x, p.z - seat.z) < 0.64) {
blocked[i] = 1;
break;
}
}
}
return blocked;
}
class MinHeap {
constructor() { this.items = []; }
push(item) {
this.items.push(item);
let i = this.items.length - 1;
while (i > 0) {
const parent = Math.floor((i - 1) / 2);
if (this.items[parent].f <= item.f) break;
this.items[i] = this.items[parent];
i = parent;
}
this.items[i] = item;
}
pop() {
if (!this.items.length) return null;
const first = this.items[0];
const last = this.items.pop();
if (!this.items.length) return first;
let i = 0;
while (true) {
const left = i * 2 + 1;
const right = left + 1;
if (left >= this.items.length) break;
let child = left;
if (
right < this.items.length &&
this.items[right].f < this.items[left].f
) child = right;
if (this.items[child].f >= last.f) break;
this.items[i] = this.items[child];
i = child;
}
this.items[i] = last;
return first;
}
get size() { return this.items.length; }
}
function findPath(blocked, start, end) {
const total = GRID.size;
const gScore = new Float32Array(total);
gScore.fill(Infinity);
const cameFrom = new Int32Array(total);
cameFrom.fill(-1);
const closed = new Uint8Array(total);
const open = new MinHeap();
const startIndex = nearestGridIndex(start.x, start.z);
const endIndex = nearestGridIndex(end.x, end.z);
if (blocked[startIndex] || blocked[endIndex]) return null;
gScore[startIndex] = 0;
open.push({ index: startIndex, f: 0 });
const heuristic = index => {
const a = gridCenter(index);
const b = gridCenter(endIndex);
return Math.hypot(a.x - b.x, a.z - b.z);
};
let reached = false;
while (open.size) {
const current = open.pop();
const index = current.index;
if (closed[index]) continue;
closed[index] = 1;
if (index === endIndex) {
reached = true;
break;
}
const cx = index % GRID.cols;
const cz = Math.floor(index / GRID.cols);
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
if (!dx && !dz) continue;
const nx = cx + dx;
const nz = cz + dz;
if (nx < 0 || nz < 0 || nx >= GRID.cols || nz >= GRID.rows) continue;
const next = nx + nz * GRID.cols;
if (blocked[next] || closed[next]) continue;
// Do not cut diagonally through blocked corners.
if (dx && dz) {
if (blocked[cx + dx + cz * GRID.cols] ||
blocked[cx + (cz + dz) * GRID.cols]) continue;
}
const step = dx && dz ? Math.SQRT2 : 1;
const tentative = gScore[index] + step;
if (tentative < gScore[next]) {
gScore[next] = tentative;
cameFrom[next] = index;
open.push({ index: next, f: tentative + heuristic(next) });
}
}
}
}
if (!reached) return null;
const indices = [];
let cursor = endIndex;
while (cursor !== -1) {
indices.push(cursor);
if (cursor === startIndex) break;
cursor = cameFrom[cursor];
}
indices.reverse();
const points = indices.map(gridCenter);
points.unshift({ x: start.x, z: start.z });
points.push({ x: end.x, z: end.z });
let length = 0;
const cumulative = [0];
for (let i = 1; i < points.length; i++) {
length += Math.hypot(
points[i].x - points[i - 1].x,
points[i].z - points[i - 1].z
);
cumulative.push(length);
}
return { points, length, cumulative };
}
const routeDefinitions = [
{
id: "west",
color: 0x2e9b91,
start: { x: -35, z: 7 },
end: { x: -10, z: -10.25 }
},
{
id: "south",
color: 0x3979a5,
start: { x: 0, z: 26.5 },
end: { x: -10, z: -10.25 }
},
{
id: "east",
color: 0x8866a8,
start: { x: 35, z: 7 },
end: { x: 20.75, z: 4 }
},
{
id: "north",
color: 0xd29a37,
start: { x: 13, z: -9.5 },
end: { x: 20.75, z: 4 }
}
];
function computeAllRoutes(seatPositions = worldSeatPositions(), stage = state.stage) {
blockedCache = buildBlockedGrid(seatPositions, stage);
return routeDefinitions.map(definition => {
const path = findPath(blockedCache, definition.start, definition.end);
return {
...definition,
reachable: !!path,
points: path ? path.points : [],
length: path ? path.length : 0,
cumulative: path ? path.cumulative : []
};
});
}
// -------------------------------------------------------------------------
// Route and pressure visualization
// -------------------------------------------------------------------------
const routeMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1.02, 0.085, 1.02),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0.9,
depthWrite: false
}),
5000
);
routeMesh.count = 0;
routeMesh.renderOrder = 3;
scene.add(routeMesh);
const pressureMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(GRID.cell * 0.91, 0.035, GRID.cell * 0.91),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0.48,
depthWrite: false
}),
GRID.size
);
pressureMesh.count = 0;
pressureMesh.renderOrder = 2;
scene.add(pressureMesh);
const walkerGroups = [];
const walkerBodies = [];
for (const route of routeDefinitions) {
const group = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color: route.color,
roughness: 0.75
});
const body = box(0.27, 0.48, 0.27, bodyMaterial, 0, 0.4, 0, group);
const head = box(0.23, 0.23, 0.23, materials.cream, 0, 0.77, 0, group);
body.castShadow = true;
head.castShadow = true;
walkerGroups.push(group);
walkerBodies.push({ body, head });
scene.add(group);
}
const routeMatrix = new THREE.Matrix4();
const heatColors = [
new THREE.Color(0x45a9a0),
new THREE.Color(0xe2b54b),
new THREE.Color(0xdf684c)
];
let activeRouteData = [];
let baselineLength = 1;
function applyRouteData(data) {
activeRouteData = data;
let routeInstance = 0;
const pressure = new Float32Array(GRID.size);
data.forEach((route, routeIndex) => {
if (!route.reachable) return;
route.points.forEach(point => {
if (routeInstance < routeMesh.count + 1 || routeInstance < 5000) {
routeMatrix.makeTranslation(point.x, 0.24, point.z);
routeMesh.setMatrixAt(routeInstance, routeMatrix);
routeMesh.setColorAt(routeInstance, new THREE.Color(route.color));
routeInstance++;
}
const gx = Math.round((point.x - GRID.minX) / GRID.cell);
const gz = Math.round((point.z - GRID.minZ) / GRID.cell);
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
const x = gx + dx;
const z = gz + dz;
if (x < 0 || z < 0 || x >= GRID.cols || z >= GRID.rows) continue;
const index = x + z * GRID.cols;
const weight = dx === 0 && dz === 0 ? 1 : 0.32;
pressure[index] += weight;
}
}
});
});
routeMesh.count = routeInstance;
routeMesh.instanceMatrix.needsUpdate = true;
if (routeMesh.instanceColor) routeMesh.instanceColor.needsUpdate = true;
// Two inexpensive blur passes create a readable pedestrian pressure field.
const blurred = new Float32Array(GRID.size);
for (let pass = 0; pass < 2; pass++) {
for (let z = 0; z < GRID.rows; z++) {
for (let x = 0; x < GRID.cols; x++) {
const index = x + z * GRID.cols;
let sum = pressure[index] * 2;
let weight = 2;
for (const [dx, dz] of [[1,0],[-1,0],[0,1],[0,-1]]) {
const nx = x + dx;
const nz = z + dz;
if (nx < 0 || nz < 0 || nx >= GRID.cols || nz >= GRID.rows) continue;
sum += pressure[nx + nz * GRID.cols];
weight++;
}
blurred[index] = sum / weight;
}
}
pressure.set(blurred);
}
let maxPressure = 0;
for (const value of pressure) maxPressure = Math.max(maxPressure, value);
let heatInstance = 0;
for (let index = 0; index < pressure.length; index++) {
if (pressure[index] <= 0.015) continue;
const normalized = maxPressure ? pressure[index] / maxPressure : 0;
const color = normalized < 0.34 ? heatColors[0] :
normalized < 0.67 ? heatColors[1] : heatColors[2];
const point = gridCenter(index);
routeMatrix.makeTranslation(point.x, 0.17, point.z);
pressureMesh.setMatrixAt(heatInstance, routeMatrix);
pressureMesh.setColorAt(heatInstance, color);
heatInstance++;
}
pressureMesh.count = heatInstance;
pressureMesh.instanceMatrix.needsUpdate = true;
if (pressureMesh.instanceColor) pressureMesh.instanceColor.needsUpdate = true;
updateMetrics(data, maxPressure);
}
function routeUsesAudienceAisle(route) {
if (!route.reachable) return false;
const c = Math.cos(state.audience.rot);
const s = Math.sin(state.audience.rot);
return route.points.some(point => {
const dx = point.x - state.audience.x;
const dz = point.z - state.audience.z;
const localX = c * dx - s * dz;
const localZ = s * dx + c * dz;
const halfDepth = (state.rows - 1) * 1.35 / 2 + 0.6;
return Math.abs(localX) < state.aisle / 2 + 0.4 &&
Math.abs(localZ) < halfDepth;
});
}
function updateMetrics(data, maxPressure = 1) {
const connected = data.filter(route => route.reachable).length;
const totalLength = data.reduce((sum, route) => sum + route.length, 0);
const detour = Math.max(0, totalLength - baselineLength);
const aisleRoutes = data.filter(routeUsesAudienceAisle).length;
const pressureScore = Math.max(
0,
Math.min(
100,
Math.round(22 + detour * 0.12 + aisleRoutes * 8 + maxPressure * 6)
)
);
document.getElementById("connectedStat").textContent = `${connected} / 4`;
document.getElementById("lengthStat").textContent = `${Math.round(totalLength)} m`;
document.getElementById("detourStat").textContent = `+${Math.round(detour)} m`;
document.getElementById("pressureStat").textContent = pressureScore;
const status = document.getElementById("flowStatus");
status.classList.toggle("warn", connected < 4 || pressureScore > 74);
if (connected < 4) {
status.textContent = "One or more entrances are disconnected";
} else if (pressureScore > 74) {
status.textContent = "High pressure — widen or reposition seating";
} else if (aisleRoutes > 0) {
status.textContent = "Aisle is absorbing through-circulation";
} else {
status.textContent = "Entrances connected with moderate pressure";
}
}
function refreshRoutes() {
const data = computeAllRoutes();
applyRouteData(data);
return data;
}
const baselineData = computeAllRoutes([], null);
baselineLength = baselineData.reduce((sum, route) => sum + route.length, 0);
applyRouteData(baselineData);
// -------------------------------------------------------------------------
// Placement ghost and UI feedback
// -------------------------------------------------------------------------
const ghost = new THREE.Mesh(
new THREE.BoxGeometry(1, 0.08, 1),
new THREE.MeshBasicMaterial({
color: 0x36a99d,
transparent: true,
opacity: 0.42,
depthWrite: false
})
);
ghost.visible = false;
ghost.renderOrder = 4;
scene.add(ghost);
const toast = document.getElementById("toast");
let toastTimer;
function showToast(message, error = false) {
toast.textContent = message;
toast.classList.toggle("error", error);
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 3200);
}
function updateSelectionLabel() {
document.getElementById("selectionLabel").textContent =
state.selected === "stage" ? "Stage selected" : "Audience selected";
}
const toolButtons = [...document.querySelectorAll("[data-tool]")];
function setMode(mode) {
state.mode = mode;
state.selected = mode === "audience" ? "audience" :
mode === "stage" ? "stage" : state.selected;
toolButtons.forEach(button => {
button.classList.toggle("active", button.dataset.tool === mode);
});
ghost.visible = mode !== "inspect";
updateSelectionLabel();
const hint = document.getElementById("toolHint");
if (mode === "stage") {
hint.textContent = "Click an open plaza location to move the stage. It will remain clear of buildings, seats, and entrance aprons.";
} else if (mode === "audience") {
hint.textContent = "Click to reposition the audience. It automatically faces the stage while keeping entrance approaches open.";
} else {
hint.textContent = "Choose a placement tool, then click an open area of the plaza. Entrance aprons are protected and cannot be blocked.";
}
}
toolButtons.forEach(button => {
button.addEventListener("click", () => setMode(button.dataset.tool));
});
function commitStage(candidate) {
const previous = { ...state.stage };
const error = validateStage(candidate);
if (error) {
showToast(error, true);
return false;
}
state.stage = { ...candidate };
const routes = computeAllRoutes();
if (routes.some(route => !route.reachable)) {
state.stage = previous;
showToast("That stage position blocks an entrance route. Try another location.", true);
updateStageTransform();
return false;
}
updateStageTransform();
applyRouteData(routes);
showToast("Stage moved. All entrance routes were checked.");
return true;
}
function commitAudience(candidate, locals = localSeatPositions()) {
const previous = { ...state.audience };
const error = validateAudience(candidate, locals);
if (error) {
showToast(error, true);
return false;
}
state.audience = { ...candidate };
const routes = computeAllRoutes(worldSeatPositions(candidate, locals), state.stage);
if (routes.some(route => !route.reachable)) {
state.audience = previous;
showToast("That audience position blocks an entrance route. Try another location.", true);
return false;
}
buildAudience();
applyRouteData(routes);
showToast("Audience moved. Circulation routes have been recalculated.");
return true;
}
function rotateSelected(delta = Math.PI / 12) {
if (state.selected === "stage") {
const candidate = { ...state.stage, rot: state.stage.rot + delta };
commitStage(candidate);
} else {
const candidate = { ...state.audience, rot: state.audience.rot + delta };
commitAudience(candidate);
}
}
document.getElementById("rotateButton").addEventListener("click", () => {
rotateSelected();
});
document.getElementById("faceButton").addEventListener("click", () => {
const oldStage = { ...state.stage };
const oldAudience = { ...state.audience };
const candidateStage = {
...state.stage,
rot: Math.atan2(
state.audience.x - state.stage.x,
state.audience.z - state.stage.z
)
};
const candidateAudience = {
...state.audience,
rot: Math.atan2(
state.stage.x - state.audience.x,
state.stage.z - state.audience.z
)
};
if (
validateStage(candidateStage) ||
validateAudience(candidateAudience)
) {
showToast("The two objects cannot be turned toward each other here.", true);
return;
}
state.stage = candidateStage;
state.audience = candidateAudience;
const routes = computeAllRoutes();
if (routes.some(route => !route.reachable)) {
state.stage = oldStage;
state.audience = oldAudience;
showToast("Turning the objects would disconnect an entrance.", true);
return;
}
updateStageTransform();
buildAudience();
applyRouteData(routes);
showToast("Stage and audience are now facing each other.");
});
function updateSeatingFromControls() {
const old = {
rows: state.rows,
seats: state.seats,
aisle: state.aisle
};
state.rows = Number(document.getElementById("rows").value);
state.seats = Number(document.getElementById("seats").value);
state.aisle = Number(document.getElementById("aisle").value);
document.getElementById("rowsOutput").value = state.rows;
document.getElementById("seatsOutput").value = state.seats;
document.getElementById("aisleOutput").value = `${state.aisle.toFixed(1)} m`;
buildAudience();
if (validateAudience(state.audience)) {
Object.assign(state, old);
buildAudience();
showToast("That seating overlaps a protected area.", true);
return;
}
const routes = computeAllRoutes();
if (routes.some(route => !route.reachable)) {
Object.assign(state, old);
buildAudience();
showToast(
"That seating closes an entrance route. Increase the aisle or move the audience.",
true
);
return;
}
applyRouteData(routes);
}
for (const id of ["rows", "seats", "aisle"]) {
document.getElementById(id).addEventListener("input", updateSeatingFromControls);
}
document.getElementById("routesToggle").addEventListener("change", event => {
state.showRoutes = event.target.checked;
routeMesh.visible = state.showRoutes;
walkerGroups.forEach(group => group.visible = state.showRoutes);
});
document.getElementById("pressureToggle").addEventListener("change", event => {
state.showPressure = event.target.checked;
pressureMesh.visible = state.showPressure;
});
document.getElementById("labelsToggle").addEventListener("change", event => {
state.showLabels = event.target.checked;
labels.forEach(label => label.visible = state.showLabels);
});
document.getElementById("resetButton").addEventListener("click", () => {
state.rows = 6;
state.seats = 10;
state.aisle = 2.2;
state.stage = { x: -10, z: 3, rot: 0.86 };
state.audience = { x: 5, z: 16, rot: -2.28 };
document.getElementById("rows").value = state.rows;
document.getElementById("seats").value = state.seats;
document.getElementById("aisle").value = state.aisle;
document.getElementById("rowsOutput").value = state.rows;
document.getElementById("seatsOutput").value = state.seats;
document.getElementById("aisleOutput").value = `${state.aisle.toFixed(1)} m`;
buildAudience();
updateStageTransform();
applyRouteData(computeAllRoutes());
showToast("Example layout restored.");
});
// -------------------------------------------------------------------------
// Custom camera controls and placement interaction
// -------------------------------------------------------------------------
const cameraControl = {
target: new THREE.Vector3(0, 0, 3),
yaw: 0.59,
pitch: 0.72,
distance: 84,
desiredYaw: 0.59,
desiredPitch: 0.72,
desiredDistance: 84
};
function updateCamera() {
cameraControl.yaw += (cameraControl.desiredYaw - cameraControl.yaw) * 0.12;
cameraControl.pitch += (cameraControl.desiredPitch - cameraControl.pitch) * 0.12;
cameraControl.distance +=
(cameraControl.desiredDistance - cameraControl.distance) * 0.12;
const horizontal = Math.cos(cameraControl.pitch) * cameraControl.distance;
camera.position.set(
cameraControl.target.x + Math.sin(cameraControl.yaw) * horizontal,
cameraControl.target.y + Math.sin(cameraControl.pitch) * cameraControl.distance,
cameraControl.target.z + Math.cos(cameraControl.yaw) * horizontal
);
camera.lookAt(cameraControl.target);
}
updateCamera();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const canvas = renderer.domElement;
function setRayFromEvent(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);
}
function plazaPoint(event) {
setRayFromEvent(event);
const hit = raycaster.intersectObject(tiles, false)[0];
return hit ? hit.point : null;
}
function updateGhost(event) {
if (state.mode === "inspect") {
ghost.visible = false;
return;
}
const point = plazaPoint(event);
if (!point) {
ghost.visible = false;
return;
}
const x = Math.round(point.x * 2) / 2;
const z = Math.round(point.z * 2) / 2;
let error = null;
if (state.mode === "stage") {
const candidate = { ...state.stage, x, z };
error = validateStage(candidate);
ghost.scale.set(7, 1, 5);
} else {
const candidate = {
...state.audience,
x,
z,
rot: Math.atan2(state.stage.x - x, state.stage.z - z)
};
error = validateAudience(candidate);
const width = Math.max(5, state.seats * 0.6 + state.aisle);
const depth = Math.max(3, (state.rows - 1) * 1.35);
ghost.scale.set(width, 1, depth);
}
ghost.position.set(x, 0.31, z);
ghost.material.color.set(error ? 0xdf684c : 0x36a99d);
ghost.visible = true;
}
function findPartAncestor(object) {
while (object) {
if (object.userData.part) return object.userData.part;
object = object.parent;
}
return null;
}
function pickPart(event) {
setRayFromEvent(event);
const hit = raycaster.intersectObjects([stageGroup, audienceGroup], true)[0];
if (!hit) return;
const part = findPartAncestor(hit.object);
if (part) {
state.selected = part;
updateSelectionLabel();
}
}
let pointerState = null;
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
pointerState = {
id: event.pointerId,
button: event.button,
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false
};
});
canvas.addEventListener("pointermove", event => {
if (!pointerState) {
updateGhost(event);
return;
}
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
const totalDistance = Math.hypot(
event.clientX - pointerState.startX,
event.clientY - pointerState.startY
);
if (totalDistance > 4) pointerState.moved = true;
if (pointerState.moved) {
if (pointerState.button === 2 || pointerState.button === 1) {
const scale = cameraControl.distance * 0.0015;
const right = new THREE.Vector3(
Math.cos(cameraControl.yaw),
0,
-Math.sin(cameraControl.yaw)
);
const forward = new THREE.Vector3(
-Math.sin(cameraControl.yaw),
0,
-Math.cos(cameraControl.yaw)
);
cameraControl.target.addScaledVector(right, -dx * scale);
cameraControl.target.addScaledVector(forward, -dy * scale);
} else {
cameraControl.desiredYaw -= dx * 0.005;
cameraControl.desiredPitch += dy * 0.004;
cameraControl.desiredPitch = THREE.MathUtils.clamp(
cameraControl.desiredPitch,
0.22,
1.35
);
}
}
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
updateGhost(event);
});
canvas.addEventListener("pointerup", event => {
if (!pointerState || pointerState.id !== event.pointerId) return;
const wasClick = !pointerState.moved && pointerState.button === 0;
if (wasClick && state.mode === "inspect") {
pickPart(event);
} else if (wasClick && state.mode !== "inspect") {
const point = plazaPoint(event);
if (point) {
const x = Math.round(point.x * 2) / 2;
const z = Math.round(point.z * 2) / 2;
if (state.mode === "stage") {
commitStage({ ...state.stage, x, z });
} else {
commitAudience({
...state.audience,
x,
z,
rot: Math.atan2(state.stage.x - x, state.stage.z - z)
});
}
}
}
pointerState = null;
updateGhost(event);
});
canvas.addEventListener("pointercancel", () => {
pointerState = null;
});
canvas.addEventListener("pointerleave", () => {
if (!pointerState) ghost.visible = false;
});
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraControl.desiredDistance = THREE.MathUtils.clamp(
cameraControl.desiredDistance + event.deltaY * 0.065,
35,
135
);
}, { passive: false });
function nudgeSelected(dx, dz) {
if (state.selected === "stage") {
commitStage({
...state.stage,
x: state.stage.x + dx,
z: state.stage.z + dz
});
} else {
commitAudience({
...state.audience,
x: state.audience.x + dx,
z: state.audience.z + dz
});
}
}
window.addEventListener("keydown", event => {
if (["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement.tagName)) {
return;
}
if (event.key.toLowerCase() === "r") {
rotateSelected();
} else if (event.key === "ArrowLeft") {
event.preventDefault();
nudgeSelected(-1, 0);
} else if (event.key === "ArrowRight") {
event.preventDefault();
nudgeSelected(1, 0);
} else if (event.key === "ArrowUp") {
event.preventDefault();
nudgeSelected(0, -1);
} else if (event.key === "ArrowDown") {
event.preventDefault();
nudgeSelected(0, 1);
} else if (event.key === "Escape") {
setMode("inspect");
ghost.visible = false;
}
});
// -------------------------------------------------------------------------
// Animated pedestrians and render loop
// -------------------------------------------------------------------------
function sampleRoute(route, distance) {
if (!route.reachable || route.points.length < 2) return null;
const d = ((distance % route.length) + route.length) % route.length;
for (let i = 1; i < route.cumulative.length; i++) {
if (d <= route.cumulative[i]) {
const segmentLength = route.cumulative[i] - route.cumulative[i - 1];
const t = segmentLength
? (d - route.cumulative[i - 1]) / segmentLength
: 0;
const a = route.points[i - 1];
const b = route.points[i];
return {
x: THREE.MathUtils.lerp(a.x, b.x, t),
z: THREE.MathUtils.lerp(a.z, b.z, t),
angle: Math.atan2(b.x - a.x, b.z - a.z)
};
}
}
return { ...route.points[route.points.length - 1], angle: 0 };
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
updateCamera();
walkerGroups.forEach((group, index) => {
const route = activeRouteData[index];
if (!route || !route.reachable) {
group.visible = false;
return;
}
group.visible = state.showRoutes;
const speed = 2.2 + index * 0.18;
const sample = sampleRoute(route, elapsed * speed + index * 13);
if (!sample) return;
group.position.set(sample.x, 0, sample.z);
group.rotation.y = sample.angle;
const walker = walkerBodies[index];
const bob = Math.sin(elapsed * 8 + index) * 0.035;
walker.body.position.y = 0.4 + bob;
walker.head.position.y = 0.77 + bob;
});
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
document.getElementById("loading").remove();
animate();
</script>
</body>
</html>
```