Prompt specification
Build or customize the Three.js 3D scene "Place a public screen event within an irregular plaza" 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: Place a public screen event within an irregular plaza
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/place-a-public-screen-event-within-an-irregular-plaza-x3008
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring a voxel public-screen event in an irregular plaza. Keep the surrounding building edges, steps, and terrace levels fixed, and place one temporary screen along a suitable edge of the square. Let users move a few rectangular viewing zones and connect walking corridors between entrances. Show which zones have an unobstructed view of the screen and whether the corridors remain connected around them. A seated audience can be represented by sparse simple figures rather than a dense crowd. The event layout is fictional; the exercise concerns sightlines and circulation within the chosen plaza geometry.
Working Three.js Starter (place-a-public-screen-event-within-an-irregular-plaza-x3008):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Plaza Sightline Lab</title>
<style>
:root {
color-scheme: light;
--ink: #17212b;
--muted: #647383;
--panel: rgba(250, 252, 253, 0.94);
--line: rgba(23, 33, 43, 0.12);
--blue: #2878e3;
--green: #20a982;
--red: #e94e68;
--amber: #f2b84b;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
background: #dce5ea;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.panel {
position: absolute;
top: 18px;
left: 18px;
width: 342px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 18px;
border: 1px solid rgba(255, 255, 255, 0.82);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 18px 48px rgba(31, 47, 59, 0.16),
0 2px 8px rgba(31, 47, 59, 0.08);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
z-index: 10;
}
.eyebrow {
margin-bottom: 6px;
color: var(--blue);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 24px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.intro {
margin: 9px 0 15px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.fixed-note {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 14px;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.62);
color: #52606e;
font-size: 11px;
line-height: 1.35;
}
.fixed-note::before {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: #7a8792;
content: "";
}
.section {
margin-top: 15px;
padding-top: 14px;
border-top: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
font-size: 12px;
font-weight: 800;
}
.section-title small {
color: var(--muted);
font-size: 10px;
font-weight: 600;
}
.zone-list,
.corridor-list {
display: grid;
gap: 6px;
}
.list-button {
display: flex;
width: 100%;
align-items: center;
gap: 8px;
padding: 8px 9px;
border: 1px solid transparent;
border-radius: 9px;
background: rgba(255, 255, 255, 0.62);
cursor: pointer;
text-align: left;
font-size: 11px;
}
.list-button:hover,
.list-button.selected {
border-color: rgba(40, 120, 227, 0.32);
background: #fff;
}
.dot {
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 3px;
}
.list-button .status {
margin-left: auto;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.status.clear {
color: var(--green);
}
.status.blocked {
color: var(--red);
}
.status.open {
color: var(--green);
}
.selection {
margin-top: 10px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.54);
}
.selection-title {
margin-bottom: 8px;
font-size: 11px;
font-weight: 800;
}
.slider-row {
display: grid;
grid-template-columns: 14px 1fr 44px;
align-items: center;
gap: 8px;
margin: 6px 0;
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.slider-row output {
color: var(--ink);
text-align: right;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--blue);
}
.button-row {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.button {
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 9px;
background: #fff;
cursor: pointer;
font-size: 10px;
font-weight: 750;
transition:
transform 0.12s ease,
border-color 0.12s ease,
background 0.12s ease;
}
.button:hover {
transform: translateY(-1px);
border-color: rgba(40, 120, 227, 0.4);
}
.button.active {
border-color: var(--blue);
background: var(--blue);
color: white;
}
.button.danger {
color: var(--red);
}
.entrance-row {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
margin-top: 8px;
}
.entrance-row .button {
padding: 8px 4px;
}
.hint {
min-height: 30px;
margin-top: 8px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.stats {
position: absolute;
top: 18px;
right: 18px;
display: grid;
width: 218px;
gap: 8px;
z-index: 9;
}
.stat-card {
padding: 12px 14px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 13px;
background: rgba(250, 252, 253, 0.9);
box-shadow: 0 8px 24px rgba(31, 47, 59, 0.11);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
.stat-label {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.stat-value {
margin-top: 3px;
font-size: 18px;
font-weight: 850;
letter-spacing: -0.025em;
}
.stat-detail {
margin-top: 2px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.viewbar {
position: absolute;
right: 18px;
bottom: 18px;
display: flex;
gap: 6px;
padding: 6px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 12px;
background: rgba(250, 252, 253, 0.9);
box-shadow: 0 8px 24px rgba(31, 47, 59, 0.11);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
z-index: 9;
}
.viewbar .button {
border-color: transparent;
background: transparent;
}
.viewbar .button:hover,
.viewbar .button.active {
background: #e8eff6;
}
.toast {
position: absolute;
left: 50%;
bottom: 22px;
max-width: min(520px, calc(100vw - 40px));
padding: 10px 14px;
transform: translate(-50%, 20px);
border-radius: 10px;
background: rgba(23, 33, 43, 0.9);
color: #fff;
font-size: 11px;
line-height: 1.4;
opacity: 0;
pointer-events: none;
transition:
opacity 0.2s ease,
transform 0.2s ease;
z-index: 20;
}
.toast.visible {
transform: translate(-50%, 0);
opacity: 1;
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
color: var(--muted);
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.legend-swatch {
width: 12px;
height: 7px;
border-radius: 2px;
}
@media (max-width: 760px) {
.panel {
top: 10px;
left: 10px;
width: min(330px, calc(100vw - 20px));
max-height: 48vh;
padding: 14px;
}
.stats {
top: auto;
right: 10px;
bottom: 62px;
width: 190px;
}
.stat-card {
padding: 9px 11px;
}
.stat-value {
font-size: 15px;
}
.viewbar {
right: 10px;
bottom: 10px;
}
.toast {
bottom: 66px;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<aside class="panel">
<div class="eyebrow">Public Realm / Event Planning</div>
<h1>Plaza Sightline Lab</h1>
<p class="intro">
Move the temporary viewing zones, test their screen sightlines, and route
walking corridors between entrances.
</p>
<div class="fixed-note">
Plaza outline, buildings, steps, terraces, and the service core are fixed.
Only zones and corridor routes are editable.
</div>
<section class="section">
<div class="section-title">
<span>Viewing zones</span>
<small>Drag zones in the scene</small>
</div>
<div id="zoneList" class="zone-list"></div>
<div id="zoneSelection" class="selection">
<div id="zoneSelectionTitle" class="selection-title">Select a zone</div>
<label class="slider-row">
X
<input id="zoneX" type="range" min="-13" max="13" step="0.1" />
<output id="zoneXValue"></output>
</label>
<label class="slider-row">
Z
<input id="zoneZ" type="range" min="-9" max="9.5" step="0.1" />
<output id="zoneZValue"></output>
</label>
<label class="slider-row">
W
<input id="zoneW" type="range" min="3" max="8" step="0.1" />
<output id="zoneWValue"></output>
</label>
<label class="slider-row">
D
<input id="zoneD" type="range" min="2.5" max="6" step="0.1" />
<output id="zoneDValue"></output>
</label>
</div>
</section>
<section class="section">
<div class="section-title">
<span>Walking corridors</span>
<small>Select a route to edit</small>
</div>
<div class="button-row">
<button id="routeButton" class="button">Connect entrances</button>
<button id="addBendButton" class="button">Add bend</button>
<button id="deleteCorridorButton" class="button danger">Delete route</button>
</div>
<div class="entrance-row">
<button class="button entrance-button" data-entrance="A">A</button>
<button class="button entrance-button" data-entrance="B">B</button>
<button class="button entrance-button" data-entrance="C">C</button>
<button class="button entrance-button" data-entrance="D">D</button>
</div>
<div id="routeHint" class="hint">
Click “Connect entrances”, then choose two entrances. Drag yellow route
handles to move a corridor around an obstruction.
</div>
<div id="corridorList" class="corridor-list"></div>
</section>
<section class="section">
<div class="section-title"><span>Legend</span></div>
<div class="legend">
<div class="legend-item">
<span class="legend-swatch" style="background:#20a982"></span>
Clear screen view
</div>
<div class="legend-item">
<span class="legend-swatch" style="background:#e94e68"></span>
Blocked sightline
</div>
<div class="legend-item">
<span class="legend-swatch" style="background:#2878e3"></span>
Open corridor
</div>
<div class="legend-item">
<span class="legend-swatch" style="background:#f2b84b"></span>
Editable route handle
</div>
</div>
</section>
</aside>
<div class="stats">
<div class="stat-card">
<div class="stat-label">Screen sightlines</div>
<div id="sightlineStat" class="stat-value">—</div>
<div class="stat-detail">Clear means the zone center has an unobstructed screen sightline.</div>
</div>
<div class="stat-card">
<div class="stat-label">Entrance connectivity</div>
<div id="connectionStat" class="stat-value">—</div>
<div id="connectionDetail" class="stat-detail"></div>
</div>
</div>
<div class="viewbar">
<button id="orbitButton" class="button active">Orbit</button>
<button id="topButton" class="button">Top view</button>
<button id="resetButton" class="button">Reset view</button>
</div>
<div id="toast" class="toast"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and renderer
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const toast = document.querySelector("#toast");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce5ea);
scene.fog = new THREE.Fog(0xdce5ea, 38, 78);
const camera = new THREE.PerspectiveCamera(44, 1, 0.1, 160);
const cameraTarget = new THREE.Vector3(0, 0, 0);
let cameraRadius = 42;
let cameraTheta = 0.68;
let cameraPhi = 0.88;
let topView = false;
const hemisphere = new THREE.HemisphereLight(0xf4fbff, 0x87939b, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff4df, 3.2);
sun.position.set(-18, 30, 16);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -32;
sun.shadow.camera.right = 32;
sun.shadow.camera.top = 32;
sun.shadow.camera.bottom = -32;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 80;
sun.shadow.bias = -0.0003;
scene.add(sun);
const screenLight = new THREE.PointLight(0x6ddcff, 22, 18, 2);
screenLight.position.set(0, 4.2, -8.8);
scene.add(screenLight);
// -------------------------------------------------------------------------
// Geometry and data
// -------------------------------------------------------------------------
const plazaPolygon = [
[-16, -12],
[13, -12],
[16, -7],
[15, 9],
[8, 12],
[-11, 12],
[-16, 7],
[-15, -5]
];
const screen = {
centerX: 0,
centerZ: -10.85,
centerY: 3.7,
width: 12.4,
height: 3.8
};
const fixedObstacles = [
{
id: "service core",
x: 1.6,
z: -5.4,
width: 2.2,
depth: 2.4,
height: 3.3
},
{
id: "light tower",
x: -6.9,
z: -6.25,
width: 0.55,
depth: 0.55,
height: 3.05
}
];
const entrances = [
{ id: "A", name: "West entrance", x: -15.45, z: -1.0 },
{ id: "B", name: "South entrance", x: -1.0, z: 11.65 },
{ id: "C", name: "East entrance", x: 15.15, z: 4.5 },
{ id: "D", name: "Northwest entrance", x: -10.8, z: -10.65 }
];
const zones = [];
const corridors = [];
const zoneMeshes = [];
const entranceMeshes = [];
const corridorMeshes = [];
const waypointMeshes = [];
let selectedZone = null;
let selectedCorridor = null;
let connectMode = false;
let firstEntrance = null;
let corridorCounter = 0;
const colors = {
clear: 0x20a982,
blocked: 0xe94e68,
corridor: 0x2878e3,
handle: 0xf2b84b
};
// -------------------------------------------------------------------------
// Small helpers
// -------------------------------------------------------------------------
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function terrainHeightAt(x, z) {
if (x >= 9.7 && z >= -5.1 && z <= 9.8) return 0.8;
if (x <= -12.8 && z >= -8.0 && z <= -2.0) return 0.45;
return 0;
}
function pointOnSegment(px, pz, ax, az, bx, bz) {
const dx = bx - ax;
const dz = bz - az;
const lengthSquared = dx * dx + dz * dz;
if (lengthSquared === 0) {
return Math.hypot(px - ax, pz - az) < 0.0001;
}
const t = clamp(((px - ax) * dx + (pz - az) * dz) / lengthSquared, 0, 1);
const x = ax + t * dx;
const z = az + t * dz;
return Math.hypot(px - x, pz - z) < 0.001;
}
function pointInPolygon(x, z, includeBoundary = false) {
let inside = false;
for (
let i = 0, j = plazaPolygon.length - 1;
i < plazaPolygon.length;
j = i++
) {
const a = plazaPolygon[i];
const b = plazaPolygon[j];
if (
includeBoundary &&
pointOnSegment(x, z, a[0], a[1], b[0], b[1])
) {
return true;
}
const intersects =
a[1] > z !== b[1] > z &&
x < ((b[0] - a[0]) * (z - a[1])) / (b[1] - a[1]) + a[0];
if (intersects) inside = !inside;
}
return inside;
}
function rectangleIntersectsRectangle(a, b) {
return (
a.x - a.width / 2 < b.x + b.width / 2 &&
a.x + a.width / 2 > b.x - b.width / 2 &&
a.z - a.depth / 2 < b.z + b.depth / 2 &&
a.z + a.depth / 2 > b.z - b.depth / 2
);
}
function segmentIntersectsRect(ax, az, bx, bz, rect) {
const dx = bx - ax;
const dz = bz - az;
let t0 = 0;
let t1 = 1;
const axes = [
[ax, dx, rect.x - rect.width / 2, rect.x + rect.width / 2],
[az, dz, rect.z - rect.depth / 2, rect.z + rect.depth / 2]
];
for (const [origin, direction, min, max] of axes) {
if (Math.abs(direction) < 1e-8) {
if (origin < min || origin > max) return null;
} else {
let near = (min - origin) / direction;
let far = (max - origin) / direction;
if (near > far) [near, far] = [far, near];
t0 = Math.max(t0, near);
t1 = Math.min(t1, far);
if (t0 > t1) return null;
}
}
if (t1 <= 0 || t0 >= 1) return null;
return clamp(t0, 0, 1);
}
function rayHitsObstacle(origin, target, obstacle) {
const dx = target.x - origin.x;
const dy = target.y - origin.y;
const dz = target.z - origin.z;
let tMin = 0;
let tMax = 1;
const horizontalAxes = [
[origin.x, dx, obstacle.x - obstacle.width / 2, obstacle.x + obstacle.width / 2],
[origin.z, dz, obstacle.z - obstacle.depth / 2, obstacle.z + obstacle.depth / 2]
];
for (const [start, direction, min, max] of horizontalAxes) {
if (Math.abs(direction) < 1e-8) {
if (start < min || start > max) return false;
} else {
let near = (min - start) / direction;
let far = (max - start) / direction;
if (near > far) [near, far] = [far, near];
tMin = Math.max(tMin, near);
tMax = Math.min(tMax, far);
if (tMin > tMax) return false;
}
}
if (Math.abs(dy) < 1e-8) {
if (origin.y < 0 || origin.y > obstacle.height) return false;
} else {
let near = (0 - origin.y) / dy;
let far = (obstacle.height - origin.y) / dy;
if (near > far) [near, far] = [far, near];
tMin = Math.max(tMin, near);
tMax = Math.min(tMax, far);
}
return tMax >= tMin;
}
function roundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
function createLabelSprite(text, options = {}) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(options.width ?? 3.8, options.height ?? 0.95, 1);
sprite.renderOrder = 20;
sprite.userData.setText = (nextText, nextColor = "#ffffff") => {
ctx.clearRect(0, 0, 512, 128);
roundedRect(ctx, 8, 12, 496, 104, 26);
ctx.fillStyle = "rgba(23,33,43,0.91)";
ctx.fill();
ctx.strokeStyle = nextColor;
ctx.lineWidth = 4;
ctx.stroke();
ctx.fillStyle = nextColor;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "700 36px system-ui, sans-serif";
ctx.fillText(nextText, 256, 66);
texture.needsUpdate = true;
};
sprite.userData.setText(text, options.color ?? "#ffffff");
return sprite;
}
function showToast(message) {
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(showToast.timer);
showToast.timer = setTimeout(() => toast.classList.remove("visible"), 2600);
}
function addBox(width, height, depth, x, y, z, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Fixed plaza, paving, buildings, terraces, and screen
// -------------------------------------------------------------------------
const stoneMaterial = new THREE.MeshStandardMaterial({
color: 0xcbd3d6,
roughness: 0.92,
metalness: 0.02
});
const terraceMaterial = new THREE.MeshStandardMaterial({
color: 0xb8c2c5,
roughness: 0.9
});
const buildingMaterial = new THREE.MeshStandardMaterial({
color: 0xaeb9c0,
roughness: 0.86
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x26323c,
roughness: 0.7,
metalness: 0.15
});
const plazaShape = new THREE.Shape();
plazaShape.moveTo(plazaPolygon[0][0], plazaPolygon[0][1]);
for (let i = 1; i < plazaPolygon.length; i++) {
plazaShape.lineTo(plazaPolygon[i][0], plazaPolygon[i][1]);
}
plazaShape.closePath();
const plazaGeometry = new THREE.ExtrudeGeometry(plazaShape, {
depth: 0.35,
bevelEnabled: false
});
plazaGeometry.rotateX(Math.PI / 2);
const plaza = new THREE.Mesh(plazaGeometry, stoneMaterial);
plaza.receiveShadow = true;
scene.add(plaza);
const surroundingGround = new THREE.Mesh(
new THREE.PlaneGeometry(130, 130),
new THREE.MeshStandardMaterial({
color: 0xb9c5ca,
roughness: 1
})
);
surroundingGround.rotation.x = -Math.PI / 2;
surroundingGround.position.y = -0.37;
surroundingGround.receiveShadow = true;
scene.add(surroundingGround);
function polygonIntervals(axis, value) {
const intervals = [];
const values = [];
for (let i = 0; i < plazaPolygon.length; i++) {
const a = plazaPolygon[i];
const b = plazaPolygon[(i + 1) % plazaPolygon.length];
if (axis === "x") {
if (
(a[0] <= value && b[0] > value) ||
(b[0] <= value && a[0] > value)
) {
const t = (value - a[0]) / (b[0] - a[0]);
values.push(a[1] + t * (b[1] - a[1]));
}
} else {
if (
(a[1] <= value && b[1] > value) ||
(b[1] <= value && a[1] > value)
) {
const t = (value - a[1]) / (b[1] - a[1]);
values.push(a[0] + t * (b[0] - a[0]));
}
}
}
values.sort((a, b) => a - b);
for (let i = 0; i + 1 < values.length; i += 2) {
intervals.push([values[i], values[i + 1]]);
}
return intervals;
}
const pavingVertices = [];
for (let x = -15; x <= 15; x += 3) {
for (const [z0, z1] of polygonIntervals("x", x)) {
pavingVertices.push(x, 0.018, z0, x, 0.018, z1);
}
}
for (let z = -12; z <= 12; z += 3) {
for (const [x0, x1] of polygonIntervals("z", z)) {
pavingVertices.push(x0, 0.018, z, x1, 0.018, z);
}
}
const pavingGeometry = new THREE.BufferGeometry();
pavingGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(pavingVertices, 3)
);
const paving = new THREE.LineSegments(
pavingGeometry,
new THREE.LineBasicMaterial({
color: 0x9ca9ad,
transparent: true,
opacity: 0.42
})
);
scene.add(paving);
const boundaryPoints = plazaPolygon.map(
([x, z]) => new THREE.Vector3(x, 0.035, z)
);
boundaryPoints.push(boundaryPoints[0].clone());
scene.add(
new THREE.Line(
new THREE.BufferGeometry().setFromPoints(boundaryPoints),
new THREE.LineBasicMaterial({ color: 0x66747b })
)
);
// Fixed building edges.
addBox(9, 7, 4.5, -10.3, 3.5, -15.2, buildingMaterial);
addBox(8, 9, 4.5, 1.1, 4.5, -15.7, buildingMaterial);
addBox(8.5, 6, 4.5, 11.2, 3, -15, buildingMaterial);
addBox(4.5, 8, 14, -18, 4, -1.5, buildingMaterial);
addBox(4.5, 6, 9, -18.1, 3, 10, buildingMaterial);
addBox(4.5, 7, 8, 18, 3.5, -2, buildingMaterial);
addBox(4.5, 5, 8, 18.1, 2.5, 10, buildingMaterial);
addBox(9, 5, 4, -7, 2.5, 15, buildingMaterial);
addBox(9, 6, 4, 7.5, 3, 15, buildingMaterial);
// East terrace and steps.
addBox(5.6, 0.8, 15, 12.5, 0.4, 2.35, terraceMaterial);
addBox(1.1, 0.6, 15, 9.15, 0.3, 2.35, terraceMaterial);
addBox(1.1, 0.4, 15, 8.5, 0.2, 2.35, terraceMaterial);
// Smaller northwest terrace and steps.
addBox(2.8, 0.45, 6, -14.1, 0.225, -5, terraceMaterial);
addBox(1.0, 0.3, 6, -12.45, 0.15, -5, terraceMaterial);
// Fixed sightline obstructions.
const coreMaterial = new THREE.MeshStandardMaterial({
color: 0x8e9aa0,
roughness: 0.88
});
addBox(
fixedObstacles[0].width,
fixedObstacles[0].height,
fixedObstacles[0].depth,
fixedObstacles[0].x,
fixedObstacles[0].height / 2,
fixedObstacles[0].z,
coreMaterial
);
addBox(
fixedObstacles[1].width,
fixedObstacles[1].height,
fixedObstacles[1].depth,
fixedObstacles[1].x,
fixedObstacles[1].height / 2,
fixedObstacles[1].z,
darkMaterial
);
// Temporary public screen.
addBox(13.1, 4.55, 0.42, 0, 3.7, -11.08, darkMaterial);
addBox(0.32, 1.35, 0.42, -4.7, 0.675, -11.08, darkMaterial);
addBox(0.32, 1.35, 0.42, 4.7, 0.675, -11.08, darkMaterial);
function makeScreenTexture() {
const c = document.createElement("canvas");
c.width = 1024;
c.height = 512;
const ctx = c.getContext("2d");
const gradient = ctx.createLinearGradient(0, 0, 1024, 512);
gradient.addColorStop(0, "#092b4c");
gradient.addColorStop(0.48, "#136b87");
gradient.addColorStop(1, "#1ab39c");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 1024, 512);
ctx.strokeStyle = "rgba(255,255,255,0.12)";
ctx.lineWidth = 2;
for (let x = 0; x <= 1024; x += 64) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, 512);
ctx.stroke();
}
for (let y = 0; y <= 512; y += 64) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(1024, y);
ctx.stroke();
}
ctx.fillStyle = "rgba(4,20,36,0.48)";
ctx.fillRect(0, 0, 1024, 512);
ctx.textAlign = "center";
ctx.fillStyle = "#ffffff";
ctx.font = "800 88px system-ui, sans-serif";
ctx.fillText("PUBLIC SCREEN", 512, 210);
ctx.font = "600 36px system-ui, sans-serif";
ctx.fillStyle = "#bcefff";
ctx.fillText("LIVE / PLAZA SESSION", 512, 285);
ctx.fillStyle = "#f5c65b";
ctx.beginPath();
ctx.arc(512, 365, 11, 0, Math.PI * 2);
ctx.fill();
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const screenMaterial = new THREE.MeshBasicMaterial({
map: makeScreenTexture()
});
const screenFace = new THREE.Mesh(
new THREE.PlaneGeometry(screen.width, screen.height),
screenMaterial
);
screenFace.position.set(screen.centerX, screen.centerY, -10.84);
scene.add(screenFace);
// -------------------------------------------------------------------------
// Sparse seated audience
// -------------------------------------------------------------------------
const audienceTorsoGeometry = new THREE.CylinderGeometry(0.17, 0.2, 0.48, 8);
const audienceHeadGeometry = new THREE.SphereGeometry(0.14, 10, 8);
const audienceLegGeometry = new THREE.BoxGeometry(0.12, 0.38, 0.13);
const audienceThighGeometry = new THREE.BoxGeometry(0.13, 0.12, 0.36);
const audienceArmGeometry = new THREE.BoxGeometry(0.09, 0.35, 0.09);
const audienceMaterials = [
new THREE.MeshStandardMaterial({ color: 0x526c86, roughness: 0.9 }),
new THREE.MeshStandardMaterial({ color: 0xc26961, roughness: 0.9 }),
new THREE.MeshStandardMaterial({ color: 0x567c68, roughness: 0.9 }),
new THREE.MeshStandardMaterial({ color: 0xa08a5c, roughness: 0.9 })
];
const skinMaterial = new THREE.MeshStandardMaterial({
color: 0xd5a27d,
roughness: 0.95
});
function createSeatedPerson(material) {
const person = new THREE.Group();
const torso = new THREE.Mesh(audienceTorsoGeometry, material);
torso.position.y = 0.66;
torso.castShadow = true;
person.add(torso);
const head = new THREE.Mesh(audienceHeadGeometry, skinMaterial);
head.position.y = 1.03;
head.castShadow = true;
person.add(head);
for (const side of [-1, 1]) {
const leg = new THREE.Mesh(audienceLegGeometry, darkMaterial);
leg.position.set(side * 0.1, 0.24, -0.25);
leg.castShadow = true;
person.add(leg);
const thigh = new THREE.Mesh(audienceThighGeometry, darkMaterial);
thigh.position.set(side * 0.1, 0.35, -0.1);
thigh.castShadow = true;
person.add(thigh);
const arm = new THREE.Mesh(audienceArmGeometry, material);
arm.position.set(side * 0.23, 0.64, -0.02);
arm.rotation.z = side * -0.12;
person.add(arm);
}
return person;
}
// -------------------------------------------------------------------------
// Viewing zones
// -------------------------------------------------------------------------
function createZone(id, x, z, width, depth) {
const group = new THREE.Group();
group.position.set(x, terrainHeightAt(x, z) + 0.035, z);
scene.add(group);
const fillMaterial = new THREE.MeshBasicMaterial({
color: colors.clear,
transparent: true,
opacity: 0.25,
depthWrite: false
});
const fill = new THREE.Mesh(
new THREE.BoxGeometry(width, 0.055, depth),
fillMaterial
);
fill.position.y = 0.028;
fill.userData.zoneId = id;
group.add(fill);
const outline = new THREE.LineSegments(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: colors.clear,
transparent: true,
opacity: 0.95
})
);
outline.position.y = 0.068;
group.add(outline);
const label = createLabelSprite(`${id} · CHECKING`, {
width: 3.6,
height: 0.9
});
label.position.set(0, 1.65, 0);
group.add(label);
const audience = new THREE.Group();
group.add(audience);
const zone = {
id,
group,
fill,
outline,
label,
audience,
width,
depth,
clear: false,
visibleRatio: 1,
blockReason: ""
};
zones.push(zone);
zoneMeshes.push(fill);
rebuildZoneGeometry(zone);
return zone;
}
function rebuildZoneGeometry(zone) {
zone.fill.geometry.dispose();
zone.fill.geometry = new THREE.BoxGeometry(zone.width, 0.055, zone.depth);
const hw = zone.width / 2;
const hd = zone.depth / 2;
const points = [
new THREE.Vector3(-hw, 0, -hd),
new THREE.Vector3(hw, 0, -hd),
new THREE.Vector3(hw, 0, hd),
new THREE.Vector3(-hw, 0, hd),
new THREE.Vector3(-hw, 0, -hd)
];
zone.outline.geometry.dispose();
zone.outline.geometry = new THREE.BufferGeometry().setFromPoints(points);
zone.audience.clear();
const layouts = [
[-0.31, -0.27],
[0.03, -0.30],
[0.30, -0.08],
[-0.27, 0.22],
[0.16, 0.28]
];
layouts.forEach(([fx, fz], index) => {
const person = createSeatedPerson(
audienceMaterials[(index + zones.indexOf(zone)) % audienceMaterials.length]
);
person.position.set(fx * zone.width, 0, fz * zone.depth);
person.rotation.y = Math.PI;
zone.audience.add(person);
});
}
const zone1 = createZone("V1", -4.8, 2.6, 7, 4);
const zone2 = createZone("V2", 11.5, 3.4, 4.2, 4.4);
const zone3 = createZone("V3", -9.4, -4.7, 5.2, 3.2);
selectedZone = zone1;
function canPlaceZone(zone, x, z, width = zone.width, depth = zone.depth) {
const hw = width / 2;
const hd = depth / 2;
const corners = [
[x - hw, z - hd],
[x + hw, z - hd],
[x + hw, z + hd],
[x - hw, z + hd]
];
if (!corners.every(([cx, cz]) => pointInPolygon(cx, cz, true))) {
return false;
}
const candidate = { x, z, width, depth };
return !fixedObstacles.some((obstacle) =>
rectangleIntersectsRectangle(candidate, obstacle)
);
}
function setZonePosition(zone, x, z) {
x = clamp(x, -13.2, 13.2);
z = clamp(z, -9.2, 9.5);
if (!canPlaceZone(zone, x, z)) return false;
zone.group.position.x = x;
zone.group.position.z = z;
zone.group.position.y = terrainHeightAt(x, z) + 0.035;
return true;
}
// -------------------------------------------------------------------------
// Entrances and editable corridors
// -------------------------------------------------------------------------
const entranceMaterial = new THREE.MeshStandardMaterial({
color: 0x2878e3,
emissive: 0x0b2e5e,
emissiveIntensity: 0.35,
roughness: 0.55
});
for (const entrance of entrances) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(0.4, 0.4, 0.28, 24),
entranceMaterial
);
mesh.position.set(entrance.x, 0.18, entrance.z);
mesh.castShadow = true;
mesh.userData.entranceId = entrance.id;
scene.add(mesh);
entrance.mesh = mesh;
entranceMeshes.push(mesh);
const label = createLabelSprite(entrance.id, {
width: 1.35,
height: 0.68,
color: "#8ed3ff"
});
label.position.set(entrance.x, 1.0, entrance.z);
scene.add(label);
entrance.label = label;
}
class PolylineCurve extends THREE.Curve {
constructor(points) {
super();
this.points = points;
this.lengths = [];
this.totalLength = 0;
for (let i = 0; i < points.length - 1; i++) {
const length = points[i].distanceTo(points[i + 1]);
this.lengths.push(length);
this.totalLength += length;
}
}
getPoint(t, target = new THREE.Vector3()) {
let distance = clamp(t, 0, 1) * this.totalLength;
for (let i = 0; i < this.lengths.length; i++) {
if (distance <= this.lengths[i] || i === this.lengths.length - 1) {
const localT = this.lengths[i] === 0 ? 0 : distance / this.lengths[i];
return target.lerpVectors(this.points[i], this.points[i + 1], localT);
}
distance -= this.lengths[i];
}
return target.copy(this.points[this.points.length - 1]);
}
}
const corridorMaterial = new THREE.MeshStandardMaterial({
color: colors.corridor,
roughness: 0.55,
metalness: 0.05
});
const handleGeometry = new THREE.SphereGeometry(0.26, 16, 12);
const handleMaterial = new THREE.MeshBasicMaterial({
color: colors.handle
});
function entranceById(id) {
return entrances.find((entrance) => entrance.id === id);
}
function createCorridor(fromId, toId, points = null) {
const from = entranceById(fromId);
const to = entranceById(toId);
if (!points) {
points = [
{ x: from.x, z: from.z },
{ x: (from.x + to.x) / 2, z: (from.z + to.z) / 2 },
{ x: to.x, z: to.z }
];
}
const corridor = {
id: `C${++corridorCounter}`,
fromId,
toId,
points,
handles: [],
blocked: false,
blockReason: ""
};
const mesh = new THREE.Mesh(
new THREE.BufferGeometry(),
corridorMaterial.clone()
);
mesh.userData.corridorId = corridor.id;
scene.add(mesh);
corridor.mesh = mesh;
corridorMeshes.push(mesh);
const dashedMaterial = new THREE.LineDashedMaterial({
color: colors.blocked,
dashSize: 0.55,
gapSize: 0.3,
transparent: true,
opacity: 0.95
});
const dashedLine = new THREE.Line(
new THREE.BufferGeometry(),
dashedMaterial
);
scene.add(dashedLine);
corridor.dashedLine = dashedLine;
const blockMarker = new THREE.Mesh(
new THREE.RingGeometry(0.32, 0.52, 24),
new THREE.MeshBasicMaterial({
color: colors.blocked,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.9
})
);
blockMarker.rotation.x = -Math.PI / 2;
blockMarker.visible = false;
scene.add(blockMarker);
corridor.blockMarker = blockMarker;
corridors.push(corridor);
syncWaypointHandles(corridor);
updateCorridorVisual(corridor);
return corridor;
}
function syncWaypointHandles(corridor) {
for (const handle of corridor.handles) {
scene.remove(handle);
}
waypointMeshes.splice(
0,
waypointMeshes.length,
...waypointMeshes.filter((mesh) => mesh.userData.corridorId !== corridor.id)
);
corridor.handles = [];
for (let i = 1; i < corridor.points.length - 1; i++) {
const point = corridor.points[i];
const handle = new THREE.Mesh(handleGeometry, handleMaterial);
handle.position.set(point.x, 0.32, point.z);
handle.userData.corridorId = corridor.id;
handle.userData.pointIndex = i;
handle.userData.type = "waypoint";
scene.add(handle);
corridor.handles.push(handle);
waypointMeshes.push(handle);
}
}
function updateCorridorVisual(corridor) {
const points = corridor.points.map(
(point) => new THREE.Vector3(point.x, 0.16, point.z)
);
const curve = new PolylineCurve(points);
const radius = corridor === selectedCorridor ? 0.18 : 0.12;
corridor.mesh.geometry.dispose();
corridor.mesh.geometry = new THREE.TubeGeometry(
curve,
Math.max(18, points.length * 10),
radius,
6,
false
);
corridor.mesh.material.color.set(
corridor.blocked ? colors.blocked : colors.corridor
);
corridor.dashedLine.geometry.dispose();
corridor.dashedLine.geometry = new THREE.BufferGeometry().setFromPoints(
points.map((point) => new THREE.Vector3(point.x, 0.21, point.z))
);
corridor.dashedLine.computeLineDistances();
corridor.dashedLine.visible = corridor.blocked;
corridor.blockMarker.visible = corridor.blocked;
if (corridor.blockMarker.visible && corridor.blockPoint) {
corridor.blockMarker.position.set(
corridor.blockPoint.x,
0.24,
corridor.blockPoint.z
);
}
}
createCorridor("A", "B", [
{ x: -15.45, z: -1 },
{ x: -12.0, z: 3.0 },
{ x: -6.0, z: 8.0 },
{ x: -1.0, z: 11.65 }
]);
createCorridor("B", "C", [
{ x: -1.0, z: 11.65 },
{ x: 5.0, z: 9.0 },
{ x: 11.0, z: 7.0 },
{ x: 15.15, z: 4.5 }
]);
createCorridor("A", "D", [
{ x: -15.45, z: -1 },
{ x: -12.2, z: -6.0 },
{ x: -10.8, z: -10.65 }
]);
// -------------------------------------------------------------------------
// Analysis: sightlines, corridor obstruction, graph connectivity
// -------------------------------------------------------------------------
function analyzeZoneSightline(zone) {
const centerX = zone.group.position.x;
const centerZ = zone.group.position.z;
const centerOrigin = new THREE.Vector3(
centerX,
terrainHeightAt(centerX, centerZ) + 0.95,
centerZ
);
const centerTarget = new THREE.Vector3(
screen.centerX,
screen.centerY,
screen.centerZ
);
let centerClear = true;
for (const obstacle of fixedObstacles) {
if (rayHitsObstacle(centerOrigin, centerTarget, obstacle)) {
centerClear = false;
break;
}
}
let visible = 0;
let samples = 0;
const zoneFractions = [-0.38, 0, 0.38];
const screenFractions = [-0.5, -0.25, 0, 0.25, 0.5];
for (const fx of zoneFractions) {
for (const fz of zoneFractions) {
const x = centerX + fx * zone.width;
const z = centerZ + fz * zone.depth;
const origin = new THREE.Vector3(
x,
terrainHeightAt(x, z) + 0.95,
z
);
for (const sf of screenFractions) {
const target = new THREE.Vector3(
screen.centerX + sf * screen.width,
screen.centerY,
screen.centerZ
);
const blocked = fixedObstacles.some((obstacle) =>
rayHitsObstacle(origin, target, obstacle)
);
if (!blocked) visible++;
samples++;
}
}
}
return {
clear: centerClear,
ratio: visible / samples
};
}
function analyzeCorridor(corridor) {
for (let s = 0; s < corridor.points.length - 1; s++) {
const a = corridor.points[s];
const b = corridor.points[s + 1];
for (const zone of zones) {
const rect = {
x: zone.group.position.x,
z: zone.group.position.z,
width: zone.width,
depth: zone.depth
};
const t = segmentIntersectsRect(a.x, a.z, b.x, b.z, rect);
if (t !== null) {
return {
blocked: true,
reason: `blocked by ${zone.id}`,
point: {
x: a.x + (b.x - a.x) * t,
z: a.z + (b.z - a.z) * t
}
};
}
}
for (const obstacle of fixedObstacles) {
const t = segmentIntersectsRect(a.x, a.z, b.x, b.z, obstacle);
if (t !== null) {
return {
blocked: true,
reason: `blocked by ${obstacle.id}`,
point: {
x: a.x + (b.x - a.x) * t,
z: a.z + (b.z - a.z) * t
}
};
}
}
for (const t of [0.25, 0.5, 0.75]) {
const x = a.x + (b.x - a.x) * t;
const z = a.z + (b.z - a.z) * t;
if (!pointInPolygon(x, z, true)) {
return {
blocked: true,
reason: "outside the plaza",
point: { x, z }
};
}
}
}
return {
blocked: false,
reason: "open",
point: null
};
}
function calculateComponents() {
const adjacency = new Map(entrances.map((entrance) => [entrance.id, []]));
for (const corridor of corridors) {
if (!corridor.blocked) {
adjacency.get(corridor.fromId).push(corridor.toId);
adjacency.get(corridor.toId).push(corridor.fromId);
}
}
const visited = new Set();
const components = [];
for (const entrance of entrances) {
if (visited.has(entrance.id)) continue;
const stack = [entrance.id];
const component = [];
while (stack.length) {
const id = stack.pop();
if (visited.has(id)) continue;
visited.add(id);
component.push(id);
for (const neighbor of adjacency.get(id)) {
if (!visited.has(neighbor)) stack.push(neighbor);
}
}
component.sort();
components.push(component);
}
return components;
}
function updateZoneAppearance(zone) {
const color = zone.clear ? colors.clear : colors.blocked;
zone.fill.material.color.setHex(color);
zone.outline.material.color.setHex(color);
zone.label.userData.setText(
`${zone.id} · ${zone.clear ? "CLEAR" : "BLOCKED"}`,
zone.clear ? "#75f0c6" : "#ff9caf"
);
}
function updateAnalysis() {
for (const zone of zones) {
const result = analyzeZoneSightline(zone);
zone.clear = result.clear;
zone.visibleRatio = result.ratio;
updateZoneAppearance(zone);
}
for (const corridor of corridors) {
const result = analyzeCorridor(corridor);
corridor.blocked = result.blocked;
corridor.blockReason = result.reason;
corridor.blockPoint = result.point;
updateCorridorVisual(corridor);
}
updateZoneList();
updateCorridorList();
updateStats();
syncSelectedInputs();
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const zoneList = document.querySelector("#zoneList");
const corridorList = document.querySelector("#corridorList");
const routeButton = document.querySelector("#routeButton");
const routeHint = document.querySelector("#routeHint");
const zoneX = document.querySelector("#zoneX");
const zoneZ = document.querySelector("#zoneZ");
const zoneW = document.querySelector("#zoneW");
const zoneD = document.querySelector("#zoneD");
const zoneXValue = document.querySelector("#zoneXValue");
const zoneZValue = document.querySelector("#zoneZValue");
const zoneWValue = document.querySelector("#zoneWValue");
const zoneDValue = document.querySelector("#zoneDValue");
function selectZone(zone) {
selectedZone = zone;
selectedCorridor = null;
updateZoneList();
updateCorridorList();
syncSelectedInputs();
updateAnalysis();
}
function selectCorridor(corridor) {
selectedCorridor = corridor;
selectedZone = null;
updateZoneList();
updateCorridorList();
updateAnalysis();
}
function updateZoneList() {
zoneList.replaceChildren();
for (const zone of zones) {
const button = document.createElement("button");
button.className = `list-button${selectedZone === zone ? " selected" : ""}`;
const dot = document.createElement("span");
dot.className = "dot";
dot.style.background = zone.clear ? "#20a982" : "#e94e68";
const title = document.createElement("span");
title.textContent = zone.id;
const status = document.createElement("span");
status.className = `status ${zone.clear ? "clear" : "blocked"}`;
status.textContent = zone.clear
? `clear · ${Math.round(zone.visibleRatio * 100)}% rays`
: "blocked";
button.append(dot, title, status);
button.addEventListener("click", () => selectZone(zone));
zoneList.append(button);
}
}
function updateCorridorList() {
corridorList.replaceChildren();
for (const corridor of corridors) {
const button = document.createElement("button");
button.className = `list-button${
selectedCorridor === corridor ? " selected" : ""
}`;
const dot = document.createElement("span");
dot.className = "dot";
dot.style.background = corridor.blocked ? "#e94e68" : "#2878e3";
const title = document.createElement("span");
title.textContent = `${corridor.id}: ${corridor.fromId} ↔ ${corridor.toId}`;
const status = document.createElement("span");
status.className = `status ${corridor.blocked ? "blocked" : "open"}`;
status.textContent = corridor.blocked ? "blocked" : "open";
button.append(dot, title, status);
button.addEventListener("click", () => selectCorridor(corridor));
corridorList.append(button);
}
}
function updateStats() {
const clearCount = zones.filter((zone) => zone.clear).length;
const openCount = corridors.filter((corridor) => !corridor.blocked).length;
const components = calculateComponents();
document.querySelector("#sightlineStat").textContent =
`${clearCount} / ${zones.length} zones clear`;
document.querySelector("#connectionStat").textContent =
components.length === 1
? "All entrances connected"
: `${components.length} entrance groups`;
document.querySelector("#connectionDetail").textContent =
`${openCount}/${corridors.length} routes open · ` +
components.map((component) => component.join("–")).join(" / ");
}
function syncSelectedInputs() {
const disabled = !selectedZone;
for (const input of [zoneX, zoneZ, zoneW, zoneD]) input.disabled = disabled;
document.querySelector("#zoneSelectionTitle").textContent = selectedZone
? `${selectedZone.id} geometry`
: "Select a zone";
if (!selectedZone) return;
zoneX.value = selectedZone.group.position.x.toFixed(1);
zoneZ.value = selectedZone.group.position.z.toFixed(1);
zoneW.value = selectedZone.width.toFixed(1);
zoneD.value = selectedZone.depth.toFixed(1);
zoneXValue.value = `${selectedZone.group.position.x.toFixed(1)} m`;
zoneZValue.value = `${selectedZone.group.position.z.toFixed(1)} m`;
zoneWValue.value = `${selectedZone.width.toFixed(1)} m`;
zoneDValue.value = `${selectedZone.depth.toFixed(1)} m`;
}
function handleZoneGeometryInput() {
if (!selectedZone) return;
const x = Number(zoneX.value);
const z = Number(zoneZ.value);
const width = Number(zoneW.value);
const depth = Number(zoneD.value);
const oldWidth = selectedZone.width;
const oldDepth = selectedZone.depth;
selectedZone.width = width;
selectedZone.depth = depth;
if (!canPlaceZone(selectedZone, x, z, width, depth)) {
selectedZone.width = oldWidth;
selectedZone.depth = oldDepth;
showToast("That placement overlaps fixed geometry or leaves the plaza.");
syncSelectedInputs();
return;
}
setZonePosition(selectedZone, x, z);
rebuildZoneGeometry(selectedZone);
updateAnalysis();
}
for (const input of [zoneX, zoneZ, zoneW, zoneD]) {
input.addEventListener("input", handleZoneGeometryInput);
}
function setConnectMode(enabled) {
connectMode = enabled;
firstEntrance = null;
routeButton.classList.toggle("active", enabled);
routeHint.textContent = enabled
? "Choose the first entrance."
: "Click “Connect entrances”, then choose two entrances. Drag yellow route handles to move a corridor around an obstruction.";
}
routeButton.addEventListener("click", () => {
setConnectMode(!connectMode);
});
function chooseEntrance(id) {
if (!connectMode) {
showToast("Enable “Connect entrances” before choosing an entrance.");
return;
}
if (!firstEntrance) {
firstEntrance = id;
routeHint.textContent = `Entrance ${id} selected. Choose a second entrance.`;
return;
}
if (firstEntrance === id) {
routeHint.textContent = "Choose a different second entrance.";
return;
}
const duplicate = corridors.find(
(corridor) =>
corridor.fromId === firstEntrance && corridor.toId === id
);
if (duplicate) {
selectCorridor(duplicate);
} else {
const corridor = createCorridor(firstEntrance, id);
selectCorridor(corridor);
}
setConnectMode(false);
showToast(`Corridor ${firstEntrance}–${id} created. Drag its yellow handle to route it.`);
}
for (const button of document.querySelectorAll(".entrance-button")) {
button.addEventListener("click", () => {
chooseEntrance(button.dataset.entrance);
});
}
document.querySelector("#addBendButton").addEventListener("click", () => {
if (!selectedCorridor) {
showToast("Select a corridor first.");
return;
}
const points = selectedCorridor.points;
let longest = 0;
let longestLength = -1;
for (let i = 0; i < points.length - 1; i++) {
const length = Math.hypot(
points[i + 1].x - points[i].x,
points[i + 1].z - points[i].z
);
if (length > longestLength) {
longestLength = length;
longest = i;
}
}
const a = points[longest];
const b = points[longest + 1];
const insertionIndex = Math.min(longest + 1, points.length - 1);
points.splice(insertionIndex, 0, {
x: (a.x + b.x) / 2,
z: (a.z + b.z) / 2
});
syncWaypointHandles(selectedCorridor);
updateAnalysis();
showToast("Bend added. Drag the yellow handle to avoid the obstruction.");
});
document.querySelector("#deleteCorridorButton").addEventListener("click", () => {
if (!selectedCorridor) {
showToast("Select a corridor first.");
return;
}
const corridor = selectedCorridor;
for (const handle of corridor.handles) scene.remove(handle);
waypointMeshes.splice(
0,
waypointMeshes.length,
...waypointMeshes.filter((mesh) => mesh.userData.corridorId !== corridor.id)
);
scene.remove(corridor.mesh);
scene.remove(corridor.dashedLine);
scene.remove(corridor.blockMarker);
corridorMeshes.splice(
corridorMeshes.indexOf(corridor.mesh),
1
);
corridors.splice(corridors.indexOf(corridor), 1);
selectedCorridor = null;
updateAnalysis();
});
// -------------------------------------------------------------------------
// Custom camera controls and pointer interaction
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.1);
const dragPoint = new THREE.Vector3();
let pointerState = null;
function updatePointer(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 updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
function setTopView(enabled) {
topView = enabled;
cameraTarget.set(0, 0, 0);
cameraRadius = enabled ? 42 : 40;
cameraTheta = enabled ? 0 : 0.68;
cameraPhi = enabled ? 0.055 : 0.88;
document.querySelector("#topButton").classList.toggle("active", enabled);
document.querySelector("#orbitButton").classList.toggle("active", !enabled);
updateCamera();
}
document.querySelector("#topButton").addEventListener("click", () => {
setTopView(true);
});
document.querySelector("#orbitButton").addEventListener("click", () => {
setTopView(false);
});
document.querySelector("#resetButton").addEventListener("click", () => {
setTopView(false);
cameraTarget.set(0, 0, 0);
cameraRadius = 42;
cameraTheta = 0.68;
cameraPhi = 0.88;
updateCamera();
});
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
updatePointer(event);
canvas.setPointerCapture(event.pointerId);
if (event.button === 2 || event.shiftKey) {
pointerState = {
type: "pan",
lastX: event.clientX,
lastY: event.clientY
};
return;
}
const handleHits = raycaster.intersectObjects(waypointMeshes, false);
if (handleHits.length) {
const handle = handleHits[0].object;
const corridor = corridors.find(
(item) => item.id === handle.userData.corridorId
);
selectCorridor(corridor);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
const point = corridor.points[handle.userData.pointIndex];
pointerState = {
type: "waypoint",
corridor,
index: handle.userData.pointIndex,
offsetX: point.x - dragPoint.x,
offsetZ: point.z - dragPoint.z
};
}
return;
}
if (connectMode) {
const entranceHits = raycaster.intersectObjects(entranceMeshes, false);
if (entranceHits.length) {
chooseEntrance(entranceHits[0].object.userData.entranceId);
return;
}
}
const zoneHits = raycaster.intersectObjects(zoneMeshes, false);
if (zoneHits.length) {
const zone = zones.find(
(item) => item.id === zoneHits[0].object.userData.zoneId
);
selectZone(zone);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
pointerState = {
type: "zone",
zone,
offsetX: zone.group.position.x - dragPoint.x,
offsetZ: zone.group.position.z - dragPoint.z
};
}
return;
}
const entranceHits = raycaster.intersectObjects(entranceMeshes, false);
if (entranceHits.length) {
chooseEntrance(entranceHits[0].object.userData.entranceId);
return;
}
const corridorHits = raycaster.intersectObjects(corridorMeshes, false);
if (corridorHits.length) {
const corridor = corridors.find(
(item) => item.id === corridorHits[0].object.userData.corridorId
);
selectCorridor(corridor);
return;
}
pointerState = {
type: "orbit",
lastX: event.clientX,
lastY: event.clientY
};
});
canvas.addEventListener("pointermove", (event) => {
if (!pointerState) return;
updatePointer(event);
if (pointerState.type === "orbit") {
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
cameraTheta -= dx * 0.006;
cameraPhi = clamp(cameraPhi - dy * 0.005, 0.08, 1.42);
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
updateCamera();
return;
}
if (pointerState.type === "pan") {
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().crossVectors(forward, camera.up).normalize();
const scale = cameraRadius * 0.0017;
cameraTarget.addScaledVector(right, -dx * scale);
cameraTarget.addScaledVector(forward, dy * scale);
updateCamera();
return;
}
if (!raycaster.ray.intersectPlane(dragPlane, dragPoint)) return;
if (pointerState.type === "zone") {
const x = dragPoint.x + pointerState.offsetX;
const z = dragPoint.z + pointerState.offsetZ;
setZonePosition(pointerState.zone, x, z);
updateAnalysis();
}
if (pointerState.type === "waypoint") {
const x = dragPoint.x + pointerState.offsetX;
const z = dragPoint.z + pointerState.offsetZ;
if (!pointInPolygon(x, z, true)) return;
const point = pointerState.corridor.points[pointerState.index];
point.x = x;
point.z = z;
const handle =
pointerState.corridor.handles[pointerState.index - 1];
if (handle) handle.position.set(x, 0.32, z);
updateAnalysis();
}
});
function endPointer(event) {
pointerState = null;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
14,
65
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (!selectedZone) return;
const step = event.shiftKey ? 0.75 : 0.25;
let x = selectedZone.group.position.x;
let z = selectedZone.group.position.z;
if (event.key === "ArrowLeft") x -= step;
else if (event.key === "ArrowRight") x += step;
else if (event.key === "ArrowUp") z -= step;
else if (event.key === "ArrowDown") z += step;
else return;
event.preventDefault();
setZonePosition(selectedZone, x, z);
updateAnalysis();
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = canvas.clientWidth;
const height = canvas.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
resize();
updateCamera();
updateAnalysis();
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
screenLight.intensity = 20 + Math.sin(elapsed * 1.4) * 2.2;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```