@kruschdev/pascal-plugin-furnishings 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,711 @@
1
+ /**
2
+ * Ergonomics, Clearance, AV Acoustics, Electrical Coordination & Botanical Audit Engine
3
+ * (`src/furnishings/audit.ts`).
4
+ *
5
+ * Pure framework-free TypeScript: zero `three`, `react`, `@pascal-app/*`, or `next` imports.
6
+ */
7
+
8
+ import {
9
+ extractNodeYawRad,
10
+ type OrientedPrismY,
11
+ } from '@kruschdev/pascal-mep-kernel'
12
+ import {
13
+ type CanonicalWall,
14
+ compileBuildingAnatomy,
15
+ findNearestWallToPoint,
16
+ isPointEnclosedByWalls,
17
+ resolveNodeLevelId,
18
+ } from '@kruschdev/pascal-mep-kernel/anatomy'
19
+ import { deriveDisplayDimensionsM, getFurnishingSpec } from './catalog'
20
+ import {
21
+ type FurnishingWallAnalysis,
22
+ createFurnishingPrismY,
23
+ expandOpeningPrism,
24
+ extractBuildingFurnishingsAnatomy,
25
+ findContainingRoom,
26
+ minDistanceToExteriorWallM,
27
+ orientedPrismsIntersect,
28
+ } from './geometry'
29
+ import {
30
+ PLANT_MATURITY_SCALE,
31
+ type PlantMaturity,
32
+ type SceneNodeLike,
33
+ round2,
34
+ } from './types'
35
+
36
+ export type AuditSeverity = 'error' | 'warning' | 'info'
37
+
38
+ export type FurnishingAuditFinding = {
39
+ readonly code: string
40
+ readonly severity: AuditSeverity
41
+ readonly category: 'clearance' | 'ergonomics' | 'av-acoustics' | 'electrical' | 'botanical'
42
+ readonly nodeId: string
43
+ readonly relatedNodeId?: string
44
+ readonly roomName: string
45
+ readonly message: string
46
+ readonly recommendation: string
47
+ }
48
+
49
+ export type FurnishingAuditResult = {
50
+ readonly passed: boolean
51
+ readonly errorCount: number
52
+ readonly warningCount: number
53
+ readonly infoCount: number
54
+ readonly totalItemsAudited: number
55
+ readonly totalElectricalDemandW: number
56
+ readonly findings: readonly FurnishingAuditFinding[]
57
+ }
58
+
59
+ type AuditedItem = {
60
+ readonly node: SceneNodeLike
61
+ readonly levelId: string | null
62
+ readonly kind: string
63
+ readonly label: string
64
+ readonly roomName: string
65
+ readonly x: number
66
+ readonly y: number
67
+ readonly z: number
68
+ readonly yaw: number
69
+ readonly widthM: number
70
+ readonly depthM: number
71
+ readonly heightM: number
72
+ readonly wattageW: number
73
+ readonly isFloorCovering: boolean
74
+ readonly isDeskTopItem: boolean
75
+ readonly isWallMounted: boolean
76
+ readonly isCeilingMounted: boolean
77
+ readonly isHardwiredLight: boolean
78
+ readonly indoorOnly: boolean
79
+ readonly outdoorOnly: boolean
80
+ readonly minFoundationClearanceM: number
81
+ readonly prism: OrientedPrismY
82
+ }
83
+
84
+ function safeNum(v: unknown, fallback = 0): number {
85
+ return typeof v === 'number' && Number.isFinite(v) ? v : fallback
86
+ }
87
+
88
+ function sameLevel(a: string | null, b: string | null): boolean {
89
+ return !a || !b || a === b
90
+ }
91
+
92
+ function roomLevelKey(levelId: string | null, roomName: string): string {
93
+ return `${levelId ?? ''}::${roomName}`
94
+ }
95
+
96
+ function extractAuditedItems(nodes: Readonly<Record<string, SceneNodeLike>>): AuditedItem[] {
97
+ const out: AuditedItem[] = []
98
+ for (const node of Object.values(nodes)) {
99
+ if (node.visible === false) continue
100
+ if (
101
+ node.type !== 'furnishings:item' &&
102
+ node.type !== 'furnishings:electronics' &&
103
+ node.type !== 'furnishings:plant'
104
+ ) {
105
+ continue
106
+ }
107
+ const kind = String(node.itemKind ?? node.plantKind ?? '')
108
+ const spec = getFurnishingSpec(kind)
109
+ const pos = Array.isArray(node.position) ? node.position : [0, 0, 0]
110
+ const x = safeNum(pos[0])
111
+ const y = safeNum(pos[1], spec?.defaultElevationM ?? 0)
112
+ const z = safeNum(pos[2])
113
+ const yaw = extractNodeYawRad(node.rotation)
114
+
115
+ let widthM = Math.max(0.01, safeNum(node.widthM, spec?.widthM ?? 0.8))
116
+ let depthM = Math.max(0.01, safeNum(node.depthM, spec?.depthM ?? 0.8))
117
+ let heightM = Math.max(0.01, safeNum(node.heightM, spec?.heightM ?? 0.8))
118
+
119
+ if (node.type === 'furnishings:electronics' && typeof node.screenDiagonalIn === 'number') {
120
+ const derived = deriveDisplayDimensionsM(kind, node.screenDiagonalIn)
121
+ const usesCatalogDefaults =
122
+ (node.widthM === undefined || node.widthM === spec?.widthM) &&
123
+ (node.heightM === undefined || node.heightM === spec?.heightM)
124
+ if (derived && usesCatalogDefaults) {
125
+ widthM = Math.max(0.01, derived.widthM)
126
+ heightM = Math.max(0.01, derived.heightM)
127
+ }
128
+ }
129
+
130
+ if (node.type === 'furnishings:plant') {
131
+ const matKey = String(node.maturity ?? 'mature') as PlantMaturity
132
+ const scale = PLANT_MATURITY_SCALE[matKey] ?? 1.0
133
+ const canopyR = Math.max(0.01, safeNum(node.canopyRadiusM, (spec?.widthM ?? 1.0) / 2))
134
+ widthM = Math.max(0.01, canopyR * 2 * scale)
135
+ const isLinearPlant = kind === 'bush-hedge-row' || kind === 'plant-succulent-trough'
136
+ depthM = Math.max(0.01, isLinearPlant ? (spec?.depthM ?? 0.5) * scale : canopyR * 2 * scale)
137
+ heightM = Math.max(0.01, safeNum(node.heightM, spec?.heightM ?? 1.2) * scale)
138
+ }
139
+
140
+ const qty = Math.max(1, Math.round(safeNum(node.quantity, 1)))
141
+ const unitW = Math.max(0, safeNum(node.wattageW, spec?.wattageW ?? 0))
142
+
143
+ const prism = createFurnishingPrismY({
144
+ centerX: x,
145
+ centerZ: z,
146
+ yawRad: yaw,
147
+ widthM,
148
+ depthM,
149
+ yMin: y,
150
+ yMax: y + heightM,
151
+ })
152
+
153
+ const isWallMounted =
154
+ kind === 'vent-grille-return-flush'
155
+ ? y < 2.1
156
+ : Boolean(spec?.isWallMounted || node.mountStyle === 'wall-mount')
157
+ const isCeilingMounted =
158
+ kind === 'vent-grille-return-flush'
159
+ ? y >= 2.1
160
+ : Boolean(spec?.isCeilingMounted || node.mountStyle === 'ceiling-mount')
161
+
162
+ out.push({
163
+ node,
164
+ levelId: resolveNodeLevelId(nodes, node),
165
+ kind,
166
+ label: typeof node.name === 'string' && node.name.trim() ? node.name : (spec?.label ?? kind),
167
+ roomName: String(node.roomName ?? node.zoneName ?? 'Unassigned'),
168
+ x,
169
+ y,
170
+ z,
171
+ yaw,
172
+ widthM,
173
+ depthM,
174
+ heightM,
175
+ wattageW: unitW * qty,
176
+ isFloorCovering: Boolean(spec?.isFloorCovering),
177
+ isDeskTopItem: Boolean(spec?.isDeskTopItem || node.mountStyle === 'desk'),
178
+ isWallMounted,
179
+ isCeilingMounted,
180
+ isHardwiredLight: Boolean(spec?.isHardwiredLight),
181
+ indoorOnly: Boolean(spec?.indoorOnly),
182
+ outdoorOnly: Boolean(spec?.outdoorOnly),
183
+ minFoundationClearanceM: spec?.minFoundationClearanceM ?? 0,
184
+ prism,
185
+ })
186
+ }
187
+ return out
188
+ }
189
+
190
+ export function auditSceneFurnishings(
191
+ nodes: Readonly<Record<string, SceneNodeLike>>,
192
+ ): FurnishingAuditResult {
193
+ const anatomy = extractBuildingFurnishingsAnatomy(nodes)
194
+ const items = extractAuditedItems(nodes)
195
+ const findings: FurnishingAuditFinding[] = []
196
+
197
+ const kernelAnatomy = compileBuildingAnatomy(nodes)
198
+ const getCanonicalLevelWalls = (levelId: string | null): readonly CanonicalWall[] => {
199
+ if (levelId) {
200
+ return kernelAnatomy.getWalls(levelId)
201
+ }
202
+ if (anatomy.primaryLevelId) {
203
+ const lw = kernelAnatomy.getWalls(anatomy.primaryLevelId)
204
+ if (lw.length > 0) return lw
205
+ }
206
+ return kernelAnatomy.getWalls(null)
207
+ }
208
+ const isWithinInteriorWallTolerance = (
209
+ x: number,
210
+ z: number,
211
+ levelWalls: readonly CanonicalWall[],
212
+ furnishingWalls: readonly FurnishingWallAnalysis[],
213
+ ): boolean => {
214
+ const proj = findNearestWallToPoint(x, z, levelWalls)
215
+ if (!proj) return false
216
+ const halfThick = proj.wall.thicknessM / 2
217
+ if (proj.distM > halfThick + 0.12) return false
218
+ const fw = furnishingWalls.find((w) => w.id === proj.wall.id)
219
+ if (fw && fw.exteriorNormalSign !== 0) {
220
+ const signedOutward = proj.perpDistM * fw.exteriorNormalSign
221
+ if (signedOutward > halfThick + 0.03) return false
222
+ }
223
+ return true
224
+ }
225
+ const isUnzonedOutdoor = (x: number, z: number, levelId: string | null): boolean => {
226
+ const levelWalls = getCanonicalLevelWalls(levelId)
227
+ if (levelWalls.length < 3) return false
228
+ const fw = levelId ? anatomy.walls.filter((w) => !w.levelId || w.levelId === levelId) : anatomy.walls
229
+ if (!fw.some((w) => w.exteriorNormalSign !== 0)) return false
230
+ if (isWithinInteriorWallTolerance(x, z, levelWalls, fw)) return false
231
+ return !isPointEnclosedByWalls(x, z, levelWalls)
232
+ }
233
+
234
+ const totalElectricalDemandW = round2(
235
+ items.reduce((sum, it) => sum + (it.isHardwiredLight ? 0 : it.wattageW), 0),
236
+ )
237
+
238
+ // 1. FRN-CLR-01: Floor-standing furniture footprint overlap check
239
+ const solidFloorItems = items.filter(
240
+ (it) =>
241
+ it.node.type !== 'furnishings:plant' &&
242
+ !it.isFloorCovering &&
243
+ !it.isDeskTopItem &&
244
+ !it.isWallMounted &&
245
+ !it.isCeilingMounted &&
246
+ it.kind !== 'dining-chair',
247
+ )
248
+ for (let i = 0; i < solidFloorItems.length; i++) {
249
+ for (let j = i + 1; j < solidFloorItems.length; j++) {
250
+ const a = solidFloorItems[i]!
251
+ const b = solidFloorItems[j]!
252
+ if (a.levelId && b.levelId && a.levelId !== b.levelId) continue
253
+ // Symmetric exact OBB-vs-OBB SAT overlap with 4cm XZ / 2cm Y flush tolerance (thin heights <= 0.06m skip Y shrink)
254
+ if (orientedPrismsIntersect(a.prism, b.prism, 0.04, 0.02)) {
255
+ findings.push({
256
+ code: 'FRN-CLR-01',
257
+ severity: 'error',
258
+ category: 'clearance',
259
+ nodeId: a.node.id,
260
+ relatedNodeId: b.node.id,
261
+ roomName: a.roomName,
262
+ message: `"${a.label}" overlaps "${b.label}" in 3D space.`,
263
+ recommendation: 'Separate footprints by at least 0.05m (or 0.76m for an active walkway).',
264
+ })
265
+ }
266
+ }
267
+ }
268
+
269
+ // 1b. FRN-CLR-01 (wall-mounted pass): Catch overlapping wall-mounted items (e.g. HVAC grate inside OLED TV or framed art)
270
+ const wallMountedItems = items.filter(
271
+ (it) => it.isWallMounted && it.kind !== 'curtain-drape' && it.node.type !== 'furnishings:plant',
272
+ )
273
+ for (let i = 0; i < wallMountedItems.length; i++) {
274
+ for (let j = i + 1; j < wallMountedItems.length; j++) {
275
+ const a = wallMountedItems[i]!
276
+ const b = wallMountedItems[j]!
277
+ if (!sameLevel(a.levelId, b.levelId)) continue
278
+ if (orientedPrismsIntersect(a.prism, b.prism, 0.02, 0.02)) {
279
+ findings.push({
280
+ code: 'FRN-CLR-01',
281
+ severity: 'error',
282
+ category: 'clearance',
283
+ nodeId: a.node.id,
284
+ relatedNodeId: b.node.id,
285
+ roomName: a.roomName,
286
+ message: `Wall-mounted "${a.label}" overlaps "${b.label}" on the same wall plane.`,
287
+ recommendation: 'Relocate wall-mounted displays, art, sconces, and HVAC registers so they do not intersect.',
288
+ })
289
+ }
290
+ }
291
+ }
292
+
293
+ // 1c. FRN-CLR-04: Floor HVAC supply register airflow obstruction check (covered by furniture or rug)
294
+ const floorHvacGrates = items.filter((it) => it.kind === 'vent-grate-floor-brass')
295
+ const floorRegisterBlockers = items.filter(
296
+ (it) =>
297
+ it.kind !== 'vent-grate-floor-brass' &&
298
+ !it.isWallMounted &&
299
+ !it.isCeilingMounted &&
300
+ !it.isDeskTopItem &&
301
+ (it.kind === 'area-rug-rect' || it.kind === 'area-rug-round' || !it.isFloorCovering),
302
+ )
303
+ for (const grate of floorHvacGrates) {
304
+ const airflowPrism = createFurnishingPrismY({
305
+ centerX: grate.x,
306
+ centerZ: grate.z,
307
+ yawRad: grate.yaw,
308
+ widthM: grate.widthM,
309
+ depthM: grate.depthM,
310
+ yMin: grate.y,
311
+ yMax: grate.y + Math.max(grate.heightM, 0.5),
312
+ })
313
+ for (const blocker of floorRegisterBlockers) {
314
+ if (!sameLevel(grate.levelId, blocker.levelId)) continue
315
+ if (orientedPrismsIntersect(airflowPrism, blocker.prism, 0.02, 0)) {
316
+ findings.push({
317
+ code: 'FRN-CLR-04',
318
+ severity: 'warning',
319
+ category: 'clearance',
320
+ nodeId: grate.node.id,
321
+ relatedNodeId: blocker.node.id,
322
+ roomName: grate.roomName,
323
+ message: `Floor HVAC register "${grate.label}" is obstructed by "${blocker.label}".`,
324
+ recommendation: 'Keep at least 0.15m clearance around floor supply registers so conditioned airflow is not blocked.',
325
+ })
326
+ break
327
+ }
328
+ }
329
+ }
330
+
331
+ // 1d. FRN-CLR-05: Indoor-only items (e.g. HVAC registers/grilles) placed in outdoor zones or unzoned yards
332
+ for (const it of items) {
333
+ if (!it.indoorOnly || it.node.type === 'furnishings:plant') continue
334
+ const levelRooms = it.levelId
335
+ ? anatomy.rooms.filter((r) => !r.levelId || r.levelId === it.levelId)
336
+ : anatomy.rooms
337
+ const insideRoom = findContainingRoom(it.x, it.z, levelRooms)
338
+ const unzonedOutdoor = !insideRoom && isUnzonedOutdoor(it.x, it.z, it.levelId)
339
+ if (insideRoom?.isOutdoor || unzonedOutdoor) {
340
+ findings.push({
341
+ code: 'FRN-CLR-05',
342
+ severity: 'warning',
343
+ category: 'clearance',
344
+ nodeId: it.node.id,
345
+ roomName: insideRoom?.name ?? it.roomName,
346
+ message: insideRoom
347
+ ? `Indoor-only item "${it.label}" is placed in outdoor zone "${insideRoom.name}".`
348
+ : `Indoor-only item "${it.label}" is placed outdoors outside the enclosed building envelope.`,
349
+ recommendation: 'Relocate indoor-only items and HVAC registers inside conditioned interior spaces.',
350
+ })
351
+ }
352
+ }
353
+
354
+ // 2. FRN-CLR-02: Door swing / egress pathway obstruction check (>= 0.914m / 36" clear, same level only)
355
+ for (const it of items) {
356
+ if (it.isFloorCovering || it.isCeilingMounted || it.isDeskTopItem) continue
357
+ for (const dp of anatomy.doorPrisms) {
358
+ if (it.levelId && dp.levelId && it.levelId !== dp.levelId) continue
359
+ const expanded = expandOpeningPrism(dp, 0.45, 0.45)
360
+ if (orientedPrismsIntersect(it.prism, expanded)) {
361
+ findings.push({
362
+ code: 'FRN-CLR-02',
363
+ severity: 'error',
364
+ category: 'clearance',
365
+ nodeId: it.node.id,
366
+ roomName: it.roomName,
367
+ message: `"${it.label}" obstructs door swing / egress clearance zone (${dp.id}).`,
368
+ recommendation: 'Maintain at least 0.914m (36") unobstructed clearance at all doorway swings.',
369
+ })
370
+ break
371
+ }
372
+ }
373
+ }
374
+
375
+ // 2b. FRN-CLR-03: Wall-mounted item / tall furniture window glazing occlusion check
376
+ for (const it of items) {
377
+ if (it.isFloorCovering || it.isCeilingMounted || it.isDeskTopItem) continue
378
+ if (it.kind === 'curtain-drape' || it.node.type === 'furnishings:plant') continue
379
+ const isWallMounted =
380
+ it.isWallMounted ||
381
+ it.kind === 'tv-oled-wall' ||
382
+ it.kind === 'wall-art-framed' ||
383
+ it.kind === 'light-wall-sconce' ||
384
+ it.kind === 'light-exterior-sconce' ||
385
+ it.kind === 'projector-screen'
386
+ if (!isWallMounted && it.heightM < 1.4) continue
387
+
388
+ for (const wp of anatomy.windowPrisms) {
389
+ if (it.levelId && wp.levelId && it.levelId !== wp.levelId) continue
390
+ // Expand 0.04m along the wall tangent and 0.35m perpendicular to the wall plane in
391
+ // `wp`'s exact wall-aligned `(cos, sin)` frame so diagonal walls work identically to cardinal walls.
392
+ const expanded = expandOpeningPrism(wp, 0.04, 0.35)
393
+ if (orientedPrismsIntersect(it.prism, expanded)) {
394
+ findings.push({
395
+ code: 'FRN-CLR-03',
396
+ severity: 'error',
397
+ category: 'clearance',
398
+ nodeId: it.node.id,
399
+ roomName: it.roomName,
400
+ message: `"${it.label}" overlaps window opening (${wp.id}).`,
401
+ recommendation: 'Mount TVs, wall decor, sconces, and tall storage on solid opening-free wall spans.',
402
+ })
403
+ break
404
+ }
405
+ }
406
+ }
407
+
408
+ // 3. FRN-ERG-01: Coffee table to sofa ergonomic reach (0.35m - 0.60m ideal along sofa forward axis)
409
+ const sofas = items.filter((it) => it.kind.startsWith('sofa-') || it.kind === 'loveseat')
410
+ const coffeeTables = items.filter((it) => it.kind === 'coffee-table')
411
+ for (const ct of coffeeTables) {
412
+ let nearestDist = Number.POSITIVE_INFINITY
413
+ for (const sf of sofas) {
414
+ if (sf.roomName !== ct.roomName || !sameLevel(sf.levelId, ct.levelId)) continue
415
+ const dx = ct.x - sf.x
416
+ const dz = ct.z - sf.z
417
+ const fwdX = Math.sin(sf.yaw)
418
+ const fwdZ = Math.cos(sf.yaw)
419
+ const latX = Math.cos(sf.yaw)
420
+ const latZ = -Math.sin(sf.yaw)
421
+ const forwardCenter = dx * fwdX + dz * fwdZ
422
+ const lateralCenter = dx * latX + dz * latZ
423
+ const relYaw = ct.yaw - sf.yaw
424
+ const absSin = Math.abs(Math.sin(relYaw))
425
+ const absCos = Math.abs(Math.cos(relYaw))
426
+ const ctHalfFwd = (ct.widthM / 2) * absSin + (ct.depthM / 2) * absCos
427
+ const ctHalfLat = (ct.widthM / 2) * absCos + (ct.depthM / 2) * absSin
428
+ // Only evaluate coffee tables positioned in front of the sofa within its lateral span
429
+ if (forwardCenter < -sf.depthM / 2) continue
430
+ if (Math.abs(lateralCenter) - sf.widthM / 2 - ctHalfLat > 0.15) continue
431
+ const edgeDist = forwardCenter - sf.depthM / 2 - ctHalfFwd
432
+ if (edgeDist < nearestDist) nearestDist = edgeDist
433
+ }
434
+ if (Number.isFinite(nearestDist) && nearestDist < 0.35) {
435
+ findings.push({
436
+ code: 'FRN-ERG-01',
437
+ severity: 'warning',
438
+ category: 'ergonomics',
439
+ nodeId: ct.node.id,
440
+ roomName: ct.roomName,
441
+ message: `Coffee table is only ${round2(Math.max(0, nearestDist))}m from sofa front seat edge (< 0.35m legroom).`,
442
+ recommendation: 'Position coffee table 0.35m–0.55m (14"–22") from the front sofa seat edge.',
443
+ })
444
+ }
445
+ }
446
+
447
+ // 4. FRN-AV-01: TV / display viewing distance & eye-level mount check (THX/SMPTE 1.2x–2.8x diagonal)
448
+ const displays = items.filter(
449
+ (it) =>
450
+ it.node.type === 'furnishings:electronics' &&
451
+ (it.kind === 'tv-oled-wall' || it.kind === 'tv-oled-stand' || it.kind === 'projector-screen'),
452
+ )
453
+ for (const tv of displays) {
454
+ const diagIn = safeNum(tv.node.screenDiagonalIn, 65)
455
+ const diagM = diagIn * 0.0254
456
+ const centerY = tv.y + tv.heightM / 2
457
+ if (tv.kind === 'tv-oled-wall' && centerY > 1.75) {
458
+ findings.push({
459
+ code: 'FRN-AV-01',
460
+ severity: 'warning',
461
+ category: 'av-acoustics',
462
+ nodeId: tv.node.id,
463
+ roomName: tv.roomName,
464
+ message: `${diagIn}" wall-mounted display center is ${round2(centerY)}m AFF (exceeds 1.75m ergonomic neck-angle limit).`,
465
+ recommendation: 'Mount TV center near seated eye level (1.05m–1.35m AFF) to prevent viewing strain.',
466
+ })
467
+ }
468
+ const roomSofas = sofas.filter((sf) => sf.roomName === tv.roomName && sameLevel(sf.levelId, tv.levelId))
469
+ if (roomSofas.length > 0) {
470
+ const distM = Math.min(...roomSofas.map((sf) => Math.hypot(sf.x - tv.x, sf.z - tv.z)))
471
+ const minView = diagM * 1.1
472
+ const maxView = diagM * 3.0
473
+ if (distM < minView) {
474
+ findings.push({
475
+ code: 'FRN-AV-01',
476
+ severity: 'warning',
477
+ category: 'av-acoustics',
478
+ nodeId: tv.node.id,
479
+ roomName: tv.roomName,
480
+ message: `Seating distance (${round2(distM)}m) is too close for a ${diagIn}" display (recommended >= ${round2(minView)}m).`,
481
+ recommendation: 'Increase viewing distance or downsize screen diagonal for comfortable 30°–40° FOV.',
482
+ })
483
+ } else if (distM > maxView) {
484
+ findings.push({
485
+ code: 'FRN-AV-01',
486
+ severity: 'info',
487
+ category: 'av-acoustics',
488
+ nodeId: tv.node.id,
489
+ roomName: tv.roomName,
490
+ message: `Seating distance (${round2(distM)}m) exceeds optimal 4K acuity range for a ${diagIn}" display (<= ${round2(maxView)}m).`,
491
+ recommendation: 'Consider upsizing the display or moving primary seating closer.',
492
+ })
493
+ }
494
+ }
495
+ }
496
+
497
+ // 5. FRN-AV-02: Stereo / 5.1 Left-Right speaker symmetry check (scoped by level + room)
498
+ const speakersByRoom = new Map<string, { roomName: string; left?: AuditedItem; right?: AuditedItem; display?: AuditedItem }>()
499
+ for (const it of items) {
500
+ if (it.node.type !== 'furnishings:electronics') continue
501
+ const role = String(it.node.channelRole ?? '')
502
+ const key = roomLevelKey(it.levelId, it.roomName)
503
+ const entry = speakersByRoom.get(key) ?? { roomName: it.roomName }
504
+ if (role === 'left') entry.left = it
505
+ if (role === 'right') entry.right = it
506
+ if (role === 'display') entry.display = it
507
+ speakersByRoom.set(key, entry)
508
+ }
509
+ for (const group of speakersByRoom.values()) {
510
+ const { roomName } = group
511
+ if ((group.left && !group.right) || (!group.left && group.right)) {
512
+ const present = (group.left ?? group.right)!
513
+ findings.push({
514
+ code: 'FRN-AV-02',
515
+ severity: 'warning',
516
+ category: 'av-acoustics',
517
+ nodeId: present.node.id,
518
+ roomName,
519
+ message: `Unpaired stereo channel in ${roomName} (only "${present.node.channelRole}" speaker placed).`,
520
+ recommendation: 'Place matching Left and Right main speakers symmetrically around the display.',
521
+ })
522
+ } else if (group.left && group.right && group.display) {
523
+ const dL = Math.hypot(group.left.x - group.display.x, group.left.z - group.display.z)
524
+ const dR = Math.hypot(group.right.x - group.display.x, group.right.z - group.display.z)
525
+ if (Math.abs(dL - dR) > 0.65) {
526
+ findings.push({
527
+ code: 'FRN-AV-02',
528
+ severity: 'info',
529
+ category: 'av-acoustics',
530
+ nodeId: group.left.node.id,
531
+ roomName,
532
+ message: `L/R speakers are asymmetric relative to the display (L=${round2(dL)}m vs R=${round2(dR)}m).`,
533
+ recommendation: 'Equalize L/R speaker spacing from the display center for balanced stereo imaging.',
534
+ })
535
+ }
536
+ }
537
+ }
538
+
539
+ // 6. FRN-ELC-01: Room plug-in electrical load aggregation & NEC 80% 15A branch circuit check (1440W, scoped by level + room)
540
+ const wattsByRoom = new Map<string, { roomName: string; watts: number; firstNodeId: string }>()
541
+ for (const it of items) {
542
+ if (it.wattageW <= 0 || it.isHardwiredLight) continue
543
+ const key = roomLevelKey(it.levelId, it.roomName)
544
+ const prev = wattsByRoom.get(key)
545
+ wattsByRoom.set(key, {
546
+ roomName: it.roomName,
547
+ watts: (prev?.watts ?? 0) + it.wattageW,
548
+ firstNodeId: prev?.firstNodeId ?? it.node.id,
549
+ })
550
+ }
551
+ for (const load of wattsByRoom.values()) {
552
+ if (load.watts > 1440) {
553
+ findings.push({
554
+ code: 'FRN-ELC-01',
555
+ severity: 'warning',
556
+ category: 'electrical',
557
+ nodeId: load.firstNodeId,
558
+ roomName: load.roomName,
559
+ message: `Combined plug-in AV/workstation load in ${load.roomName} is ${round2(load.watts)}W (${round2(load.watts / 120)}A), exceeding 80% continuous rating of a single 15A 120V circuit (1440W).`,
560
+ recommendation: 'Coordinate a dedicated 20A circuit or split workstation/AV loads across two branch circuits in krusch:electrical.',
561
+ })
562
+ }
563
+ }
564
+
565
+ // 7. FRN-ELC-02: Outlet proximity check if krusch:electrical receptacles are present in scene (plug-in items on same level only)
566
+ if (anatomy.outlets.length > 0) {
567
+ for (const it of items) {
568
+ if (it.wattageW < 50 || it.isHardwiredLight) continue
569
+ const matchingOutlets = anatomy.outlets.filter((o) =>
570
+ o.levelId && it.levelId ? o.levelId === it.levelId : Math.abs(o.y - it.y) <= 2.5,
571
+ )
572
+ if (matchingOutlets.length === 0) {
573
+ findings.push({
574
+ code: 'FRN-ELC-02',
575
+ severity: 'info',
576
+ category: 'electrical',
577
+ nodeId: it.node.id,
578
+ roomName: it.roomName,
579
+ message: `"${it.label}" (${it.wattageW}W) has no electrical receptacle on the same level.`,
580
+ recommendation: 'Add a duplex or recessed media receptacle within 1.8m (6 ft) in krusch:electrical.',
581
+ })
582
+ continue
583
+ }
584
+ const minOutletM = Math.min(...matchingOutlets.map((o) => Math.hypot(o.x - it.x, o.z - it.z)))
585
+ if (minOutletM > 2.4) {
586
+ findings.push({
587
+ code: 'FRN-ELC-02',
588
+ severity: 'info',
589
+ category: 'electrical',
590
+ nodeId: it.node.id,
591
+ roomName: it.roomName,
592
+ message: `"${it.label}" (${it.wattageW}W) is ${round2(minOutletM)}m from the nearest electrical receptacle (> 2.4m standard cord reach).`,
593
+ recommendation: 'Add a duplex or recessed media receptacle within 1.8m (6 ft) in krusch:electrical.',
594
+ })
595
+ }
596
+ }
597
+ }
598
+
599
+ // 8. FRN-BOT-01 & FRN-BOT-02: Botanical foundation root clearance & indoor/outdoor species checks (level-scoped)
600
+ const plantItems = items.filter((it) => it.node.type === 'furnishings:plant')
601
+ for (const pl of plantItems) {
602
+ const levelRooms = pl.levelId
603
+ ? anatomy.rooms.filter((r) => !r.levelId || r.levelId === pl.levelId)
604
+ : anatomy.rooms
605
+ const insideRoom = findContainingRoom(pl.x, pl.z, levelRooms)
606
+ const canonWalls = getCanonicalLevelWalls(pl.levelId)
607
+ const unzonedOutdoor = !insideRoom && isUnzonedOutdoor(pl.x, pl.z, pl.levelId)
608
+ const unzonedIndoor =
609
+ !insideRoom && canonWalls.length >= 3 && !unzonedOutdoor && isPointEnclosedByWalls(pl.x, pl.z, canonWalls)
610
+ if (pl.outdoorOnly && ((insideRoom && !insideRoom.isOutdoor) || unzonedIndoor)) {
611
+ const targetRoomName = insideRoom?.name ?? pl.roomName
612
+ findings.push({
613
+ code: 'FRN-BOT-02',
614
+ severity: 'error',
615
+ category: 'botanical',
616
+ nodeId: pl.node.id,
617
+ roomName: targetRoomName,
618
+ message: `Outdoor landscape species "${pl.label}" is placed inside enclosed interior room "${targetRoomName}".`,
619
+ recommendation: 'Move outside to the yard/patio or swap to a potted indoor houseplant (Fiddle-Leaf Fig, Monstera, Snake Plant).',
620
+ })
621
+ } else if (pl.indoorOnly && (insideRoom?.isOutdoor || unzonedOutdoor)) {
622
+ const targetZoneName = insideRoom?.name ?? pl.roomName
623
+ findings.push({
624
+ code: 'FRN-BOT-02',
625
+ severity: 'warning',
626
+ category: 'botanical',
627
+ nodeId: pl.node.id,
628
+ roomName: targetZoneName,
629
+ message: insideRoom
630
+ ? `Indoor houseplant "${pl.label}" is placed in outdoor zone "${insideRoom.name}".`
631
+ : `Indoor houseplant "${pl.label}" is placed outdoors outside the enclosed building envelope.`,
632
+ recommendation: 'Relocate tropical houseplants indoors or swap to an outdoor-hardy shrub or planter.',
633
+ })
634
+ } else if (pl.minFoundationClearanceM > 0 && anatomy.walls.length > 0 && (!insideRoom || insideRoom.isOutdoor)) {
635
+ const levelWalls = pl.levelId
636
+ ? anatomy.walls.filter((w) => !w.levelId || w.levelId === pl.levelId)
637
+ : anatomy.walls
638
+ const distM = minDistanceToExteriorWallM(pl.x, pl.z, levelWalls.length > 0 ? levelWalls : anatomy.walls)
639
+ if (distM < pl.minFoundationClearanceM - 0.05) {
640
+ findings.push({
641
+ code: 'FRN-BOT-01',
642
+ severity: pl.minFoundationClearanceM >= 2.5 ? 'error' : 'warning',
643
+ category: 'botanical',
644
+ nodeId: pl.node.id,
645
+ roomName: pl.roomName,
646
+ message: `"${pl.label}" is ${round2(distM)}m from the exterior wall/foundation (minimum ${pl.minFoundationClearanceM}m required for root & canopy clearance).`,
647
+ recommendation: `Relocate at least ${pl.minFoundationClearanceM}m from foundation walls and roof eaves.`,
648
+ })
649
+ }
650
+ }
651
+ }
652
+
653
+ // 9. FRN-BOT-03: Tree trunk & canopy crowding check (same level only)
654
+ const trees = plantItems.filter((p) => p.kind.startsWith('tree-'))
655
+ for (let i = 0; i < trees.length; i++) {
656
+ for (let j = i + 1; j < trees.length; j++) {
657
+ const a = trees[i]!
658
+ const b = trees[j]!
659
+ if (!sameLevel(a.levelId, b.levelId)) continue
660
+ const dist = Math.hypot(a.x - b.x, a.z - b.z)
661
+ const minSpacing = (a.widthM + b.widthM) * 0.35
662
+ if (dist < minSpacing) {
663
+ findings.push({
664
+ code: 'FRN-BOT-03',
665
+ severity: 'warning',
666
+ category: 'botanical',
667
+ nodeId: a.node.id,
668
+ relatedNodeId: b.node.id,
669
+ roomName: a.roomName,
670
+ message: `Tree "${a.label}" and "${b.label}" are crowded (${round2(dist)}m apart; recommended >= ${round2(minSpacing)}m).`,
671
+ recommendation: 'Increase spacing so mature canopies receive sunlight and airflow.',
672
+ })
673
+ }
674
+ }
675
+ }
676
+
677
+ // 10. FRN-ROOM-01: Sleep furniture must never be placed in non-sleeping wet/service rooms (bathroom, closet, kitchen, laundry, garage, hallway)
678
+ const NON_SLEEP_ROOM_KINDS = new Set(['bathroom', 'closet', 'kitchen', 'laundry', 'garage', 'hallway'])
679
+ for (const it of items) {
680
+ if (!it.kind.startsWith('bed-') && it.kind !== 'bunk-bed') continue
681
+ const levelRooms = it.levelId
682
+ ? anatomy.rooms.filter((r) => !r.levelId || r.levelId === it.levelId)
683
+ : anatomy.rooms
684
+ const containing = findContainingRoom(it.x, it.z, levelRooms)
685
+ if (containing && NON_SLEEP_ROOM_KINDS.has(containing.kind)) {
686
+ findings.push({
687
+ code: 'FRN-ROOM-01',
688
+ severity: 'error',
689
+ category: 'ergonomics',
690
+ nodeId: it.node.id,
691
+ roomName: containing.name,
692
+ message: `Bed "${it.label}" is placed inside non-bedroom "${containing.name}" (classified as ${containing.kind}).`,
693
+ recommendation: 'Remove sleep furniture from wet/service/closet spaces or verify the room zone classification.',
694
+ })
695
+ }
696
+ }
697
+
698
+ const errorCount = findings.filter((f) => f.severity === 'error').length
699
+ const warningCount = findings.filter((f) => f.severity === 'warning').length
700
+ const infoCount = findings.filter((f) => f.severity === 'info').length
701
+
702
+ return {
703
+ passed: errorCount === 0,
704
+ errorCount,
705
+ warningCount,
706
+ infoCount,
707
+ totalItemsAudited: items.length,
708
+ totalElectricalDemandW,
709
+ findings,
710
+ }
711
+ }