@kruschdev/pascal-plugin-plumbing 0.0.0-stage → 0.3.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,843 @@
1
+ /**
2
+ * Pure TypeScript interoperability helpers for:
3
+ * 1. Pascal's `@pascal-app/plugin-bones` (`bones:framing` and `bones:service` nodes)
4
+ * 2. Cross-trade electrical power coordination (`electricalDemand` contract shared with
5
+ * `@kruschdev/pascal-plugin-electrical` and future `@kruschdev/pascal-plugin-hvac`)
6
+ *
7
+ * Framework-free: zero React, Three.js, or `@pascal-app/*` imports.
8
+ */
9
+
10
+ import {
11
+ belongsToLevel as kernelBelongsToLevel,
12
+ getLowerWalledLevelIds as kernelGetLowerWalledLevelIds,
13
+ isGroundOrLowestWalledLevel as kernelIsGroundOrLowestWalledLevel,
14
+ resolveNodeLevelId as kernelResolveNodeLevelId,
15
+ } from '@kruschdev/pascal-mep-kernel'
16
+ import { IPC_RULE_THRESHOLDS } from './rules'
17
+ import {
18
+ type EquipmentKind,
19
+ type FixtureKind,
20
+ INCHES_TO_METERS,
21
+ METERS_TO_INCHES,
22
+ type PipeMaterial,
23
+ type PipeNominalSize,
24
+ getPipeOuterDiameterM,
25
+ } from './tables'
26
+
27
+ export type Vec3 = readonly [number, number, number]
28
+
29
+ export type SceneNodeLike = {
30
+ id: string
31
+ type: string
32
+ name?: string
33
+ parentId?: string | null
34
+ position?: readonly [number, number, number]
35
+ rotation?: number | readonly [number, number, number]
36
+ start?: readonly [number, number]
37
+ end?: readonly [number, number]
38
+ height?: number
39
+ thickness?: number
40
+ width?: number
41
+ depth?: number
42
+ polygon?: ReadonlyArray<readonly [number, number]>
43
+ path?: ReadonlyArray<readonly [number, number, number]>
44
+ children?: readonly string[]
45
+ [key: string]: unknown
46
+ }
47
+
48
+ /**
49
+ * Standardized cross-trade electrical power demand payload published by powered
50
+ * plumbing (and future HVAC) equipment/fixture nodes so `@kruschdev/pascal-plugin-electrical`
51
+ * can automatically allocate breakers, panel schedules, NEC 220 loads, and 3D power runs
52
+ * with zero hard package dependency.
53
+ */
54
+ export type ElectricalPowerDemand = {
55
+ required: boolean
56
+ voltage: 120 | 208 | 240 | 480
57
+ poles: 1 | 2 | 3
58
+ breakerAmps: number
59
+ loadVa: number
60
+ continuous: boolean
61
+ dedicatedCircuit: boolean
62
+ gfciRequired: boolean
63
+ afciRequired: boolean
64
+ loadCategory: 'fixed' | 'appliance' | 'motor' | 'hvac-heating' | 'hvac-cooling' | 'heat-pump'
65
+ label: string
66
+ }
67
+
68
+ const NEC_STANDARD_BREAKERS = [
69
+ 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100, 125, 150, 175, 200, 225, 250, 300, 350, 400,
70
+ ] as const
71
+
72
+ /**
73
+ * Compute minimum NEC 240.6(A) standard breaker rating for a continuous water-heating/equipment load
74
+ * per NEC 422.11(E) / 422.13 (125% of nameplate current).
75
+ */
76
+ export function standardNec240BreakerAmps(watts: number, voltage = 240): number {
77
+ const minAmps = (Math.max(100, watts) / voltage) * 1.25
78
+ for (const std of NEC_STANDARD_BREAKERS) {
79
+ if (std >= minAmps) return std
80
+ }
81
+ return Math.ceil(minAmps / 50) * 50
82
+ }
83
+
84
+ /**
85
+ * Default NEC-compliant electrical power demands for powered plumbing equipment.
86
+ */
87
+ export function getEquipmentElectricalDemand(
88
+ kind: EquipmentKind,
89
+ customWatts?: number,
90
+ ): ElectricalPowerDemand | null {
91
+ switch (kind) {
92
+ case 'water-heater-tank-electric': {
93
+ const watts = customWatts && customWatts > 0 ? customWatts : 4500
94
+ const amps = Math.max(30, standardNec240BreakerAmps(watts, 240))
95
+ return {
96
+ required: true,
97
+ voltage: 240,
98
+ poles: 2,
99
+ breakerAmps: amps,
100
+ loadVa: watts,
101
+ continuous: true,
102
+ dedicatedCircuit: true,
103
+ gfciRequired: false,
104
+ afciRequired: false,
105
+ loadCategory: 'fixed',
106
+ label: `Electric Water Heater (${(watts / 1000).toFixed(1)} kW)`,
107
+ }
108
+ }
109
+ case 'water-heater-hpwh': {
110
+ const watts = customWatts && customWatts > 0 ? customWatts : 4500
111
+ const amps = Math.max(30, standardNec240BreakerAmps(watts, 240))
112
+ return {
113
+ required: true,
114
+ voltage: 240,
115
+ poles: 2,
116
+ breakerAmps: amps,
117
+ loadVa: watts,
118
+ continuous: true,
119
+ dedicatedCircuit: true,
120
+ gfciRequired: false,
121
+ afciRequired: false,
122
+ loadCategory: 'fixed',
123
+ label: 'Heat Pump Water Heater (Hybrid)',
124
+ }
125
+ }
126
+ case 'water-heater-tankless-gas': {
127
+ const watts = customWatts && customWatts > 0 ? customWatts : 300
128
+ const amps = Math.max(15, standardNec240BreakerAmps(watts, 120))
129
+ return {
130
+ required: true,
131
+ voltage: 120,
132
+ poles: 1,
133
+ breakerAmps: amps,
134
+ loadVa: watts,
135
+ continuous: false,
136
+ dedicatedCircuit: false,
137
+ gfciRequired: true,
138
+ afciRequired: false,
139
+ loadCategory: 'appliance',
140
+ label: 'Tankless Gas WH Ignition / Blower',
141
+ }
142
+ }
143
+ case 'sump-pump': {
144
+ const watts = customWatts && customWatts > 0 ? customWatts : 1200
145
+ const amps = Math.max(20, standardNec240BreakerAmps(watts, 120))
146
+ return {
147
+ required: true,
148
+ voltage: 120,
149
+ poles: 1,
150
+ breakerAmps: amps,
151
+ loadVa: watts,
152
+ continuous: false,
153
+ dedicatedCircuit: true,
154
+ gfciRequired: true,
155
+ afciRequired: false,
156
+ loadCategory: 'motor',
157
+ label: 'Sump Pump (Dedicated GFCI)',
158
+ }
159
+ }
160
+ case 'sewage-ejector': {
161
+ const watts = customWatts && customWatts > 0 ? customWatts : 1440
162
+ const amps = Math.max(20, standardNec240BreakerAmps(watts, 120))
163
+ return {
164
+ required: true,
165
+ voltage: 120,
166
+ poles: 1,
167
+ breakerAmps: amps,
168
+ loadVa: watts,
169
+ continuous: false,
170
+ dedicatedCircuit: true,
171
+ gfciRequired: true,
172
+ afciRequired: false,
173
+ loadCategory: 'motor',
174
+ label: 'Sewage Ejector Pump (Dedicated GFCI)',
175
+ }
176
+ }
177
+ case 'recirc-pump': {
178
+ const watts = customWatts && customWatts > 0 ? customWatts : 180
179
+ const amps = Math.max(15, standardNec240BreakerAmps(watts, 120))
180
+ return {
181
+ required: true,
182
+ voltage: 120,
183
+ poles: 1,
184
+ breakerAmps: amps,
185
+ loadVa: watts,
186
+ continuous: true,
187
+ dedicatedCircuit: false,
188
+ gfciRequired: true,
189
+ afciRequired: false,
190
+ loadCategory: 'motor',
191
+ label: 'Hot Water Recirculation Pump',
192
+ }
193
+ }
194
+ case 'water-softener': {
195
+ const watts = customWatts && customWatts > 0 ? customWatts : 150
196
+ const amps = Math.max(15, standardNec240BreakerAmps(watts, 120))
197
+ return {
198
+ required: true,
199
+ voltage: 120,
200
+ poles: 1,
201
+ breakerAmps: amps,
202
+ loadVa: watts,
203
+ continuous: false,
204
+ dedicatedCircuit: false,
205
+ gfciRequired: true,
206
+ afciRequired: false,
207
+ loadCategory: 'appliance',
208
+ label: 'Water Softener Control Head',
209
+ }
210
+ }
211
+ default:
212
+ return null
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Default NEC-compliant electrical power demands for powered plumbing fixtures.
218
+ */
219
+ export function getFixtureElectricalDemand(kind: FixtureKind): ElectricalPowerDemand | null {
220
+ switch (kind) {
221
+ case 'dishwasher':
222
+ return {
223
+ required: true,
224
+ voltage: 120,
225
+ poles: 1,
226
+ breakerAmps: 20,
227
+ loadVa: 1500,
228
+ continuous: false,
229
+ dedicatedCircuit: true,
230
+ gfciRequired: true,
231
+ afciRequired: true,
232
+ loadCategory: 'appliance',
233
+ label: 'Dishwasher (NEC 210.8(D) GFCI)',
234
+ }
235
+ case 'garbage-disposal':
236
+ return {
237
+ required: true,
238
+ voltage: 120,
239
+ poles: 1,
240
+ breakerAmps: 20,
241
+ loadVa: 1000,
242
+ continuous: false,
243
+ dedicatedCircuit: true,
244
+ gfciRequired: true,
245
+ afciRequired: true,
246
+ loadCategory: 'appliance',
247
+ label: 'Garbage Disposal (3/4 HP)',
248
+ }
249
+ case 'clothes-washer':
250
+ return {
251
+ required: true,
252
+ voltage: 120,
253
+ poles: 1,
254
+ breakerAmps: 20,
255
+ loadVa: 1500,
256
+ continuous: false,
257
+ dedicatedCircuit: true,
258
+ gfciRequired: true,
259
+ afciRequired: true,
260
+ loadCategory: 'appliance',
261
+ label: 'Laundry Washer Branch (NEC 210.11(C)(2))',
262
+ }
263
+ case 'bidet':
264
+ return {
265
+ required: true,
266
+ voltage: 120,
267
+ poles: 1,
268
+ breakerAmps: 15,
269
+ loadVa: 1200,
270
+ continuous: false,
271
+ dedicatedCircuit: true, // NEC 210.23(B)(2): 1200 VA > 50% of 15A branch rating
272
+ gfciRequired: true,
273
+ afciRequired: false,
274
+ loadCategory: 'appliance',
275
+ label: 'Heated Bidet Seat (Dedicated GFCI)',
276
+ }
277
+ default:
278
+ return null
279
+ }
280
+ }
281
+
282
+ export type BonesWallConstruction = 'framed' | 'lgs' | 'cmu' | 'skip'
283
+
284
+ export type BonesWallRule = {
285
+ construction: BonesWallConstruction
286
+ spacingIn: 12 | 16 | 24
287
+ studThicknessM: number
288
+ /** Per-wall stud cavity depth in inches from `structural:assembly.wallOverrides[id].studSize` (`5.5` for 2x6, `3.5` for 2x4). */
289
+ studDepthIn?: number
290
+ isLoadBearing?: boolean
291
+ isWetWall?: boolean
292
+ }
293
+
294
+ export type BonesPlumbingServiceType = 'water-heater' | 'water-entry' | 'sewer-exit'
295
+
296
+ export type BonesPlumbingServiceAnchor = {
297
+ nodeId: string
298
+ serviceType: BonesPlumbingServiceType
299
+ wallId?: string
300
+ wallT?: number
301
+ heightAff?: number
302
+ position?: Vec3
303
+ }
304
+
305
+ export type BonesPlumbingContext = {
306
+ framingPresent: boolean
307
+ /** Authoritative source of framing rules (`structural` takes Priority #1 over `bones`). */
308
+ source?: 'structural' | 'bones' | 'default'
309
+ defaultSpacingIn: 12 | 16 | 24
310
+ /** Authoritative stud cavity depth in inches from Priority #1 `structural:assembly` (`5.5` for 2x6, `3.5` for 2x4). */
311
+ defaultStudDepthIn?: number
312
+ framingSystem: 'lumber' | 'lgs'
313
+ floorSystem?: 'dimensional' | 'tji-ijoist' | 'open-web-truss' | 'slab-on-grade'
314
+ wallRules: ReadonlyMap<string, BonesWallRule>
315
+ waterHeaterAnchor: BonesPlumbingServiceAnchor | null
316
+ waterEntryAnchor: BonesPlumbingServiceAnchor | null
317
+ sewerExitAnchor: BonesPlumbingServiceAnchor | null
318
+ hasPlumbingSchematic: boolean
319
+ }
320
+
321
+ export const DRESSED_STUD_THICKNESS_M = 1.5 * INCHES_TO_METERS
322
+ /** Standard 2x4 cavity depth = 3.5" (0.0889 m); finished 2x4 wall = ~4.5" (0.114 m). */
323
+ export const WALL_2X4_MAX_THICKNESS_M = IPC_RULE_THRESHOLDS.wetWallMax2x4ThicknessM
324
+ /** Standard 2x6 cavity depth = 5.5" (0.1397 m); finished 2x6 wall = ~6.5" (0.165 m). */
325
+ export const WALL_2X6_MIN_THICKNESS_M = IPC_RULE_THRESHOLDS.wetWallMinThicknessM
326
+
327
+ export function belongsToLevel(
328
+ nodes: Readonly<Record<string, SceneNodeLike>>,
329
+ node: SceneNodeLike,
330
+ levelId: string | null,
331
+ ): boolean {
332
+ return kernelBelongsToLevel(nodes, node, levelId)
333
+ }
334
+
335
+ export function resolveNodeLevelId(
336
+ nodes: Readonly<Record<string, SceneNodeLike>>,
337
+ node: SceneNodeLike,
338
+ ): string | null {
339
+ return kernelResolveNodeLevelId(nodes, node)
340
+ }
341
+
342
+ /**
343
+ * Return the IDs of all lower walled sibling levels in the same building as `levelId`,
344
+ * sorted from lowest to highest story. Returns an empty array when `levelId` is null/missing
345
+ * or is already the lowest walled level in its building.
346
+ */
347
+ export function getLowerWalledLevelIds(
348
+ nodes: Readonly<Record<string, SceneNodeLike>>,
349
+ levelId: string | null | undefined,
350
+ ): string[] {
351
+ return kernelGetLowerWalledLevelIds(nodes, levelId)
352
+ }
353
+
354
+ /**
355
+ * Returns `true` if `levelId` is null/missing, has no lower walled sibling levels in the same
356
+ * building, or is the lowest walled level in its building. Returns `false` for upper stories
357
+ * (e.g. Floor 1 / Floor 2) when a lower walled ground story exists in the same building.
358
+ */
359
+ export function isGroundOrLowestWalledLevel(
360
+ nodes: Readonly<Record<string, SceneNodeLike>>,
361
+ levelId: string | null | undefined,
362
+ ): boolean {
363
+ return kernelIsGroundOrLowestWalledLevel(nodes, levelId)
364
+ }
365
+
366
+ const bonesContextCache = new WeakMap<
367
+ Readonly<Record<string, SceneNodeLike>>,
368
+ Map<string, BonesPlumbingContext>
369
+ >()
370
+
371
+ /**
372
+ * Extract `@pascal-app/plugin-bones` framing rules and authoritative `bones:service` plumbing anchors
373
+ * (`water-heater`, `water-entry`, `sewer-exit`) for a level. WeakMap-memoized per scene nodes object.
374
+ */
375
+ export function extractBonesPlumbingContext(
376
+ nodes: Readonly<Record<string, SceneNodeLike>>,
377
+ levelId: string | null = null,
378
+ ): BonesPlumbingContext {
379
+ const key = levelId ?? '__all__'
380
+ let byLevel = bonesContextCache.get(nodes)
381
+ if (!byLevel) {
382
+ byLevel = new Map()
383
+ bonesContextCache.set(nodes, byLevel)
384
+ }
385
+ const cached = byLevel.get(key)
386
+ if (cached) return cached
387
+
388
+ const all = Object.values(nodes)
389
+ // Priority #1: Dedicated `@kruschdev/pascal-plugin-structural` (`structural:assembly`) takes precedence over `bones:framing`.
390
+ const structuralNode = all.find(
391
+ (n) => n.type === 'structural:assembly' && belongsToLevel(nodes, n, levelId),
392
+ )
393
+ const bonesNode = all.find(
394
+ (n) => n.type === 'bones:framing' && belongsToLevel(nodes, n, levelId),
395
+ )
396
+ const framingNode = structuralNode ?? bonesNode
397
+ const source: 'structural' | 'bones' | 'default' = structuralNode
398
+ ? 'structural'
399
+ : bonesNode
400
+ ? 'bones'
401
+ : 'default'
402
+
403
+ const defaultSpacingIn: 12 | 16 | 24 =
404
+ framingNode?.studSpacingIn === 12
405
+ ? 12
406
+ : framingNode?.studSpacingIn === 24
407
+ ? 24
408
+ : 16
409
+ const defaultStudDepthIn: number | undefined =
410
+ structuralNode?.studSize === '2x6'
411
+ ? 5.5
412
+ : structuralNode?.studSize === '2x4'
413
+ ? 3.5
414
+ : undefined
415
+ const framingSystem: 'lumber' | 'lgs' = framingNode?.framingSystem === 'lgs' ? 'lgs' : 'lumber'
416
+ const floorSystem =
417
+ structuralNode?.floorSystem === 'tji-ijoist' ||
418
+ structuralNode?.floorSystem === 'open-web-truss' ||
419
+ structuralNode?.floorSystem === 'dimensional' ||
420
+ structuralNode?.floorSystem === 'slab-on-grade'
421
+ ? structuralNode.floorSystem
422
+ : undefined
423
+ const wallRules = new Map<string, BonesWallRule>()
424
+
425
+ const defaultConstruction: BonesWallConstruction = framingSystem === 'lgs' ? 'lgs' : 'framed'
426
+ const applyOverrides = (rawOverrides: unknown) => {
427
+ if (!rawOverrides || typeof rawOverrides !== 'object') return
428
+ for (const [wallId, rawRule] of Object.entries(rawOverrides as Record<string, unknown>)) {
429
+ if (typeof rawRule === 'string') {
430
+ const construction: BonesWallConstruction =
431
+ rawRule === 'lgs' || rawRule === 'cmu' || rawRule === 'skip'
432
+ ? rawRule
433
+ : rawRule === 'framed'
434
+ ? 'framed'
435
+ : defaultConstruction
436
+ wallRules.set(wallId, {
437
+ construction,
438
+ spacingIn: defaultSpacingIn,
439
+ studThicknessM: DRESSED_STUD_THICKNESS_M,
440
+ isLoadBearing: rawRule === 'shear-wall',
441
+ isWetWall: false,
442
+ })
443
+ continue
444
+ }
445
+ if (!rawRule || typeof rawRule !== 'object') continue
446
+ const r = rawRule as Record<string, unknown>
447
+ const prev = wallRules.get(wallId)
448
+ const construction: BonesWallConstruction =
449
+ r.construction === 'lgs' || r.construction === 'cmu' || r.construction === 'skip'
450
+ ? r.construction
451
+ : r.construction === 'framed'
452
+ ? 'framed'
453
+ : (prev?.construction ?? defaultConstruction)
454
+ const rawSpacing = r.studSpacingIn ?? r.spacingIn
455
+ const spacingIn: 12 | 16 | 24 =
456
+ rawSpacing === 12
457
+ ? 12
458
+ : rawSpacing === 16
459
+ ? 16
460
+ : rawSpacing === 24
461
+ ? 24
462
+ : (prev?.spacingIn ?? defaultSpacingIn)
463
+ const studDepthIn: number | undefined =
464
+ r.studSize === '2x6' ? 5.5 : r.studSize === '2x4' ? 3.5 : prev?.studDepthIn
465
+ wallRules.set(wallId, {
466
+ construction,
467
+ spacingIn,
468
+ studThicknessM: DRESSED_STUD_THICKNESS_M,
469
+ ...(typeof studDepthIn === 'number' ? { studDepthIn } : {}),
470
+ isLoadBearing:
471
+ r.isLoadBearing !== undefined || r.isShearWall !== undefined || r.construction === 'shear-wall'
472
+ ? Boolean(r.isLoadBearing || r.isShearWall || r.construction === 'shear-wall')
473
+ : Boolean(prev?.isLoadBearing),
474
+ isWetWall: r.isWetWall !== undefined ? Boolean(r.isWetWall) : Boolean(prev?.isWetWall),
475
+ })
476
+ }
477
+ }
478
+ // Seed per-wall Bones overrides first, then layer Priority #1 Structural overrides on top
479
+ applyOverrides(bonesNode?.wallOverrides)
480
+ applyOverrides(structuralNode?.wallOverrides)
481
+
482
+ let waterHeaterAnchor: BonesPlumbingServiceAnchor | null = null
483
+ let waterEntryAnchor: BonesPlumbingServiceAnchor | null = null
484
+ let sewerExitAnchor: BonesPlumbingServiceAnchor | null = null
485
+
486
+ for (const n of all) {
487
+ if (n.type !== 'bones:service' || !belongsToLevel(nodes, n, levelId)) continue
488
+ const st = n.serviceType
489
+ if (st !== 'water-heater' && st !== 'water-entry' && st !== 'sewer-exit') continue
490
+ const rawPos = Array.isArray(n.position) && n.position.length >= 3
491
+ ? ([Number(n.position[0]), Number(n.position[1]), Number(n.position[2])] as Vec3)
492
+ : undefined
493
+ const pos =
494
+ rawPos &&
495
+ Number.isFinite(rawPos[0]) &&
496
+ Number.isFinite(rawPos[1]) &&
497
+ Number.isFinite(rawPos[2])
498
+ ? rawPos
499
+ : undefined
500
+ const anchor: BonesPlumbingServiceAnchor = {
501
+ nodeId: n.id,
502
+ serviceType: st,
503
+ wallId: typeof n.wallId === 'string' ? n.wallId : undefined,
504
+ wallT: typeof n.wallT === 'number' ? n.wallT : undefined,
505
+ heightAff: typeof n.heightAff === 'number' ? n.heightAff : undefined,
506
+ position: pos,
507
+ }
508
+ if (st === 'water-heater' && !waterHeaterAnchor) waterHeaterAnchor = anchor
509
+ if (st === 'water-entry' && !waterEntryAnchor) waterEntryAnchor = anchor
510
+ if (st === 'sewer-exit' && !sewerExitAnchor) sewerExitAnchor = anchor
511
+ }
512
+
513
+ const ctx: BonesPlumbingContext = {
514
+ framingPresent: Boolean(framingNode),
515
+ source,
516
+ defaultSpacingIn,
517
+ defaultStudDepthIn,
518
+ framingSystem,
519
+ floorSystem,
520
+ wallRules,
521
+ waterHeaterAnchor,
522
+ waterEntryAnchor,
523
+ sewerExitAnchor,
524
+ hasPlumbingSchematic: Boolean(waterHeaterAnchor || waterEntryAnchor || sewerExitAnchor),
525
+ }
526
+ byLevel.set(key, ctx)
527
+ return ctx
528
+ }
529
+
530
+ /**
531
+ * Resolve effective wall thickness (m) honoring per-wall `structural:assembly` `wallOverrides[id].studSize`
532
+ * first (without inflating a `2x4` interior partition to a global `2x6` default), falling back to global
533
+ * `defaultStudDepthIn` when no per-wall override is present.
534
+ */
535
+ export function resolveEffectiveWallThicknessM(
536
+ wallThicknessM: number,
537
+ bonesContext?: BonesPlumbingContext | null,
538
+ wallRule?: BonesWallRule,
539
+ ): number {
540
+ if (typeof wallRule?.studDepthIn === 'number') {
541
+ return wallRule.studDepthIn * INCHES_TO_METERS + INCHES_TO_METERS
542
+ }
543
+ if (bonesContext?.source === 'structural' && typeof bonesContext.defaultStudDepthIn === 'number') {
544
+ return Math.max(wallThicknessM, bonesContext.defaultStudDepthIn * INCHES_TO_METERS + INCHES_TO_METERS)
545
+ }
546
+ return wallThicknessM
547
+ }
548
+
549
+ /**
550
+ * IRC R602.6 / IPC wet-wall cavity check:
551
+ * - A 3" or 4" PVC/ABS DWV pipe (3.5" / 4.5" OD + hub) cannot fit inside a 2x4 stud wall (3.5" cavity).
552
+ * - Boring through load-bearing studs is limited to 40% of stud depth (60% non-load-bearing), measured on drilled hole diameter.
553
+ * - Steel nail shield plates are required when the edge of the bored hole is < 1-1/4" (1.25") from the stud face (IRC R602.6 / IPC 305.6).
554
+ */
555
+ export function checkWetWallPipeFit(params: {
556
+ wallThicknessM: number
557
+ pipeSize: PipeNominalSize
558
+ material: PipeMaterial
559
+ isLoadBearing?: boolean
560
+ isHorizontalBore?: boolean
561
+ }): {
562
+ fits: boolean
563
+ needs2x6WetWall: boolean
564
+ needsNailPlate: boolean
565
+ borePctOfStud: number
566
+ codeRef: string
567
+ reason?: string
568
+ } {
569
+ const {
570
+ wallThicknessM,
571
+ pipeSize,
572
+ material,
573
+ isLoadBearing = false,
574
+ isHorizontalBore = false,
575
+ } = params
576
+ // Approximate stud cavity depth = wallThickness - 1" total drywall (0.0254 m)
577
+ const cavityDepthM = Math.max(0.0889, wallThicknessM - 0.0254)
578
+ const pipeOdM = getPipeOuterDiameterM(pipeSize, material)
579
+ const boreM = recommendHoleSawIn(pipeSize, material) * INCHES_TO_METERS
580
+ const hubAllowanceM = material === 'pvc-dwv' || material === 'abs-dwv' || material === 'cast-iron' ? 0.014 : 0
581
+ const requiredCavityM = pipeOdM + hubAllowanceM
582
+ const borePct = Math.round(((isHorizontalBore ? boreM : pipeOdM) / cavityDepthM) * 100)
583
+ const maxBorePct = isLoadBearing ? 40 : 60
584
+ const needsNailPlate = (cavityDepthM - boreM) / 2 < 1.25 * INCHES_TO_METERS
585
+
586
+ if (requiredCavityM > cavityDepthM + 0.002) {
587
+ return {
588
+ fits: false,
589
+ needs2x6WetWall: true,
590
+ needsNailPlate: true,
591
+ borePctOfStud: borePct,
592
+ codeRef: 'IRC R602.6 / Wet Wall',
593
+ reason: `${pipeSize} ${material.toUpperCase()} (${(requiredCavityM * METERS_TO_INCHES).toFixed(2)}" w/ hub) exceeds ${(cavityDepthM * METERS_TO_INCHES).toFixed(1)}" stud cavity; upgrade to 2x6 wet wall (5.5" cavity) or pipe chase.`,
594
+ }
595
+ }
596
+
597
+ if (isHorizontalBore && borePct > maxBorePct) {
598
+ return {
599
+ fits: false,
600
+ needs2x6WetWall: cavityDepthM < 0.13,
601
+ needsNailPlate,
602
+ borePctOfStud: borePct,
603
+ codeRef: 'IRC R602.6',
604
+ reason: `Horizontal bore (${(boreM / INCHES_TO_METERS).toFixed(2)}" hole = ${borePct}% of stud depth) exceeds ${maxBorePct}% ${isLoadBearing ? 'load-bearing' : 'non-load-bearing'} limit.`,
605
+ }
606
+ }
607
+
608
+ return {
609
+ fits: true,
610
+ needs2x6WetWall: false,
611
+ needsNailPlate,
612
+ borePctOfStud: borePct,
613
+ codeRef: 'IRC R602.6',
614
+ }
615
+ }
616
+
617
+ /**
618
+ * Resolve a `bones:service` anchor into level-local 3D coordinates using wall geometry when wall-anchored.
619
+ */
620
+ export function resolveBonesAnchorPosition(
621
+ nodes: Readonly<Record<string, SceneNodeLike>>,
622
+ anchor: BonesPlumbingServiceAnchor,
623
+ fallbackY = 0,
624
+ ): Vec3 | null {
625
+ const pos = anchor.position
626
+ const hasExplicitPos =
627
+ pos && (Math.abs(pos[0]) > 1e-4 || Math.abs(pos[1]) > 1e-4 || Math.abs(pos[2]) > 1e-4)
628
+ if (hasExplicitPos) {
629
+ return pos
630
+ }
631
+ if (anchor.wallId && nodes[anchor.wallId]) {
632
+ const w = nodes[anchor.wallId]!
633
+ if (Array.isArray(w.start) && Array.isArray(w.end)) {
634
+ const t = typeof anchor.wallT === 'number' ? Math.max(0.05, Math.min(0.95, anchor.wallT)) : 0.5
635
+ const x = w.start[0] + (w.end[0] - w.start[0]) * t
636
+ const z = w.start[1] + (w.end[1] - w.start[1]) * t
637
+ const y = typeof anchor.heightAff === 'number' ? anchor.heightAff : fallbackY
638
+ return [x, y, z]
639
+ }
640
+ }
641
+ return pos ?? null
642
+ }
643
+
644
+ export type FramingMemberKind = 'stud' | 'sole-plate' | 'top-plate' | 'floor-joist'
645
+
646
+ export type FramingPenetration = {
647
+ id: string
648
+ pipeRunId: string
649
+ wallId?: string
650
+ memberKind: FramingMemberKind
651
+ memberLabel: string
652
+ position: Vec3
653
+ /** Direction vector along the pipe at penetration (unit vector). */
654
+ pipeDirection: Vec3
655
+ /** Unit normal `[nx, nz]` perpendicular to the penetrated wall plane for nail-plate orientation. */
656
+ wallNormal: readonly [number, number]
657
+ /** Nominal stud cavity depth (m) for accurate front/back nail-plate surface offset. */
658
+ studDepthM: number
659
+ pipeSize: PipeNominalSize
660
+ material: PipeMaterial
661
+ /** Recommended drill bit / hole-saw diameter in inches (OD + 1/4" clearance, rounded to 1/8"). */
662
+ holeSawIn: number
663
+ borePctOfStud: number
664
+ needsNailPlate: boolean
665
+ codeCompliant: boolean
666
+ codeRef: string
667
+ note?: string
668
+ }
669
+
670
+ /**
671
+ * Compute recommended hole-saw / auger-bit diameter (inches) for a nominal pipe & material.
672
+ */
673
+ export function recommendHoleSawIn(pipeSize: PipeNominalSize, material: PipeMaterial): number {
674
+ const odIn = getPipeOuterDiameterM(pipeSize, material) / INCHES_TO_METERS
675
+ const clearance = odIn >= 1.5 ? 0.25 : 0.1875
676
+ return Math.ceil((odIn + clearance) * 8) / 8
677
+ }
678
+
679
+ /**
680
+ * Compute exact 3D stud, sole-plate, and top-plate penetrations where a pipe run
681
+ * crosses `@pascal-app/plugin-bones` framing members (16" or 24" OC studs + plates).
682
+ */
683
+ export function computePipeFramingPenetrations(params: {
684
+ pipeRunId: string
685
+ path: ReadonlyArray<Vec3>
686
+ pipeSize: PipeNominalSize
687
+ material: PipeMaterial
688
+ walls: ReadonlyArray<{
689
+ id: string
690
+ start: readonly [number, number]
691
+ end: readonly [number, number]
692
+ lengthM: number
693
+ thicknessM: number
694
+ heightM: number
695
+ ux: number
696
+ uz: number
697
+ nx: number
698
+ nz: number
699
+ }>
700
+ bonesContext?: BonesPlumbingContext | null
701
+ }): FramingPenetration[] {
702
+ const { pipeRunId, path, pipeSize, material, walls, bonesContext } = params
703
+ if (path.length < 2) return []
704
+
705
+ const penetrations: FramingPenetration[] = []
706
+ const holeSawIn = recommendHoleSawIn(pipeSize, material)
707
+ const defaultSpacingIn = bonesContext?.defaultSpacingIn ?? 16
708
+ let seq = 1
709
+
710
+ for (let i = 1; i < path.length; i++) {
711
+ const a = path[i - 1]!
712
+ const b = path[i]!
713
+ const dx = b[0] - a[0]
714
+ const dy = b[1] - a[1]
715
+ const dz = b[2] - a[2]
716
+ const segLen = Math.hypot(dx, dy, dz)
717
+ if (segLen < 0.02) continue
718
+ const dir: Vec3 = [dx / segLen, dy / segLen, dz / segLen]
719
+
720
+ for (const wall of walls) {
721
+ const rule = bonesContext?.wallRules.get(wall.id)
722
+ if (rule?.construction === 'skip' || rule?.construction === 'cmu') continue
723
+ const spacingM = (rule?.spacingIn ?? defaultSpacingIn) * INCHES_TO_METERS
724
+ const effectiveWallThicknessM = resolveEffectiveWallThicknessM(wall.thicknessM, bonesContext, rule)
725
+ const studDepthM = Math.max(0.0889, effectiveWallThicknessM - INCHES_TO_METERS)
726
+ const halfThick = effectiveWallThicknessM / 2 + 0.04
727
+
728
+ // Project endpoints into wall-local coordinates (u along wall, n perpendicular to wall)
729
+ const ua = (a[0] - wall.start[0]) * wall.ux + (a[2] - wall.start[1]) * wall.uz
730
+ const na = (a[0] - wall.start[0]) * wall.nx + (a[2] - wall.start[1]) * wall.nz
731
+ const ub = (b[0] - wall.start[0]) * wall.ux + (b[2] - wall.start[1]) * wall.uz
732
+ const nb = (b[0] - wall.start[0]) * wall.nx + (b[2] - wall.start[1]) * wall.nz
733
+
734
+ // Check if segment travels inside or right along this wall cavity
735
+ const minAbsN = Math.min(Math.abs(na), Math.abs(nb))
736
+ const crossesWallPlane = na * nb <= 0
737
+ if (minAbsN > halfThick && !crossesWallPlane) continue
738
+
739
+ const uMin = Math.min(ua, ub)
740
+ const uMax = Math.max(ua, ub)
741
+ if (uMax < 0 || uMin > wall.lengthM) continue
742
+
743
+ // 1. Vertical crossings of Sole Plate (y = 0.02 m) and Double Top Plate (y = wall.heightM - 0.04 m)
744
+ const yMin = Math.min(a[1], b[1])
745
+ const yMax = Math.max(a[1], b[1])
746
+ if (Math.abs(dy) > 0.05) {
747
+ const plateHeights: Array<{ kind: FramingMemberKind; label: string; y: number }> = [
748
+ { kind: 'sole-plate', label: `Sole Plate (${wall.id})`, y: 0.02 },
749
+ { kind: 'top-plate', label: `Double Top Plate (${wall.id})`, y: wall.heightM - 0.04 },
750
+ ]
751
+ for (const plate of plateHeights) {
752
+ if (yMin <= plate.y && yMax >= plate.y) {
753
+ const t = (plate.y - a[1]) / dy
754
+ if ((i === 1 ? t < 0 : t <= 1e-6) || t > 1) continue
755
+ const px = a[0] + dx * t
756
+ const pz = a[2] + dz * t
757
+ const pu = (px - wall.start[0]) * wall.ux + (pz - wall.start[1]) * wall.uz
758
+ const pn = Math.abs((px - wall.start[0]) * wall.nx + (pz - wall.start[1]) * wall.nz)
759
+ if (pu >= 0 && pu <= wall.lengthM && pn <= halfThick) {
760
+ const fit = checkWetWallPipeFit({
761
+ wallThicknessM: effectiveWallThicknessM,
762
+ pipeSize,
763
+ material,
764
+ isLoadBearing: rule?.isLoadBearing ?? false,
765
+ isHorizontalBore: false,
766
+ })
767
+ const firestopNote =
768
+ bonesContext?.source === 'structural'
769
+ ? 'IRC R302.11(5) firestop collar / intumescent caulk required at plate penetration.'
770
+ : undefined
771
+ penetrations.push({
772
+ id: `${pipeRunId}_pen_${seq++}`,
773
+ pipeRunId,
774
+ wallId: wall.id,
775
+ memberKind: plate.kind,
776
+ memberLabel: plate.label,
777
+ position: [px, plate.y, pz],
778
+ pipeDirection: dir,
779
+ wallNormal: [wall.nx, wall.nz],
780
+ studDepthM,
781
+ pipeSize,
782
+ material,
783
+ holeSawIn,
784
+ borePctOfStud: fit.borePctOfStud,
785
+ needsNailPlate: fit.needsNailPlate,
786
+ codeCompliant: fit.fits,
787
+ codeRef: bonesContext?.source === 'structural' ? 'IRC R602.6 / R302.11(5)' : fit.codeRef,
788
+ note: [fit.reason, firestopNote].filter(Boolean).join(' ') || undefined,
789
+ })
790
+ }
791
+ }
792
+ }
793
+ }
794
+
795
+ // 2. Horizontal crossings of individual 16"/24" OC wall studs
796
+ const du = ub - ua
797
+ if (Math.abs(du) > 0.05 && yMax > 0.05 && yMin < wall.heightM - 0.08) {
798
+ const firstIdx = Math.max(1, Math.ceil(uMin / spacingM))
799
+ const lastIdx = Math.min(Math.floor((wall.lengthM - 0.05) / spacingM), Math.floor(uMax / spacingM))
800
+ for (let studIdx = firstIdx; studIdx <= lastIdx; studIdx++) {
801
+ const studU = studIdx * spacingM
802
+ const t = (studU - ua) / du
803
+ if ((i === 1 ? t < 0 : t <= 1e-6) || t > 1) continue
804
+ const py = a[1] + dy * t
805
+ if (py <= 0.05 || py >= wall.heightM - 0.08) continue
806
+ const px = a[0] + dx * t
807
+ const pz = a[2] + dz * t
808
+ const pn = Math.abs((px - wall.start[0]) * wall.nx + (pz - wall.start[1]) * wall.nz)
809
+ if (pn > halfThick) continue
810
+
811
+ const fit = checkWetWallPipeFit({
812
+ wallThicknessM: effectiveWallThicknessM,
813
+ pipeSize,
814
+ material,
815
+ isLoadBearing: rule?.isLoadBearing ?? false,
816
+ isHorizontalBore: true,
817
+ })
818
+ penetrations.push({
819
+ id: `${pipeRunId}_pen_${seq++}`,
820
+ pipeRunId,
821
+ wallId: wall.id,
822
+ memberKind: 'stud',
823
+ memberLabel: `Stud #${studIdx} @ ${Math.round(studU / INCHES_TO_METERS)}" OC`,
824
+ position: [px, py, pz],
825
+ pipeDirection: dir,
826
+ wallNormal: [wall.nx, wall.nz],
827
+ studDepthM,
828
+ pipeSize,
829
+ material,
830
+ holeSawIn,
831
+ borePctOfStud: fit.borePctOfStud,
832
+ needsNailPlate: fit.needsNailPlate,
833
+ codeCompliant: fit.fits,
834
+ codeRef: fit.codeRef,
835
+ note: fit.reason,
836
+ })
837
+ }
838
+ }
839
+ }
840
+ }
841
+
842
+ return penetrations
843
+ }