Prompt specification
Build or customize the Three.js 3D scene "Flock obstacle response sandbox" 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: Flock obstacle response sandbox
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/flock-obstacle-response-sandbox-x0688
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing bird flocking. Create a controlled aerial arena with movable obstacles and adjustable neighborhood radius; compare group paths and collision avoidance under the declared algorithm, not as a complete biological model. Voxel style.
Working Three.js Starter (flock-obstacle-response-sandbox-x0688):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Flock Lab — Voxel Boids Comparison</title>
<style>
:root {
color-scheme: dark;
--bg: #07101b;
--panel: #0b1725;
--panel-2: #101e2e;
--line: #22364d;
--text: #e8f2ff;
--muted: #8da3bb;
--baseline: #ff786b;
--safety: #43e4c2;
--yellow: #ffd166;
--radius: 12px;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
color: var(--text);
background:
radial-gradient(circle at 12% 0%, #13283d 0, transparent 30rem),
var(--bg);
}
button,
input,
select {
font: inherit;
}
button,
select {
color: var(--text);
}
button {
cursor: pointer;
}
.topbar {
height: 72px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: rgba(7, 16, 27, 0.9);
backdrop-filter: blur(14px);
position: sticky;
top: 0;
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 39px;
height: 39px;
position: relative;
flex: 0 0 auto;
}
.brand-mark i {
position: absolute;
display: block;
background: var(--safety);
box-shadow: 0 0 18px rgba(67, 228, 194, 0.2);
}
.brand-mark i:nth-child(1) {
width: 13px;
height: 13px;
left: 0;
top: 13px;
}
.brand-mark i:nth-child(2) {
width: 13px;
height: 13px;
left: 15px;
top: 0;
background: #79b7ff;
}
.brand-mark i:nth-child(3) {
width: 13px;
height: 13px;
left: 15px;
top: 15px;
background: var(--baseline);
}
.brand-mark i:nth-child(4) {
width: 13px;
height: 13px;
left: 30px;
top: 13px;
background: #b695ff;
}
.brand h1 {
margin: 0;
font-size: 18px;
line-height: 1.1;
letter-spacing: 0.14em;
text-transform: uppercase;
white-space: nowrap;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.top-actions {
display: flex;
align-items: center;
gap: 8px;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
margin-right: 8px;
color: var(--muted);
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.status::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--safety);
box-shadow: 0 0 12px var(--safety);
}
.status.paused::before {
background: var(--yellow);
box-shadow: 0 0 12px var(--yellow);
}
.btn {
min-height: 36px;
border: 1px solid var(--line);
border-radius: 8px;
padding: 0 13px;
background: #101d2c;
color: #dceaff;
font-size: 12px;
font-weight: 750;
letter-spacing: 0.04em;
transition: border-color 150ms, background 150ms, transform 150ms;
}
.btn:hover {
border-color: #3f668c;
background: #14253a;
}
.btn:active {
transform: translateY(1px);
}
.btn.primary {
border-color: #277d72;
background: #123b37;
color: #a9fff0;
}
.app {
height: calc(100vh - 72px);
display: grid;
grid-template-columns: 294px minmax(0, 1fr);
}
.sidebar {
min-width: 0;
overflow-y: auto;
padding: 16px;
border-right: 1px solid var(--line);
background: rgba(8, 18, 30, 0.82);
scrollbar-width: thin;
scrollbar-color: #29425d transparent;
}
.section {
padding: 15px;
margin-bottom: 12px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: linear-gradient(145deg, rgba(18, 33, 49, 0.96), rgba(10, 23, 37, 0.96));
}
.section-title {
margin: 0 0 14px;
color: #b8cbe0;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.section-title span {
color: var(--safety);
margin-right: 7px;
}
.control {
margin-bottom: 14px;
}
.control:last-child {
margin-bottom: 0;
}
.control-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
color: #c9d8e8;
font-size: 11px;
font-weight: 700;
}
.control-label output {
flex: 0 0 auto;
min-width: 56px;
padding: 4px 6px;
border: 1px solid #294059;
border-radius: 5px;
background: #081421;
color: #8fe8d6;
text-align: center;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
appearance: none;
border-radius: 999px;
background: #263b52;
accent-color: var(--safety);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
appearance: none;
border: 2px solid #bafff0;
border-radius: 3px;
background: #2dcbb0;
box-shadow: 0 0 0 3px rgba(67, 228, 194, 0.12);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid #bafff0;
border-radius: 3px;
background: #2dcbb0;
}
.tool-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.tool {
padding: 9px 8px;
border: 1px solid #2a4057;
border-radius: 7px;
background: #0a1725;
color: #9eb2c8;
font-size: 11px;
font-weight: 750;
}
.tool.active {
border-color: #35bda7;
background: #103530;
color: #bafff0;
}
.check-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 7px 0;
color: #b9c9da;
font-size: 11px;
}
.check-row input {
width: 16px;
height: 16px;
accent-color: var(--safety);
}
.select-wrap {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
color: #b9c9da;
font-size: 11px;
}
select {
min-width: 118px;
padding: 7px 9px;
border: 1px solid #2a4057;
border-radius: 7px;
background: #091624;
font-size: 11px;
}
.algorithm {
color: #a8bbce;
font-size: 11px;
line-height: 1.55;
}
.equation {
margin: 11px 0;
padding: 10px;
overflow-x: auto;
border: 1px solid #294158;
border-radius: 7px;
background: #07131f;
color: #a8f3e5;
font: 11px/1.65 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
}
.algorithm strong {
color: #eef8ff;
}
.algorithm .note {
display: block;
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid var(--line);
color: #7f96ad;
}
.workspace {
min-width: 0;
overflow: auto;
padding: 14px;
scrollbar-width: thin;
scrollbar-color: #29425d transparent;
}
.workspace-head {
min-height: 38px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
margin-bottom: 11px;
color: var(--muted);
font: 700 10px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.workspace-head strong {
color: #d7e8f8;
}
.legend {
display: flex;
align-items: center;
gap: 14px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.legend i {
width: 9px;
height: 9px;
display: inline-block;
border-radius: 2px;
}
.legend .a {
background: var(--baseline);
}
.legend .b {
background: var(--safety);
}
.panels {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.panel {
min-width: 0;
height: max(500px, calc(100vh - 285px));
display: flex;
flex-direction: column;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 13px;
background: #091522;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.22);
}
.panel-head {
min-height: 68px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 14px;
border-bottom: 1px solid var(--line);
background: #0c1927;
}
.panel-heading {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
}
.panel-letter {
width: 31px;
height: 31px;
display: grid;
place-items: center;
flex: 0 0 auto;
border-radius: 7px;
background: #321d25;
color: var(--baseline);
border: 1px solid #6a3436;
font: 900 14px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.panel.safe .panel-letter {
color: var(--safety);
background: #10332e;
border-color: #28685f;
}
.panel-heading h2 {
margin: 0;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
white-space: nowrap;
}
.panel-heading p {
margin: 4px 0 0;
color: var(--muted);
font-size: 10px;
white-space: nowrap;
}
.camera-tools {
display: flex;
gap: 4px;
}
.camera-tools button {
width: 28px;
height: 28px;
padding: 0;
border: 1px solid #2b4057;
border-radius: 6px;
background: #101e2e;
color: #a8bfd5;
font-size: 14px;
line-height: 1;
}
.camera-tools button:hover {
border-color: #477497;
color: white;
}
.viewport {
position: relative;
min-height: 0;
flex: 1 1 auto;
overflow: hidden;
background: #08121e;
}
.viewport canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.viewport.move-mode canvas {
cursor: crosshair;
}
.view-badge {
position: absolute;
top: 11px;
left: 11px;
z-index: 3;
padding: 7px 9px;
border: 1px solid rgba(255, 120, 107, 0.36);
border-radius: 6px;
background: rgba(39, 18, 25, 0.76);
color: #ffafa6;
font: 800 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.09em;
pointer-events: none;
}
.safe .view-badge {
border-color: rgba(67, 228, 194, 0.36);
background: rgba(11, 47, 41, 0.78);
color: #a3f6e7;
}
.view-hint {
position: absolute;
left: 11px;
bottom: 10px;
z-index: 3;
max-width: calc(100% - 22px);
padding: 7px 9px;
border: 1px solid rgba(69, 95, 123, 0.7);
border-radius: 6px;
background: rgba(5, 14, 23, 0.72);
color: #91a7bc;
font-size: 9px;
pointer-events: none;
}
.metrics {
display: grid;
grid-template-columns: repeat(4, 1fr);
border-top: 1px solid var(--line);
background: #0b1724;
}
.metric {
min-width: 0;
padding: 10px 9px;
border-right: 1px solid var(--line);
}
.metric:last-child {
border-right: 0;
}
.metric span {
display: block;
overflow: hidden;
color: #738aa2;
font: 700 8px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric strong {
display: block;
margin-top: 6px;
color: #e2efff;
font: 800 14px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.safe .metric:first-child strong {
color: var(--safety);
}
.not-baseline .metric:first-child strong {
color: var(--baseline);
}
.map-panel {
margin-top: 12px;
padding: 12px 14px 14px;
border: 1px solid var(--line);
border-radius: 12px;
background: #0a1724;
}
.map-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 9px;
}
.map-head h2 {
margin: 0;
color: #c5d7e8;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.map-head p {
margin: 4px 0 0;
color: #728aa2;
font-size: 10px;
}
#pathMap {
width: 100%;
height: 170px;
display: block;
border: 1px solid #20364c;
border-radius: 8px;
background: #07121e;
}
.model-note {
margin: 10px 2px 0;
color: #73899f;
font-size: 10px;
line-height: 1.5;
}
@media (max-width: 1050px) {
.app {
height: auto;
grid-template-columns: 260px minmax(0, 1fr);
}
.panels {
grid-template-columns: 1fr;
}
.panel {
height: 560px;
}
}
@media (max-width: 740px) {
.topbar {
height: auto;
min-height: 72px;
padding: 12px;
align-items: flex-start;
}
.brand p,
.status {
display: none;
}
.top-actions {
flex-wrap: wrap;
justify-content: flex-end;
}
.top-actions .btn {
min-height: 32px;
padding: 0 9px;
font-size: 10px;
}
.app {
display: flex;
flex-direction: column;
}
.workspace {
order: 1;
padding: 10px;
}
.sidebar {
order: 2;
border-right: 0;
border-top: 1px solid var(--line);
}
.panel {
height: 520px;
}
.workspace-head {
align-items: flex-start;
flex-direction: column;
}
.metrics {
grid-template-columns: repeat(2, 1fr);
}
.metric:nth-child(2) {
border-right: 0;
}
.metric:nth-child(-n + 2) {
border-bottom: 1px solid var(--line);
}
}
</style>
</head>
<body>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"><i></i><i></i><i></i><i></i></div>
<div>
<h1>Flock / Lab</h1>
<p>Controlled voxel aerial comparison</p>
</div>
</div>
<div class="top-actions">
<div class="status" id="runStatus">Running</div>
<button class="btn" id="pauseButton">Pause</button>
<button class="btn" id="resetButton">Reset</button>
<button class="btn primary" id="seedButton">New Seed</button>
</div>
</header>
<div class="app">
<aside class="sidebar">
<section class="section">
<h2 class="section-title"><span>01</span>Flock Parameters</h2>
<div id="flockControls"></div>
</section>
<section class="section">
<h2 class="section-title"><span>02</span>Obstacle Parameters</h2>
<div id="obstacleControls"></div>
</section>
<section class="section">
<h2 class="section-title"><span>03</span>Arena Tools</h2>
<div class="tool-grid">
<button class="tool active" data-tool="orbit">Orbit Camera</button>
<button class="tool" data-tool="move">Move Obstacles</button>
</div>
<label class="check-row">
<span>Leader / centroid trails</span>
<input id="showTrails" type="checkbox" checked />
</label>
<label class="check-row">
<span>Neighborhood radius</span>
<input id="showNeighborhood" type="checkbox" checked />
</label>
<label class="check-row">
<span>Safety influence bounds</span>
<input id="showInfluence" type="checkbox" />
</label>
<label class="check-row">
<span>Link both cameras</span>
<input id="linkCameras" type="checkbox" checked />
</label>
<div class="select-wrap">
<span>Map path</span>
<select id="trailMode">
<option value="leader">Leader bird</option>
<option value="centroid">Flock centroid</option>
</select>
</div>
</section>
<section class="section">
<h2 class="section-title"><span>04</span>Declared Algorithm</h2>
<div class="algorithm">
<strong>A — Classic neighborhood boids.</strong>
Weighted cohesion, alignment and separation inside the selected radius.
Boundaries are constrained, but obstacles have no steering field.
<div class="equation">
a = w<sub>C</sub>a<sub>C</sub> + w<sub>A</sub>a<sub>A</sub> + w<sub>S</sub>a<sub>S</sub>
</div>
<strong>B — Predictive safety extension.</strong>
Variant A plus an obstacle field evaluated at
<strong>p* = p + vτ</strong>. The force uses the normalized vector from
the closest point on the obstacle to p*, scaled by distance to the
influence radius.
<div class="equation">
a = a<sub>A</sub> + k<sub>O</sub>(1 − d/R<sub>O</sub>)²n
</div>
Both variants start from identical seeded positions and velocities.
Only B receives obstacle information.
<span class="note">
This is a controlled steering demonstration, not a complete biological model.
</span>
</div>
</section>
</aside>
<main class="workspace">
<div class="workspace-head">
<div>
Identical experiment / seed <strong id="seedLabel">1042</strong> /
arena 40 × 16 × 28 m
</div>
<div class="legend">
<span><i class="a"></i>A Classic</span>
<span><i class="b"></i>B Predictive safety</span>
</div>
</div>
<div class="panels">
<article class="panel not-baseline">
<header class="panel-head">
<div class="panel-heading">
<div class="panel-letter">A</div>
<div>
<h2>Classic Boids</h2>
<p>Neighborhood forces / no obstacle field</p>
</div>
</div>
<div class="camera-tools">
<button data-camera="zoom-out" data-arena="base" title="Zoom out">−</button>
<button data-camera="zoom-in" data-arena="base" title="Zoom in">+</button>
<button data-camera="reset" data-arena="base" title="Reset camera">⌂</button>
</div>
</header>
<div class="viewport" id="baseViewport">
<div class="view-badge">A / CLASSIC</div>
<div class="view-hint">Drag: orbit · Right-drag: pan · Wheel: zoom</div>
</div>
<div class="metrics">
<div class="metric"><span>Obstacle contacts</span><strong id="baseCollisions">0</strong></div>
<div class="metric"><span>Flock spread</span><strong id="baseSpread">0.0</strong></div>
<div class="metric"><span>Avg speed</span><strong id="baseSpeed">0.0</strong></div>
<div class="metric"><span>Avg neighbors</span><strong id="baseNeighbors">0</strong></div>
</div>
</article>
<article class="panel safe">
<header class="panel-head">
<div class="panel-heading">
<div class="panel-letter">B</div>
<div>
<h2>Predictive Safety</h2>
<p>Same flock / added obstacle prediction</p>
</div>
</div>
<div class="camera-tools">
<button data-camera="zoom-out" data-arena="safe" title="Zoom out">−</button>
<button data-camera="zoom-in" data-arena="safe" title="Zoom in">+</button>
<button data-camera="reset" data-arena="safe" title="Reset camera">⌂</button>
</div>
</header>
<div class="viewport" id="safeViewport">
<div class="view-badge">B / PREDICTIVE</div>
<div class="view-hint">Drag: orbit · Right-drag: pan · Wheel: zoom</div>
</div>
<div class="metrics">
<div class="metric"><span>Obstacle contacts</span><strong id="safeCollisions">0</strong></div>
<div class="metric"><span>Flock spread</span><strong id="safeSpread">0.0</strong></div>
<div class="metric"><span>Avg speed</span><strong id="safeSpeed">0.0</strong></div>
<div class="metric"><span>Avg neighbors</span><strong id="safeNeighbors">0</strong></div>
</div>
</article>
</div>
<section class="map-panel">
<div class="map-head">
<div>
<h2>Top-down path comparison</h2>
<p id="comparisonVerdict">Collecting collision data…</p>
</div>
<div class="legend">
<span><i class="a"></i>A</span>
<span><i class="b"></i>B</span>
</div>
</div>
<canvas id="pathMap" aria-label="Top-down comparison of flock paths"></canvas>
<p class="model-note">
Contacts are counted once per bird after a 0.8-second cooldown.
Moving an obstacle in either arena mirrors its position in the other arena.
Use “Move Obstacles” to drag the voxel columns on the arena floor.
</p>
</section>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const COLORS = {
baseline: 0xff786b,
safety: 0x43e4c2,
bird: 0xd4e8ff
};
const ARENA = {
width: 40,
height: 16,
depth: 28,
minY: 1.2,
maxY: 14.8
};
const OBSTACLE_LAYOUT = [
{ x: -4.5, z: -2.5 },
{ x: 5.0, z: 3.7 },
{ x: 0.0, z: 7.5 }
];
const state = {
paused: false,
seed: 1042,
count: 32,
radius: 4.6,
speed: 6.2,
separation: 1.8,
obstacleSize: 2.8,
obstacleHeight: 5.2,
obstacleCount: 2,
clearance: 1.5,
horizon: 1.0,
tool: "orbit",
showTrails: true,
showNeighborhood: true,
showInfluence: false,
linkCameras: true,
trailMode: "leader"
};
const controlDefinitions = [
{
group: "flockControls",
items: [
{ key: "count", label: "Flock size", min: 12, max: 48, step: 1, format: v => `${v} birds`, rebuild: true },
{ key: "radius", label: "Neighborhood radius", min: 2, max: 8, step: 0.1, format: v => `${v.toFixed(1)} m` },
{ key: "speed", label: "Desired speed", min: 3, max: 9, step: 0.1, format: v => `${v.toFixed(1)} m/s` },
{ key: "separation", label: "Separation weight", min: 0.4, max: 3, step: 0.1, format: v => v.toFixed(1) }
]
},
{
group: "obstacleControls",
items: [
{ key: "obstacleCount", label: "Obstacle columns", min: 1, max: 3, step: 1, format: v => `${v}`, rebuild: true },
{ key: "obstacleSize", label: "Obstacle width", min: 1, max: 4.5, step: 0.1, format: v => `${v.toFixed(1)} m` },
{ key: "obstacleHeight", label: "Obstacle height", min: 1, max: 8, step: 0.1, format: v => `${v.toFixed(1)} m` },
{ key: "clearance", label: "Safety influence radius", min: 0.5, max: 3, step: 0.1, format: v => `${v.toFixed(1)} m` },
{ key: "horizon", label: "Prediction horizon τ", min: 0.4, max: 2, step: 0.1, format: v => `${v.toFixed(1)} s` }
]
}
];
const controlElements = new Map();
for (const group of controlDefinitions) {
for (const item of group.items) {
const wrap = document.createElement("div");
wrap.className = "control";
wrap.innerHTML = `
<label class="control-label">
<span>${item.label}</span>
<output></output>
</label>
<input type="range" min="${item.min}" max="${item.max}" step="${item.step}" />
`;
$(group.group).appendChild(wrap);
const input = wrap.querySelector("input");
const output = wrap.querySelector("output");
input.value = state[item.key];
output.textContent = item.format(state[item.key]);
controlElements.set(item.key, { input, output, item });
}
}
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const birdBodyGeometry = new THREE.BoxGeometry(0.48, 0.28, 0.72);
const birdHeadGeometry = new THREE.BoxGeometry(0.29, 0.27, 0.29);
const birdTailGeometry = new THREE.BoxGeometry(0.22, 0.13, 0.32);
const birdWingGeometry = new THREE.BoxGeometry(0.36, 0.08, 0.42);
function mulberry32(seed) {
return function () {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function clampVectorLength(vector, maximum) {
const lengthSq = vector.lengthSq();
if (lengthSq > maximum * maximum) {
vector.multiplyScalar(maximum / Math.sqrt(lengthSq));
}
return vector;
}
function steeringToward(direction, velocity, desiredSpeed, maximumForce) {
const result = new THREE.Vector3();
if (direction.lengthSq() < 1e-8) return result;
const desired = direction.clone().normalize().multiplyScalar(desiredSpeed);
result.copy(desired).sub(velocity);
return clampVectorLength(result, maximumForce);
}
function closestPointOnBox(point, obstacle) {
const x = THREE.MathUtils.clamp(point.x, obstacle.x - obstacle.hx, obstacle.x + obstacle.hx);
const y = THREE.MathUtils.clamp(point.y, 0, obstacle.height);
const z = THREE.MathUtils.clamp(point.z, obstacle.z - obstacle.hz, obstacle.z + obstacle.hz);
return new THREE.Vector3(x, y, z);
}
function nearestFaceNormal(point, obstacle) {
const dxPositive = obstacle.x + obstacle.hx - point.x;
const dxNegative = point.x - (obstacle.x - obstacle.hx);
const dyPositive = obstacle.height - point.y;
const dyNegative = point.y;
const dzPositive = obstacle.z + obstacle.hz - point.z;
const dzNegative = point.z - (obstacle.z - obstacle.hz);
let minimum = dyNegative;
let normal = new THREE.Vector3(0, -1, 0);
if (dxNegative < minimum) {
minimum = dxNegative;
normal.set(-1, 0, 0);
}
if (dxPositive < minimum) {
minimum = dxPositive;
normal.set(1, 0, 0);
}
if (dyPositive < minimum) {
minimum = dyPositive;
normal.set(0, 1, 0);
}
if (dzNegative < minimum) {
minimum = dzNegative;
normal.set(0, 0, -1);
}
if (dzPositive < minimum) {
normal.set(0, 0, 1);
}
return normal;
}
class Arena {
constructor(hostId, variant) {
this.host = $(hostId);
this.variant = variant;
this.isSafety = variant === "safe";
this.accent = this.isSafety ? COLORS.safety : COLORS.baseline;
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0x08121e);
this.scene.fog = new THREE.Fog(0x08121e, 34, 78);
this.camera = new THREE.PerspectiveCamera(44, 1, 0.1, 120);
this.cameraTarget = new THREE.Vector3(0, 5.2, 0);
this.theta = 0.72;
this.phi = 1.02;
this.cameraRadius = 45;
this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.6));
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.12;
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
this.host.appendChild(this.renderer.domElement);
this.raycaster = new THREE.Raycaster();
this.pointer = new THREE.Vector2();
this.groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
this.drag = null;
this.selectedObstacle = -1;
this.birds = [];
this.obstacles = [];
this.simTime = 0;
this.trailClock = 0;
this.stats = {
collisions: 0,
currentContacts: 0,
spread: 0,
speed: 0,
neighbors: 0
};
this.trails = {
leader: [],
centroid: []
};
this.buildEnvironment();
this.buildObstacles();
this.buildBirds();
this.buildTrails();
this.buildHelpers();
this.resetBirds();
this.installInput();
this.updateCamera();
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(this.host);
this.resize();
}
buildEnvironment() {
const hemisphere = new THREE.HemisphereLight(0x9bc9ff, 0x152033, 1.75);
this.scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xdcecff, 2.4);
sun.position.set(-15, 28, 12);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -28;
sun.shadow.camera.right = 28;
sun.shadow.camera.top = 24;
sun.shadow.camera.bottom = -24;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 70;
sun.shadow.bias = -0.0007;
this.scene.add(sun);
const rim = new THREE.PointLight(this.accent, 18, 40, 2);
rim.position.set(12, 11, -13);
this.scene.add(rim);
const floor = new THREE.Mesh(
unitBox,
new THREE.MeshStandardMaterial({
color: 0x0d1b29,
roughness: 0.95,
metalness: 0.05
})
);
floor.scale.set(ARENA.width, 0.4, ARENA.depth);
floor.position.y = -0.22;
floor.receiveShadow = true;
this.scene.add(floor);
const vertices = [];
for (let x = -20; x <= 20; x += 2) {
vertices.push(x, 0.015, -14, x, 0.015, 14);
}
for (let z = -14; z <= 14; z += 2) {
vertices.push(-20, 0.015, z, 20, 0.015, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute("position", new THREE.Float32BufferAttribute(vertices, 3));
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x46617d,
transparent: true,
opacity: 0.18
})
);
this.scene.add(grid);
const boundaryGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(ARENA.width, ARENA.height, ARENA.depth)
);
const boundary = new THREE.LineSegments(
boundaryGeometry,
new THREE.LineBasicMaterial({
color: this.accent,
transparent: true,
opacity: 0.42
})
);
boundary.position.y = ARENA.height / 2;
this.scene.add(boundary);
const postMaterial = new THREE.MeshStandardMaterial({
color: 0x20354a,
roughness: 0.8
});
for (const x of [-19.7, 19.7]) {
for (const z of [-13.7, 13.7]) {
const post = new THREE.Mesh(unitBox, postMaterial);
post.scale.set(0.28, 1.3, 0.28);
post.position.set(x, 0.65, z);
post.castShadow = true;
this.scene.add(post);
const beacon = new THREE.Mesh(
unitBox,
new THREE.MeshBasicMaterial({ color: this.accent })
);
beacon.scale.set(0.34, 0.16, 0.34);
beacon.position.set(x, 1.37, z);
this.scene.add(beacon);
}
}
}
buildObstacles() {
for (const obstacle of this.obstacles) {
this.scene.remove(obstacle.group);
obstacle.group.traverse(child => {
if (child.isMesh && child.material) child.material.dispose();
});
}
this.obstacles = [];
for (let i = 0; i < state.obstacleCount; i++) {
const layout = OBSTACLE_LAYOUT[i];
const material = new THREE.MeshStandardMaterial({
color: 0x2a4059,
roughness: 0.8,
metalness: 0.12,
emissive: 0x000000,
emissiveIntensity: 0
});
const group = new THREE.Group();
group.position.set(layout.x, 0, layout.z);
const main = new THREE.Mesh(unitBox, material);
main.castShadow = true;
main.receiveShadow = true;
group.add(main);
const cap = new THREE.Mesh(unitBox, material);
cap.castShadow = true;
group.add(cap);
const inset = new THREE.Mesh(unitBox, material);
inset.castShadow = true;
group.add(inset);
const obstacle = {
group,
main,
cap,
inset,
material,
x: layout.x,
z: layout.z,
hx: state.obstacleSize / 2,
hz: state.obstacleSize * 0.36,
height: state.obstacleHeight,
flash: 0
};
group.userData.obstacle = obstacle;
this.scene.add(group);
this.obstacles.push(obstacle);
this.updateObstacleGeometry(obstacle);
}
}
updateObstacleGeometry(obstacle) {
const width = state.obstacleSize;
const depth = state.obstacleSize * 0.72;
const height = state.obstacleHeight;
obstacle.hx = width / 2;
obstacle.hz = depth / 2;
obstacle.height = height;
obstacle.main.scale.set(width, height, depth);
obstacle.main.position.set(0, height / 2, 0);
obstacle.cap.scale.set(width * 0.46, height * 0.22, depth * 0.46);
obstacle.cap.position.set(0, height - height * 0.11, 0);
obstacle.inset.scale.set(width * 0.18, height * 0.34, depth * 0.18);
obstacle.inset.position.set(width * 0.22, height * 0.38, -depth * 0.21);
}
buildBirds() {
for (const bird of this.birds) {
this.scene.remove(bird.group);
bird.material.dispose();
}
this.birds = [];
const palette = [0xd9e9ff, 0x75b8ff, 0xb79bff, 0x8be6d4, 0xf4f7ff];
for (let i = 0; i < state.count; i++) {
const color = i === 0
? this.accent
: palette[Math.floor(i / palette.length) % palette.length];
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.03,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0
});
const group = new THREE.Group();
const body = new THREE.Mesh(birdBodyGeometry, material);
body.castShadow = true;
group.add(body);
const head = new THREE.Mesh(birdHeadGeometry, material);
head.position.set(0, 0.16, 0.46);
head.castShadow = true;
group.add(head);
const tail = new THREE.Mesh(birdTailGeometry, material);
tail.position.set(0, 0.01, -0.49);
tail.castShadow = true;
group.add(tail);
const leftWing = new THREE.Mesh(birdWingGeometry, material);
leftWing.position.set(-0.34, 0.01, 0);
leftWing.castShadow = true;
group.add(leftWing);
const rightWing = new THREE.Mesh(birdWingGeometry, material);
rightWing.position.set(0.34, 0.01, 0);
rightWing.castShadow = true;
group.add(rightWing);
const bird = {
group,
material,
leftWing,
rightWing,
position: new THREE.Vector3(),
velocity: new THREE.Vector3(),
acceleration: new THREE.Vector3(),
phase: 0,
flash: 0,
neighborCount: 0,
lastHit: -100
};
this.birds.push(bird);
this.scene.add(group);
}
}
buildTrails() {
this.trailLines = {};
for (const type of ["leader", "centroid"]) {
const geometry = new THREE.BufferGeometry();
const attribute = new THREE.BufferAttribute(new Float32Array(240 * 3), 3);
attribute.setUsage(THREE.DynamicDrawUsage);
geometry.setAttribute("position", attribute);
geometry.setDrawRange(0, 0);
const material = new THREE.LineBasicMaterial({
color: this.accent,
transparent: true,
opacity: type === "leader" ? 0.78 : 0.42,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.frustumCulled = false;
this.scene.add(line);
this.trailLines[type] = line;
}
}
buildHelpers() {
this.neighborhood = new THREE.Mesh(
new THREE.SphereGeometry(1, 16, 10),
new THREE.MeshBasicMaterial({
color: this.accent,
wireframe: true,
transparent: true,
opacity: 0.11,
depthWrite: false
})
);
this.neighborhood.renderOrder = 2;
this.scene.add(this.neighborhood);
this.selectionBox = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)),
new THREE.LineBasicMaterial({
color: this.accent,
transparent: true,
opacity: 0.9
})
);
this.selectionBox.visible = false;
this.scene.add(this.selectionBox);
this.influenceLines = [];
for (let i = 0; i < 3; i++) {
const line = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)),
new THREE.LineBasicMaterial({
color: COLORS.safety,
transparent: true,
opacity: 0.35
})
);
line.visible = false;
this.scene.add(line);
this.influenceLines.push(line);
}
}
resetBirds() {
const random = mulberry32(state.seed);
const initialSpeed = state.speed;
for (let i = 0; i < this.birds.length; i++) {
const bird = this.birds[i];
let valid = false;
for (let attempt = 0; attempt < 30; attempt++) {
bird.position.set(
-17 + random() * 34,
2.5 + random() * 10.5,
-10.5 + random() * 21
);
valid = true;
for (const obstacle of this.obstacles) {
const expandedX = obstacle.hx + 1.5;
const expandedZ = obstacle.hz + 1.5;
if (
Math.abs(bird.position.x - obstacle.x) < expandedX &&
Math.abs(bird.position.z - obstacle.z) < expandedZ &&
bird.position.y < obstacle.height + 1.2
) {
valid = false;
break;
}
}
if (valid) break;
}
const azimuth = random() * Math.PI * 2;
const vertical = (random() - 0.5) * 0.55;
bird.velocity.set(
Math.sin(azimuth),
vertical,
Math.cos(azimuth)
).normalize().multiplyScalar(initialSpeed);
bird.phase = random() * Math.PI * 2;
bird.flash = 0;
bird.lastHit = -100;
bird.neighborCount = 0;
}
this.stats.collisions = 0;
this.stats.currentContacts = 0;
this.simTime = 0;
this.trailClock = 0;
this.clearTrails();
this.updateStats();
}
clearTrails() {
this.trails.leader.length = 0;
this.trails.centroid.length = 0;
for (const type of ["leader", "centroid"]) {
const line = this.trailLines[type];
line.geometry.setDrawRange(0, 0);
}
}
computeObstacleForce(bird) {
const force = new THREE.Vector3();
const future = bird.position.clone().addScaledVector(bird.velocity, state.horizon);
const influenceRadius = state.clearance + 0.9;
for (const obstacle of this.obstacles) {
const closestFuture = closestPointOnBox(future, obstacle);
const futureDelta = future.clone().sub(closestFuture);
const futureDistance = futureDelta.length();
if (futureDistance < influenceRadius) {
let direction;
if (futureDistance > 0.0001) {
direction = futureDelta.clone().multiplyScalar(1 / futureDistance);
} else {
direction = nearestFaceNormal(future, obstacle);
}
const normalizedDistance = THREE.MathUtils.clamp(
futureDistance / influenceRadius,
0,
1
);
const magnitude = 4.4 * Math.pow(1 - normalizedDistance, 2);
force.addScaledVector(direction, magnitude);
}
const closestCurrent = closestPointOnBox(bird.position, obstacle);
const currentDelta = bird.position.clone().sub(closestCurrent);
const currentDistance = currentDelta.length();
if (currentDistance < 0.72) {
let direction;
if (currentDistance > 0.0001) {
direction = currentDelta.clone().multiplyScalar(1 / currentDistance);
} else {
direction = nearestFaceNormal(bird.position, obstacle);
}
force.addScaledVector(direction, 7 * (1 - currentDistance / 0.72));
}
}
return force;
}
updateSimulation(dt) {
this.simTime += dt;
this.stats.currentContacts = 0;
const separationRadius = Math.max(1.05, state.radius * 0.42);
for (const bird of this.birds) {
const neighbors = [];
let center = new THREE.Vector3();
let averageVelocity = new THREE.Vector3();
let separation = new THREE.Vector3();
for (const other of this.birds) {
if (other === bird) continue;
const distanceSq = bird.position.distanceToSquared(other.position);
if (distanceSq <= state.radius * state.radius) {
neighbors.push(other);
center.add(other.position);
averageVelocity.add(other.velocity);
if (distanceSq <= separationRadius * separationRadius) {
const distance = Math.sqrt(distanceSq);
separation.addScaledVector(
bird.position.clone().sub(other.position),
1 / (distanceSq + 0.08)
);
}
}
}
bird.neighborCount = neighbors.length;
const acceleration = new THREE.Vector3();
if (neighbors.length > 0) {
center.multiplyScalar(1 / neighbors.length);
averageVelocity.multiplyScalar(1 / neighbors.length);
const cohesion = steeringToward(
center.sub(bird.position),
bird.velocity,
state.speed,
2.1
);
const alignment = steeringToward(
averageVelocity,
bird.velocity,
state.speed,
2.0
);
acceleration.addScaledVector(cohesion, 0.68);
acceleration.addScaledVector(alignment, 0.88);
if (separation.lengthSq() > 1e-8) {
const avoidance = steeringToward(
separation,
bird.velocity,
state.speed,
3.4
);
acceleration.addScaledVector(avoidance, state.separation);
}
}
const speed = bird.velocity.length();
if (speed > 0.001) {
acceleration.addScaledVector(
bird.velocity.clone().multiplyScalar(1 / speed),
(state.speed - speed) * 0.18
);
}
// Boundary steering is shared by both variants.
const marginX = 17.2;
const marginZ = 11.2;
if (bird.position.x > marginX) acceleration.x -= (bird.position.x - marginX) * 3.2;
if (bird.position.x < -marginX) acceleration.x += (-marginX - bird.position.x) * 3.2;
if (bird.position.z > marginZ) acceleration.z -= (bird.position.z - marginZ) * 3.2;
if (bird.position.z < -marginZ) acceleration.z += (-marginZ - bird.position.z) * 3.2;
if (bird.position.y > 13.2) acceleration.y -= (bird.position.y - 13.2) * 3.6;
if (bird.position.y < 2.7) acceleration.y += (2.7 - bird.position.y) * 3.6;
// Only variant B receives obstacle information.
if (this.isSafety) {
acceleration.add(this.computeObstacleForce(bird));
}
clampVectorLength(acceleration, 5.3);
bird.velocity.addScaledVector(acceleration, dt);
const maxSpeed = state.speed + 2.4;
const velocityLength = bird.velocity.length();
if (velocityLength > maxSpeed) {
bird.velocity.multiplyScalar(maxSpeed / velocityLength);
} else if (velocityLength < 2.2 && velocityLength > 0.001) {
bird.velocity.multiplyScalar(2.2 / velocityLength);
}
bird.position.addScaledVector(bird.velocity, dt);
// Hard arena containment is shared by both variants.
if (bird.position.x < -19.7) {
bird.position.x = -19.7;
bird.velocity.x = Math.abs(bird.velocity.x);
}
if (bird.position.x > 19.7) {
bird.position.x = 19.7;
bird.velocity.x = -Math.abs(bird.velocity.x);
}
if (bird.position.z < -13.7) {
bird.position.z = -13.7;
bird.velocity.z = Math.abs(bird.velocity.z);
}
if (bird.position.z > 13.7) {
bird.position.z = 13.7;
bird.velocity.z = -Math.abs(bird.velocity.z);
}
if (bird.position.y < ARENA.minY) {
bird.position.y = ARENA.minY;
bird.velocity.y = Math.abs(bird.velocity.y);
}
if (bird.position.y > ARENA.maxY) {
bird.position.y = ARENA.maxY;
bird.velocity.y = -Math.abs(bird.velocity.y);
}
}
// Obstacle contacts are measured after integration.
for (const bird of this.birds) {
for (const obstacle of this.obstacles) {
const touching =
Math.abs(bird.position.x - obstacle.x) <= obstacle.hx + 0.27 &&
Math.abs(bird.position.z - obstacle.z) <= obstacle.hz + 0.27 &&
bird.position.y >= -0.27 &&
bird.position.y <= obstacle.height + 0.27;
if (touching) {
this.stats.currentContacts++;
bird.flash = 1;
obstacle.flash = 1;
if (this.simTime - bird.lastHit > 0.8) {
this.stats.collisions++;
bird.lastHit = this.simTime;
}
}
}
}
this.trailClock += dt;
if (this.trailClock >= 0.08) {
this.trailClock %= 0.08;
this.sampleTrails();
}
this.updateStats();
}
updateStats() {
if (!this.birds.length) return;
const centroid = new THREE.Vector3();
let totalSpeed = 0;
let totalNeighbors = 0;
for (const bird of this.birds) {
centroid.add(bird.position);
totalSpeed += bird.velocity.length();
totalNeighbors += bird.neighborCount;
}
centroid.multiplyScalar(1 / this.birds.length);
let spread = 0;
for (const bird of this.birds) {
spread += bird.position.distanceTo(centroid);
}
this.stats.speed = totalSpeed / this.birds.length;
this.stats.neighbors = totalNeighbors / this.birds.length;
this.stats.spread = spread / this.birds.length;
}
sampleTrails() {
if (!this.birds.length) return;
const leader = this.birds[0].position.clone();
const centroid = new THREE.Vector3();
for (const bird of this.birds) centroid.add(bird.position);
centroid.multiplyScalar(1 / this.birds.length);
for (const [type, point] of [["leader", leader], ["centroid", centroid]]) {
const points = this.trails[type];
points.push(point);
if (points.length > 240) points.shift();
const line = this.trailLines[type];
const attribute = line.geometry.getAttribute("position");
for (let i = 0; i < points.length; i++) {
attribute.setXYZ(i, points[i].x, points[i].y, points[i].z);
}
attribute.needsUpdate = true;
line.geometry.setDrawRange(0, points.length);
}
}
updateVisuals(delta) {
for (const bird of this.birds) {
bird.group.position.copy(bird.position);
const speed = Math.max(0.001, bird.velocity.length());
bird.group.rotation.order = "YXZ";
bird.group.rotation.y = Math.atan2(bird.velocity.x, bird.velocity.z);
bird.group.rotation.x = -Math.asin(
THREE.MathUtils.clamp(bird.velocity.y / speed, -1, 1)
);
const flap = Math.sin(this.simTime * 9 + bird.phase) * 0.36;
bird.leftWing.rotation.z = flap;
bird.rightWing.rotation.z = -flap;
bird.flash = Math.max(0, bird.flash - delta * 2.8);
bird.material.emissive.setHex(0xff3b30);
bird.material.emissiveIntensity = bird.flash * 1.7;
}
for (const obstacle of this.obstacles) {
obstacle.flash = Math.max(0, obstacle.flash - delta * 2.5);
obstacle.material.emissive.setHex(0xff4438);
obstacle.material.emissiveIntensity = obstacle.flash * 0.7;
}
if (this.birds.length) {
this.neighborhood.position.copy(this.birds[0].position);
this.neighborhood.scale.setScalar(state.radius);
this.neighborhood.visible = state.showNeighborhood;
}
for (let i = 0; i < this.influenceLines.length; i++) {
const line = this.influenceLines[i];
const obstacle = this.obstacles[i];
if (!obstacle) {
line.visible = false;
continue;
}
const radius = state.clearance + 0.9;
line.scale.set(
obstacle.hx * 2 + radius * 2,
obstacle.height + radius * 2,
obstacle.hz * 2 + radius * 2
);
line.position.set(obstacle.x, obstacle.height / 2, obstacle.z);
line.visible = this.isSafety && state.showInfluence;
}
const selected = this.obstacles[this.selectedObstacle];
if (selected) {
this.selectionBox.visible = true;
this.selectionBox.scale.set(
state.obstacleSize + 0.38,
state.obstacleHeight + 0.38,
state.obstacleSize * 0.72 + 0.38
);
this.selectionBox.position.set(
selected.x,
state.obstacleHeight / 2,
selected.z
);
} else {
this.selectionBox.visible = false;
}
this.trailLines.leader.visible =
state.showTrails && state.trailMode === "leader";
this.trailLines.centroid.visible =
state.showTrails && state.trailMode === "centroid";
}
setObstaclePosition(index, x, z) {
const obstacle = this.obstacles[index];
if (!obstacle) return;
obstacle.x = THREE.MathUtils.clamp(
x,
-ARENA.width / 2 + obstacle.hx + 0.5,
ARENA.width / 2 - obstacle.hx - 0.5
);
obstacle.z = THREE.MathUtils.clamp(
z,
-ARENA.depth / 2 + obstacle.hz + 0.5,
ARENA.depth / 2 - obstacle.hz - 0.5
);
obstacle.group.position.set(obstacle.x, 0, obstacle.z);
}
selectObstacle(index) {
this.selectedObstacle = index;
}
updateCamera() {
const spherical = new THREE.Spherical(
this.cameraRadius,
this.phi,
this.theta
);
this.camera.position.setFromSpherical(spherical).add(this.cameraTarget);
this.camera.lookAt(this.cameraTarget);
this.camera.updateMatrixWorld();
}
resetCamera() {
this.cameraTarget.set(0, 5.2, 0);
this.theta = 0.72;
this.phi = 1.02;
this.cameraRadius = 45;
this.updateCamera();
}
syncCameraFrom(other) {
this.cameraTarget.copy(other.cameraTarget);
this.theta = other.theta;
this.phi = other.phi;
this.cameraRadius = other.cameraRadius;
this.updateCamera();
}
resize() {
const width = Math.max(1, this.host.clientWidth);
const height = Math.max(1, this.host.clientHeight);
this.renderer.setSize(width, height, false);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
}
render() {
this.renderer.render(this.scene, this.camera);
}
installInput() {
const canvas = this.renderer.domElement;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
this.updatePointer(event);
const isPan = event.button === 2 || event.button === 1 || event.shiftKey;
this.drag = {
id: event.pointerId,
mode: isPan ? "pan" : "orbit",
lastX: event.clientX,
lastY: event.clientY
};
if (!isPan && state.tool === "move") {
this.raycaster.setFromCamera(this.pointer, this.camera);
const hits = this.raycaster.intersectObjects(
this.obstacles.map(obstacle => obstacle.group),
true
);
if (hits.length) {
let object = hits[0].object;
while (object && !object.userData.obstacle) object = object.parent;
const obstacle = object?.userData.obstacle;
if (obstacle) {
const index = this.obstacles.indexOf(obstacle);
this.selectObstacle(index);
const other = this.isSafety ? baseArena : safeArena;
other.selectObstacle(index);
const groundPoint = new THREE.Vector3();
this.raycaster.ray.intersectPlane(this.groundPlane, groundPoint);
this.drag.mode = "obstacle";
this.drag.obstacleIndex = index;
this.drag.offsetX = groundPoint.x - obstacle.x;
this.drag.offsetZ = groundPoint.z - obstacle.z;
}
}
}
});
canvas.addEventListener("pointermove", event => {
if (!this.drag || event.pointerId !== this.drag.id) return;
const dx = event.clientX - this.drag.lastX;
const dy = event.clientY - this.drag.lastY;
this.drag.lastX = event.clientX;
this.drag.lastY = event.clientY;
if (this.drag.mode === "orbit") {
this.theta -= dx * 0.006;
this.phi = THREE.MathUtils.clamp(this.phi - dy * 0.005, 0.3, 1.42);
} else if (this.drag.mode === "pan") {
const right = new THREE.Vector3()
.setFromMatrixColumn(this.camera.matrix, 0);
const up = new THREE.Vector3()
.setFromMatrixColumn(this.camera.matrix, 1);
const panScale = this.cameraRadius * 0.0016;
this.cameraTarget.addScaledVector(right, -dx * panScale);
this.cameraTarget.addScaledVector(up, dy * panScale);
this.cameraTarget.x = THREE.MathUtils.clamp(
this.cameraTarget.x, -12, 12
);
this.cameraTarget.y = THREE.MathUtils.clamp(
this.cameraTarget.y, 1, 12
);
this.cameraTarget.z = THREE.MathUtils.clamp(
this.cameraTarget.z, -10, 10
);
} else if (this.drag.mode === "obstacle") {
this.updatePointer(event);
this.raycaster.setFromCamera(this.pointer, this.camera);
const groundPoint = new THREE.Vector3();
if (this.raycaster.ray.intersectPlane(this.groundPlane, groundPoint)) {
const x = groundPoint.x - this.drag.offsetX;
const z = groundPoint.z - this.drag.offsetZ;
this.setObstaclePosition(this.drag.obstacleIndex, x, z);
const other = this.isSafety ? baseArena : safeArena;
other.setObstaclePosition(this.drag.obstacleIndex, x, z);
}
}
this.updateCamera();
if (state.linkCameras) {
const other = this.isSafety ? baseArena : safeArena;
other.syncCameraFrom(this);
}
});
const endDrag = event => {
if (this.drag && event.pointerId === this.drag.id) {
this.drag = null;
}
};
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("wheel", event => {
event.preventDefault();
this.cameraRadius = THREE.MathUtils.clamp(
this.cameraRadius * Math.exp(event.deltaY * 0.001),
18,
76
);
this.updateCamera();
if (state.linkCameras) {
const other = this.isSafety ? baseArena : safeArena;
other.syncCameraFrom(this);
}
}, { passive: false });
}
updatePointer(event) {
const rect = this.renderer.domElement.getBoundingClientRect();
this.pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
this.pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
}
const baseArena = new Arena("baseViewport", "base");
const safeArena = new Arena("safeViewport", "safe");
function resetExperiment() {
baseArena.resetBirds();
safeArena.resetBirds();
updateMetricUI();
}
function updateMetricUI() {
$("baseCollisions").textContent = baseArena.stats.collisions;
$("safeCollisions").textContent = safeArena.stats.collisions;
$("baseSpread").textContent = baseArena.stats.spread.toFixed(1);
$("safeSpread").textContent = safeArena.stats.spread.toFixed(1);
$("baseSpeed").textContent = baseArena.stats.speed.toFixed(1);
$("safeSpeed").textContent = safeArena.stats.speed.toFixed(1);
$("baseNeighbors").textContent = baseArena.stats.neighbors.toFixed(1);
$("safeNeighbors").textContent = safeArena.stats.neighbors.toFixed(1);
const difference = baseArena.stats.collisions - safeArena.stats.collisions;
if (difference > 0) {
$("comparisonVerdict").textContent =
`B has ${difference} fewer obstacle contact${difference === 1 ? "" : "s"} than A.`;
} else if (difference < 0) {
$("comparisonVerdict").textContent =
`B currently has ${-difference} more obstacle contact${difference === -1 ? "" : "s"} than A.`;
} else {
$("comparisonVerdict").textContent =
"Contact counts are currently equal; move an obstacle or run longer.";
}
}
function updateObstacleGeometryAll() {
for (const arena of [baseArena, safeArena]) {
for (const obstacle of arena.obstacles) {
arena.updateObstacleGeometry(obstacle);
}
}
}
for (const [key, { input, output, item }] of controlElements) {
input.addEventListener("input", () => {
const value = Number(input.value);
state[key] = value;
output.textContent = item.format(value);
if (key === "count") {
baseArena.buildBirds();
safeArena.buildBirds();
resetExperiment();
} else if (key === "obstacleCount") {
baseArena.buildObstacles();
safeArena.buildObstacles();
resetExperiment();
} else if (key === "obstacleSize" || key === "obstacleHeight") {
updateObstacleGeometryAll();
}
});
}
document.querySelectorAll("[data-tool]").forEach(button => {
button.addEventListener("click", () => {
state.tool = button.dataset.tool;
document.querySelectorAll("[data-tool]").forEach(item => {
item.classList.toggle("active", item === button);
});
$("baseViewport").classList.toggle("move-mode", state.tool === "move");
$("safeViewport").classList.toggle("move-mode", state.tool === "move");
});
});
$("showTrails").addEventListener("change", event => {
state.showTrails = event.target.checked;
});
$("showNeighborhood").addEventListener("change", event => {
state.showNeighborhood = event.target.checked;
});
$("showInfluence").addEventListener("change", event => {
state.showInfluence = event.target.checked;
});
$("linkCameras").addEventListener("change", event => {
state.linkCameras = event.target.checked;
if (state.linkCameras) safeArena.syncCameraFrom(baseArena);
});
$("trailMode").addEventListener("change", event => {
state.trailMode = event.target.value;
});
$("pauseButton").addEventListener("click", () => {
state.paused = !state.paused;
$("pauseButton").textContent = state.paused ? "Resume" : "Pause";
$("runStatus").textContent = state.paused ? "Paused" : "Running";
$("runStatus").classList.toggle("paused", state.paused);
});
$("resetButton").addEventListener("click", () => {
resetExperiment();
});
$("seedButton").addEventListener("click", () => {
state.seed += 97;
$("seedLabel").textContent = state.seed;
resetExperiment();
});
document.querySelectorAll("[data-camera]").forEach(button => {
button.addEventListener("click", event => {
event.stopPropagation();
const arena = button.dataset.arena === "safe" ? safeArena : baseArena;
const other = arena === safeArena ? baseArena : safeArena;
if (button.dataset.camera === "zoom-in") {
arena.cameraRadius = Math.max(18, arena.cameraRadius * 0.86);
} else if (button.dataset.camera === "zoom-out") {
arena.cameraRadius = Math.min(76, arena.cameraRadius * 1.16);
} else {
arena.resetCamera();
}
arena.updateCamera();
if (state.linkCameras) other.syncCameraFrom(arena);
});
});
const mapCanvas = $("pathMap");
const mapContext = mapCanvas.getContext("2d");
function drawPathMap() {
const rect = mapCanvas.getBoundingClientRect();
const width = Math.max(1, rect.width);
const height = Math.max(1, rect.height);
const dpr = Math.min(window.devicePixelRatio || 1, 2);
if (mapCanvas.width !== Math.round(width * dpr) ||
mapCanvas.height !== Math.round(height * dpr)) {
mapCanvas.width = Math.round(width * dpr);
mapCanvas.height = Math.round(height * dpr);
}
mapContext.setTransform(dpr, 0, 0, dpr, 0, 0);
mapContext.clearRect(0, 0, width, height);
const padding = 14;
const plotWidth = width - padding * 2;
const plotHeight = height - padding * 2;
const mapX = x => padding + ((x + 20) / 40) * plotWidth;
const mapZ = z => padding + ((z + 14) / 28) * plotHeight;
mapContext.fillStyle = "#081522";
mapContext.fillRect(0, 0, width, height);
mapContext.strokeStyle = "rgba(76, 111, 145, 0.16)";
mapContext.lineWidth = 1;
for (let x = -20; x <= 20; x += 5) {
mapContext.beginPath();
mapContext.moveTo(mapX(x), padding);
mapContext.lineTo(mapX(x), height - padding);
mapContext.stroke();
}
for (let z = -14; z <= 14; z += 7) {
mapContext.beginPath();
mapContext.moveTo(padding, mapZ(z));
mapContext.lineTo(width - padding, mapZ(z));
mapContext.stroke();
}
mapContext.strokeStyle = "rgba(92, 127, 162, 0.45)";
mapContext.strokeRect(padding, padding, plotWidth, plotHeight);
for (const obstacle of baseArena.obstacles) {
const x = mapX(obstacle.x - obstacle.hx);
const y = mapZ(obstacle.z - obstacle.hz);
const w = (obstacle.hx * 2 / 40) * plotWidth;
const d = (obstacle.hz * 2 / 28) * plotHeight;
mapContext.fillStyle = "#354b64";
mapContext.fillRect(x, y, w, d);
mapContext.strokeStyle = "#718ba6";
mapContext.strokeRect(x, y, w, d);
}
if (state.showTrails) {
const drawTrail = (arena, color, alpha) => {
const points = arena.trails[state.trailMode];
if (points.length < 2) return;
mapContext.beginPath();
mapContext.strokeStyle = color;
mapContext.globalAlpha = alpha;
mapContext.lineWidth = 2;
mapContext.lineJoin = "round";
for (let i = 0; i < points.length; i++) {
const point = points[i];
if (i === 0) mapContext.moveTo(mapX(point.x), mapZ(point.z));
else mapContext.lineTo(mapX(point.x), mapZ(point.z));
}
mapContext.stroke();
mapContext.globalAlpha = 1;
};
drawTrail(baseArena, "#ff786b", 0.9);
drawTrail(safeArena, "#43e4c2", 0.9);
}
for (const [arena, color] of [
[baseArena, "#ff786b"],
[safeArena, "#43e4c2"]
]) {
if (!arena.birds.length) continue;
const point = state.trailMode === "leader"
? arena.birds[0].position
: arena.birds.reduce(
(sum, bird) => sum.add(bird.position),
new THREE.Vector3()
).multiplyScalar(1 / arena.birds.length);
mapContext.fillStyle = color;
mapContext.beginPath();
mapContext.arc(mapX(point.x), mapZ(point.z), 3.5, 0, Math.PI * 2);
mapContext.fill();
}
}
let previousTime = performance.now() / 1000;
let accumulator = 0;
let lastMetricTime = 0;
const fixedStep = 1 / 60;
function animate() {
const now = performance.now() / 1000;
const delta = Math.min(now - previousTime, 0.05);
previousTime = now;
if (!state.paused) {
accumulator += delta;
let steps = 0;
while (accumulator >= fixedStep && steps < 4) {
baseArena.updateSimulation(fixedStep);
safeArena.updateSimulation(fixedStep);
accumulator -= fixedStep;
steps++;
}
} else {
accumulator = 0;
}
baseArena.updateVisuals(delta);
safeArena.updateVisuals(delta);
baseArena.render();
safeArena.render();
if (now - lastMetricTime > 0.25) {
updateMetricUI();
drawPathMap();
lastMetricTime = now;
}
requestAnimationFrame(animate);
}
$("seedLabel").textContent = state.seed;
updateMetricUI();
drawPathMap();
animate();
</script>
</body>
</html>
```