aldi-aros-hq-z-axis-site-configurator-safety-engine.html
<!-- Copyright © Albert Lane. All Rights Reserved.
Proprietary and Confidential — Albert Lane Proprietary Software License.
Unauthorized use, copying, or distribution is prohibited.
License inquiries: https://albertlane.net -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="copyright" content="© Albert Lane. All Rights Reserved. Albert Lane Proprietary Software License. https://albertlane.net" />
<title>1 Other Hacker Sucks Ln — Z-Axis Site Configurator & Safety Engine</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet" />
<style>
:root {
--bg-void: #070b12;
--bg-panel: #0d131f;
--bg-card: #121a2a;
--border-dim: #1e293b;
--accent-cyan: #22d3ee;
--accent-amber: #f59e0b;
--accent-emerald: #10b981;
--accent-magenta: #e879f9;
--accent-red: #f43f5e;
}
* {
box-sizing: border-box;
user-select: none;
}
body {
margin: 0;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background-color: var(--bg-void);
color: #e2e8f0;
overflow-x: hidden;
}
.font-mono-tech {
font-family: 'JetBrains Mono', monospace;
}
/* Custom subtle scrollbars for side panels */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: #0a0f18;
}
::-webkit-scrollbar-thumb {
background: #263449;
border-radius: 9999px;
}
::-webkit-scrollbar-thumb:hover {
background: #38bdf8;
}
.cad-glow-cyan {
box-shadow: 0 0 18px rgba(34, 211, 238, 0.16);
}
.cad-glow-red {
box-shadow: 0 0 20px rgba(244, 63, 94, 0.25);
}
.cad-glow-emerald {
box-shadow: 0 0 18px rgba(16, 185, 129, 0.2);
}
</style>
</head>
<body class="min-h-screen flex flex-col bg-[#070b12] text-slate-200">
<!-- TOP ARCHITECTURAL HEADER BAR -->
<header class="border-b border-slate-800/90 bg-[#0b101b]/95 backdrop-blur px-4 py-2.5 flex flex-wrap items-center justify-between gap-3 z-20">
<div class="flex items-center gap-3">
<div class="w-9 h-9 rounded-lg bg-cyan-500/10 border border-cyan-400/40 flex items-center justify-center text-cyan-400 font-mono-tech font-bold text-sm cad-glow-cyan">
Z//27
</div>
<div>
<div class="flex items-center gap-2 flex-wrap">
<h1 class="text-sm sm:text-base font-extrabold tracking-tight text-white">
1 OTHER HACKER SUCKS LN
</h1>
<span class="text-[10px] font-mono-tech uppercase tracking-widest px-2 py-0.5 rounded bg-cyan-950/80 text-cyan-300 border border-cyan-500/30">
Z-Axis CAD & Heuristics v2027.4
</span>
</div>
<p class="text-[11px] text-slate-400 hidden sm:block">
Suburban WFH Corporate Skatepark, Glulam LinkingLogs & MicroLED Graffiti Campus (48m × 32m Datum)
</p>
</div>
</div>
<!-- VIEW & PRESET CONTROLS -->
<div class="flex flex-wrap items-center gap-2">
<!-- 2D / 2.5D Isometric View Toggle -->
<div class="inline-flex rounded-lg bg-slate-900/90 p-1 border border-slate-700/80">
<button id="btnView2D" onclick="setViewMode('2D')" class="px-2.5 py-1 rounded-md text-xs font-mono-tech font-semibold transition bg-cyan-500 text-slate-950 shadow">
2D CAD PLAN
</button>
<button id="btnViewISO" onclick="setViewMode('ISO')" class="px-2.5 py-1 rounded-md text-xs font-mono-tech font-semibold transition text-slate-300 hover:text-white">
2.5D ISO Z-VIEW
</button>
</div>
<!-- Preset Loaders -->
<button onclick="loadPreset('SAFE_HAWK')" class="px-2.5 py-1.5 rounded-lg text-xs font-semibold bg-emerald-500/15 hover:bg-emerald-500/25 text-emerald-300 border border-emerald-500/40 transition flex items-center gap-1.5">
<span class="w-2 h-2 rounded-full bg-emerald-400"></span>
Preset: Tony Hawk Bowl + Safe Bridge
</button>
<button onclick="loadPreset('UNSAFE_KID')" class="px-2.5 py-1.5 rounded-lg text-xs font-semibold bg-rose-500/15 hover:bg-rose-500/25 text-rose-300 border border-rose-500/40 transition flex items-center gap-1.5">
<span class="w-2 h-2 rounded-full bg-rose-400"></span>
Preset: Unsafe Kid Tower
</button>
<button onclick="clearAllModules()" class="px-2.5 py-1.5 rounded-lg text-xs font-mono-tech bg-slate-800/90 hover:bg-slate-700 text-slate-300 border border-slate-700 transition">
CLEAR
</button>
</div>
</header>
<!-- MAIN WORKSPACE GRID -->
<main class="flex-1 grid grid-cols-1 lg:grid-cols-12 gap-0 overflow-hidden">
<!-- LEFT SIDEBAR: COMPONENT PALETTE & SPRAY SIMULATOR -->
<aside class="lg:col-span-3 border-b lg:border-b-0 lg:border-r border-slate-800 bg-[#0b101b] p-3 flex flex-col gap-3 overflow-y-auto max-h-[calc(100vh-105px)]">
<!-- Active Tool Controls -->
<div class="rounded-xl bg-[#111827] border border-slate-800 p-2.5">
<div class="flex items-center justify-between mb-1.5">
<span class="text-[11px] font-mono-tech uppercase tracking-wider text-slate-400">Placement Tool</span>
<span id="rotationBadge" class="text-[11px] font-mono-tech text-cyan-400 bg-cyan-950/70 px-2 py-0.5 rounded border border-cyan-500/30">
ROT: 0°
</span>
</div>
<div class="grid grid-cols-3 gap-1.5 text-xs">
<button onclick="setToolMode('PLACE')" id="toolPlace" class="py-1.5 px-2 rounded-lg font-semibold bg-cyan-500/20 text-cyan-300 border border-cyan-500/50 transition">
+ Place
</button>
<button onclick="rotateSelection()" class="py-1.5 px-2 rounded-lg font-mono-tech bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 transition">
↻ Rot [R]
</button>
<button onclick="setToolMode('SELECT')" id="toolSelect" class="py-1.5 px-2 rounded-lg font-semibold bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700 transition">
Inspect
</button>
</div>
<p class="text-[11px] text-slate-400 mt-2 leading-snug">
Click grid to place/move. <span class="text-slate-200 font-mono-tech">[R]</span> rotates 90°. Right-click or <span class="text-slate-200 font-mono-tech">[Del]</span> removes.
</p>
</div>
<!-- Palette Group 1: Skatepark Modules -->
<div>
<div class="flex items-center justify-between px-1 mb-1.5">
<h2 class="text-xs font-bold uppercase tracking-wider text-cyan-400 flex items-center gap-1.5">
<span>🛹</span> Skate Modules (SKT)
</h2>
<span class="text-[10px] font-mono-tech text-slate-500">v = 11 m/s</span>
</div>
<div id="paletteSkate" class="space-y-1.5"></div>
</div>
<!-- Palette Group 2: LinkingLogs Glulam -->
<div>
<div class="flex items-center justify-between px-1 mb-1.5">
<h2 class="text-xs font-bold uppercase tracking-wider text-amber-400 flex items-center gap-1.5">
<span>🪵</span> LinkingLogs (LLG)
</h2>
<span class="text-[10px] font-mono-tech text-slate-500">E = 12.4 GPa</span>
</div>
<div id="paletteLogs" class="space-y-1.5"></div>
</div>
<!-- Palette Group 3: Digital Graffiti Glass -->
<div>
<div class="flex items-center justify-between px-1 mb-1.5">
<h2 class="text-xs font-bold uppercase tracking-wider text-fuchsia-400 flex items-center gap-1.5">
<span>🎨</span> Graffiti Glass (GRF)
</h2>
<span class="text-[10px] font-mono-tech text-slate-500">4500 nits</span>
</div>
<div id="paletteGraffiti" class="space-y-1.5"></div>
</div>
<!-- Interactive Mini Rattle-Can Test Spray Simulator -->
<div class="rounded-xl bg-[#111827] border border-fuchsia-500/30 p-2.5 mt-auto">
<div class="flex items-center justify-between mb-1.5">
<span class="text-[11px] font-bold uppercase tracking-wider text-fuchsia-300">
MicroLED Glass Test Spray
</span>
<button onclick="clearSprayCanvas()" class="text-[10px] font-mono-tech text-slate-400 hover:text-white underline">
Buff Glass
</button>
</div>
<div class="flex items-center gap-1.5 mb-2">
<button onclick="setSprayColor('#22d3ee')" class="w-5 h-5 rounded-full bg-cyan-400 ring-2 ring-offset-1 ring-offset-slate-900 ring-white" title="Cyan Neon"></button>
<button onclick="setSprayColor('#e879f9')" class="w-5 h-5 rounded-full bg-fuchsia-400" title="Magenta Neon"></button>
<button onclick="setSprayColor('#a3e635')" class="w-5 h-5 rounded-full bg-lime-400" title="Acid Lime"></button>
<button onclick="setSprayColor('#fbbf24')" class="w-5 h-5 rounded-full bg-amber-400" title="Solar Amber"></button>
<button onclick="setSprayColor('#fb7185')" class="w-5 h-5 rounded-full bg-rose-400" title="Laser Coral"></button>
<span class="ml-auto text-[10px] font-mono-tech text-slate-400">Drag to tag ↓</span>
</div>
<canvas id="sprayPreviewCanvas" class="w-full h-24 rounded-lg bg-slate-950 border border-slate-700/80 cursor-crosshair"></canvas>
<p class="text-[10px] text-slate-400 mt-1">
Tags sync live onto placed <span class="text-fuchsia-300 font-mono-tech">GRF-GLS-3045</span> bays on the site grid.
</p>
</div>
</aside>
<!-- CENTER: INTERACTIVE 48m x 32m Z-AXIS SITE CANVAS -->
<section class="lg:col-span-6 relative flex flex-col bg-[#060910] min-h-[440px]">
<!-- Top Canvas Telemetry Overlay -->
<div class="flex flex-wrap items-center justify-between gap-2 px-3 py-2 bg-[#0a0f1a]/90 border-b border-slate-800/80 text-[11px] font-mono-tech">
<div class="flex items-center gap-3">
<span id="cursorCoords" class="text-cyan-300">X: 00.0m | Y: 00.0m</span>
<span id="hoverZoneLabel" class="text-slate-400">ZONE: SITE DATUM</span>
</div>
<div class="flex items-center gap-3">
<label class="inline-flex items-center gap-1.5 cursor-pointer text-slate-300">
<input id="toggleFallZones" type="checkbox" checked onchange="renderSite()" class="accent-cyan-400 rounded" />
<span>Fall Envelopes</span>
</label>
<label class="inline-flex items-center gap-1.5 cursor-pointer text-slate-300">
<input id="toggleCoG" type="checkbox" checked onchange="renderSite()" class="accent-amber-400 rounded" />
<span>CoG & Kern</span>
</label>
</div>
</div>
<!-- Main Responsive Canvas Container -->
<div id="canvasContainer" class="relative flex-1 w-full h-full overflow-hidden">
<canvas id="siteCanvas" class="block w-full h-full cursor-crosshair"></canvas>
<!-- Floating Zone Legend Pill (Bottom-Left) -->
<div class="absolute bottom-3 left-3 pointer-events-none bg-[#0b101b]/85 backdrop-blur-md border border-slate-800 rounded-xl p-2.5 text-[10px] font-mono-tech space-y-1 hidden sm:block">
<div class="text-slate-400 font-semibold uppercase tracking-wider mb-1">Campus Zoning (48m × 32m)</div>
<div class="flex items-center gap-2"><span class="w-2.5 h-2.5 rounded-sm bg-cyan-500/30 border border-cyan-400"></span> Z1: Sunken Vert & Flow Bowl</div>
<div class="flex items-center gap-2"><span class="w-2.5 h-2.5 rounded-sm bg-sky-500/25 border border-sky-400"></span> Z2: Hydraulic Street Plaza</div>
<div class="flex items-center gap-2"><span class="w-2.5 h-2.5 rounded-sm bg-amber-500/25 border border-amber-400"></span> Z3: LinkingLogs EPDM Pit</div>
<div class="flex items-center gap-2"><span class="w-2.5 h-2.5 rounded-sm bg-fuchsia-500/30 border border-fuchsia-400"></span> Z4: MicroLED Graffiti Spine</div>
<div class="flex items-center gap-2"><span class="w-2.5 h-2.5 rounded-sm bg-emerald-500/20 border border-emerald-400"></span> Z5: WFH Acoustic Pods (<38 dBA)</div>
</div>
<!-- Floating Selected Item Inspector (Bottom-Right) -->
<div id="selectedInspector" class="hidden absolute bottom-3 right-3 bg-[#0d1422]/95 backdrop-blur-md border border-cyan-500/40 rounded-xl p-3 text-xs w-60 shadow-xl">
<div class="flex items-center justify-between mb-1">
<span id="inspTitle" class="font-bold text-white truncate">Module</span>
<button onclick="deleteSelected()" class="text-[11px] font-mono-tech text-rose-400 hover:text-rose-300">
[Delete]
</button>
</div>
<div id="inspDetails" class="text-[11px] font-mono-tech text-slate-300 space-y-0.5"></div>
<div class="mt-2 flex gap-1.5">
<button onclick="rotateSelectedModule()" class="flex-1 py-1 rounded bg-slate-800 hover:bg-slate-700 text-[11px] font-mono-tech text-cyan-300 border border-slate-700">
Rotate 90°
</button>
<button onclick="deselectModule()" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-[11px] font-mono-tech text-slate-400">
Done
</button>
</div>
</div>
</div>
</section>
<!-- RIGHT SIDEBAR: LIVE Z-AXIS VALIDATION ENGINE & BOM -->
<aside class="lg:col-span-3 border-t lg:border-t-0 lg:border-l border-slate-800 bg-[#0b101b] p-3 flex flex-col gap-3 overflow-y-auto max-h-[calc(100vh-105px)]">
<!-- Hydraulic Lockout / Pass-Fail Banner -->
<div id="safetyStatusCard" class="rounded-xl p-3 border transition-all bg-emerald-950/30 border-emerald-500/50 cad-glow-emerald">
<div class="flex items-center justify-between">
<span class="text-[10px] font-mono-tech uppercase tracking-widest text-slate-400">Z-Axis Safety Gate</span>
<span id="safetyBadge" class="text-[10px] font-mono-tech font-bold px-2 py-0.5 rounded bg-emerald-500 text-slate-950">
CLEARED
</span>
</div>
<div id="safetyHeadline" class="text-sm font-extrabold text-emerald-300 mt-1">
HYDRAULIC LOCKS: ARMED
</div>
<p id="safetySubtext" class="text-[11px] text-slate-300 mt-0.5 leading-snug">
All C1 seams, G-loads, Euler-Bernoulli spans & CoG kerns within tolerance.
</p>
</div>
<!-- Real-Time Physics Telemetry Grid -->
<div class="rounded-xl bg-[#111827] border border-slate-800 p-2.5">
<div class="text-[11px] font-mono-tech uppercase tracking-wider text-slate-400 mb-2">
Live Physics & Heuristics
</div>
<div class="grid grid-cols-2 gap-2 font-mono-tech">
<div class="p-2 rounded-lg bg-slate-950/80 border border-slate-800/90">
<div class="text-[10px] text-slate-400">Peak Centripetal</div>
<div id="metricPeakG" class="text-sm font-bold text-cyan-300">1.00 G</div>
<div class="text-[9px] text-slate-500">Limit ≤ 3.20 G</div>
</div>
<div class="p-2 rounded-lg bg-slate-950/80 border border-slate-800/90">
<div class="text-[10px] text-slate-400">Max Deflection δ</div>
<div id="metricDeflection" class="text-sm font-bold text-amber-300">0.0 mm</div>
<div class="text-[9px] text-slate-500">Limit ≤ L/360</div>
</div>
<div class="p-2 rounded-lg bg-slate-950/80 border border-slate-800/90">
<div class="text-[10px] text-slate-400">Min Bending FoS</div>
<div id="metricFoS" class="text-sm font-bold text-emerald-300">∞</div>
<div class="text-[9px] text-slate-500">Limit ≥ 2.50</div>
</div>
<div class="p-2 rounded-lg bg-slate-950/80 border border-slate-800/90">
<div class="text-[10px] text-slate-400">Total Mass</div>
<div id="metricMass" class="text-sm font-bold text-slate-200">0 kg</div>
<div id="metricCoG" class="text-[9px] text-slate-500">CoG: (—, —)</div>
</div>
</div>
</div>
<!-- Diagnostic Violations & Warnings Log -->
<div class="rounded-xl bg-[#111827] border border-slate-800 p-2.5 flex-1 flex flex-col min-h-[150px]">
<div class="flex items-center justify-between mb-2">
<span class="text-[11px] font-mono-tech uppercase tracking-wider text-slate-400">
Heuristics Diagnostic Feed
</span>
<span id="issueCountBadge" class="text-[10px] font-mono-tech px-1.5 py-0.5 rounded bg-slate-800 text-slate-300">
0 ISSUES
</span>
</div>
<div id="diagnosticsList" class="space-y-1.5 overflow-y-auto text-[11px] pr-1 flex-1">
<div class="text-slate-500 font-mono-tech text-[11px] p-2 rounded bg-slate-950/60 border border-slate-800/70">
Place modules on the grid or load a preset to run real-time Z-axis safety checks.
</div>
</div>
</div>
<!-- Live Procurement BOM & Cost Telemetry -->
<div class="rounded-xl bg-[#111827] border border-slate-800 p-2.5">
<div class="flex items-center justify-between mb-1.5">
<span class="text-[11px] font-mono-tech uppercase tracking-wider text-slate-400">
Live Procurement BOM
</span>
<span id="bomTotalCost" class="text-xs font-mono-tech font-bold text-emerald-400">
$0
</span>
</div>
<div class="grid grid-cols-3 gap-1.5 text-center font-mono-tech">
<div class="p-1.5 rounded bg-slate-950 border border-cyan-500/20">
<div class="text-[10px] text-cyan-400">SKT</div>
<div id="bomSktCount" class="text-sm font-bold text-white">0</div>
</div>
<div class="p-1.5 rounded bg-slate-950 border border-amber-500/20">
<div class="text-[10px] text-amber-400">LLG</div>
<div id="bomLlgCount" class="text-sm font-bold text-white">0</div>
</div>
<div class="p-1.5 rounded bg-slate-950 border border-fuchsia-500/20">
<div class="text-[10px] text-fuchsia-400">GRF</div>
<div id="bomGrfCount" class="text-sm font-bold text-white">0</div>
</div>
</div>
</div>
</aside>
</main>
<!-- FOOTER LICENSE NOTICE -->
<footer class="border-t border-slate-800/90 bg-[#080c14] px-4 py-1.5 text-[10px] font-mono-tech text-slate-500 flex flex-wrap items-center justify-between gap-2">
<span>© Albert Lane. All Rights Reserved. | Proprietary and Confidential</span>
<span>Albert Lane Proprietary Software License • https://albertlane.net</span>
</footer>
<script>
// =========================================================================
// COPYRIGHT © ALBERT LANE. ALL RIGHTS RESERVED.
// PROPRIETARY AND CONFIDENTIAL — ALBERT LANE PROPRIETARY SOFTWARE LICENSE.
// UNAUTHORIZED USE, COPYING, OR DISTRIBUTION IS PROHIBITED.
// LICENSE INQUIRIES: https://albertlane.net
// =========================================================================
const GRAVITY = 9.80665; // m/s^2
const SITE_WIDTH_M = 48;
const SITE_HEIGHT_M = 32;
// Physical Constants matching Python ZAxisParkValidator
const LIMITS = {
maxSeamLipM: 0.002,
maxSlopeDeltaRad: 0.035,
maxGForce: 3.2,
designSpeedMps: 11.0,
adultDynamicLoadN: 1800.0, // ~90kg rider * 2.0 impact factor
minSafetyFactor: 2.5,
lateralImpactN: 1200.0,
glulamDensity: 550.0, // kg/m^3
glulamE: 12.4e9, // Pa
glulamAllowStress: 16.5e6 // Pa
};
// Component Catalog Definitions
const CATALOG = [
// SKATE MODULES
{
type: 'SKT_FLAT',
category: 'SKT',
sku: 'SKT-FLT-04',
name: 'Flat Deck Module',
w: 4.0,
d: 3.0,
zStart: 0.0,
zEnd: 0.0,
slopeStart: 0.0,
slopeEnd: 0.0,
radius: null,
massKg: 260,
cost: 4200,
color: '#0ea5e9',
badge: '4×3m • z=0m'
},
{
type: 'SKT_QP_VERT',
category: 'SKT',
sku: 'SKT-QP-13',
name: '13ft Vert Quarter-Pipe',
w: 3.2,
d: 3.0,
zStart: 0.0,
zEnd: 2.8,
slopeStart: 0.0,
slopeEnd: 1.35,
radius: 3.2,
massKg: 680,
cost: 14800,
color: '#22d3ee',
badge: 'R=3.2m • Tony Spec'
},
{
type: 'SKT_QP_WHIP',
category: 'SKT',
sku: 'SKT-QP-WHP',
name: 'Tight Whip Quarter-Pipe',
w: 2.0,
d: 3.0,
zStart: 0.0,
zEnd: 2.2,
slopeStart: 0.0,
slopeEnd: 1.45,
radius: 1.6, // Intentionally tight -> triggers >3.2G warning at 11 m/s
massKg: 490,
cost: 9600,
color: '#38bdf8',
badge: 'R=1.6m • High-G!'
},
{
type: 'SKT_EURO',
category: 'SKT',
sku: 'SKT-EUR-18',
name: 'Euro Gap Bank (18°)',
w: 4.0,
d: 3.0,
zStart: 0.0,
zEnd: 1.1,
slopeStart: 0.314,
slopeEnd: 0.314,
radius: null,
massKg: 540,
cost: 11200,
color: '#0284c7',
badge: '4×3m • 18° Slope'
},
// LINKINGLOGS STRUCTURES
{
type: 'LLG_PIER',
category: 'LLG',
sku: 'LLG-BM-2300',
name: 'Glulam Pier Stack',
w: 1.8,
d: 1.8,
zStart: 0.0,
zEnd: 1.2,
beamWidth: 0.20,
beamDepth: 0.20,
supportedSpan: 0.0,
cantilever: 0.0,
isBrace: false,
massKg: 320,
cost: 3400,
color: '#d97706',
badge: '1.8×1.8m • h=1.2m'
},
{
type: 'LLG_BRIDGE_SAFE',
category: 'LLG',
sku: 'LLG-BM-4600',
name: 'Safe Span Bridge (4.2m)',
w: 4.6,
d: 1.8,
zStart: 1.2,
zEnd: 1.45,
beamWidth: 0.20,
beamDepth: 0.25,
supportedSpan: 4.2,
cantilever: 0.2,
isBrace: false,
massKg: 510,
cost: 6800,
color: '#f59e0b',
badge: 'L=4.2m • FoS Safe'
},
{
type: 'LLG_BRIDGE_DANGER',
category: 'LLG',
sku: 'LLG-BM-7500X',
name: 'Over-Spanned Danger Bridge',
w: 7.5,
d: 1.8,
zStart: 1.2,
zEnd: 1.45,
beamWidth: 0.20,
beamDepth: 0.25,
supportedSpan: 7.0, // Intentionally fails L/360 deflection & FoS < 2.5
cantilever: 0.25,
isBrace: false,
massKg: 825,
cost: 9200,
color: '#fbbf24',
badge: 'L=7.0m • Deflects!'
},
{
type: 'LLG_TOWER_TALL',
category: 'LLG',
sku: 'LLG-TWR-520',
name: 'Unbraced Tall Tower',
w: 1.5,
d: 1.5,
zStart: 0.0,
zEnd: 5.2, // 5.2 / 1.5 = 3.47:1 -> fails 3:1 aspect ratio & CoG kern unless braced
beamWidth: 0.20,
beamDepth: 0.20,
supportedSpan: 0.0,
cantilever: 0.0,
isBrace: false,
massKg: 740,
cost: 8400,
color: '#b45309',
badge: '1.5×1.5m • h=5.2m'
},
{
type: 'LLG_BRACE',
category: 'LLG',
sku: 'LLG-BRC-DIAG',
name: 'Diagonal Al-6061 Brace',
w: 2.2,
d: 2.2,
zStart: 0.0,
zEnd: 2.8,
beamWidth: 0.08,
beamDepth: 0.08,
supportedSpan: 0.0,
cantilever: 0.0,
isBrace: true,
massKg: 48,
cost: 1650,
color: '#34d399',
badge: 'Stabilizes Towers'
},
// DIGITAL GRAFFITI GLASS
{
type: 'GRF_BAY',
category: 'GRF',
sku: 'GRF-GLS-3045',
name: 'MicroLED Graffiti Glass Bay',
w: 3.0,
d: 0.6,
zStart: 0.0,
zEnd: 4.5,
massKg: 610,
cost: 38500,
color: '#e879f9',
badge: '3.0×4.5m • Interactive'
}
];
// Pre-zoned Site Layout Areas (meters on 48m x 32m campus)
const SITE_ZONES = [
{
id: 'Z1',
name: 'ZONE 1: VERT & FLOW BOWL COMPLEX',
x: 1, y: 21, w: 28, h: 10,
fill: 'rgba(34, 211, 238, 0.08)',
stroke: 'rgba(34, 211, 238, 0.45)',
text: '#22d3ee'
},
{
id: 'Z2',
name: 'ZONE 2: HYDRAULIC STREET PLAZA',
x: 25, y: 11, w: 22, h: 9,
fill: 'rgba(56, 189, 248, 0.07)',
stroke: 'rgba(56, 189, 248, 0.4)',
text: '#38bdf8'
},
{
id: 'Z3',
name: 'ZONE 3: LINKINGLOGS EPDM SAFETY PIT',
x: 1, y: 11, w: 22, h: 9,
fill: 'rgba(245, 158, 11, 0.08)',
stroke: 'rgba(245, 158, 11, 0.45)',
text: '#fbbf24'
},
{
id: 'Z4',
name: 'ZONE 4: DIGITAL GRAFFITI GLASS SPINE',
x: 1, y: 8.5, w: 46, h: 2,
fill: 'rgba(232, 121, 249, 0.11)',
stroke: 'rgba(232, 121, 249, 0.55)',
text: '#f0abfc'
},
{
id: 'Z5',
name: 'ZONE 5: WFH ACOUSTIC FOCUS PODS (< 38 dBA)',
x: 1, y: 1, w: 46, h: 6.5,
fill: 'rgba(16, 185, 129, 0.07)',
stroke: 'rgba(16, 185, 129, 0.4)',
text: '#34d399'
}
];
// Application State
let state = {
viewMode: '2D', // '2D' | 'ISO'
toolMode: 'PLACE', // 'PLACE' | 'SELECT'
activeCatalogType: 'SKT_QP_VERT',
placementRotation: 0, // 0, 90, 180, 270
placedModules: [],
selectedId: null,
hoverGrid: null, // { x, y }
draggingId: null,
dragOffset: { x: 0, y: 0 },
invalidIds: new Set(),
lastReport: null,
sprayColor: '#22d3ee',
isSpraying: false
};
let nextInstanceCounter = 1;
// =========================================================================
// INITIALIZATION & PALETTE RENDERING
// =========================================================================
function initApp() {
buildPalette();
initSprayPreview();
loadPreset('SAFE_HAWK');
setupCanvasEvents();
window.addEventListener('resize', resizeCanvases);
window.addEventListener('keydown', handleKeyDown);
resizeCanvases();
}
function buildPalette() {
const skateEl = document.getElementById('paletteSkate');
const logsEl = document.getElementById('paletteLogs');
const grafEl = document.getElementById('paletteGraffiti');
CATALOG.forEach(item => {
const btn = document.createElement('button');
btn.id = `pal_${item.type}`;
btn.onclick = () => selectPaletteItem(item.type);
btn.className =
'w-full text-left p-2 rounded-lg border transition flex items-center justify-between gap-2 bg-[#111827] hover:bg-slate-800/90 border-slate-800';
btn.innerHTML = `
<div class="min-w-0">
<div class="text-xs font-semibold text-slate-100 truncate">${item.name}</div>
<div class="text-[10px] font-mono-tech text-slate-400">${item.badge}</div>
</div>
<span class="w-2.5 h-2.5 rounded-full shrink-0" style="background:${item.color}"></span>
`;
if (item.category === 'SKT') skateEl.appendChild(btn);
else if (item.category === 'LLG') logsEl.appendChild(btn);
else grafEl.appendChild(btn);
});
highlightActivePalette();
}
function highlightActivePalette() {
CATALOG.forEach(item => {
const el = document.getElementById(`pal_${item.type}`);
if (!el) return;
if (state.toolMode === 'PLACE' && state.activeCatalogType === item.type) {
el.classList.add('border-cyan-400', 'bg-cyan-950/30');
el.classList.remove('border-slate-800');
} else {
el.classList.remove('border-cyan-400', 'bg-cyan-950/30');
el.classList.add('border-slate-800');
}
});
}
function selectPaletteItem(type) {
state.activeCatalogType = type;
setToolMode('PLACE');
highlightActivePalette();
}
function setToolMode(mode) {
state.toolMode = mode;
const btnPlace = document.getElementById('toolPlace');
const btnSelect = document.getElementById('toolSelect');
if (mode === 'PLACE') {
btnPlace.className = 'py-1.5 px-2 rounded-lg font-semibold bg-cyan-500/20 text-cyan-300 border border-cyan-500/50 transition';
btnSelect.className = 'py-1.5 px-2 rounded-lg font-semibold bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700 transition';
} else {
btnSelect.className = 'py-1.5 px-2 rounded-lg font-semibold bg-cyan-500/20 text-cyan-300 border border-cyan-500/50 transition';
btnPlace.className = 'py-1.5 px-2 rounded-lg font-semibold bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700 transition';
}
highlightActivePalette();
renderSite();
}
function setViewMode(mode) {
state.viewMode = mode;
const b2d = document.getElementById('btnView2D');
const biso = document.getElementById('btnViewISO');
if (mode === '2D') {
b2d.className = 'px-2.5 py-1 rounded-md text-xs font-mono-tech font-semibold transition bg-cyan-500 text-slate-950 shadow';
biso.className = 'px-2.5 py-1 rounded-md text-xs font-mono-tech font-semibold transition text-slate-300 hover:text-white';
} else {
biso.className = 'px-2.5 py-1 rounded-md text-xs font-mono-tech font-semibold transition bg-cyan-500 text-slate-950 shadow';
b2d.className = 'px-2.5 py-1 rounded-md text-xs font-mono-tech font-semibold transition text-slate-300 hover:text-white';
}
renderSite();
}
function rotateSelection() {
if (state.selectedId) {
rotateSelectedModule();
} else {
state.placementRotation = (state.placementRotation + 90) % 360;
document.getElementById('rotationBadge').textContent = `ROT: ${state.placementRotation}°`;
renderSite();
}
}
function getOrientedDims(spec, rotation) {
const rot = ((rotation % 360) + 360) % 360;
if (rot === 90 || rot === 270) {
return { w: spec.d, d: spec.w };
}
return { w: spec.w, d: spec.d };
}
// =========================================================================
// PRESETS & CRUD OPERATIONS
// =========================================================================
function createModuleInstance(type, x, y, rotation = 0) {
const spec = CATALOG.find(c => c.type === type);
if (!spec) return null;
return {
id: `${spec.sku}-${String(nextInstanceCounter++).padStart(2, '0')}`,
type: spec.type,
category: spec.category,
sku: spec.sku,
name: spec.name,
x: x,
y: y,
rotation: rotation,
spec: spec
};
}
function loadPreset(presetName) {
state.placedModules = [];
state.selectedId = null;
nextInstanceCounter = 1;
if (presetName === 'SAFE_HAWK') {
// Zone 1: Aligned Vert Quarter-Pipe + Flat Deck line (C0 & C1 continuous)
state.placedModules.push(createModuleInstance('SKT_FLAT', 6, 24, 0));
state.placedModules.push(createModuleInstance('SKT_QP_VERT', 10, 24, 0));
state.placedModules.push(createModuleInstance('SKT_EURO', 18, 24, 0));
// Zone 3: Safe LinkingLogs Bridge supported by two Glulam Pier Stacks
state.placedModules.push(createModuleInstance('LLG_PIER', 6.2, 14.5, 0));
state.placedModules.push(createModuleInstance('LLG_PIER', 10.6, 14.5, 0));
state.placedModules.push(createModuleInstance('LLG_BRIDGE_SAFE', 7.0, 14.5, 0));
// Zone 4: Digital Graffiti Glass Spine bays
state.placedModules.push(createModuleInstance('GRF_BAY', 8, 9.2, 0));
state.placedModules.push(createModuleInstance('GRF_BAY', 12, 9.2, 0));
state.placedModules.push(createModuleInstance('GRF_BAY', 16, 9.2, 0));
} else if (presetName === 'UNSAFE_KID') {
// Tight whip ramp (>3.2G violation) + misaligned seam
state.placedModules.push(createModuleInstance('SKT_FLAT', 6, 24, 0));
state.placedModules.push(createModuleInstance('SKT_QP_WHIP', 10.2, 24, 0)); // 0.2m gap + high G
// Over-spanned 7m Danger Bridge + Unbraced 5.2m Tall Tower
state.placedModules.push(createModuleInstance('LLG_BRIDGE_DANGER', 4, 14, 0));
state.placedModules.push(createModuleInstance('LLG_TOWER_TALL', 15, 14.5, 0));
// Graffiti Glass Bay
state.placedModules.push(createModuleInstance('GRF_BAY', 10, 9.2, 0));
}
updateInspector();
runZAxisValidation();
renderSite();
}
function clearAllModules() {
state.placedModules = [];
state.selectedId = null;
updateInspector();
runZAxisValidation();
renderSite();
}
function deleteSelected() {
if (!state.selectedId) return;
state.placedModules = state.placedModules.filter(m => m.id !== state.selectedId);
state.selectedId = null;
updateInspector();
runZAxisValidation();
renderSite();
}
function rotateSelectedModule() {
const mod = state.placedModules.find(m => m.id === state.selectedId);
if (!mod) return;
mod.rotation = (mod.rotation + 90) % 360;
const dims = getOrientedDims(mod.spec, mod.rotation);
mod.x = Math.max(0, Math.min(SITE_WIDTH_M - dims.w, mod.x));
mod.y = Math.max(0, Math.min(SITE_HEIGHT_M - dims.d, mod.y));
updateInspector();
runZAxisValidation();
renderSite();
}
function deselectModule() {
state.selectedId = null;
updateInspector();
renderSite();
}
function updateInspector() {
const box = document.getElementById('selectedInspector');
const mod = state.placedModules.find(m => m.id === state.selectedId);
if (!mod) {
box.classList.add('hidden');
return;
}
box.classList.remove('hidden');
const dims = getOrientedDims(mod.spec, mod.rotation);
document.getElementById('inspTitle').textContent = `${mod.id}`;
document.getElementById('inspDetails').innerHTML = `
<div>${mod.name}</div>
<div>Pos: (${mod.x.toFixed(1)}m, ${mod.y.toFixed(1)}m)</div>
<div>Footprint: ${dims.w.toFixed(1)}m × ${dims.d.toFixed(1)}m</div>
<div>Z-Profile: ${mod.spec.zStart.toFixed(2)}m → ${mod.spec.zEnd.toFixed(2)}m</div>
<div>Mass: ${mod.spec.massKg} kg | $${mod.spec.cost.toLocaleString()}</div>
`;
}
// =========================================================================
// LIVE Z-AXIS STRUCTURAL & SKATE VALIDATION ENGINE
// =========================================================================
function runZAxisValidation() {
const errors = [];
const warnings = [];
const invalidIds = new Set();
let peakG = 1.0;
let maxDeflectionMm = 0.0;
let minFoS = Infinity;
let totalMassKg = 0.0;
const skateMods = state.placedModules.filter(m => m.category === 'SKT');
const logMods = state.placedModules.filter(m => m.category === 'LLG');
const grfMods = state.placedModules.filter(m => m.category === 'GRF');
state.placedModules.forEach(m => {
totalMassKg += m.spec.massKg;
});
// 1. SKATE LINE HEURISTICS (Centripetal G-Force + C0/C1 Seam Continuity)
for (let i = 0; i < skateMods.length; i++) {
const mod = skateMods[i];
const s = mod.spec;
const dims = getOrientedDims(s, mod.rotation);
// Centripetal G-load check
if (s.radius !== null && s.radius > 0) {
const gLoad = 1.0 + (LIMITS.designSpeedMps ** 2) / (GRAVITY * s.radius);
peakG = Math.max(peakG, gLoad);
if (gLoad > LIMITS.maxGForce) {
invalidIds.add(mod.id);
errors.push({
id: mod.id,
msg: `[${mod.id}] Radius R=${s.radius.toFixed(1)}m generates ${gLoad.toFixed(2)}G at 11 m/s (exceeds ${LIMITS.maxGForce}G knee-whip limit).`
});
}
}
// Check nearby adjacent skate modules for C0 seam gap/lip & C1 slope continuity
for (let j = i + 1; j < skateMods.length; j++) {
const other = skateMods[j];
const oDims = getOrientedDims(other.spec, other.rotation);
// Check Y overlap
const yOverlap = Math.min(mod.y + dims.d, other.y + oDims.d) - Math.max(mod.y, other.y);
if (yOverlap > 0.5) {
// Distance between X edges
const gapRight = Math.abs((mod.x + dims.w) - other.x);
const gapLeft = Math.abs((other.x + oDims.w) - mod.x);
const minEdgeDist = Math.min(gapRight, gapLeft);
// Near-abutting seam (0.01m to 0.45m accidental wheel-trap gap)
if (minEdgeDist > LIMITS.maxSeamLipM && minEdgeDist < 0.45) {
invalidIds.add(mod.id);
invalidIds.add(other.id);
errors.push({
id: mod.id,
msg: `[Seam ${mod.id} ↔ ${other.id}] C0 wheel-trap gap of ${(minEdgeDist * 1000).toFixed(0)}mm exceeds 2mm tolerance.`
});
}
// Abutting seam C1 slope check
if (minEdgeDist <= LIMITS.maxSeamLipM) {
const leftMod = mod.x < other.x ? mod : other;
const rightMod = mod.x < other.x ? other : mod;
const slopeDelta = Math.abs(leftMod.spec.slopeEnd - rightMod.spec.slopeStart);
if (slopeDelta > LIMITS.maxSlopeDeltaRad && leftMod.spec.zEnd === 0 && rightMod.spec.zStart === 0) {
invalidIds.add(leftMod.id);
invalidIds.add(rightMod.id);
errors.push({
id: leftMod.id,
msg: `[Seam ${leftMod.id} → ${rightMod.id}] C1 tangent kink (${(slopeDelta * 57.2958).toFixed(1)}°) exceeds 2.0° transition limit.`
});
}
}
}
}
}
// 2. LINKINGLOGS STRUCTURAL & CRITICAL THINKING HEURISTICS
let logMassTotal = 0;
let cogX = 0;
let cogY = 0;
let cogZ = 0;
const braces = logMods.filter(m => m.spec.isBrace);
logMods.forEach(mod => {
const s = mod.spec;
const dims = getOrientedDims(s, mod.rotation);
const cx = mod.x + dims.w / 2;
const cy = mod.y + dims.d / 2;
const cz = (s.zStart + s.zEnd) / 2;
logMassTotal += s.massKg;
cogX += s.massKg * cx;
cogY += s.massKg * cy;
cogZ += s.massKg * cz;
// A. Euler-Bernoulli Span Deflection & Bending Factor of Safety
if (s.supportedSpan > 0) {
const L = s.supportedSpan;
const b = s.beamWidth;
const d = s.beamDepth;
const I = (b * Math.pow(d, 3)) / 12.0;
// Two parallel longitudinal beams share the bridge deck load
const w0 = ((s.massKg / 2) / L) * GRAVITY;
const pLivePerBeam = LIMITS.adultDynamicLoadN / 2;
const deltaDead = (5.0 * w0 * Math.pow(L, 4)) / (384.0 * LIMITS.glulamE * I);
const deltaLive = (pLivePerBeam * Math.pow(L, 3)) / (48.0 * LIMITS.glulamE * I);
const deltaTotal = deltaDead + deltaLive;
const deltaLimit = L / 360.0;
maxDeflectionMm = Math.max(maxDeflectionMm, deltaTotal * 1000);
if (deltaTotal > deltaLimit) {
invalidIds.add(mod.id);
errors.push({
id: mod.id,
msg: `[${mod.id}] Euler-Bernoulli deflection ${(deltaTotal * 1000).toFixed(1)}mm exceeds L/360 (${(deltaLimit * 1000).toFixed(1)}mm) over ${L.toFixed(1)}m span.`
});
}
const mMax = (w0 * Math.pow(L, 2)) / 8.0 + (pLivePerBeam * L) / 4.0;
const sigmaMax = (mMax * (d / 2.0)) / I;
const fos = LIMITS.glulamAllowStress / sigmaMax;
minFoS = Math.min(minFoS, fos);
if (fos < LIMITS.minSafetyFactor) {
invalidIds.add(mod.id);
errors.push({
id: mod.id,
msg: `[${mod.id}] Bending Factor of Safety is ${fos.toFixed(2)} (minimum required: ${LIMITS.minSafetyFactor.toFixed(2)}).`
});
}
// Check if bridge ends actually rest on Pier Stacks
const piers = logMods.filter(p => p.type === 'LLG_PIER');
if (piers.length < 2) {
warnings.push({
id: mod.id,
msg: `[${mod.id}] Bridge span requires at least 2 Glulam Pier Stacks for end-notch bearing.`
});
}
}
// B. Slenderness Aspect Ratio (H / B_min <= 3.0) & Middle-Third Kern CoG Tipping
if (!s.isBrace && s.zEnd > 2.5) {
const minBase = Math.min(dims.w, dims.d);
const aspectRatio = s.zEnd / minBase;
// Check if a Diagonal Aluminum Cross-Brace is within 2.5m of this tower
const hasNearbyBrace = braces.some(br => {
const bDims = getOrientedDims(br.spec, br.rotation);
const dist = Math.hypot((br.x + bDims.w / 2) - cx, (br.y + bDims.d / 2) - cy);
return dist <= 2.6;
});
if (aspectRatio > 3.0 && !hasNearbyBrace) {
invalidIds.add(mod.id);
errors.push({
id: mod.id,
msg: `[${mod.id}] Height-to-base ratio (${aspectRatio.toFixed(2)}:1) exceeds 3.0:1 without a Diagonal Al-6061 Brace.`
});
}
// Middle-Third Kern Lateral Skate Impact Check (1200N)
const kernHalf = minBase / 6.0;
const weightN = s.massKg * GRAVITY;
const lateralShift = (LIMITS.lateralImpactN / weightN) * cz;
if (lateralShift > kernHalf && !hasNearbyBrace) {
invalidIds.add(mod.id);
errors.push({
id: mod.id,
msg: `[${mod.id}] CoG shifts ${(lateralShift * 100).toFixed(0)}cm outside middle-third kern (${(kernHalf * 100).toFixed(0)}cm) under 1200N skate impact.`
});
}
}
// C. Fall-Zone Envelope Notice for elevated structures > 0.6m
if (!s.isBrace && s.zEnd > 0.6) {
const rFall = Math.max(1.5, 1.25 * s.zEnd);
warnings.push({
id: mod.id,
msg: `[${mod.id}] z=${s.zEnd.toFixed(1)}m reserves a ${rFall.toFixed(2)}m padded EPDM fall-zone envelope.`
});
}
});
// 3. ZONE PLACEMENT ADVISORIES
grfMods.forEach(g => {
if (g.y > 12.5) {
warnings.push({
id: g.id,
msg: `[${g.id}] Placed outside Zone 4 acoustic spine — WFH pod noise isolation drops below STC-52.`
});
}
});
state.invalidIds = invalidIds;
const cogDisplay = logMassTotal > 0
? `(${(cogX / logMassTotal).toFixed(1)}, ${(cogY / logMassTotal).toFixed(1)}, ${(cogZ / logMassTotal).toFixed(1)}m)`
: '(—, —)';
state.lastReport = {
passed: errors.length === 0,
errors,
warnings,
peakG,
maxDeflectionMm,
minFoS,
totalMassKg,
cogDisplay,
logCoG: logMassTotal > 0 ? { x: cogX / logMassTotal, y: cogY / logMassTotal, z: cogZ / logMassTotal } : null
};
updateDashboardUI();
}
function updateDashboardUI() {
const rep = state.lastReport;
if (!rep) return;
const card = document.getElementById('safetyStatusCard');
const badge = document.getElementById('safetyBadge');
const headline = document.getElementById('safetyHeadline');
const subtext = document.getElementById('safetySubtext');
if (rep.passed) {
card.className = 'rounded-xl p-3 border transition-all bg-emerald-950/30 border-emerald-500/50 cad-glow-emerald';
badge.className = 'text-[10px] font-mono-tech font-bold px-2 py-0.5 rounded bg-emerald-500 text-slate-950';
badge.textContent = 'CLEARED';
headline.className = 'text-sm font-extrabold text-emerald-300 mt-1';
headline.textContent = 'HYDRAULIC LOCKS: ARMED';
subtext.textContent = 'All C1 seams, G-loads, Euler-Bernoulli spans & CoG kerns within tolerance.';
} else {
card.className = 'rounded-xl p-3 border transition-all bg-rose-950/40 border-rose-500/60 cad-glow-red';
badge.className = 'text-[10px] font-mono-tech font-bold px-2 py-0.5 rounded bg-rose-500 text-white';
badge.textContent = 'LOCKOUT';
headline.className = 'text-sm font-extrabold text-rose-300 mt-1';
headline.textContent = 'SAFETY VIOLATION DETECTED';
subtext.textContent = 'Hydraulic leveling pins locked in Maintenance Mode until red modules are resolved.';
}
// Telemetry Metrics
const gEl = document.getElementById('metricPeakG');
gEl.textContent = `${rep.peakG.toFixed(2)} G`;
gEl.className = rep.peakG > LIMITS.maxGForce ? 'text-sm font-bold text-rose-400' : 'text-sm font-bold text-cyan-300';
const defEl = document.getElementById('metricDeflection');
defEl.textContent = `${rep.maxDeflectionMm.toFixed(1)} mm`;
defEl.className = rep.errors.some(e => e.msg.includes('deflection'))
? 'text-sm font-bold text-rose-400'
: 'text-sm font-bold text-amber-300';
const fosEl = document.getElementById('metricFoS');
fosEl.textContent = rep.minFoS === Infinity ? '∞' : rep.minFoS.toFixed(2);
fosEl.className = rep.minFoS < LIMITS.minSafetyFactor ? 'text-sm font-bold text-rose-400' : 'text-sm font-bold text-emerald-300';
document.getElementById('metricMass').textContent = `${rep.totalMassKg.toLocaleString()} kg`;
document.getElementById('metricCoG').textContent = `CoG: ${rep.cogDisplay}`;
// Issues Feed
const totalIssues = rep.errors.length + rep.warnings.length;
document.getElementById('issueCountBadge').textContent = `${totalIssues} ${totalIssues === 1 ? 'NOTE' : 'NOTES'}`;
const listEl = document.getElementById('diagnosticsList');
if (totalIssues === 0) {
listEl.innerHTML = `
<div class="text-emerald-300/90 font-mono-tech text-[11px] p-2 rounded bg-emerald-950/25 border border-emerald-500/30">
✓ Zero structural or geometric violations detected.
</div>
`;
} else {
let html = '';
rep.errors.forEach(err => {
html += `
<div class="p-2 rounded bg-rose-950/40 border border-rose-500/50 text-rose-200 font-mono-tech leading-snug">
<span class="text-rose-400 font-bold">ERR:</span> ${err.msg}
</div>
`;
});
rep.warnings.forEach(warn => {
html += `
<div class="p-2 rounded bg-amber-950/30 border border-amber-500/40 text-amber-200 font-mono-tech leading-snug">
<span class="text-amber-400 font-bold">WARN:</span> ${warn.msg}
</div>
`;
});
listEl.innerHTML = html;
}
// BOM Counts & Cost
let sktCount = 0, llgCount = 0, grfCount = 0, totalCost = 0;
state.placedModules.forEach(m => {
totalCost += m.spec.cost;
if (m.category === 'SKT') sktCount++;
else if (m.category === 'LLG') llgCount++;
else if (m.category === 'GRF') grfCount++;
});
document.getElementById('bomSktCount').textContent = sktCount;
document.getElementById('bomLlgCount').textContent = llgCount;
document.getElementById('bomGrfCount').textContent = grfCount;
document.getElementById('bomTotalCost').textContent = `$${totalCost.toLocaleString()}`;
}
// =========================================================================
// MINI DIGITAL GRAFFITI RATTLE-CAN SPRAY PREVIEW
// =========================================================================
let sprayCanvas, sprayCtx, lastSprayPos = null;
function initSprayPreview() {
sprayCanvas = document.getElementById('sprayPreviewCanvas');
sprayCtx = sprayCanvas.getContext('2d');
const getPos = (e) => {
const rect = sprayCanvas.getBoundingClientRect();
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
return {
x: ((clientX - rect.left) / rect.width) * sprayCanvas.width,
y: ((clientY - rect.top) / rect.height) * sprayCanvas.height
};
};
const startSpray = (e) => {
e.preventDefault();
state.isSpraying = true;
lastSprayPos = getPos(e);
paintAerosol(lastSprayPos.x, lastSprayPos.y);
};
const moveSpray = (e) => {
if (!state.isSpraying) return;
e.preventDefault();
const pos = getPos(e);
const dist = Math.hypot(pos.x - lastSprayPos.x, pos.y - lastSprayPos.y);
const steps = Math.max(1, Math.floor(dist / 3));
for (let i = 1; i <= steps; i++) {
const ix = lastSprayPos.x + ((pos.x - lastSprayPos.x) * i) / steps;
const iy = lastSprayPos.y + ((pos.y - lastSprayPos.y) * i) / steps;
paintAerosol(ix, iy);
}
lastSprayPos = pos;
renderSite(); // Sync live tag onto placed graffiti glass bays
};
const endSpray = () => {
state.isSpraying = false;
lastSprayPos = null;
};
sprayCanvas.addEventListener('mousedown', startSpray);
sprayCanvas.addEventListener('mousemove', moveSpray);
window.addEventListener('mouseup', endSpray);
sprayCanvas.addEventListener('touchstart', startSpray, { passive: false });
sprayCanvas.addEventListener('touchmove', moveSpray, { passive: false });
window.addEventListener('touchend', endSpray);
}
function paintAerosol(cx, cy) {
if (!sprayCtx) return;
const radius = 14;
const grad = sprayCtx.createRadialGradient(cx, cy, 1, cx, cy, radius);
grad.addColorStop(0, state.sprayColor);
grad.addColorStop(0.5, state.sprayColor + '88');
grad.addColorStop(1, 'rgba(0,0,0,0)');
sprayCtx.fillStyle = grad;
sprayCtx.beginPath();
sprayCtx.arc(cx, cy, radius, 0, Math.PI * 2);
sprayCtx.fill();
// Occasional wet paint drip simulation
if (Math.random() < 0.16) {
sprayCtx.strokeStyle = state.sprayColor + 'aa';
sprayCtx.lineWidth = 1.6;
sprayCtx.beginPath();
sprayCtx.moveTo(cx, cy);
sprayCtx.lineTo(cx + (Math.random() - 0.5) * 2, cy + 8 + Math.random() * 14);
sprayCtx.stroke();
}
}
function setSprayColor(hex) {
state.sprayColor = hex;
}
function clearSprayCanvas() {
if (!sprayCtx) return;
sprayCtx.clearRect(0, 0, sprayCanvas.width, sprayCanvas.height);
drawDefaultTag();
renderSite();
}
function drawDefaultTag() {
if (!sprayCtx || !sprayCanvas) return;
sprayCtx.save();
sprayCtx.font = 'italic 800 22px Inter, sans-serif';
sprayCtx.fillStyle = '#e879f9';
sprayCtx.shadowColor = '#22d3ee';
sprayCtx.shadowBlur = 10;
sprayCtx.fillText('OHS // 2027', 22, 46);
sprayCtx.strokeStyle = '#22d3ee';
sprayCtx.lineWidth = 2;
sprayCtx.beginPath();
sprayCtx.moveTo(18, 54);
sprayCtx.quadraticCurveTo(95, 64, 175, 48);
sprayCtx.stroke();
sprayCtx.restore();
}
// =========================================================================
// SITE CANVAS RENDERER (2D CAD PLAN & 2.5D ISOMETRIC Z-AXIS VIEW)
// =========================================================================
let siteCanvas, siteCtx;
function resizeCanvases() {
const container = document.getElementById('canvasContainer');
siteCanvas = document.getElementById('siteCanvas');
if (!container || !siteCanvas) return;
const dpr = window.devicePixelRatio || 1;
const rect = container.getBoundingClientRect();
siteCanvas.width = Math.max(300, Math.floor(rect.width * dpr));
siteCanvas.height = Math.max(300, Math.floor(rect.height * dpr));
siteCtx = siteCanvas.getContext('2d');
siteCtx.setTransform(dpr, 0, 0, dpr, 0, 0);
if (sprayCanvas) {
const sRect = sprayCanvas.getBoundingClientRect();
if (sprayCanvas.width === 300 && sRect.width > 0) {
sprayCanvas.width = Math.floor(sRect.width);
sprayCanvas.height = Math.floor(sRect.height);
drawDefaultTag();
}
}
renderSite();
}
// Coordinate projection helpers
function get2DTransform() {
const rect = siteCanvas.getBoundingClientRect();
const pad = 28;
const availW = rect.width - pad * 2;
const availH = rect.height - pad * 2;
const scale = Math.min(availW / SITE_WIDTH_M, availH / SITE_HEIGHT_M);
const offsetX = (rect.width - SITE_WIDTH_M * scale) / 2;
const offsetY = (rect.height - SITE_HEIGHT_M * scale) / 2;
return { scale, offsetX, offsetY, width: rect.width, height: rect.height };
}
function getIsoTransform() {
const rect = siteCanvas.getBoundingClientRect();
// Isometric projection where 1m in X/Y projects cleanly into viewport
const scale = Math.min(rect.width / 74, rect.height / 54);
const originX = rect.width * 0.5;
const originY = rect.height * 0.22;
return { scale, originX, originY, width: rect.width, height: rect.height };
}
function isoProject(gx, gy, gz, iso) {
const ix = (gx - gy) * 0.866025 * iso.scale + iso.originX;
const iy = (gx + gy) * 0.5 * iso.scale - gz * 1.15 * iso.scale + iso.originY;
return { x: ix, y: iy };
}
function screenToGrid(clientX, clientY) {
const rect = siteCanvas.getBoundingClientRect();
const sx = clientX - rect.left;
const sy = clientY - rect.top;
if (state.viewMode === '2D') {
const t = get2DTransform();
const gx = (sx - t.offsetX) / t.scale;
const gy = (sy - t.offsetY) / t.scale;
return {
x: Math.round(gx * 2) / 2,
y: Math.round(gy * 2) / 2,
rawX: gx,
rawY: gy
};
} else {
const iso = getIsoTransform();
const dx = (sx - iso.originX) / (0.866025 * iso.scale);
const dy = (sy - iso.originY) / (0.5 * iso.scale);
const gx = (dx + dy) / 2;
const gy = (dy - dx) / 2;
return {
x: Math.round(gx * 2) / 2,
y: Math.round(gy * 2) / 2,
rawX: gx,
rawY: gy
};
}
}
function renderSite() {
if (!siteCtx || !siteCanvas) return;
const rect = siteCanvas.getBoundingClientRect();
siteCtx.clearRect(0, 0, rect.width, rect.height);
// Subtle radial CAD background gradient
const bgGrad = siteCtx.createRadialGradient(
rect.width / 2, rect.height / 2, 20,
rect.width / 2, rect.height / 2, Math.max(rect.width, rect.height) * 0.7
);
bgGrad.addColorStop(0, '#0b1220');
bgGrad.addColorStop(1, '#05080f');
siteCtx.fillStyle = bgGrad;
siteCtx.fillRect(0, 0, rect.width, rect.height);
if (state.viewMode === '2D') {
render2DView();
} else {
renderIsoView();
}
}
// -------------------------------------------------------------------------
// 2D TOP-DOWN CAD PLAN RENDERER
// -------------------------------------------------------------------------
function render2DView() {
const t = get2DTransform();
const ctx = siteCtx;
// 1. Site Boundary & 1m Grid Lines
ctx.save();
ctx.strokeStyle = 'rgba(30, 41, 59, 0.65)';
ctx.lineWidth = 1;
for (let x = 0; x <= SITE_WIDTH_M; x++) {
const px = t.offsetX + x * t.scale;
ctx.beginPath();
ctx.strokeStyle = x % 5 === 0 ? 'rgba(51, 65, 85, 0.85)' : 'rgba(30, 41, 59, 0.45)';
ctx.moveTo(px, t.offsetY);
ctx.lineTo(px, t.offsetY + SITE_HEIGHT_M * t.scale);
ctx.stroke();
}
for (let y = 0; y <= SITE_HEIGHT_M; y++) {
const py = t.offsetY + y * t.scale;
ctx.beginPath();
ctx.strokeStyle = y % 5 === 0 ? 'rgba(51, 65, 85, 0.85)' : 'rgba(30, 41, 59, 0.45)';
ctx.moveTo(t.offsetX, py);
ctx.lineTo(t.offsetX + SITE_WIDTH_M * t.scale, py);
ctx.stroke();
}
// Outer Datum Border
ctx.strokeStyle = '#334155';
ctx.lineWidth = 2;
ctx.strokeRect(t.offsetX, t.offsetY, SITE_WIDTH_M * t.scale, SITE_HEIGHT_M * t.scale);
// 2. Pre-Zoned Areas
SITE_ZONES.forEach(z => {
const zx = t.offsetX + z.x * t.scale;
const zy = t.offsetY + z.y * t.scale;
const zw = z.w * t.scale;
const zh = z.h * t.scale;
ctx.fillStyle = z.fill;
ctx.fillRect(zx, zy, zw, zh);
ctx.setLineDash([5, 4]);
ctx.strokeStyle = z.stroke;
ctx.lineWidth = 1.2;
ctx.strokeRect(zx, zy, zw, zh);
ctx.setLineDash([]);
ctx.fillStyle = z.text;
ctx.font = '600 10px "JetBrains Mono", monospace';
ctx.fillText(z.name, zx + 6, zy + 13);
});
// Decorative WFH Pods in Zone 5
for (let i = 0; i < 6; i++) {
const px = t.offsetX + (3 + i * 7.2) * t.scale;
const py = t.offsetY + 2.8 * t.scale;
ctx.fillStyle = 'rgba(16, 185, 129, 0.14)';
ctx.strokeStyle = 'rgba(52, 211, 153, 0.45)';
ctx.lineWidth = 1;
ctx.fillRect(px, py, 4.2 * t.scale, 3.2 * t.scale);
ctx.strokeRect(px, py, 4.2 * t.scale, 3.2 * t.scale);
ctx.fillStyle = 'rgba(167, 243, 208, 0.6)';
ctx.font = '9px "JetBrains Mono", monospace';
ctx.fillText(`POD-0${i + 1}`, px + 4, py + 12);
}
// 3. Fall-Zone Envelopes (if toggled on)
const showFall = document.getElementById('toggleFallZones')?.checked;
if (showFall) {
state.placedModules.forEach(mod => {
if (mod.category === 'LLG' && !mod.spec.isBrace && mod.spec.zEnd > 0.6) {
const dims = getOrientedDims(mod.spec, mod.rotation);
const cx = t.offsetX + (mod.x + dims.w / 2) * t.scale;
const cy = t.offsetY + (mod.y + dims.d / 2) * t.scale;
const rFall = Math.max(1.5, 1.25 * mod.spec.zEnd) * t.scale;
ctx.save();
ctx.setLineDash([4, 4]);
ctx.strokeStyle = 'rgba(251, 191, 36, 0.45)';
ctx.fillStyle = 'rgba(251, 191, 36, 0.04)';
ctx.beginPath();
ctx.arc(cx, cy, rFall, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
ctx.restore();
}
});
}
// 4. Placed Modules
state.placedModules.forEach(mod => {
const dims = getOrientedDims(mod.spec, mod.rotation);
const mx = t.offsetX + mod.x * t.scale;
const my = t.offsetY + mod.y * t.scale;
const mw = dims.w * t.scale;
const md = dims.d * t.scale;
const isInvalid = state.invalidIds.has(mod.id);
const isSelected = state.selectedId === mod.id;
ctx.save();
ctx.fillStyle = isInvalid ? 'rgba(244, 63, 94, 0.35)' : mod.spec.color + '44';
ctx.strokeStyle = isInvalid ? '#f43f5e' : (isSelected ? '#ffffff' : mod.spec.color);
ctx.lineWidth = isInvalid || isSelected ? 2.4 : 1.5;
ctx.fillRect(mx, my, mw, md);
ctx.strokeRect(mx, my, mw, md);
// Render live spray-can artwork texture onto Graffiti Glass bays
if (mod.category === 'GRF' && sprayCanvas) {
ctx.drawImage(sprayCanvas, mx + 1, my + 1, Math.max(1, mw - 2), Math.max(1, md - 2));
}
// Transition slope contour lines for Quarter-Pipes & Banks
if (mod.category === 'SKT' && mod.spec.zEnd > 0) {
ctx.strokeStyle = 'rgba(255,255,255,0.35)';
ctx.lineWidth = 1;
for (let step = 1; step <= 3; step++) {
const frac = step / 4;
ctx.beginPath();
if (mod.rotation === 0) {
ctx.moveTo(mx + mw * frac, my);
ctx.lineTo(mx + mw * frac, my + md);
} else if (mod.rotation === 180) {
ctx.moveTo(mx + mw * (1 - frac), my);
ctx.lineTo(mx + mw * (1 - frac), my + md);
} else if (mod.rotation === 90) {
ctx.moveTo(mx, my + md * frac);
ctx.lineTo(mx + mw, my + md * frac);
} else {
ctx.moveTo(mx, my + md * (1 - frac));
ctx.lineTo(mx + mw, my + md * (1 - frac));
}
ctx.stroke();
}
}
// Glulam timber grain lines for LinkingLogs
if (mod.category === 'LLG' && !mod.spec.isBrace) {
ctx.strokeStyle = 'rgba(253, 230, 138, 0.35)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(mx + 3, my + md * 0.33);
ctx.lineTo(mx + mw - 3, my + md * 0.33);
ctx.moveTo(mx + 3, my + md * 0.66);
ctx.lineTo(mx + mw - 3, my + md * 0.66);
ctx.stroke();
}
// Diagonal cross-brace X symbol
if (mod.spec.isBrace) {
ctx.strokeStyle = '#34d399';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(mx, my);
ctx.lineTo(mx + mw, my + md);
ctx.moveTo(mx + mw, my);
ctx.lineTo(mx, my + md);
ctx.stroke();
}
// Label
ctx.fillStyle = isInvalid ? '#fecdd3' : '#f8fafc';
ctx.font = '700 9.5px "JetBrains Mono", monospace';
ctx.fillText(mod.id, mx + 4, my + 12);
if (md > 22) {
ctx.fillStyle = 'rgba(226, 232, 240, 0.75)';
ctx.font = '9px "JetBrains Mono", monospace';
ctx.fillText(`z:${mod.spec.zEnd.toFixed(1)}m`, mx + 4, my + 22);
}
ctx.restore();
});
// 5. Composite LinkingLogs CoG Crosshair (if toggled on)
const showCoG = document.getElementById('toggleCoG')?.checked;
if (showCoG && state.lastReport?.logCoG) {
const cog = state.lastReport.logCoG;
const cx = t.offsetX + cog.x * t.scale;
const cy = t.offsetY + cog.y * t.scale;
ctx.save();
ctx.strokeStyle = '#fbbf24';
ctx.fillStyle = '#fbbf24';
ctx.lineWidth = 1.8;
ctx.beginPath();
ctx.arc(cx, cy, 5, 0, Math.PI * 2);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(cx - 9, cy);
ctx.lineTo(cx + 9, cy);
ctx.moveTo(cx, cy - 9);
ctx.lineTo(cx, cy + 9);
ctx.stroke();
ctx.font = '700 9px "JetBrains Mono", monospace';
ctx.fillText(`CoG z=${cog.z.toFixed(2)}m`, cx + 8, cy - 6);
ctx.restore();
}
// 6. Ghost Placement Preview under Cursor
if (state.toolMode === 'PLACE' && state.hoverGrid && !state.draggingId) {
const spec = CATALOG.find(c => c.type === state.activeCatalogType);
if (spec) {
const dims = getOrientedDims(spec, state.placementRotation);
const gx = Math.max(0, Math.min(SITE_WIDTH_M - dims.w, state.hoverGrid.x));
const gy = Math.max(0, Math.min(SITE_HEIGHT_M - dims.d, state.hoverGrid.y));
const px = t.offsetX + gx * t.scale;
const py = t.offsetY + gy * t.scale;
ctx.save();
ctx.setLineDash([4, 3]);
ctx.fillStyle = spec.color + '33';
ctx.strokeStyle = '#22d3ee';
ctx.lineWidth = 1.8;
ctx.fillRect(px, py, dims.w * t.scale, dims.d * t.scale);
ctx.strokeRect(px, py, dims.w * t.scale, dims.d * t.scale);
ctx.restore();
}
}
ctx.restore();
}
// -------------------------------------------------------------------------
// 2.5D ISOMETRIC Z-AXIS ELEVATION VIEW RENDERER
// -------------------------------------------------------------------------
function renderIsoView() {
const iso = getIsoTransform();
const ctx = siteCtx;
// 1. Isometric Ground Plane & Grid
const p00 = isoProject(0, 0, 0, iso);
const pW0 = isoProject(SITE_WIDTH_M, 0, 0, iso);
const pWH = isoProject(SITE_WIDTH_M, SITE_HEIGHT_M, 0, iso);
const p0H = isoProject(0, SITE_HEIGHT_M, 0, iso);
ctx.save();
ctx.fillStyle = '#0a101d';
ctx.strokeStyle = '#334155';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(p00.x, p00.y);
ctx.lineTo(pW0.x, pW0.y);
ctx.lineTo(pWH.x, pWH.y);
ctx.lineTo(p0H.x, p0H.y);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Grid lines every 2m
ctx.strokeStyle = 'rgba(30, 41, 59, 0.7)';
ctx.lineWidth = 1;
for (let x = 0; x <= SITE_WIDTH_M; x += 2) {
const a = isoProject(x, 0, 0, iso);
const b = isoProject(x, SITE_HEIGHT_M, 0, iso);
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.stroke();
}
for (let y = 0; y <= SITE_HEIGHT_M; y += 2) {
const a = isoProject(0, y, 0, iso);
const b = isoProject(SITE_WIDTH_M, y, 0, iso);
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.stroke();
}
// 2. Zone Polygons on Floor
SITE_ZONES.forEach(z => {
const a = isoProject(z.x, z.y, 0, iso);
const b = isoProject(z.x + z.w, z.y, 0, iso);
const c = isoProject(z.x + z.w, z.y + z.h, 0, iso);
const d = isoProject(z.x, z.y + z.h, 0, iso);
ctx.fillStyle = z.fill;
ctx.strokeStyle = z.stroke;
ctx.lineWidth = 1.2;
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.lineTo(c.x, c.y);
ctx.lineTo(d.x, d.y);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.fillStyle = z.text;
ctx.font = '700 9px "JetBrains Mono", monospace';
ctx.fillText(z.id, a.x + 6, a.y + 10);
});
// 3. Depth-Sort Modules by (x + y) for proper Painter's Algorithm Z-occlusion
const sorted = [...state.placedModules].sort((a, b) => (a.x + a.y) - (b.x + b.y));
sorted.forEach(mod => {
drawIsoExtrudedModule(mod, iso);
});
ctx.restore();
}
function drawIsoExtrudedModule(mod, iso) {
const ctx = siteCtx;
const dims = getOrientedDims(mod.spec, mod.rotation);
const x0 = mod.x;
const y0 = mod.y;
const x1 = mod.x + dims.w;
const y1 = mod.y + dims.d;
const z0 = mod.spec.zStart;
const z1 = Math.max(0.18, mod.spec.zEnd); // Minimum visual thickness
const isInvalid = state.invalidIds.has(mod.id);
const isSelected = state.selectedId === mod.id;
const baseColor = isInvalid ? '#f43f5e' : mod.spec.color;
// Determine Z heights of the 4 top corners (ramps slope from z0 to z1)
let zTL = z1, zTR = z1, zBR = z1, zBL = z1;
if (mod.category === 'SKT' && mod.spec.zEnd > 0) {
const lowZ = 0.08;
if (mod.rotation === 0) {
zTL = lowZ; zBL = lowZ; zTR = z1; zBR = z1;
} else if (mod.rotation === 180) {
zTL = z1; zBL = z1; zTR = lowZ; zBR = lowZ;
} else if (mod.rotation === 90) {
zTL = lowZ; zTR = lowZ; zBL = z1; zBR = z1;
} else {
zTL = z1; zTR = z1; zBL = lowZ; zBR = lowZ;
}
}
const bTL = isoProject(x0, y0, mod.type.includes('BRIDGE') ? z0 : 0, iso);
const bTR = isoProject(x1, y0, mod.type.includes('BRIDGE') ? z0 : 0, iso);
const bBR = isoProject(x1, y1, mod.type.includes('BRIDGE') ? z0 : 0, iso);
const bBL = isoProject(x0, y1, mod.type.includes('BRIDGE') ? z0 : 0, iso);
const tTL = isoProject(x0, y0, zTL, iso);
const tTR = isoProject(x1, y0, zTR, iso);
const tBR = isoProject(x1, y1, zBR, iso);
const tBL = isoProject(x0, y1, zBL, iso);
ctx.save();
ctx.strokeStyle = isInvalid ? '#fecdd3' : (isSelected ? '#ffffff' : baseColor);
ctx.lineWidth = isInvalid || isSelected ? 2 : 1.2;
// Left/South-West visible face (bBL -> bBR -> tBR -> tBL)
ctx.fillStyle = baseColor + (mod.category === 'GRF' ? '44' : '66');
ctx.beginPath();
ctx.moveTo(bBL.x, bBL.y);
ctx.lineTo(bBR.x, bBR.y);
ctx.lineTo(tBR.x, tBR.y);
ctx.lineTo(tBL.x, tBL.y);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Right/South-East visible face (bBR -> bTR -> tTR -> tBR)
ctx.fillStyle = baseColor + (mod.category === 'GRF' ? '33' : '44');
ctx.beginPath();
ctx.moveTo(bBR.x, bBR.y);
ctx.lineTo(bTR.x, bTR.y);
ctx.lineTo(tTR.x, tTR.y);
ctx.lineTo(tBR.x, tBR.y);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Top Deck / Ramp Surface
ctx.fillStyle = baseColor + (mod.category === 'GRF' ? '66' : '99');
ctx.beginPath();
ctx.moveTo(tTL.x, tTL.y);
ctx.lineTo(tTR.x, tTR.y);
ctx.lineTo(tBR.x, tBR.y);
ctx.lineTo(tBL.x, tBL.y);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Floating Z-height tag
ctx.fillStyle = isInvalid ? '#fda4af' : '#f8fafc';
ctx.font = '700 9px "JetBrains Mono", monospace';
ctx.fillText(`${mod.id} (${mod.spec.zEnd.toFixed(1)}m)`, tTL.x, tTL.y - 5);
ctx.restore();
}
// =========================================================================
// CANVAS INTERACTION HANDLERS (CLICK, DRAG, RIGHT-CLICK DELETE)
// =========================================================================
function findModuleAt(rawX, rawY) {
for (let i = state.placedModules.length - 1; i >= 0; i--) {
const mod = state.placedModules[i];
const dims = getOrientedDims(mod.spec, mod.rotation);
if (rawX >= mod.x && rawX <= mod.x + dims.w && rawY >= mod.y && rawY <= mod.y + dims.d) {
return mod;
}
}
return null;
}
function setupCanvasEvents() {
const canvas = document.getElementById('siteCanvas');
canvas.addEventListener('mousemove', (e) => {
const pt = screenToGrid(e.clientX, e.clientY);
state.hoverGrid = pt;
const clampedX = Math.max(0, Math.min(SITE_WIDTH_M, pt.rawX));
const clampedY = Math.max(0, Math.min(SITE_HEIGHT_M, pt.rawY));
document.getElementById('cursorCoords').textContent =
`X: ${clampedX.toFixed(1)}m | Y: ${clampedY.toFixed(1)}m`;
const zone = SITE_ZONES.find(
z => clampedX >= z.x && clampedX <= z.x + z.w && clampedY >= z.y && clampedY <= z.y + z.h
);
document.getElementById('hoverZoneLabel').textContent = zone ? zone.name : 'ZONE: CIRCULATION SPINE';
if (state.draggingId) {
const mod = state.placedModules.find(m => m.id === state.draggingId);
if (mod) {
const dims = getOrientedDims(mod.spec, mod.rotation);
const nx = Math.round((pt.rawX - state.dragOffset.x) * 2) / 2;
const ny = Math.round((pt.rawY - state.dragOffset.y) * 2) / 2;
mod.x = Math.max(0, Math.min(SITE_WIDTH_M - dims.w, nx));
mod.y = Math.max(0, Math.min(SITE_HEIGHT_M - dims.d, ny));
updateInspector();
runZAxisValidation();
}
}
renderSite();
});
canvas.addEventListener('mousedown', (e) => {
if (e.button === 2) return; // Handled by contextmenu
const pt = screenToGrid(e.clientX, e.clientY);
const hit = findModuleAt(pt.rawX, pt.rawY);
if (hit) {
state.selectedId = hit.id;
state.draggingId = hit.id;
state.dragOffset = { x: pt.rawX - hit.x, y: pt.rawY - hit.y };
updateInspector();
renderSite();
return;
}
if (state.toolMode === 'PLACE') {
const spec = CATALOG.find(c => c.type === state.activeCatalogType);
if (spec && pt.rawX >= 0 && pt.rawX <= SITE_WIDTH_M && pt.rawY >= 0 && pt.rawY <= SITE_HEIGHT_M) {
const dims = getOrientedDims(spec, state.placementRotation);
const px = Math.max(0, Math.min(SITE_WIDTH_M - dims.w, pt.x));
const py = Math.max(0, Math.min(SITE_HEIGHT_M - dims.d, pt.y));
const inst = createModuleInstance(spec.type, px, py, state.placementRotation);
state.placedModules.push(inst);
state.selectedId = inst.id;
updateInspector();
runZAxisValidation();
renderSite();
}
} else {
state.selectedId = null;
updateInspector();
renderSite();
}
});
window.addEventListener('mouseup', () => {
state.draggingId = null;
});
canvas.addEventListener('contextmenu', (e) => {
e.preventDefault();
const pt = screenToGrid(e.clientX, e.clientY);
const hit = findModuleAt(pt.rawX, pt.rawY);
if (hit) {
state.placedModules = state.placedModules.filter(m => m.id !== hit.id);
if (state.selectedId === hit.id) state.selectedId = null;
updateInspector();
runZAxisValidation();
renderSite();
}
});
}
function handleKeyDown(e) {
if (e.key === 'r' || e.key === 'R') {
rotateSelection();
} else if (e.key === 'Delete' || e.key === 'Backspace') {
if (document.activeElement.tagName !== 'INPUT') {
deleteSelected();
}
} else if (e.key === 'Escape') {
deselectModule();
}
}
window.onload = initApp;
</script>
</body>
</html>