1. Why Four Independent MEP Plugins Started Fighting Over Geometry
Building one deterministic MEP plugin for a browser-based 3D architectural editor is manageable. Building four of them (Structural framing, Plumbing DWV and PEX, HVAC ducting and loads, and NEC Electrical) that have to coexist inside the exact same house exposes a harder systems problem than any single code table.
Before extracting a shared kernel, each of my four MIT plugins (pascal-plugin-structural, pascal-plugin-plumbing, pascal-plugin-hvac, and pascal-plugin-electrical) worked cleanly in isolation. The cracks showed up when I ran all four sequentially against a corpus of 246 real user-authored public buildings exported from Pascal Editor's public scene catalog. Auditing roughly 30,300 lines of engine code across autopopulate.ts, routing.ts, audit.ts, openings.ts, and building-skeleton.ts surfaced three structural failure modes:
- Four Incompatible Geometry Stacks: Every plugin had grown its own interpretation of levels, roofs, wall openings, concave footprints, and 3D bounding boxes.
pointInPolygon2Dwas copy-pasted six times. Concave indoor enclosure used three completely different algorithms (planar half-edge faces in Electrical, 8-ray room-first in HVAC, 16-ray raycasting in Structural).Aabb3did not even share a shape ({ min: Vec3, max: Vec3 }in Electrical versus flat{ minX..maxZ }in Plumbing and HVAC). Worse, Pascal Editor levels default tobaseElevation: 0unless explicitly overridden, so sorting stories bybaseElevationbefore explicitlevelordinal silently flattened two-story houses into a single floor inside Electrical and inside Plumbing's roof elevation helper. - Post-Hoc Obstacle Dodging Instead of Legal Cavities: HVAC and Plumbing enumerated hardcoded template offsets in free 3D space and repaired clashes afterward; Electrical built a 2D wall graph with a soft
+200penalty for crossing openings followed by an 8-iteration greedy detour patch. Soft penalties look reasonable on simple boxes, yet on a U-shaped courtyard house with 30 doors and windows, a soft penalty eventually loses to path length and lets a cable jump across an open pool courtyard or clip through storefront glass. - 28 Concrete Generator-vs-Auditor Rule Drifts: Almost every code rule had been written twice: once imperatively inside
autopopulate.tsorrouting.ts, and a second time insideaudit.ts. Over weeks of real-world hardening, thresholds drifted apart by centimeters, inches, and feet.
| Code Reference | Generator / Router Threshold (Before) | Post-Hoc Auditor Threshold (Before) | Failure Mode Produced |
|---|---|---|---|
NEC 406.9(C) / 410.10(D) |
0.925 m wet-zone clearance |
0.914 m (36 in) clearance |
Subtle placement/audit drift around tubs and showers |
NEC 404.4(C) |
0.25 m switch separation |
0.15 m switch separation |
Unnecessary switch displacement or missed wet-zone flags |
NEC 210.52(C) |
0.15 m stove margin, [0.65, 1.75] band |
0.08 m margin, [0.75, 1.65] band |
Countertop receptacle placed legally, flagged immediately on audit |
NEC 406.5(E) |
Sink edge < 0.25 m, height <= 1.2 m |
Sink edge === 0, height <= 1.05 m |
Floor-adjacent and vanity outlets diverged between passes |
IECC R403.3.1 |
Attic duct check on vertex > levelH - 0.02 |
Segment midpoint >= levelH + 0.05 |
Ducts right along the ceiling plane missed R-8 insulation |
IMC 307.2.1 |
Condensate slope >= 0.125"/ft |
Condensate audit < 0.12"/ft |
Borderline floating-point drops behaved inconsistently |
IFGC 402.4 |
Fuel gas length clamp at 15 ft |
Audit warning threshold at 10 ft |
Router emitted runs that immediately failed its own audit |
IRC R602.6 & M1502.4 |
3" WC branch wet-wall fit & 35 ft dryer vent unchecked | Flagged only during post-hoc audit | Dryer vents exceeded 35 ft and 3" hubs entered 2x4 stud bays |
The diagnosis was clear: adding more special-case if statements inside four separate plugins would only widen the divergence. All four trades needed a single deterministic geometry, routing, and constraint kernel built around construction-by-correctness.
2. The 3-Layer Spatial Kernel Architecture
I froze a specification (spec.md) with 11 hard invariants (INV-MEP-01 through INV-MEP-11) and extracted @kruschdev/pascal-mep-kernel as a standalone MIT package with three strict layers and five subpath exports (., ./types, ./anatomy, ./router, and ./rules).
Figure 1: All four MIT Pascal Editor MEP plugins consume one framework-free spatial kernel in real jobsite right-of-way priority order (Structural #1 -> Plumbing #2 -> HVAC #3 -> Electrical #4).
Before writing a single geometry helper, I locked down INV-MEP-01 with an automated purity script (scripts/check-purity.ts). The kernel is strictly forbidden from importing react, react-dom, three, @pascal-app/*, next, zod, zustand, or Node/Bun built-ins (node:*, bun:*). Because the published npm tarball is just 77 KB of precompiled pure ESM + .d.ts with zero dependencies, it drops straight into Next.js App Router, Turbopack, Vite, Bun, Node, or headless MCP agents without React Server Component boundary errors or extra transpilePackages hacks. Across all five repositories, 25/25 boundary and purity gates enforce this separation on every build.
3. Layer 1: Shared Cross-Trade Spatial Anatomy
The first design decision was ensuring all four trades observe the exact same building in O(1) amortized time. Calling compileBuildingAnatomy(nodes) returns a WeakMap-memoized BuildingAnatomy keyed by the scene's nodes record reference. Inside that compiled anatomy sit five canonical primitives that eliminated more than 2,300 lines of duplicated math across the four plugin repos:
- Monotonic Story Ordering (
src/anatomy/levels.ts):compareLevelsVerticallyranks explicitlevelordinal strictly ahead ofelevationandbaseElevation, defeating Pascal's defaultbaseElevation: 0flattening bug while still supporting synthetic flat test scenes that omit level nodes. - Single 7-Type Canonical Roof Shell (
src/anatomy/roof.ts): Unifiesflat,shed,gable,hip,dutch,mansard, andconicalroof segments with full multi-hop parentrooftransform accumulation, per-segment spatial adoption, and upper-wing seating (isDirectUpperWingRoof). Instead of four incompatible roof calculators, every trade queriesroofSurfaceY(x, z),minRoofYOverAabb(...), andisPathClearOfRoof(path, halfV, clearanceM)parameterized only by explicit boolean flags (includeHidden,clampOverhangToEave). - Dual-Sill Wall & 3D Opening Prisms (
src/anatomy/openings.ts): Extracts both nativedoor/windownodes and wall-attacheditemopenings into exact rotated 3DOrientedPrismYkeepouts. Each opening exposes bothrawSillYM(unclamped down to0 mso Electrical can identify floor-to-ceiling storefront glass underNEC 210.52(A)(2)(1)) andframedSillYM(clamped to>= 0.08 mfor IRC cripple-stud framing). - Concave Footprint Enclosure & Courtyard Exclusion (
src/anatomy/footprint.ts): Combines exact planar half-edge bounded faces (whenever closed wall loops cover at least72%of total wall length) with a 16-ray enclosure fallback for open pavilions and partial scenes, plus NFD-normalized multilingual room polygon parsing so outdoor spaces (Lanai,Patio,Pool,Veranda,Loggia,Pergola) are explicitly excluded from the conditioned envelope. - Priority-Aware Spatial Occupancy Grid (
src/anatomy/occupancy.ts):TradeOccupancyGridtracks committed structural beams, columns, plumbing stacks, HVAC trunks, and electrical conduits using exact rotated OBB (OrientedPrismY) and swept-segment intersection math with strict priority rankstructural (1) < plumbing (2) < hvac (3) < electrical (4).
4. Layer 2: Legal-Space-First Cavity Routing
The biggest conceptual shift in the kernel happens in Layer 2 (src/router/cavity-graph.ts and src/router/shortest-path.ts). Instead of routing through open air and trying to nudge colliding segments out of windows or courtyards after the fact, compileLegalCavityGraph constructs the navigable graph strictly out of spaces where building codes actually permit pipes, ducts, and cables to travel:
- Wall Stud Bays Minus Opening Prisms: Horizontal chases along
under-sill,mid-wall, andtop-plateelevation bands plus vertical king-stud riser piers on either side of doors and windows. Any wall edge intersecting a 3D door, window, header, or structural column prism is omitted from the graph at construction time. - Enclosed Overhead Plenums & Attics: Overhead edges are trimmed against both the concave indoor footprint (so outdoor courtyards are literally non-existent in the graph) and against
roofSurfaceY(x, z) - clearanceM - halfVso ducts, cables, and air handlers cannot pierce hip corners or flat soffits. - Under-Slab & Crawlspace Trenches: Sub-floor routing bands supporting gravity DWV drainage and dry crawlspace pulls while allowing code rules to ban wet crawlspace
NM-Bcables cleanly.
On top of that pre-pruned cavity graph, routeInLegalCavities runs a constrained shortest-path solver across four explicit physics modes: orthogonal (rigid EMT/RMC conduit and rectangular/round HVAC trunks), euclidean-cavity (flexible NM-B/MC cable and PEX inside open attics or dry crawlspaces), gravity-slope (DWV drains and HVAC condensate enforcing strict monotonic fall without ever silently inserting an uphill segment), and non-descending-vent (IPC 905.5 dry re-vents staying at least 6 in / 0.1524 m above flood-level rim with zero inverted-U traps). Cumulative bend angles track against caps like NEC 358.26 (360° between pull points), and every committed route reserves its swept envelope inside TradeOccupancyGrid before the next lower-priority trade routes.
Figure 2: Live Pascal Editor main-floor slice of Aymeric House. Because the open U-shaped Lanai pool courtyard and all 30 door/window prisms are excluded from the legal cavity graph by construction, HVAC splits cleanly into West 4-Ton and East 2-Ton wings and zero wires cross the courtyard or glass.
5. Layer 3: Single-Source Declarative Code Rules
Fixing geometry alone still leaves half the bug class alive if generators and auditors encode code requirements separately. Layer 3 (src/rules/schema.ts and src/rules/evaluator.ts) defines a compact, typed DeclarativeRule record covering nine constraint kinds (prohibited-zone, fixture-keepout, opening-keepout, elevation-band, working-space, material-policy, routing-constraint, wall-cavity-fit, and wind-seismic-threshold).
Figure 3: Dual-projection rule evaluation guarantees soundness by construction. Because placementMarginM >= 0 is validated at load time, a placement pass can be stricter than the audit threshold for safety cushion, never looser.
import {
compileBuildingAnatomy,
compileLegalCavityGraph,
routeInLegalCavities,
filterLegalCandidates,
evaluateDeclarativeRules,
validateRuleTable,
} from '@kruschdev/pascal-mep-kernel'
// 1. Compile shared O(1) WeakMap-memoized anatomy once for all 4 trades
const anatomy = compileBuildingAnatomy(scene.nodes)
const grid = anatomy.createOccupancyGrid(levelId, { forTrade: 'electrical' })
// 2. Build navigable cavities excluding 3D openings, roof clearances & courtyards
const graph = compileLegalCavityGraph(anatomy, levelId, {
clearanceM: 0.05,
allowedBands: ['under-sill', 'mid-wall', 'top-plate', 'overhead-plenum', 'attic'],
})
// 3. Route in priority order with bend caps & automatic occupancy reservation
const route = routeInLegalCavities(graph, grid, {
trade: 'electrical',
from: panelPort,
to: receptaclePort,
halfXZ: 0.012,
halfY: 0.012,
clearanceM: 0.025,
allowedBands: ['under-sill', 'mid-wall', 'top-plate', 'attic'],
mode: 'euclidean-cavity',
maxBendDegrees: 360,
reserveOnCommit: true,
})
// 4. Enforce identical thresholds across both placement and post-hoc audit
validateRuleTable(NEC_DECLARATIVE_RULES)
const legalSpots = filterLegalCandidates(candidates, NEC_DECLARATIVE_RULES, anatomy)
const auditReport = evaluateDeclarativeRules(placedNodes, NEC_DECLARATIVE_RULES, anatomy)
6. Verification: 582 Unit Tests, 246 Real Public Buildings, and Aymeric House
Refactors that touch geometry math across four engineering disciplines are notorious for breaking edge cases quietly. I gated every wave of the refactor (Layer 1 anatomy adoption, Layer 2 cavity routing adoption, and Layer 3 declarative rule migration) on three checks: the full unit suite across all five repositories, the 25/25 framework purity and Next.js RSC boundary checks, and an automated sweep across 246 real user-built public Pascal buildings fetched via Pascal Editor's public read API.
| Priority | Repository (MIT) | Standards & Scope | 3D CAD Models | Unit Tests |
|---|---|---|---|---|
| Core | @kruschdev/pascal-mep-kernel v0.1.0 |
Spatial anatomy, legal-cavity router, declarative rule engine (npm) | Zero-dep pure TS | 169 / 169 (135,888 assertions) |
| #1 | @kruschdev/pascal-plugin-structural v0.2.0 |
IRC / AWC NDS / AISC framing, engineered beams, Simpson-class connectors, fire blocking | 62 MIT .glb |
104 / 104 (1,493 assertions) |
| #2 | @kruschdev/pascal-plugin-plumbing v0.2.0 |
IPC / UPC / IFGC gravity DWV, dry vents, PEX manifolds, gas, dryer vents | 47 MIT .glb |
79 / 79 (2,762 assertions) |
| #3 | @kruschdev/pascal-plugin-hvac v0.2.0 |
IMC / ACCA Manual J-D-S / IECC dual-wing & mini-split HVAC, ERV, condensate | 42 MIT .glb |
95 / 95 (1,669 assertions) |
| #4 | @kruschdev/pascal-plugin-electrical v0.2.7 |
NEC / NFPA 72 Art. 220 loads, 3D cover-off panelboards, opening-safe routing (npm) | 50 MIT .glb |
135 / 135 (2,343 assertions) |
| Total | 5 Coordinated MIT Repositories | 4-Trade Jobsite Right-of-Way + 33 Pure-Zod Agent Operations | 201 MIT .glb |
582 / 582 (144,155 assertions) |
On the live flagship stress test, Aymeric House (two stories, 21 zones, a U-shaped open Lanai courtyard with pool, pitched gable wing roofs, and a central flat roof), running all four plugins in priority order stamps 1,412 coordinated nodes with 0 / 0 / 0 / 0 audit errors, zero ducts or electrical cables spanning the open courtyard, zero wires intersecting any of the 30 door and window openings, a 0.09% balanced main panel schedule, and a combined $185,414 priced bill of materials across all four trades. Across all 246 real public Pascal buildings, the suite completes with 0 crashes, 0 NaN geometry outputs, and 145 / 246 buildings completely 0/0/0/0 clean across all four trades simultaneously (PLB 245/246, HVC 222/246, ELC 198/246, STR 167/246; 17/17 Plumbing and 17/17 Electrical zero-error on official Pascal demo scenes). Remote installation of all four hosted-Pascal-packaged plugins together via bun add completes in 2.06 s at 6.1 MB total unpacked.
Figure 4: Full two-story Aymeric House cutaway rendered live in Pascal Editor with Structural Framing X-Ray active and all four MEP trades layered cleanly beneath pitched wing roofs and the central flat roof.
7. Honest Scope Boundaries and Known Edge Cases
@kruschdev/pascal-mep-kernel and all four MIT Pascal MEP plugins are deterministic drafting, visualization, and preliminary engineering aids, never stamped engineering and never a substitute for a licensed Professional Engineer (PE), master tradesperson, or local Authority Having Jurisdiction (AHJ) plan review.
Shipping real geometry code against 246 uncurated user buildings also reveals exactly where deterministic heuristics still have boundaries worth documenting openly:
- Framing X-Ray Hidden-Wall Interaction: When Structural's
Framing X-Raytoggle hides architectural drywall (wall.visible = false),resolveLevelHeightM(which ignores hidden walls by default) can fall back below2.8 mon levels lacking an explicitlevel.heightif short knee walls remain visible, occasionally triggering anIMC 601.5false positive in HVAC until drywall is shown or a hidden-wall fallback is enabled. - Cross-Trade Firestop Re-Sync Order: Running Electrical (Priority #4) after Structural (Priority #1) introduces new top-plate and bottom-plate cable penetrations that Structural's
IRC R302.11(5)auditor correctly flags until Structural's firestop pass is re-run. That reflects real jobsite sequencing (rough-in inspections verify firestopping after MEP trades finish drilling plates), though a one-click cross-trade firestop sync action will make the editor workflow smoother. - Open Pavilions & Over-Constrained Endpoints: On incomplete wall loops below the
72%half-edge coverage threshold, the footprint falls back to 16-ray enclosure plus tight wall AABB so open gazebos and partial drafts do not false-reject valid interior points. When a user manually drags a fixture directly inside a beam or window prism,routeInLegalCavitiesnever hangs or emitsNaN; it routes cleanly from the nearest legal port and reports the irreducibleclashObstacleIdsoropeningHitshonestly inCavityRouteResult. - Remaining
101/246Corpus Audits: Most non-zero findings across the remaining public community buildings come from genuinely unconditioned outdoor sheds, incomplete architectural drafts with missing roofs or walls, or unconventional geometries where structural framing cannot infer a continuous load path without human engineering judgment.
8. Install and Verify Locally
The kernel and all four Pascal Editor plugins are published under the MIT License and can be installed or verified locally in seconds:
# 1. Install the zero-dependency spatial kernel from npm
npm install @kruschdev/pascal-mep-kernel
# or
bun add @kruschdev/pascal-mep-kernel
# 2. Clone and run full typecheck, 169 unit tests, 5/5 purity gates & ESM build
git clone https://github.com/kruschdev/pascal-mep-kernel.git && cd pascal-mep-kernel
bun install && bun run check
# 3. Install all 4 coordinated MIT plugins in any Pascal Editor host
bun add \
@kruschdev/pascal-plugin-electrical \
github:kruschdev/pascal-plugin-structural \
github:kruschdev/pascal-plugin-plumbing \
github:kruschdev/pascal-plugin-hvac