Prompt specification
Build or customize the Three.js 3D scene "Compare visibility at square and chamfered corners" 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: Compare visibility at square and chamfered corners
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/compare-visibility-at-square-and-chamfered-corners-x2812
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing the chamfered intersections of Barcelona's Eixample. Let users switch a schematic building corner between two shapes. Show sightlines and available corner area while keeping street width and observer positions fixed. Low-poly.
Working Three.js Starter (compare-visibility-at-square-and-chamfered-corners-x2812):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Eixample Chamfer Study</title>
<style>
:root {
--ink: #17252b;
--muted: #a9b9bd;
--panel: rgba(17, 31, 37, 0.93);
--line: rgba(255, 255, 255, 0.12);
--orange: #ed8b5c;
--blue: #4eb8df;
--green: #66d39b;
--red: #ff6b67;
--yellow: #f4c95d;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: #cfdde1;
color: white;
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active { cursor: grabbing; }
.panel {
position: fixed;
top: 18px;
left: 18px;
width: 350px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 20px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(22, 35, 40, 0.22);
backdrop-filter: blur(14px);
z-index: 10;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: #a9c9cf;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--orange);
box-shadow: 0 0 0 4px rgba(237, 139, 92, 0.14);
}
h1 {
margin: 0;
font-size: 27px;
line-height: 1.06;
letter-spacing: -0.035em;
}
.intro {
margin: 10px 0 18px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.section-label {
margin: 17px 0 9px;
color: #91a9ae;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.shape-switch {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.shape-button {
position: relative;
min-height: 72px;
padding: 11px 10px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.035);
color: #d9e5e7;
cursor: pointer;
text-align: left;
transition: 160ms ease;
}
.shape-button:hover {
border-color: rgba(255, 255, 255, 0.3);
background: rgba(255, 255, 255, 0.065);
}
.shape-button.active {
border-color: var(--orange);
background: rgba(237, 139, 92, 0.12);
box-shadow: inset 0 0 0 1px rgba(237, 139, 92, 0.1);
}
.shape-button strong {
display: block;
margin-top: 8px;
font-size: 12px;
}
.shape-button small {
display: block;
margin-top: 3px;
color: #91a6ab;
font-size: 10px;
}
.shape-icon {
display: block;
width: 31px;
height: 24px;
border-left: 3px solid #91a6ab;
border-bottom: 3px solid #91a6ab;
background: #91a6ab;
clip-path: polygon(0 0, 100% 0, 100% 42%, 42% 100%, 0 100%);
}
.shape-button.active .shape-icon {
border-color: var(--orange);
background: var(--orange);
}
.shape-button.shallow .shape-icon {
clip-path: polygon(0 0, 100% 0, 100% 70%, 70% 100%, 0 100%);
}
.fixed-list {
margin: 0;
padding: 0;
list-style: none;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
.fixed-list li {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 9px 0;
color: #aebfc3;
font-size: 11px;
}
.fixed-list li + li { border-top: 1px solid rgba(255,255,255,0.055); }
.fixed-list strong {
color: #edf4f5;
font-weight: 650;
text-align: right;
}
.lock {
color: var(--green);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 67px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.035);
}
.metric span {
display: block;
color: #91a6ab;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 7px;
font-size: 18px;
font-weight: 750;
letter-spacing: -0.025em;
}
.status-pill {
display: inline-flex;
align-items: center;
margin-top: 9px;
padding: 6px 9px;
border-radius: 999px;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.status-pill.good {
background: rgba(102, 211, 155, 0.14);
color: var(--green);
}
.status-pill.bad {
background: rgba(255, 107, 103, 0.14);
color: var(--red);
}
.options {
display: grid;
gap: 9px;
}
.option {
display: flex;
align-items: center;
justify-content: space-between;
color: #bdcbce;
font-size: 11px;
cursor: pointer;
}
.option input {
appearance: none;
position: relative;
width: 34px;
height: 19px;
margin: 0;
border-radius: 99px;
background: #405158;
cursor: pointer;
transition: 150ms ease;
}
.option input::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 13px;
height: 13px;
border-radius: 50%;
background: white;
transition: 150ms ease;
}
.option input:checked { background: var(--blue); }
.option input:checked::after { transform: translateX(15px); }
.viewbar {
position: fixed;
top: 18px;
right: 18px;
display: flex;
gap: 6px;
padding: 6px;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--panel);
box-shadow: 0 10px 30px rgba(22, 35, 40, 0.17);
z-index: 10;
}
.viewbar button {
padding: 9px 11px;
border: 0;
border-radius: 8px;
background: transparent;
color: #b8c7ca;
cursor: pointer;
font: inherit;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.04em;
}
.viewbar button:hover,
.viewbar button.active {
background: rgba(255, 255, 255, 0.09);
color: white;
}
.legend {
position: fixed;
right: 18px;
bottom: 18px;
display: grid;
gap: 7px;
padding: 12px 14px;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--panel);
z-index: 10;
pointer-events: none;
}
.legend div {
display: flex;
align-items: center;
gap: 8px;
color: #bdcccf;
font-size: 10px;
}
.swatch {
width: 18px;
height: 3px;
border-radius: 3px;
}
.swatch.green { background: var(--green); }
.swatch.red { background: var(--red); }
.swatch.blue { background: var(--blue); }
.swatch.yellow { background: var(--yellow); }
.instructions {
position: fixed;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
padding: 8px 12px;
border-radius: 999px;
background: rgba(17, 31, 37, 0.72);
color: #b8c7ca;
font-size: 10px;
pointer-events: none;
z-index: 8;
}
#loading {
position: fixed;
inset: 0;
display: grid;
place-items: center;
background: #cfdde1;
color: #23343a;
font-size: 13px;
font-weight: 700;
letter-spacing: 0.06em;
z-index: 30;
}
@media (max-width: 760px) {
.panel {
top: 10px;
left: 10px;
right: 10px;
width: auto;
max-height: 48vh;
padding: 15px;
border-radius: 14px;
}
h1 { font-size: 22px; }
.intro { margin-bottom: 12px; }
.viewbar {
top: auto;
right: 10px;
bottom: 10px;
}
.legend, .instructions { display: none; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly model of Barcelona's Eixample intersections"></canvas>
<aside class="panel">
<div class="eyebrow">Barcelona · Eixample</div>
<h1>Chamfered<br />intersections</h1>
<p class="intro">
Compare two schematic corner cuts. The 20 m street corridor,
fixed observers, and target remain locked while the building changes.
</p>
<div class="section-label">Building corner</div>
<div class="shape-switch">
<button class="shape-button active" data-shape="standard" aria-pressed="true">
<span class="shape-icon"></span>
<strong>45° Standard</strong>
<small>Equal 6 m set-backs</small>
</button>
<button class="shape-button shallow" data-shape="shallow" aria-pressed="false">
<span class="shape-icon"></span>
<strong>30° Shallow</strong>
<small>Long, lower-angle cut</small>
</button>
</div>
<div class="section-label">Fixed conditions</div>
<ul class="fixed-list">
<li><span>Street width</span><strong>20 m <i class="lock">locked</i></strong></li>
<li><span>Observer positions</span><strong>3 <i class="lock">locked</i></strong></li>
<li><span>Visual target</span><strong>Fixed <i class="lock">locked</i></strong></li>
</ul>
<div class="section-label">Live comparison</div>
<div class="metrics">
<div class="metric">
<span>Corner area</span>
<strong id="areaValue">18.0 m²</strong>
</div>
<div class="metric">
<span>Diagonal span</span>
<strong id="spanValue">8.5 m</strong>
</div>
<div class="metric">
<span>Visible observers</span>
<strong id="visibleValue">3 / 3</strong>
</div>
<div class="metric">
<span>Line of sight</span>
<strong id="statusValue">Open</strong>
<span id="statusPill" class="status-pill good">Target visible</span>
</div>
</div>
<div class="section-label">Display</div>
<div class="options">
<label class="option">
<span>Sightlines and obstructions</span>
<input id="showSightlines" type="checkbox" checked />
</label>
<label class="option">
<span>Available corner area</span>
<input id="showArea" type="checkbox" checked />
</label>
<label class="option">
<span>Labels</span>
<input id="showLabels" type="checkbox" checked />
</label>
</div>
</aside>
<nav class="viewbar" aria-label="Camera views">
<button data-view="iso" class="active">Isometric</button>
<button data-view="plan">Plan</button>
<button data-view="corner">Corner</button>
</nav>
<div class="legend">
<div><span class="swatch green"></span> Visible sightline</div>
<div><span class="swatch red"></span> Blocked sightline</div>
<div><span class="swatch blue"></span> Available public corner</div>
<div><span class="swatch yellow"></span> Fixed visual target</div>
</div>
<div class="instructions">Drag to orbit · Shift/right-drag to pan · Scroll to zoom</div>
<div id="loading">BUILDING THE EIXAMPLE MODEL…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants
// -------------------------------------------------------------------------
const STREET_WIDTH = 20;
const STREET_HALF = STREET_WIDTH / 2;
const BUILDING_LINE = 10;
const EYE_HEIGHT = 1.7;
const SELECTED_HEIGHT = 16;
const FIXED_TARGET = new THREE.Vector2(10.8, 14.8);
const OBSERVERS = [
{ id: "O1", name: "South walk", x: -4.0, z: -8.5 },
{ id: "O2", name: "West walk", x: -8.5, z: 4.0 },
{ id: "O3", name: "North-west walk", x: -7.5, z: 7.5 }
];
const SHAPES = {
standard: {
label: "45° Standard",
dx: 6.0,
dz: 6.0
},
shallow: {
label: "30° Shallow",
dx: 8.7,
dz: 5.023
}
};
let currentShape = {
dx: SHAPES.standard.dx,
dz: SHAPES.standard.dz
};
let selectedShapeKey = "standard";
let shapeAnimation = null;
const canvas = document.getElementById("scene");
const loading = document.getElementById("loading");
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
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;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#cfdde1");
scene.fog = new THREE.Fog("#cfdde1", 125, 225);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
300
);
const hemi = new THREE.HemisphereLight("#eef8fb", "#9d917e", 2.1);
scene.add(hemi);
const sun = new THREE.DirectionalLight("#fff2d8", 3.3);
sun.position.set(-38, 65, -30);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -80;
sun.shadow.camera.right = 80;
sun.shadow.camera.top = 80;
sun.shadow.camera.bottom = -80;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 160;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight("#b8dce8", 0.75);
fill.position.set(45, 25, 40);
scene.add(fill);
const environmentGroup = new THREE.Group();
const buildingsGroup = new THREE.Group();
const areaGroup = new THREE.Group();
const sightlineGroup = new THREE.Group();
const markerGroup = new THREE.Group();
const labelsGroup = new THREE.Group();
scene.add(
environmentGroup,
buildingsGroup,
areaGroup,
sightlineGroup,
markerGroup,
labelsGroup
);
// -------------------------------------------------------------------------
// Materials
// -------------------------------------------------------------------------
const groundMaterial = new THREE.MeshStandardMaterial({
color: "#d9d4c6",
roughness: 1,
flatShading: true
});
const asphaltMaterial = new THREE.MeshStandardMaterial({
color: "#435158",
roughness: 0.95,
flatShading: true
});
const sidewalkMaterial = new THREE.MeshStandardMaterial({
color: "#e4dfd2",
roughness: 1,
flatShading: true
});
const markingMaterial = new THREE.MeshStandardMaterial({
color: "#f4f0e5",
roughness: 0.9
});
const laneMaterial = new THREE.MeshBasicMaterial({
color: "#d9cfaa"
});
const staticWallMaterial = new THREE.MeshStandardMaterial({
color: "#cdbfa8",
roughness: 0.88,
flatShading: true
});
const staticRoofMaterial = new THREE.MeshStandardMaterial({
color: "#b7aa96",
roughness: 0.95,
flatShading: true
});
const selectedWallMaterial = new THREE.MeshStandardMaterial({
color: "#df8054",
roughness: 0.8,
flatShading: true
});
const selectedRoofMaterial = new THREE.MeshStandardMaterial({
color: "#efaa83",
roughness: 0.92,
flatShading: true
});
const roofDetailMaterial = new THREE.MeshStandardMaterial({
color: "#a99d8b",
roughness: 1,
flatShading: true
});
const edgeMaterial = new THREE.LineBasicMaterial({
color: "#665f54",
transparent: true,
opacity: 0.5
});
const selectedEdgeMaterial = new THREE.LineBasicMaterial({
color: "#7f3f2c",
transparent: true,
opacity: 0.72
});
// -------------------------------------------------------------------------
// Geometry helpers
// -------------------------------------------------------------------------
function ensureCounterClockwise(points) {
let area = 0;
for (let i = 0; i < points.length; i++) {
const a = points[i];
const b = points[(i + 1) % points.length];
area += a.x * b.z - b.x * a.z;
}
return area < 0 ? [...points].reverse() : points;
}
function pushTriangle(array, a, b, c) {
array.push(
a.x, a.y, a.z,
b.x, b.y, b.z,
c.x, c.y, c.z
);
}
function createPrismGeometry(inputPoints, height) {
const points = ensureCounterClockwise(inputPoints);
const sideVertices = [];
const topVertices = [];
const bottomVertices = [];
for (let i = 0; i < points.length; i++) {
const a = points[i];
const b = points[(i + 1) % points.length];
const ab = { x: a.x, y: 0, z: a.z };
const at = { x: a.x, y: height, z: a.z };
const bb = { x: b.x, y: 0, z: b.z };
const bt = { x: b.x, y: height, z: b.z };
pushTriangle(sideVertices, ab, at, bt);
pushTriangle(sideVertices, ab, bt, bb);
}
for (let i = 1; i < points.length - 1; i++) {
pushTriangle(
topVertices,
{ x: points[0].x, y: height, z: points[0].z },
{ x: points[i + 1].x, y: height, z: points[i + 1].z },
{ x: points[i].x, y: height, z: points[i].z }
);
pushTriangle(
bottomVertices,
{ x: points[0].x, y: 0, z: points[0].z },
{ x: points[i].x, y: 0, z: points[i].z },
{ x: points[i + 1].x, y: 0, z: points[i + 1].z }
);
}
const all = [
...sideVertices,
...topVertices,
...bottomVertices
];
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(all, 3)
);
const sideCount = sideVertices.length / 3;
const topCount = topVertices.length / 3;
const bottomCount = bottomVertices.length / 3;
geometry.addGroup(0, sideCount, 0);
geometry.addGroup(sideCount, topCount, 1);
geometry.addGroup(sideCount + topCount, bottomCount, 0);
geometry.computeVertexNormals();
geometry.computeBoundingSphere();
return geometry;
}
function quadrantPolygon(quadrant, dx = 6, dz = 6, outer = 54) {
let points;
if (quadrant === "NE") {
points = [
{ x: 10, z: 10 + dz },
{ x: 10 + dx, z: 10 },
{ x: outer, z: 10 },
{ x: outer, z: outer },
{ x: 10, z: outer }
];
} else if (quadrant === "NW") {
points = [
{ x: -10, z: 10 + dz },
{ x: -10 - dx, z: 10 },
{ x: -outer, z: 10 },
{ x: -outer, z: outer },
{ x: -10, z: outer }
];
} else if (quadrant === "SE") {
points = [
{ x: 10, z: -10 - dz },
{ x: 10 + dx, z: -10 },
{ x: outer, z: -10 },
{ x: outer, z: -outer },
{ x: 10, z: -outer }
];
} else {
points = [
{ x: -10, z: -10 - dz },
{ x: -10 - dx, z: -10 },
{ x: -outer, z: -10 },
{ x: -outer, z: -outer },
{ x: -10, z: -outer }
];
}
return ensureCounterClockwise(points);
}
function selectedPolygon() {
return quadrantPolygon("NE", currentShape.dx, currentShape.dz);
}
function addPlane(width, depth, x, z, y, material) {
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(width, depth),
material
);
mesh.rotation.x = -Math.PI / 2;
mesh.position.set(x, y, z);
mesh.receiveShadow = true;
environmentGroup.add(mesh);
return mesh;
}
function addBox(width, height, depth, x, y, z, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.receiveShadow = true;
mesh.castShadow = true;
environmentGroup.add(mesh);
return mesh;
}
function addLine(points, color, opacity = 1) {
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color,
transparent: opacity < 1,
opacity
});
const line = new THREE.Line(geometry, material);
environmentGroup.add(line);
return line;
}
// -------------------------------------------------------------------------
// Environment: streets, sidewalks, crossings and dimension line
// -------------------------------------------------------------------------
addPlane(150, 150, 0, 0, -0.05, groundMaterial);
// Asphalt cross: 15 m carriageway plus 2.5 m sidewalks on each side.
addPlane(150, 15, 0, 0, 0.005, asphaltMaterial);
addPlane(15, 150, 0, 0, 0.006, asphaltMaterial);
// Sidewalk quadrants.
addPlane(46.5, 46.5, 30.75, 30.75, 0.04, sidewalkMaterial);
addPlane(46.5, 46.5, -30.75, 30.75, 0.04, sidewalkMaterial);
addPlane(46.5, 46.5, 30.75, -30.75, 0.04, sidewalkMaterial);
addPlane(46.5, 46.5, -30.75, -30.75, 0.04, sidewalkMaterial);
// Dashed center lines.
for (const x of [24, 32, 40, 48]) {
addBox(3.1, 0.025, 0.16, x, 0.04, 0, laneMaterial);
addBox(0.16, 0.025, 3.1, 0, 0.045, x, laneMaterial);
}
// Zebra crossings.
for (const sign of [-1, 1]) {
for (let i = 0; i < 3; i++) {
const offset = 11.5 + i * 1.5;
addBox(
11.5, 0.028, 0.72,
0, 0.052, sign * offset,
markingMaterial
);
addBox(
0.72, 0.028, 11.5,
sign * offset, 0.052, 0,
markingMaterial
);
}
}
// Fixed 20 m street-width dimension.
const dimensionPoints = [
new THREE.Vector3(-10, 0.25, 34),
new THREE.Vector3(10, 0.25, 34),
new THREE.Vector3(-10, 0.25, 32.4),
new THREE.Vector3(-10, 0.25, 35.6),
new THREE.Vector3(10, 0.25, 32.4),
new THREE.Vector3(10, 0.25, 35.6)
];
const dimensionGeometry = new THREE.BufferGeometry().setFromPoints(
dimensionPoints
);
const dimensionLine = new THREE.LineSegments(
dimensionGeometry,
new THREE.LineBasicMaterial({ color: "#50b5d7" })
);
environmentGroup.add(dimensionLine);
// -------------------------------------------------------------------------
// Low-poly trees
// -------------------------------------------------------------------------
const trunkMaterial = new THREE.MeshStandardMaterial({
color: "#80654b",
roughness: 1,
flatShading: true
});
const leafMaterial = new THREE.MeshStandardMaterial({
color: "#668b69",
roughness: 1,
flatShading: true
});
const treePositions = [
[-8.7, 24], [-8.7, 39], [8.7, 24], [8.7, 42],
[-24, 8.7], [-39, 8.7], [24, -8.7], [40, -8.7],
[-24, -8.7], [-39, -8.7], [8.7, -25], [-8.7, -40]
];
for (const [x, z] of treePositions) {
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.16, 0.22, 1.8, 5),
trunkMaterial
);
trunk.position.set(x, 0.95, z);
trunk.castShadow = true;
environmentGroup.add(trunk);
const foliage = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.25, 0),
leafMaterial
);
foliage.position.set(x, 2.65, z);
foliage.scale.set(0.9, 1.1, 0.9);
foliage.rotation.y = x * 0.2 + z * 0.1;
foliage.castShadow = true;
environmentGroup.add(foliage);
}
// -------------------------------------------------------------------------
// Buildings
// -------------------------------------------------------------------------
function addBuilding(polygon, height, wallMaterial, roofMaterial, selected = false) {
const mesh = new THREE.Mesh(
createPrismGeometry(polygon, height),
[wallMaterial, roofMaterial]
);
mesh.position.y = 0.07;
mesh.castShadow = true;
mesh.receiveShadow = true;
buildingsGroup.add(mesh);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry, 1),
selected ? selectedEdgeMaterial : edgeMaterial
);
edges.position.y = 0.075;
buildingsGroup.add(edges);
return { mesh, edges };
}
addBuilding(
quadrantPolygon("NW"),
13,
staticWallMaterial,
staticRoofMaterial
);
addBuilding(
quadrantPolygon("SW"),
15,
staticWallMaterial,
staticRoofMaterial
);
addBuilding(
quadrantPolygon("SE"),
17,
staticWallMaterial,
staticRoofMaterial
);
const selectedBuilding = addBuilding(
selectedPolygon(),
SELECTED_HEIGHT,
selectedWallMaterial,
selectedRoofMaterial,
true
);
function addRoofDetails(x, z, width, depth, height = 2.1) {
const box = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
roofDetailMaterial
);
box.position.set(x, SELECTED_HEIGHT + height / 2 + 0.12, z);
box.castShadow = true;
box.receiveShadow = true;
buildingsGroup.add(box);
}
addRoofDetails(34, 29, 13, 8);
addRoofDetails(27, 43, 9, 5, 1.4);
// -------------------------------------------------------------------------
// Labels made entirely with canvas textures
// -------------------------------------------------------------------------
function roundedRectangle(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + width - r, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + r);
ctx.lineTo(x + width, y + height - r);
ctx.quadraticCurveTo(
x + width, y + height, x + width - r, y + height
);
ctx.lineTo(x + r, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function makeLabel(text, options = {}) {
const {
color = "#ffffff",
background = "rgba(17,31,37,0.90)",
border = "rgba(255,255,255,0.20)",
width = 4.2,
depthTest = false
} = options;
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, 512, 128);
roundedRectangle(ctx, 6, 9, 500, 110, 24);
ctx.fillStyle = background;
ctx.fill();
ctx.strokeStyle = border;
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = color;
ctx.font = "700 38px Arial, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65, 465);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width / 4, 1);
sprite.renderOrder = 20;
return sprite;
}
const observerLabelGroup = new THREE.Group();
labelsGroup.add(observerLabelGroup);
for (const observer of OBSERVERS) {
const marker = new THREE.Group();
const pad = new THREE.Mesh(
new THREE.CylinderGeometry(0.58, 0.58, 0.22, 16),
new THREE.MeshStandardMaterial({
color: "#3d9fc5",
roughness: 0.7,
flatShading: true
})
);
pad.position.set(observer.x, 0.22, observer.z);
pad.castShadow = true;
marker.add(pad);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.85, 0.09, 6, 24),
new THREE.MeshBasicMaterial({ color: "#66c7e5" })
);
ring.rotation.x = Math.PI / 2;
ring.position.set(observer.x, 0.37, observer.z);
marker.add(ring);
const eye = new THREE.Mesh(
new THREE.SphereGeometry(0.25, 10, 7),
new THREE.MeshBasicMaterial({ color: "#d8f5ff" })
);
eye.position.set(observer.x, EYE_HEIGHT, observer.z);
marker.add(eye);
const stem = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(observer.x, 0.35, observer.z),
new THREE.Vector3(observer.x, EYE_HEIGHT, observer.z)
]),
new THREE.LineBasicMaterial({ color: "#6ac7e5" })
);
marker.add(stem);
markerGroup.add(marker);
const label = makeLabel(
`${observer.id} · LOCKED`,
{
color: "#dff7ff",
border: "rgba(102,199,229,0.55)",
width: 3.3
}
);
label.position.set(observer.x, 3.0, observer.z);
observerLabelGroup.add(label);
}
const targetMarker = new THREE.Group();
const targetDiamond = new THREE.Mesh(
new THREE.OctahedronGeometry(0.62, 0),
new THREE.MeshBasicMaterial({
color: "#f4c95d",
depthTest: false,
depthWrite: false
})
);
targetDiamond.position.set(
FIXED_TARGET.x,
EYE_HEIGHT,
FIXED_TARGET.y
);
targetDiamond.renderOrder = 15;
targetMarker.add(targetDiamond);
const targetStem = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(FIXED_TARGET.x, 0.15, FIXED_TARGET.y),
new THREE.Vector3(FIXED_TARGET.x, EYE_HEIGHT, FIXED_TARGET.y)
]),
new THREE.LineBasicMaterial({
color: "#f4c95d",
depthTest: false,
transparent: true,
opacity: 0.8
})
);
targetMarker.add(targetStem);
const targetRing = new THREE.Mesh(
new THREE.TorusGeometry(0.9, 0.09, 6, 24),
new THREE.MeshBasicMaterial({
color: "#f4c95d",
depthTest: false
})
);
targetRing.rotation.x = Math.PI / 2;
targetRing.position.set(FIXED_TARGET.x, 0.15, FIXED_TARGET.y);
targetRing.renderOrder = 15;
targetMarker.add(targetRing);
markerGroup.add(targetMarker);
const targetLabel = makeLabel("FIXED TARGET", {
color: "#fff0b5",
border: "rgba(244,201,93,0.60)",
width: 3.8
});
targetLabel.position.set(FIXED_TARGET.x, 3.0, FIXED_TARGET.y);
labelsGroup.add(targetLabel);
const widthLabel = makeLabel("20 m · FIXED WIDTH", {
color: "#d9f6ff",
border: "rgba(80,181,215,0.60)",
width: 4.6
});
widthLabel.position.set(0, 1.0, 37);
labelsGroup.add(widthLabel);
const selectedBlockLabel = makeLabel("SELECTED CORNER", {
color: "#fff0e6",
border: "rgba(237,139,92,0.65)",
width: 4.7
});
selectedBlockLabel.position.set(30, SELECTED_HEIGHT + 3.3, 31);
labelsGroup.add(selectedBlockLabel);
// -------------------------------------------------------------------------
// Available corner area
// -------------------------------------------------------------------------
const areaMaterial = new THREE.MeshBasicMaterial({
color: "#42add5",
transparent: true,
opacity: 0.42,
side: THREE.DoubleSide,
depthWrite: false
});
const areaMesh = new THREE.Mesh(
new THREE.BufferGeometry(),
areaMaterial
);
areaMesh.renderOrder = 3;
areaGroup.add(areaMesh);
const areaBorder = new THREE.LineLoop(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: "#287f9f",
transparent: true,
opacity: 0.9
})
);
areaBorder.renderOrder = 4;
areaGroup.add(areaBorder);
const areaLabel = makeLabel("AVAILABLE CORNER", {
color: "#dff8ff",
border: "rgba(66,173,213,0.70)",
width: 4.1
});
areaGroup.add(areaLabel);
function updateAreaGeometry() {
const points = [
new THREE.Vector3(10, 0.095, 10),
new THREE.Vector3(10, 0.095, 10 + currentShape.dz),
new THREE.Vector3(10 + currentShape.dx, 0.095, 10)
];
areaMesh.geometry.dispose();
areaMesh.geometry = new THREE.BufferGeometry().setFromPoints(points);
areaBorder.geometry.dispose();
areaBorder.geometry = new THREE.BufferGeometry().setFromPoints(points);
areaLabel.position.set(
10 + currentShape.dx * 0.34,
0.75,
10 + currentShape.dz * 0.34
);
}
// -------------------------------------------------------------------------
// Sightline geometry and exact 2D visibility tests
// -------------------------------------------------------------------------
function cross2(ax, az, bx, bz) {
return ax * bz - az * bx;
}
function pointInPolygon(point, polygon) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const a = polygon[i];
const b = polygon[j];
const intersects =
((a.z > point.y) !== (b.z > point.y)) &&
point.x <
((b.x - a.x) * (point.y - a.z)) / (b.z - a.z) + a.x;
if (intersects) inside = !inside;
}
return inside;
}
function segmentIntersection(p, p2, q, q2) {
const rx = p2.x - p.x;
const rz = p2.y - p.y;
const sx = q2.x - q.x;
const sz = q2.y - q.y;
const denominator = cross2(rx, rz, sx, sz);
if (Math.abs(denominator) < 1e-9) return null;
const qpx = q.x - p.x;
const qpz = q.y - p.y;
const t = cross2(qpx, qpz, sx, sz) / denominator;
const u = cross2(qpx, qpz, rx, rz) / denominator;
if (t < 0 || t > 1 || u < 0 || u > 1) return null;
return t;
}
function traceSightline(observer, polygon) {
const start = new THREE.Vector2(observer.x, observer.z);
const end = FIXED_TARGET.clone();
const intersections = [];
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
const t = segmentIntersection(start, end, a, b);
if (t !== null) intersections.push(t);
}
intersections.sort((a, b) => a - b);
const endpointInside = pointInPolygon(end, polygon);
if (endpointInside) {
if (intersections.length) {
return {
visible: false,
hitT: intersections[0],
hit: new THREE.Vector2().lerpVectors(start, end, intersections[0])
};
}
} else {
const samples = [0, ...intersections, 1];
for (let i = 0; i < samples.length - 1; i++) {
const middleT = (samples[i] + samples[i + 1]) / 2;
const middle = new THREE.Vector2().lerpVectors(
start,
end,
middleT
);
if (pointInPolygon(middle, polygon)) {
return {
visible: false,
hitT: samples[i],
hit: new THREE.Vector2().lerpVectors(start, end, samples[i])
};
}
}
}
return { visible: true, hitT: 1, hit: end.clone() };
}
function clearDynamicGroup(group) {
group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of materials) material.dispose();
}
});
group.clear();
}
function makeSightline(points, color, dashed = false) {
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = dashed
? new THREE.LineDashedMaterial({
color,
dashSize: 0.7,
gapSize: 0.4,
transparent: true,
opacity: 0.85
})
: new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.95
});
const line = new THREE.Line(geometry, material);
if (dashed) line.computeLineDistances();
sightlineGroup.add(line);
return line;
}
function updateSightlines() {
clearDynamicGroup(sightlineGroup);
const polygon = selectedPolygon();
let visibleCount = 0;
for (const observer of OBSERVERS) {
const result = traceSightline(observer, polygon);
const start = new THREE.Vector3(
observer.x,
EYE_HEIGHT,
observer.z
);
const hit = new THREE.Vector3(
result.hit.x,
EYE_HEIGHT,
result.hit.y
);
const targetPoint = new THREE.Vector3(
FIXED_TARGET.x,
EYE_HEIGHT,
FIXED_TARGET.y
);
if (result.visible) {
visibleCount++;
makeSightline([start, targetPoint], "#66d39b", false);
} else {
makeSightline([start, hit], "#ff6b67", false);
makeSightline([hit, targetPoint], "#ff6b67", true);
const impact = new THREE.Mesh(
new THREE.SphereGeometry(0.38, 10, 7),
new THREE.MeshBasicMaterial({ color: "#ff6b67" })
);
impact.position.copy(hit);
sightlineGroup.add(impact);
}
}
return visibleCount;
}
// -------------------------------------------------------------------------
// Selected building and UI updates
// -------------------------------------------------------------------------
function updateSelectedBuilding() {
const polygon = selectedPolygon();
selectedBuilding.mesh.geometry.dispose();
selectedBuilding.mesh.geometry = createPrismGeometry(
polygon,
SELECTED_HEIGHT
);
selectedBuilding.edges.geometry.dispose();
selectedBuilding.edges.geometry = new THREE.EdgesGeometry(
selectedBuilding.mesh.geometry,
1
);
}
const areaValue = document.getElementById("areaValue");
const spanValue = document.getElementById("spanValue");
const visibleValue = document.getElementById("visibleValue");
const statusValue = document.getElementById("statusValue");
const statusPill = document.getElementById("statusPill");
function updateReadout() {
const area = 0.5 * currentShape.dx * currentShape.dz;
const span = Math.hypot(currentShape.dx, currentShape.dz);
const visibleCount = updateSightlines();
areaValue.textContent = `${area.toFixed(1)} m²`;
spanValue.textContent = `${span.toFixed(1)} m`;
visibleValue.textContent = `${visibleCount} / ${OBSERVERS.length}`;
if (visibleCount === OBSERVERS.length) {
statusValue.textContent = "Open";
statusPill.textContent = "Target visible";
statusPill.className = "status-pill good";
} else if (visibleCount === 0) {
statusValue.textContent = "Blocked";
statusPill.textContent = "Target occluded";
statusPill.className = "status-pill bad";
} else {
statusValue.textContent = "Partial";
statusPill.textContent = "Mixed visibility";
statusPill.className = "status-pill bad";
}
}
function refreshModel() {
updateSelectedBuilding();
updateAreaGeometry();
updateReadout();
}
function easeInOutCubic(t) {
return t < 0.5
? 4 * t * t * t
: 1 - Math.pow(-2 * t + 2, 3) / 2;
}
document.querySelectorAll("[data-shape]").forEach((button) => {
button.addEventListener("click", () => {
const key = button.dataset.shape;
if (key === selectedShapeKey) return;
selectedShapeKey = key;
const next = SHAPES[key];
document.querySelectorAll("[data-shape]").forEach((other) => {
const active = other === button;
other.classList.toggle("active", active);
other.setAttribute("aria-pressed", String(active));
});
shapeAnimation = {
start: performance.now(),
duration: 700,
fromDx: currentShape.dx,
fromDz: currentShape.dz,
toDx: next.dx,
toDz: next.dz
};
});
});
document.getElementById("showSightlines").addEventListener("change", (event) => {
sightlineGroup.visible = event.target.checked;
});
document.getElementById("showArea").addEventListener("change", (event) => {
areaGroup.visible = event.target.checked;
});
document.getElementById("showLabels").addEventListener("change", (event) => {
labelsGroup.visible = event.target.checked;
areaLabel.visible = event.target.checked;
});
// -------------------------------------------------------------------------
// Camera controls implemented directly, without examples/addons
// -------------------------------------------------------------------------
const cameraState = {
theta: 2.25,
phi: 0.92,
radius: 94,
target: new THREE.Vector3(0, 0, 0)
};
const cameraGoal = {
theta: cameraState.theta,
phi: cameraState.phi,
radius: cameraState.radius,
target: cameraState.target.clone()
};
const viewPresets = {
iso: {
theta: 2.25,
phi: 0.92,
radius: 94,
target: new THREE.Vector3(0, 0, 0)
},
plan: {
theta: 2.25,
phi: 0.065,
radius: 108,
target: new THREE.Vector3(0, 0, 0)
},
corner: {
theta: 2.28,
phi: 1.03,
radius: 61,
target: new THREE.Vector3(6, 0, 7)
}
};
function setView(name) {
const preset = viewPresets[name];
cameraGoal.theta = preset.theta;
cameraGoal.phi = preset.phi;
cameraGoal.radius = preset.radius;
cameraGoal.target.copy(preset.target);
document.querySelectorAll("[data-view]").forEach((button) => {
button.classList.toggle("active", button.dataset.view === name);
});
}
document.querySelectorAll("[data-view]").forEach((button) => {
button.addEventListener("click", () => setView(button.dataset.view));
});
let drag = null;
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
drag = {
x: event.clientX,
y: event.clientY,
pan: event.button === 2 || event.shiftKey
};
document.querySelectorAll("[data-view]").forEach((button) => {
button.classList.remove("active");
});
});
canvas.addEventListener("pointermove", (event) => {
if (!drag) return;
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
drag.x = event.clientX;
drag.y = event.clientY;
if (drag.pan) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().crossVectors(
forward,
new THREE.Vector3(0, 1, 0)
);
const scale = cameraGoal.radius * 0.0015;
cameraGoal.target.addScaledVector(right, -dx * scale);
cameraGoal.target.addScaledVector(forward, dy * scale);
} else {
cameraGoal.theta -= dx * 0.006;
cameraGoal.phi -= dy * 0.005;
cameraGoal.phi = THREE.MathUtils.clamp(
cameraGoal.phi,
0.055,
1.46
);
}
});
function endDrag(event) {
if (drag && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
drag = null;
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraGoal.radius *= Math.exp(event.deltaY * 0.001);
cameraGoal.radius = THREE.MathUtils.clamp(
cameraGoal.radius,
32,
150
);
},
{ passive: false }
);
function updateCamera() {
const damping = 0.12;
cameraState.theta +=
(cameraGoal.theta - cameraState.theta) * damping;
cameraState.phi +=
(cameraGoal.phi - cameraState.phi) * damping;
cameraState.radius +=
(cameraGoal.radius - cameraState.radius) * damping;
cameraState.target.lerp(cameraGoal.target, damping);
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function onResize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
}
window.addEventListener("resize", onResize);
refreshModel();
updateCamera();
function animate(now) {
requestAnimationFrame(animate);
if (shapeAnimation) {
const t = THREE.MathUtils.clamp(
(now - shapeAnimation.start) / shapeAnimation.duration,
0,
1
);
const eased = easeInOutCubic(t);
currentShape.dx = THREE.MathUtils.lerp(
shapeAnimation.fromDx,
shapeAnimation.toDx,
eased
);
currentShape.dz = THREE.MathUtils.lerp(
shapeAnimation.fromDz,
shapeAnimation.toDz,
eased
);
refreshModel();
if (t >= 1) {
currentShape.dx = shapeAnimation.toDx;
currentShape.dz = shapeAnimation.toDz;
shapeAnimation = null;
refreshModel();
}
}
updateCamera();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
loading.remove();
</script>
</body>
</html>
```