@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.
- package/LICENSE +21 -0
- package/README.md +70 -2
- package/docs/ARCHITECTURE.md +56 -0
- package/docs/CAD-CATALOG.md +124 -0
- package/package.json +92 -4
- package/src/agent-operations.ts +851 -0
- package/src/agent-tools.ts +273 -0
- package/src/cad/catalog.ts +107 -0
- package/src/cad/electronics-geometry.ts +298 -0
- package/src/cad/furniture-geometry.ts +846 -0
- package/src/cad/index.ts +10 -0
- package/src/cad/materials.ts +274 -0
- package/src/cad/plants-geometry.ts +506 -0
- package/src/furnishings/audit.ts +711 -0
- package/src/furnishings/autopopulate.ts +1474 -0
- package/src/furnishings/catalog.ts +1848 -0
- package/src/furnishings/geometry.ts +753 -0
- package/src/furnishings/index.ts +14 -0
- package/src/furnishings/schedule.ts +503 -0
- package/src/furnishings/spatial-grounding.ts +1753 -0
- package/src/furnishings/types.ts +416 -0
- package/src/index.ts +145 -0
- package/src/nodes/assembly.ts +105 -0
- package/src/nodes/electronics.ts +187 -0
- package/src/nodes/glb-hydration.ts +269 -0
- package/src/nodes/item.ts +202 -0
- package/src/nodes/parametrics.ts +102 -0
- package/src/nodes/plant.ts +197 -0
- package/src/render.ts +55 -0
- package/src/ui/chat-card.tsx +119 -0
- package/src/ui/furnishings-panel.tsx +679 -0
- package/src/ui/inspector-card.tsx +350 -0
- package/src/ui/schedule-view.tsx +336 -0
- package/src/ui/store.ts +94 -0
|
@@ -0,0 +1,1753 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spatial Grounding, Right-Handed Interior Wall Elevation Projection, Camera-Relative
|
|
3
|
+
* Render Prompt Compiler & 4-of-7 Structural Staging Axes Diversity Gate
|
|
4
|
+
* (`src/furnishings/spatial-grounding.ts`).
|
|
5
|
+
*
|
|
6
|
+
* Adapted from harvested Roomsmith spatial-grounding & structural-diversity bricks and
|
|
7
|
+
* aligned 1:1 with Pascal's 3D `(X, Y, Z)` scene conventions:
|
|
8
|
+
* - Scene `+X` is East/right, `+Y` is vertical elevation up (`>= 0`), and `+Z` is South
|
|
9
|
+
* (`-Z` is North/up on 2D floor plans).
|
|
10
|
+
* - Mapping scene `(x, z)` -> planar right-handed `[px, py] = [x, -z]` places `+px` East/right
|
|
11
|
+
* and `+py` North/forward so interior viewer elevation offsets (`interiorLeftOffsetM`) and
|
|
12
|
+
* camera-relative wall buckets (`LEFT`, `AHEAD`, `RIGHT`, `BEHIND`) share identical right-handed
|
|
13
|
+
* chirality with zero mirror inversion.
|
|
14
|
+
*
|
|
15
|
+
* Pure framework-free TypeScript (`./furnishings` purity gate):
|
|
16
|
+
* zero `three`, `react`, `react-dom`, `@pascal-app/*`, `next`, `node:*`, `bun:*`, or `@krusch/toolkit` imports.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { extractNodeYawRad } from '@kruschdev/pascal-mep-kernel'
|
|
20
|
+
import {
|
|
21
|
+
distancePointToSegment2D,
|
|
22
|
+
pointInPolygon2D,
|
|
23
|
+
resolveNodeLevelId,
|
|
24
|
+
} from '@kruschdev/pascal-mep-kernel/anatomy'
|
|
25
|
+
import { deriveDisplayDimensionsM, getFurnishingSpec } from './catalog'
|
|
26
|
+
import {
|
|
27
|
+
type FurnishingRoomAnalysis,
|
|
28
|
+
type FurnishingWallAnalysis,
|
|
29
|
+
extractBuildingFurnishingsAnatomy,
|
|
30
|
+
} from './geometry'
|
|
31
|
+
import {
|
|
32
|
+
BUDGET_TIERS,
|
|
33
|
+
type BudgetTier,
|
|
34
|
+
PLANT_MATURITY_SCALE,
|
|
35
|
+
type PlantMaturity,
|
|
36
|
+
type SceneNodeLike,
|
|
37
|
+
type Vec2,
|
|
38
|
+
round3,
|
|
39
|
+
} from './types'
|
|
40
|
+
|
|
41
|
+
export const FURNISHING_SPATIAL_GROUNDING_DEFAULTS = Object.freeze({
|
|
42
|
+
minWallRunM: 0.05,
|
|
43
|
+
wallProximityTolM: 0.12,
|
|
44
|
+
tightRoomThresholdM: 4.0,
|
|
45
|
+
} as const)
|
|
46
|
+
|
|
47
|
+
export const DEFAULT_STAGING_DESIGN_AXES = Object.freeze([
|
|
48
|
+
'plan',
|
|
49
|
+
'ceiling',
|
|
50
|
+
'floor',
|
|
51
|
+
'seating',
|
|
52
|
+
'storage',
|
|
53
|
+
'lighting',
|
|
54
|
+
'programme',
|
|
55
|
+
] as const)
|
|
56
|
+
|
|
57
|
+
export type StagingDesignAxis = (typeof DEFAULT_STAGING_DESIGN_AXES)[number]
|
|
58
|
+
|
|
59
|
+
export type ProjectRoomWallElevationsOptions = {
|
|
60
|
+
readonly levelId?: string | null
|
|
61
|
+
readonly minWallRunM?: number
|
|
62
|
+
readonly wallProximityTolM?: number
|
|
63
|
+
readonly excludeFloorCoverings?: boolean
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type RoomWallOpeningElevation = {
|
|
67
|
+
readonly kind: 'door' | 'window'
|
|
68
|
+
readonly startU: number
|
|
69
|
+
readonly endU: number
|
|
70
|
+
readonly widthM: number
|
|
71
|
+
readonly interiorLeftOffsetM: number
|
|
72
|
+
readonly interiorRightOffsetM: number
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export type RoomWallElevationItem = {
|
|
76
|
+
readonly nodeId: string
|
|
77
|
+
readonly nodeType: 'furnishings:item' | 'furnishings:electronics' | 'furnishings:plant'
|
|
78
|
+
readonly kind: string
|
|
79
|
+
readonly label: string
|
|
80
|
+
readonly wallId: string
|
|
81
|
+
readonly wallUStartM: number
|
|
82
|
+
readonly runM: number
|
|
83
|
+
readonly centerPerpM: number
|
|
84
|
+
readonly interiorLeftOffsetM: number
|
|
85
|
+
readonly interiorRightOffsetM: number
|
|
86
|
+
readonly elevationM: number
|
|
87
|
+
readonly heightM: number
|
|
88
|
+
readonly widthM: number
|
|
89
|
+
readonly depthM: number
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export type RoomWallElevationSummary = {
|
|
93
|
+
readonly wallId: string
|
|
94
|
+
readonly name: string
|
|
95
|
+
readonly startXz: Vec2
|
|
96
|
+
readonly endXz: Vec2
|
|
97
|
+
readonly startPlan: Vec2
|
|
98
|
+
readonly endPlan: Vec2
|
|
99
|
+
readonly lengthM: number
|
|
100
|
+
readonly heightM: number
|
|
101
|
+
readonly thicknessM: number
|
|
102
|
+
readonly tangentPlan: Vec2
|
|
103
|
+
readonly inwardPlan: Vec2
|
|
104
|
+
readonly inwardPlanX: number
|
|
105
|
+
readonly inwardPlanY: number
|
|
106
|
+
readonly isExterior: boolean
|
|
107
|
+
readonly openingIntervals: readonly RoomWallOpeningElevation[]
|
|
108
|
+
readonly items: readonly RoomWallElevationItem[]
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export type RoomWallElevationProjectionResult = {
|
|
112
|
+
readonly room: FurnishingRoomAnalysis
|
|
113
|
+
readonly roomId: string
|
|
114
|
+
readonly roomName: string
|
|
115
|
+
readonly walls: readonly RoomWallElevationSummary[]
|
|
116
|
+
readonly attributions: readonly RoomWallElevationItem[]
|
|
117
|
+
readonly unattributedNodeIds: readonly string[]
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export type RoomCameraViewInput = {
|
|
121
|
+
readonly id: string
|
|
122
|
+
readonly fromXz: Vec2
|
|
123
|
+
readonly lookAtXz: Vec2
|
|
124
|
+
readonly camera?: string
|
|
125
|
+
readonly scene?: string
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export type CompileRoomRenderPromptOptions = {
|
|
129
|
+
readonly levelId?: string | null
|
|
130
|
+
readonly tightRoomThresholdM?: number
|
|
131
|
+
readonly mustAppear?: readonly string[]
|
|
132
|
+
readonly shellNotes?: readonly string[]
|
|
133
|
+
readonly includeStagedItemsInMustAppear?: boolean
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export type RoomCameraWallSides = {
|
|
137
|
+
readonly LEFT: readonly string[]
|
|
138
|
+
readonly AHEAD: readonly string[]
|
|
139
|
+
readonly RIGHT: readonly string[]
|
|
140
|
+
readonly BEHIND: readonly string[]
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export type RoomRenderPromptResult = {
|
|
144
|
+
readonly viewId: string
|
|
145
|
+
readonly roomId: string
|
|
146
|
+
readonly roomName: string
|
|
147
|
+
readonly prompt: string
|
|
148
|
+
readonly shellBlock: string
|
|
149
|
+
readonly solidClause: string
|
|
150
|
+
readonly scaleBlock: string
|
|
151
|
+
readonly orientationBlock: string
|
|
152
|
+
readonly mustAppearBlock: string
|
|
153
|
+
readonly sides: RoomCameraWallSides
|
|
154
|
+
readonly solidWallIds: readonly string[]
|
|
155
|
+
readonly visibleWindowWalls: readonly string[]
|
|
156
|
+
readonly isTightRoom: boolean
|
|
157
|
+
readonly sceneConflicts: readonly string[]
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export type StagingDirectionCandidate = {
|
|
161
|
+
readonly id: string
|
|
162
|
+
readonly name?: string
|
|
163
|
+
readonly budgetTier?: BudgetTier
|
|
164
|
+
readonly axes: Readonly<Record<string, string>>
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export type EvaluateStagingDirectionsOptions = {
|
|
168
|
+
readonly axes?: readonly string[]
|
|
169
|
+
readonly minDifferingAxes?: number
|
|
170
|
+
readonly similarityThreshold?: number
|
|
171
|
+
readonly requiredBudgetTiers?: readonly BudgetTier[]
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export type StagingDirectionPairResult = {
|
|
175
|
+
readonly a: string
|
|
176
|
+
readonly b: string
|
|
177
|
+
readonly differingAxes: readonly string[]
|
|
178
|
+
readonly sharedAxes: readonly string[]
|
|
179
|
+
readonly diffCount: number
|
|
180
|
+
readonly distinct: boolean
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export type StagingDirectionNearDuplicate = {
|
|
184
|
+
readonly a: string
|
|
185
|
+
readonly b: string
|
|
186
|
+
readonly diffCount: number
|
|
187
|
+
readonly sharedAxes: readonly string[]
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export type StagingDirectionMissingAxis = {
|
|
191
|
+
readonly id: string
|
|
192
|
+
readonly axis: string
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export type StagingDirectionsDiversityResult = {
|
|
196
|
+
readonly valid: boolean
|
|
197
|
+
readonly axes: readonly string[]
|
|
198
|
+
readonly minDifferingAxes: number
|
|
199
|
+
readonly candidateCount: number
|
|
200
|
+
readonly pairResults: readonly StagingDirectionPairResult[]
|
|
201
|
+
readonly nearDuplicates: readonly StagingDirectionNearDuplicate[]
|
|
202
|
+
readonly missingAxes: readonly StagingDirectionMissingAxis[]
|
|
203
|
+
readonly missingBudgetTiers: readonly BudgetTier[]
|
|
204
|
+
readonly summary: string
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const VALID_BUDGET_TIERS: ReadonlySet<string> = new Set<string>(BUDGET_TIERS)
|
|
208
|
+
|
|
209
|
+
function isPlainRecord(v: unknown): v is Record<string, unknown> {
|
|
210
|
+
return v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function isStrictFiniteNumber(v: unknown): v is number {
|
|
214
|
+
return typeof v === 'number' && Number.isFinite(v)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function assertStrictFiniteNumber(v: unknown, label: string): number {
|
|
218
|
+
if (!isStrictFiniteNumber(v)) {
|
|
219
|
+
throw new Error(`${label} must be a finite number.`)
|
|
220
|
+
}
|
|
221
|
+
return v
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function parseStrictVec2(v: unknown, label: string): Vec2 {
|
|
225
|
+
if (!Array.isArray(v) || v.length !== 2 || !isStrictFiniteNumber(v[0]) || !isStrictFiniteNumber(v[1])) {
|
|
226
|
+
throw new Error(`${label} must be a [number, number] tuple of finite coordinates.`)
|
|
227
|
+
}
|
|
228
|
+
return [cleanZero(v[0]), cleanZero(v[1])]
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function cleanZero(n: number): number {
|
|
232
|
+
return n === 0 ? 0 : n
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function round6(n: number): number {
|
|
236
|
+
const r = Math.round(n * 1e6) / 1e6
|
|
237
|
+
return r === 0 ? 0 : r
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function safeNum(v: unknown, fallback = 0): number {
|
|
241
|
+
return isStrictFiniteNumber(v) ? v : fallback
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Map Pascal 3D scene XZ `(x, z)` (`+X` East, `+Z` South) to planar right-handed `[px, py] = [x, -z]`
|
|
246
|
+
* (`+px` East/right, `+py` North/up).
|
|
247
|
+
*/
|
|
248
|
+
function sceneXzToPlan(x: number, z: number): Vec2 {
|
|
249
|
+
return [cleanZero(x), cleanZero(-z)]
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
type ResolvedRoomWall = {
|
|
253
|
+
readonly wallId: string
|
|
254
|
+
readonly name: string
|
|
255
|
+
readonly cardinalSide: 'north' | 'south' | 'east' | 'west' | null
|
|
256
|
+
readonly startXz: Vec2
|
|
257
|
+
readonly endXz: Vec2
|
|
258
|
+
readonly startPlan: Vec2
|
|
259
|
+
readonly endPlan: Vec2
|
|
260
|
+
readonly lengthM: number
|
|
261
|
+
readonly heightM: number
|
|
262
|
+
readonly thicknessM: number
|
|
263
|
+
readonly ux: number
|
|
264
|
+
readonly uz: number
|
|
265
|
+
readonly inwardNx: number
|
|
266
|
+
readonly inwardNz: number
|
|
267
|
+
readonly tangentPlan: Vec2
|
|
268
|
+
readonly inwardPlan: Vec2
|
|
269
|
+
readonly inwardPlanX: number
|
|
270
|
+
readonly inwardPlanY: number
|
|
271
|
+
readonly isExterior: boolean
|
|
272
|
+
readonly openingIntervals: readonly RoomWallOpeningElevation[]
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function minDistancePointToPolygonEdgesM(
|
|
276
|
+
px: number,
|
|
277
|
+
pz: number,
|
|
278
|
+
polygon: readonly Vec2[],
|
|
279
|
+
): number {
|
|
280
|
+
if (pointInPolygon2D(px, pz, polygon)) return 0
|
|
281
|
+
let minD = Number.POSITIVE_INFINITY
|
|
282
|
+
for (let i = 0; i < polygon.length; i++) {
|
|
283
|
+
const p0 = polygon[i]!
|
|
284
|
+
const p1 = polygon[(i + 1) % polygon.length]!
|
|
285
|
+
const d = distancePointToSegment2D(px, pz, p0[0], p0[1], p1[0], p1[1])
|
|
286
|
+
if (d < minD) minD = d
|
|
287
|
+
}
|
|
288
|
+
return minD
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Compute the tangential `[minRoomU, maxRoomU]` span along wall `w` where `room.polygon`
|
|
293
|
+
* actually borders `w` within perpendicular tolerance `maxBorderGap` (using 2D Liang-Barsky
|
|
294
|
+
* clipping of each polygon edge against `w`'s near-wall box, plus interior wall-sample fallback
|
|
295
|
+
* for freestanding fin walls enclosed inside `room.polygon`).
|
|
296
|
+
*
|
|
297
|
+
* Prevents distant wings of L-shaped or non-convex rooms (`perpDist >> maxBorderGap`) from
|
|
298
|
+
* inflating `minRoomU..maxRoomU` and skipping shared/continuous wall clipping.
|
|
299
|
+
*/
|
|
300
|
+
function computeNearWallPolygonSpanU(
|
|
301
|
+
w: FurnishingWallAnalysis,
|
|
302
|
+
polygon: readonly Vec2[],
|
|
303
|
+
maxBorderGap: number,
|
|
304
|
+
): { readonly minRoomU: number; readonly maxRoomU: number } | null {
|
|
305
|
+
let minRoomU = Number.POSITIVE_INFINITY
|
|
306
|
+
let maxRoomU = Number.NEGATIVE_INFINITY
|
|
307
|
+
|
|
308
|
+
const includeU = (u: number): void => {
|
|
309
|
+
if (u < minRoomU) minRoomU = u
|
|
310
|
+
if (u > maxRoomU) maxRoomU = u
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
for (let i = 0; i < polygon.length; i++) {
|
|
314
|
+
const a = polygon[i]!
|
|
315
|
+
const b = polygon[(i + 1) % polygon.length]!
|
|
316
|
+
const uA = (a[0] - w.start[0]) * w.ux + (a[1] - w.start[1]) * w.uz
|
|
317
|
+
const uB = (b[0] - w.start[0]) * w.ux + (b[1] - w.start[1]) * w.uz
|
|
318
|
+
const nA = (a[0] - w.start[0]) * w.nx + (a[1] - w.start[1]) * w.nz
|
|
319
|
+
const nB = (b[0] - w.start[0]) * w.nx + (b[1] - w.start[1]) * w.nz
|
|
320
|
+
const du = uB - uA
|
|
321
|
+
const dn = nB - nA
|
|
322
|
+
|
|
323
|
+
let t0 = 0
|
|
324
|
+
let t1 = 1
|
|
325
|
+
const clip1D = (p: number, q: number): boolean => {
|
|
326
|
+
if (Math.abs(p) <= 1e-12) return q >= -1e-9
|
|
327
|
+
const r = q / p
|
|
328
|
+
if (p < 0) {
|
|
329
|
+
if (r > t1) return false
|
|
330
|
+
if (r > t0) t0 = r
|
|
331
|
+
} else {
|
|
332
|
+
if (r < t0) return false
|
|
333
|
+
if (r < t1) t1 = r
|
|
334
|
+
}
|
|
335
|
+
return true
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
if (
|
|
339
|
+
clip1D(-dn, nA + maxBorderGap) &&
|
|
340
|
+
clip1D(dn, maxBorderGap - nA) &&
|
|
341
|
+
clip1D(-du, uA + maxBorderGap) &&
|
|
342
|
+
clip1D(du, w.lengthM + maxBorderGap - uA) &&
|
|
343
|
+
t0 <= t1
|
|
344
|
+
) {
|
|
345
|
+
includeU(uA + t0 * du)
|
|
346
|
+
includeU(uA + t1 * du)
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Fallback for freestanding interior fin walls enclosed inside a large room polygon
|
|
351
|
+
for (const frac of [0, 0.25, 0.5, 0.75, 1]) {
|
|
352
|
+
const u = frac * w.lengthM
|
|
353
|
+
const px = w.start[0] + w.ux * u
|
|
354
|
+
const pz = w.start[1] + w.uz * u
|
|
355
|
+
if (pointInPolygon2D(px, pz, polygon)) {
|
|
356
|
+
includeU(u)
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
if (!Number.isFinite(minRoomU) || !Number.isFinite(maxRoomU)) {
|
|
361
|
+
return null
|
|
362
|
+
}
|
|
363
|
+
return { minRoomU, maxRoomU }
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function minDistanceSegmentToPolygonM(
|
|
367
|
+
ax: number,
|
|
368
|
+
az: number,
|
|
369
|
+
bx: number,
|
|
370
|
+
bz: number,
|
|
371
|
+
polygon: readonly Vec2[],
|
|
372
|
+
): number {
|
|
373
|
+
let minD = Number.POSITIVE_INFINITY
|
|
374
|
+
for (let i = 0; i < polygon.length; i++) {
|
|
375
|
+
const p0 = polygon[i]!
|
|
376
|
+
const p1 = polygon[(i + 1) % polygon.length]!
|
|
377
|
+
const d0 = distancePointToSegment2D(p0[0], p0[1], ax, az, bx, bz)
|
|
378
|
+
if (d0 < minD) minD = d0
|
|
379
|
+
const d1 = distancePointToSegment2D(ax, az, p0[0], p0[1], p1[0], p1[1])
|
|
380
|
+
if (d1 < minD) minD = d1
|
|
381
|
+
const d2 = distancePointToSegment2D(bx, bz, p0[0], p0[1], p1[0], p1[1])
|
|
382
|
+
if (d2 < minD) minD = d2
|
|
383
|
+
const mx = (ax + bx) / 2
|
|
384
|
+
const mz = (az + bz) / 2
|
|
385
|
+
const dm = distancePointToSegment2D(mx, mz, p0[0], p0[1], p1[0], p1[1])
|
|
386
|
+
if (dm < minD) minD = dm
|
|
387
|
+
}
|
|
388
|
+
return minD
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function findCrossWallProjectionU(
|
|
392
|
+
wall: FurnishingWallAnalysis,
|
|
393
|
+
allLevelWalls: readonly FurnishingWallAnalysis[],
|
|
394
|
+
targetU: number,
|
|
395
|
+
minU: number,
|
|
396
|
+
maxU: number,
|
|
397
|
+
): number | null {
|
|
398
|
+
let bestU: number | null = null
|
|
399
|
+
let bestGap = Number.POSITIVE_INFINITY
|
|
400
|
+
for (const other of allLevelWalls) {
|
|
401
|
+
if (other.id === wall.id) continue
|
|
402
|
+
// Require non-parallel crossing/abutting wall
|
|
403
|
+
const cross = Math.abs(wall.ux * other.uz - wall.uz * other.ux)
|
|
404
|
+
if (cross < 0.35) continue
|
|
405
|
+
for (const pt of [other.start, other.end]) {
|
|
406
|
+
const perp = Math.abs((pt[0] - wall.start[0]) * wall.nx + (pt[1] - wall.start[1]) * wall.nz)
|
|
407
|
+
if (perp > Math.max(0.25, wall.thicknessM + other.thicknessM)) continue
|
|
408
|
+
const u = (pt[0] - wall.start[0]) * wall.ux + (pt[1] - wall.start[1]) * wall.uz
|
|
409
|
+
if (u >= minU && u <= maxU) {
|
|
410
|
+
const gap = Math.abs(u - targetU)
|
|
411
|
+
if (gap < bestGap) {
|
|
412
|
+
bestGap = gap
|
|
413
|
+
bestU = u
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
// Also check line-segment intersection between `wall` and `other`
|
|
418
|
+
const rX = wall.end[0] - wall.start[0]
|
|
419
|
+
const rZ = wall.end[1] - wall.start[1]
|
|
420
|
+
const sX = other.end[0] - other.start[0]
|
|
421
|
+
const sZ = other.end[1] - other.start[1]
|
|
422
|
+
const denom = rX * sZ - rZ * sX
|
|
423
|
+
if (Math.abs(denom) > 1e-9) {
|
|
424
|
+
const qpX = other.start[0] - wall.start[0]
|
|
425
|
+
const qpZ = other.start[1] - wall.start[1]
|
|
426
|
+
const t = (qpX * sZ - qpZ * sX) / denom
|
|
427
|
+
const uOther = (qpX * rZ - qpZ * rX) / denom
|
|
428
|
+
if (t >= -0.02 && t <= 1.02 && uOther >= -0.05 && uOther <= 1.05) {
|
|
429
|
+
const u = Math.max(0, Math.min(wall.lengthM, t * wall.lengthM))
|
|
430
|
+
if (u >= minU && u <= maxU) {
|
|
431
|
+
const gap = Math.abs(u - targetU)
|
|
432
|
+
if (gap < bestGap) {
|
|
433
|
+
bestGap = gap
|
|
434
|
+
bestU = u
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return bestU
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function inferWallNameAndCardinal(
|
|
444
|
+
wallId: string,
|
|
445
|
+
rawNodeName: unknown,
|
|
446
|
+
inwardNx: number,
|
|
447
|
+
inwardNz: number,
|
|
448
|
+
isExterior: boolean,
|
|
449
|
+
): { readonly name: string; readonly cardinalSide: 'north' | 'south' | 'east' | 'west' | null } {
|
|
450
|
+
// Outward vector in Pascal world XZ: -Z = North, +Z = South, +X = East, -X = West
|
|
451
|
+
const outX = -inwardNx
|
|
452
|
+
const outZ = -inwardNz
|
|
453
|
+
let cardinalSide: 'north' | 'south' | 'east' | 'west' | null = null
|
|
454
|
+
let dirLabel = 'Angled'
|
|
455
|
+
if (outZ <= -0.85) {
|
|
456
|
+
cardinalSide = 'north'
|
|
457
|
+
dirLabel = 'North'
|
|
458
|
+
} else if (outZ >= 0.85) {
|
|
459
|
+
cardinalSide = 'south'
|
|
460
|
+
dirLabel = 'South'
|
|
461
|
+
} else if (outX >= 0.85) {
|
|
462
|
+
cardinalSide = 'east'
|
|
463
|
+
dirLabel = 'East'
|
|
464
|
+
} else if (outX <= -0.85) {
|
|
465
|
+
cardinalSide = 'west'
|
|
466
|
+
dirLabel = 'West'
|
|
467
|
+
} else if (outZ < -0.25 && outX > 0.25) {
|
|
468
|
+
dirLabel = 'Northeast'
|
|
469
|
+
} else if (outZ < -0.25 && outX < -0.25) {
|
|
470
|
+
dirLabel = 'Northwest'
|
|
471
|
+
} else if (outZ > 0.25 && outX > 0.25) {
|
|
472
|
+
dirLabel = 'Southeast'
|
|
473
|
+
} else if (outZ > 0.25 && outX < -0.25) {
|
|
474
|
+
dirLabel = 'Southwest'
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
if (typeof rawNodeName === 'string' && rawNodeName.trim().length > 0) {
|
|
478
|
+
return { name: rawNodeName.trim(), cardinalSide }
|
|
479
|
+
}
|
|
480
|
+
const roleLabel = isExterior ? 'exterior wall' : 'partition wall'
|
|
481
|
+
return { name: `${dirLabel} ${roleLabel}`, cardinalSide }
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function computeOpeningInteriorOffsets(
|
|
485
|
+
startU: number,
|
|
486
|
+
endU: number,
|
|
487
|
+
wallLengthM: number,
|
|
488
|
+
tangentPlan: Vec2,
|
|
489
|
+
inwardPlan: Vec2,
|
|
490
|
+
): { readonly interiorLeftOffsetM: number; readonly interiorRightOffsetM: number; readonly widthM: number } {
|
|
491
|
+
const u0 = Math.max(0, Math.min(wallLengthM, startU))
|
|
492
|
+
const u1 = Math.max(u0, Math.min(wallLengthM, endU))
|
|
493
|
+
const run = round6(u1 - u0)
|
|
494
|
+
const viewDir: Vec2 = [-inwardPlan[0], -inwardPlan[1]]
|
|
495
|
+
const screenRight: Vec2 = [viewDir[1], -viewDir[0]]
|
|
496
|
+
const dotRight = tangentPlan[0] * screenRight[0] + tangentPlan[1] * screenRight[1]
|
|
497
|
+
const rawLeft = dotRight < 0 ? Math.max(0, wallLengthM - (u0 + (u1 - u0))) : Math.max(0, u0)
|
|
498
|
+
const interiorLeftOffsetM = round6(rawLeft)
|
|
499
|
+
const interiorRightOffsetM = round6(interiorLeftOffsetM + run)
|
|
500
|
+
return { interiorLeftOffsetM, interiorRightOffsetM, widthM: run }
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function resolveTargetRoomAndWalls(
|
|
504
|
+
nodes: Readonly<Record<string, SceneNodeLike>>,
|
|
505
|
+
roomIdOrName: string,
|
|
506
|
+
levelId?: string | null,
|
|
507
|
+
): {
|
|
508
|
+
readonly anatomy: ReturnType<typeof extractBuildingFurnishingsAnatomy>
|
|
509
|
+
readonly room: FurnishingRoomAnalysis
|
|
510
|
+
readonly roomWalls: readonly ResolvedRoomWall[]
|
|
511
|
+
} {
|
|
512
|
+
if (!isPlainRecord(nodes)) {
|
|
513
|
+
throw new Error('Scene nodes must be a plain object record.')
|
|
514
|
+
}
|
|
515
|
+
if (typeof roomIdOrName !== 'string' || roomIdOrName.trim().length === 0) {
|
|
516
|
+
throw new Error('roomIdOrName must be a non-empty string.')
|
|
517
|
+
}
|
|
518
|
+
if (levelId !== undefined && levelId !== null && (typeof levelId !== 'string' || levelId.trim().length === 0)) {
|
|
519
|
+
throw new Error('options.levelId must be a non-empty string or null when provided.')
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const query = roomIdOrName.trim()
|
|
523
|
+
const queryLower = query.toLowerCase()
|
|
524
|
+
const anatomy = extractBuildingFurnishingsAnatomy(nodes, levelId ?? null)
|
|
525
|
+
|
|
526
|
+
const room =
|
|
527
|
+
anatomy.rooms.find((r) => r.id === query) ??
|
|
528
|
+
anatomy.rooms.find((r) => r.name.trim().toLowerCase() === queryLower) ??
|
|
529
|
+
anatomy.rooms.find((r) => r.id.toLowerCase() === queryLower)
|
|
530
|
+
|
|
531
|
+
if (!room) {
|
|
532
|
+
throw new Error(`Room "${query}" not found in scene.`)
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const levelWalls = anatomy.walls.filter(
|
|
536
|
+
(w) => !room.levelId || !w.levelId || w.levelId === room.levelId,
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
const resolvedWalls: ResolvedRoomWall[] = []
|
|
540
|
+
|
|
541
|
+
for (const w of levelWalls) {
|
|
542
|
+
const maxBorderGap = Math.max(0.5, w.thicknessM + 0.35)
|
|
543
|
+
const spanRange = computeNearWallPolygonSpanU(w, room.polygon, maxBorderGap)
|
|
544
|
+
if (!spanRange) continue
|
|
545
|
+
const { minRoomU, maxRoomU } = spanRange
|
|
546
|
+
|
|
547
|
+
const rawStartU = Math.max(0, minRoomU)
|
|
548
|
+
const rawEndU = Math.min(w.lengthM, maxRoomU)
|
|
549
|
+
if (rawEndU - rawStartU < 0.15) continue
|
|
550
|
+
|
|
551
|
+
const cornerSnapTol = Math.max(0.35, w.thicknessM * 2)
|
|
552
|
+
let clipStartU = 0
|
|
553
|
+
if (minRoomU > cornerSnapTol) {
|
|
554
|
+
const crossStart = findCrossWallProjectionU(
|
|
555
|
+
w,
|
|
556
|
+
levelWalls,
|
|
557
|
+
minRoomU,
|
|
558
|
+
Math.max(0, minRoomU - cornerSnapTol),
|
|
559
|
+
Math.min(w.lengthM, minRoomU + 0.08),
|
|
560
|
+
)
|
|
561
|
+
clipStartU = crossStart ?? Math.max(0, minRoomU)
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
let clipEndU = w.lengthM
|
|
565
|
+
if (w.lengthM - maxRoomU > cornerSnapTol) {
|
|
566
|
+
const crossEnd = findCrossWallProjectionU(
|
|
567
|
+
w,
|
|
568
|
+
levelWalls,
|
|
569
|
+
maxRoomU,
|
|
570
|
+
Math.max(0, maxRoomU - 0.08),
|
|
571
|
+
Math.min(w.lengthM, maxRoomU + cornerSnapTol),
|
|
572
|
+
)
|
|
573
|
+
clipEndU = crossEnd ?? Math.min(w.lengthM, maxRoomU)
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
const segLen = clipEndU - clipStartU
|
|
577
|
+
if (segLen < 0.15) continue
|
|
578
|
+
|
|
579
|
+
const startX = w.start[0] + w.ux * clipStartU
|
|
580
|
+
const startZ = w.start[1] + w.uz * clipStartU
|
|
581
|
+
const endX = w.start[0] + w.ux * clipEndU
|
|
582
|
+
const endZ = w.start[1] + w.uz * clipEndU
|
|
583
|
+
|
|
584
|
+
const polyGapM = minDistanceSegmentToPolygonM(startX, startZ, endX, endZ, room.polygon)
|
|
585
|
+
const midInside = pointInPolygon2D((startX + endX) / 2, (startZ + endZ) / 2, room.polygon)
|
|
586
|
+
if (!midInside && polyGapM > maxBorderGap) continue
|
|
587
|
+
|
|
588
|
+
// Probe along both candidate normal signs (+1 and -1) across sample fractions of the wall span.
|
|
589
|
+
// Prefer the side whose closest probe distance lands strictly inside `room.polygon` so concave
|
|
590
|
+
// chimney-breast returns and thin alcove partitions never flip toward an exterior cutout.
|
|
591
|
+
const probeDists = [
|
|
592
|
+
Math.max(0.04, w.thicknessM / 2 + 0.03),
|
|
593
|
+
Math.max(0.14, w.thicknessM / 2 + 0.1),
|
|
594
|
+
0.28,
|
|
595
|
+
0.44,
|
|
596
|
+
]
|
|
597
|
+
const sampleFracs = [0.5, 0.25, 0.75, 0.125, 0.875]
|
|
598
|
+
|
|
599
|
+
let posHits = 0
|
|
600
|
+
let negHits = 0
|
|
601
|
+
let posMinDist = Number.POSITIVE_INFINITY
|
|
602
|
+
let negMinDist = Number.POSITIVE_INFINITY
|
|
603
|
+
|
|
604
|
+
for (const d of probeDists) {
|
|
605
|
+
for (const frac of sampleFracs) {
|
|
606
|
+
const sx = startX + (endX - startX) * frac
|
|
607
|
+
const sz = startZ + (endZ - startZ) * frac
|
|
608
|
+
if (pointInPolygon2D(sx + w.nx * d, sz + w.nz * d, room.polygon)) {
|
|
609
|
+
posHits += 1
|
|
610
|
+
if (d < posMinDist) posMinDist = d
|
|
611
|
+
}
|
|
612
|
+
if (pointInPolygon2D(sx - w.nx * d, sz - w.nz * d, room.polygon)) {
|
|
613
|
+
negHits += 1
|
|
614
|
+
if (d < negMinDist) negMinDist = d
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
if (posHits === 0 && negHits === 0) continue
|
|
620
|
+
|
|
621
|
+
let sign: 1 | -1
|
|
622
|
+
if (posMinDist !== negMinDist) {
|
|
623
|
+
sign = posMinDist < negMinDist ? 1 : -1
|
|
624
|
+
} else if (posHits !== negHits) {
|
|
625
|
+
sign = posHits > negHits ? 1 : -1
|
|
626
|
+
} else {
|
|
627
|
+
const midX = (startX + endX) / 2
|
|
628
|
+
const midZ = (startZ + endZ) / 2
|
|
629
|
+
const dotCentroid = (room.centroid[0] - midX) * w.nx + (room.centroid[1] - midZ) * w.nz
|
|
630
|
+
sign = dotCentroid >= 0 ? 1 : -1
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const inwardNx = cleanZero(w.nx * sign)
|
|
634
|
+
const inwardNz = cleanZero(w.nz * sign)
|
|
635
|
+
const startXz: Vec2 = [round6(startX), round6(startZ)]
|
|
636
|
+
const endXz: Vec2 = [round6(endX), round6(endZ)]
|
|
637
|
+
const startPlan = sceneXzToPlan(startXz[0], startXz[1])
|
|
638
|
+
const endPlan = sceneXzToPlan(endXz[0], endXz[1])
|
|
639
|
+
const exactLengthM = clipStartU === 0 && clipEndU === w.lengthM ? w.lengthM : round6(segLen)
|
|
640
|
+
const tangentPlan: Vec2 = [cleanZero(w.ux), cleanZero(-w.uz)]
|
|
641
|
+
const inwardPlanX = cleanZero(inwardNx)
|
|
642
|
+
const inwardPlanY = cleanZero(-inwardNz)
|
|
643
|
+
const inwardPlan: Vec2 = [inwardPlanX, inwardPlanY]
|
|
644
|
+
|
|
645
|
+
const openingIntervals: RoomWallOpeningElevation[] = []
|
|
646
|
+
for (const iv of w.openingIntervals) {
|
|
647
|
+
if (iv.endU <= clipStartU + 0.01 || iv.startU >= clipEndU - 0.01) continue
|
|
648
|
+
const localStart = round6(Math.max(0, iv.startU - clipStartU))
|
|
649
|
+
const localEnd = round6(Math.min(exactLengthM, iv.endU - clipStartU))
|
|
650
|
+
if (localEnd - localStart <= 0.01) continue
|
|
651
|
+
const offsets = computeOpeningInteriorOffsets(
|
|
652
|
+
localStart,
|
|
653
|
+
localEnd,
|
|
654
|
+
exactLengthM,
|
|
655
|
+
tangentPlan,
|
|
656
|
+
inwardPlan,
|
|
657
|
+
)
|
|
658
|
+
openingIntervals.push({
|
|
659
|
+
kind: iv.kind,
|
|
660
|
+
startU: localStart,
|
|
661
|
+
endU: localEnd,
|
|
662
|
+
widthM: offsets.widthM,
|
|
663
|
+
interiorLeftOffsetM: offsets.interiorLeftOffsetM,
|
|
664
|
+
interiorRightOffsetM: offsets.interiorRightOffsetM,
|
|
665
|
+
})
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const rawWallNode = Object.hasOwn(nodes, w.id) ? nodes[w.id] : undefined
|
|
669
|
+
const { name, cardinalSide } = inferWallNameAndCardinal(
|
|
670
|
+
w.id,
|
|
671
|
+
rawWallNode?.name,
|
|
672
|
+
inwardNx,
|
|
673
|
+
inwardNz,
|
|
674
|
+
w.isExterior,
|
|
675
|
+
)
|
|
676
|
+
|
|
677
|
+
resolvedWalls.push({
|
|
678
|
+
wallId: w.id,
|
|
679
|
+
name,
|
|
680
|
+
cardinalSide,
|
|
681
|
+
startXz,
|
|
682
|
+
endXz,
|
|
683
|
+
startPlan,
|
|
684
|
+
endPlan,
|
|
685
|
+
lengthM: exactLengthM,
|
|
686
|
+
heightM: w.heightM,
|
|
687
|
+
thicknessM: w.thicknessM,
|
|
688
|
+
ux: w.ux,
|
|
689
|
+
uz: w.uz,
|
|
690
|
+
inwardNx,
|
|
691
|
+
inwardNz,
|
|
692
|
+
tangentPlan,
|
|
693
|
+
inwardPlan,
|
|
694
|
+
inwardPlanX,
|
|
695
|
+
inwardPlanY,
|
|
696
|
+
isExterior: w.isExterior,
|
|
697
|
+
openingIntervals,
|
|
698
|
+
})
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
return { anatomy, room, roomWalls: resolvedWalls }
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
type PreparedRoomItem = {
|
|
705
|
+
readonly nodeId: string
|
|
706
|
+
readonly node: SceneNodeLike
|
|
707
|
+
readonly nodeType: 'furnishings:item' | 'furnishings:electronics' | 'furnishings:plant'
|
|
708
|
+
readonly kind: string
|
|
709
|
+
readonly label: string
|
|
710
|
+
readonly domain: string
|
|
711
|
+
readonly x: number
|
|
712
|
+
readonly y: number
|
|
713
|
+
readonly z: number
|
|
714
|
+
readonly yawRad: number
|
|
715
|
+
readonly widthM: number
|
|
716
|
+
readonly depthM: number
|
|
717
|
+
readonly heightM: number
|
|
718
|
+
readonly isFloorCovering: boolean
|
|
719
|
+
readonly isRetainOrHero: boolean
|
|
720
|
+
readonly centerPlan: Vec2
|
|
721
|
+
readonly cornersPlan: readonly Vec2[]
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
function extractRoomStagedItems(
|
|
725
|
+
nodes: Readonly<Record<string, SceneNodeLike>>,
|
|
726
|
+
room: FurnishingRoomAnalysis,
|
|
727
|
+
allRooms: readonly FurnishingRoomAnalysis[],
|
|
728
|
+
roomWalls: readonly ResolvedRoomWall[],
|
|
729
|
+
): PreparedRoomItem[] {
|
|
730
|
+
const roomNameLower = room.name.trim().toLowerCase()
|
|
731
|
+
const roomIdLower = room.id.toLowerCase()
|
|
732
|
+
const sameLevelOtherRooms: FurnishingRoomAnalysis[] = []
|
|
733
|
+
const otherRoomNames = new Set<string>()
|
|
734
|
+
for (const other of allRooms) {
|
|
735
|
+
if (other.id === room.id) continue
|
|
736
|
+
if (room.levelId && other.levelId && other.levelId !== room.levelId) continue
|
|
737
|
+
sameLevelOtherRooms.push(other)
|
|
738
|
+
otherRoomNames.add(other.name.trim().toLowerCase())
|
|
739
|
+
otherRoomNames.add(other.id.toLowerCase())
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// Precompute which room walls are true exterior walls with no room/zone on their backside
|
|
743
|
+
const unsharedExteriorWallIds = new Set<string>()
|
|
744
|
+
for (const rw of roomWalls) {
|
|
745
|
+
if (!rw.isExterior) continue
|
|
746
|
+
let hasBacksideRoom = false
|
|
747
|
+
for (const frac of [0.25, 0.5, 0.75]) {
|
|
748
|
+
const bx = rw.startXz[0] + (rw.endXz[0] - rw.startXz[0]) * frac
|
|
749
|
+
const bz = rw.startXz[1] + (rw.endXz[1] - rw.startXz[1]) * frac
|
|
750
|
+
for (const step of [rw.thicknessM / 2 + 0.05, rw.thicknessM / 2 + 0.25]) {
|
|
751
|
+
const px = bx - rw.inwardNx * step
|
|
752
|
+
const pz = bz - rw.inwardNz * step
|
|
753
|
+
if (sameLevelOtherRooms.some((other) => pointInPolygon2D(px, pz, other.polygon))) {
|
|
754
|
+
hasBacksideRoom = true
|
|
755
|
+
break
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
if (hasBacksideRoom) break
|
|
759
|
+
}
|
|
760
|
+
if (!hasBacksideRoom) {
|
|
761
|
+
unsharedExteriorWallIds.add(rw.wallId)
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
const out: PreparedRoomItem[] = []
|
|
766
|
+
|
|
767
|
+
for (const node of Object.values(nodes)) {
|
|
768
|
+
if (!node || node.visible === false) continue
|
|
769
|
+
if (
|
|
770
|
+
node.type !== 'furnishings:item' &&
|
|
771
|
+
node.type !== 'furnishings:electronics' &&
|
|
772
|
+
node.type !== 'furnishings:plant'
|
|
773
|
+
) {
|
|
774
|
+
continue
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
const itemLevelId = resolveNodeLevelId(nodes, node)
|
|
778
|
+
if (room.levelId && itemLevelId && itemLevelId !== room.levelId) continue
|
|
779
|
+
|
|
780
|
+
const kind = String(node.itemKind ?? node.plantKind ?? '')
|
|
781
|
+
const spec = getFurnishingSpec(kind)
|
|
782
|
+
const pos = Array.isArray(node.position) ? node.position : [0, 0, 0]
|
|
783
|
+
const x = safeNum(pos[0], 0)
|
|
784
|
+
const y = Math.max(0, safeNum(pos[1], spec?.defaultElevationM ?? 0))
|
|
785
|
+
const z = safeNum(pos[2], 0)
|
|
786
|
+
const yawRad = extractNodeYawRad(node.rotation)
|
|
787
|
+
|
|
788
|
+
let widthM = Math.max(0.01, safeNum(node.widthM, spec?.widthM ?? 0.8))
|
|
789
|
+
let depthM = Math.max(0.01, safeNum(node.depthM, spec?.depthM ?? 0.8))
|
|
790
|
+
let heightM = Math.max(0.01, safeNum(node.heightM, spec?.heightM ?? 0.8))
|
|
791
|
+
|
|
792
|
+
if (node.type === 'furnishings:electronics' && typeof node.screenDiagonalIn === 'number') {
|
|
793
|
+
const derived = deriveDisplayDimensionsM(kind, node.screenDiagonalIn)
|
|
794
|
+
const usesCatalogDefaults =
|
|
795
|
+
(node.widthM === undefined || node.widthM === spec?.widthM) &&
|
|
796
|
+
(node.heightM === undefined || node.heightM === spec?.heightM)
|
|
797
|
+
if (derived && usesCatalogDefaults) {
|
|
798
|
+
widthM = Math.max(0.01, derived.widthM)
|
|
799
|
+
heightM = Math.max(0.01, derived.heightM)
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
if (node.type === 'furnishings:plant') {
|
|
804
|
+
const matKey = typeof node.maturity === 'string' ? node.maturity.trim() : 'mature'
|
|
805
|
+
const rawScale = Object.hasOwn(PLANT_MATURITY_SCALE, matKey)
|
|
806
|
+
? PLANT_MATURITY_SCALE[matKey as PlantMaturity]
|
|
807
|
+
: undefined
|
|
808
|
+
const scale =
|
|
809
|
+
typeof rawScale === 'number' && Number.isFinite(rawScale) && rawScale > 0 ? rawScale : 1.0
|
|
810
|
+
const canopyR = Math.max(0.01, safeNum(node.canopyRadiusM, (spec?.widthM ?? 1.0) / 2))
|
|
811
|
+
widthM = Math.max(0.01, canopyR * 2 * scale)
|
|
812
|
+
const isLinearPlant = kind === 'bush-hedge-row' || kind === 'plant-succulent-trough'
|
|
813
|
+
depthM = Math.max(0.01, isLinearPlant ? (spec?.depthM ?? 0.5) * scale : canopyR * 2 * scale)
|
|
814
|
+
heightM = Math.max(0.01, safeNum(node.heightM, spec?.heightM ?? 1.2) * scale)
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// Check explicit room assignment vs geometric containment
|
|
818
|
+
const rawAssigned =
|
|
819
|
+
typeof node.roomName === 'string' && node.roomName.trim()
|
|
820
|
+
? node.roomName.trim()
|
|
821
|
+
: typeof node.zoneName === 'string' && node.zoneName.trim()
|
|
822
|
+
? node.zoneName.trim()
|
|
823
|
+
: ''
|
|
824
|
+
const assignedLower = rawAssigned.toLowerCase()
|
|
825
|
+
|
|
826
|
+
const explicitlyMatchesTarget =
|
|
827
|
+
assignedLower.length > 0 && (assignedLower === roomNameLower || assignedLower === roomIdLower)
|
|
828
|
+
const explicitlyMatchesOther =
|
|
829
|
+
!explicitlyMatchesTarget &&
|
|
830
|
+
assignedLower.length > 0 &&
|
|
831
|
+
assignedLower !== 'unassigned' &&
|
|
832
|
+
otherRoomNames.has(assignedLower)
|
|
833
|
+
|
|
834
|
+
if (explicitlyMatchesOther) continue
|
|
835
|
+
|
|
836
|
+
const centerPlan = sceneXzToPlan(x, z)
|
|
837
|
+
const cosY = Math.cos(yawRad)
|
|
838
|
+
const sinY = Math.sin(yawRad)
|
|
839
|
+
// Right-handed Y-up rotation in Pascal maps local (lx, ly_plan=-lz) by CCW yawRad in (px, py)=(x, -z)
|
|
840
|
+
const axisU: Vec2 = [cosY, sinY]
|
|
841
|
+
const axisV: Vec2 = [-sinY, cosY]
|
|
842
|
+
const hw = widthM / 2
|
|
843
|
+
const hd = depthM / 2
|
|
844
|
+
const cornersPlan: readonly Vec2[] = [
|
|
845
|
+
[
|
|
846
|
+
cleanZero(centerPlan[0] - hw * axisU[0] - hd * axisV[0]),
|
|
847
|
+
cleanZero(centerPlan[1] - hw * axisU[1] - hd * axisV[1]),
|
|
848
|
+
],
|
|
849
|
+
[
|
|
850
|
+
cleanZero(centerPlan[0] + hw * axisU[0] - hd * axisV[0]),
|
|
851
|
+
cleanZero(centerPlan[1] + hw * axisU[1] - hd * axisV[1]),
|
|
852
|
+
],
|
|
853
|
+
[
|
|
854
|
+
cleanZero(centerPlan[0] + hw * axisU[0] + hd * axisV[0]),
|
|
855
|
+
cleanZero(centerPlan[1] + hw * axisU[1] + hd * axisV[1]),
|
|
856
|
+
],
|
|
857
|
+
[
|
|
858
|
+
cleanZero(centerPlan[0] - hw * axisU[0] + hd * axisV[0]),
|
|
859
|
+
cleanZero(centerPlan[1] - hw * axisU[1] + hd * axisV[1]),
|
|
860
|
+
],
|
|
861
|
+
]
|
|
862
|
+
|
|
863
|
+
if (!explicitlyMatchesTarget) {
|
|
864
|
+
let inside = pointInPolygon2D(x, z, room.polygon)
|
|
865
|
+
if (!inside) {
|
|
866
|
+
// Reject unassigned items that lie inside another room polygon on the same level or are
|
|
867
|
+
// strictly closer to a neighboring room's polygon / interior wall face than to `room`.
|
|
868
|
+
const insideOtherRoom = sameLevelOtherRooms.some((other) =>
|
|
869
|
+
pointInPolygon2D(x, z, other.polygon),
|
|
870
|
+
)
|
|
871
|
+
if (!insideOtherRoom) {
|
|
872
|
+
const distToTargetPoly = minDistancePointToPolygonEdgesM(x, z, room.polygon)
|
|
873
|
+
const closerToOtherRoom = sameLevelOtherRooms.some(
|
|
874
|
+
(other) =>
|
|
875
|
+
minDistancePointToPolygonEdgesM(x, z, other.polygon) < distToTargetPoly - 1e-6,
|
|
876
|
+
)
|
|
877
|
+
if (!closerToOtherRoom) {
|
|
878
|
+
// Wall-mounted items placed flush with a wall face may sit inside the zone polygon's
|
|
879
|
+
// wall-thickness inset ONLY within this room's clipped wall span and interior half-space.
|
|
880
|
+
const nearRoomWall = roomWalls.some((rw) => {
|
|
881
|
+
const u = (x - rw.startXz[0]) * rw.ux + (z - rw.startXz[1]) * rw.uz
|
|
882
|
+
if (u < -0.01 || u > rw.lengthM + 0.01) return false
|
|
883
|
+
const signedInward =
|
|
884
|
+
(x - rw.startXz[0]) * rw.inwardNx + (z - rw.startXz[1]) * rw.inwardNz
|
|
885
|
+
if (signedInward > rw.thicknessM / 2 + 0.16) return false
|
|
886
|
+
if (unsharedExteriorWallIds.has(rw.wallId)) {
|
|
887
|
+
return signedInward >= -0.005
|
|
888
|
+
}
|
|
889
|
+
return signedInward > 0
|
|
890
|
+
})
|
|
891
|
+
if (nearRoomWall) {
|
|
892
|
+
inside = true
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
if (!inside) continue
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
const meta = isPlainRecord(node.metadata) ? node.metadata : undefined
|
|
901
|
+
const explicitRetain =
|
|
902
|
+
node.retain === true ||
|
|
903
|
+
node.hero === true ||
|
|
904
|
+
node.mustAppear === true ||
|
|
905
|
+
meta?.retain === true ||
|
|
906
|
+
meta?.hero === true ||
|
|
907
|
+
meta?.mustAppear === true
|
|
908
|
+
|
|
909
|
+
const isHeroCategory =
|
|
910
|
+
!spec?.isFloorCovering &&
|
|
911
|
+
!kind.startsWith('vent-') &&
|
|
912
|
+
(explicitRetain ||
|
|
913
|
+
spec?.domain === 'seating' ||
|
|
914
|
+
spec?.domain === 'tables-desks' ||
|
|
915
|
+
spec?.domain === 'beds-storage' ||
|
|
916
|
+
kind === 'tv-oled-wall' ||
|
|
917
|
+
kind === 'tv-oled-stand' ||
|
|
918
|
+
kind === 'projector-screen' ||
|
|
919
|
+
node.type === 'furnishings:plant')
|
|
920
|
+
|
|
921
|
+
const label =
|
|
922
|
+
typeof node.name === 'string' && node.name.trim().length > 0
|
|
923
|
+
? node.name.trim()
|
|
924
|
+
: (spec?.label ?? (kind || node.id))
|
|
925
|
+
|
|
926
|
+
out.push({
|
|
927
|
+
nodeId: node.id,
|
|
928
|
+
node,
|
|
929
|
+
nodeType: node.type,
|
|
930
|
+
kind,
|
|
931
|
+
label,
|
|
932
|
+
domain: spec?.domain ?? 'seating',
|
|
933
|
+
x,
|
|
934
|
+
y,
|
|
935
|
+
z,
|
|
936
|
+
yawRad,
|
|
937
|
+
widthM,
|
|
938
|
+
depthM,
|
|
939
|
+
heightM,
|
|
940
|
+
isFloorCovering: Boolean(spec?.isFloorCovering),
|
|
941
|
+
isRetainOrHero: explicitRetain || isHeroCategory,
|
|
942
|
+
centerPlan,
|
|
943
|
+
cornersPlan,
|
|
944
|
+
})
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
return out
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/**
|
|
951
|
+
* Sutherland-Hodgman half-plane polygon clip keeping points where `(P · normal - offset) <= maxVal`.
|
|
952
|
+
*/
|
|
953
|
+
function clipPolygonHalfPlane(
|
|
954
|
+
poly: readonly Vec2[],
|
|
955
|
+
normalX: number,
|
|
956
|
+
normalY: number,
|
|
957
|
+
offset: number,
|
|
958
|
+
maxVal: number,
|
|
959
|
+
): Vec2[] {
|
|
960
|
+
if (poly.length === 0) return []
|
|
961
|
+
const out: Vec2[] = []
|
|
962
|
+
const evalDist = (pt: Vec2): number => pt[0] * normalX + pt[1] * normalY - offset - maxVal
|
|
963
|
+
|
|
964
|
+
for (let i = 0; i < poly.length; i++) {
|
|
965
|
+
const curr = poly[i]!
|
|
966
|
+
const next = poly[(i + 1) % poly.length]!
|
|
967
|
+
const dCurr = evalDist(curr)
|
|
968
|
+
const dNext = evalDist(next)
|
|
969
|
+
const currIn = dCurr <= 1e-9
|
|
970
|
+
const nextIn = dNext <= 1e-9
|
|
971
|
+
|
|
972
|
+
if (currIn && nextIn) {
|
|
973
|
+
out.push(next)
|
|
974
|
+
} else if (currIn && !nextIn) {
|
|
975
|
+
const denom = dCurr - dNext
|
|
976
|
+
const t = Math.abs(denom) > 1e-15 ? dCurr / denom : 0
|
|
977
|
+
out.push([curr[0] + t * (next[0] - curr[0]), curr[1] + t * (next[1] - curr[1])])
|
|
978
|
+
} else if (!currIn && nextIn) {
|
|
979
|
+
const denom = dCurr - dNext
|
|
980
|
+
const t = Math.abs(denom) > 1e-15 ? dCurr / denom : 0
|
|
981
|
+
out.push([curr[0] + t * (next[0] - curr[0]), curr[1] + t * (next[1] - curr[1])])
|
|
982
|
+
out.push(next)
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
return out
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/**
|
|
989
|
+
* Project every visible staged furnishing item inside a target room onto its nearest bordering
|
|
990
|
+
* wall elevation in right-handed interior viewer coordinates.
|
|
991
|
+
*
|
|
992
|
+
* - Clips each item's rotated 4-corner 2D OBB polygon against the near-wall proximity band
|
|
993
|
+
* before projecting onto `[0, wall.lengthM]` so rotated items grazing a wall at one corner
|
|
994
|
+
* never project far interior corners onto the wall.
|
|
995
|
+
* - Rejects grazing corner contacts with `runM < minWallRunM` (`0.05m`).
|
|
996
|
+
* - Breaks multi-wall corner ties by `(round6(centerPerpM), -round6(runM))`.
|
|
997
|
+
* - Computes `interiorLeftOffsetM` & `interiorRightOffsetM` from inside the room facing the wall
|
|
998
|
+
* square-on (`viewDir = [-inwardPlanX, -inwardPlanY]`, `screenRight = [viewDir[1], -viewDir[0]]`).
|
|
999
|
+
*/
|
|
1000
|
+
export function projectRoomWallElevations(
|
|
1001
|
+
nodes: Readonly<Record<string, SceneNodeLike>>,
|
|
1002
|
+
roomIdOrName: string,
|
|
1003
|
+
options?: ProjectRoomWallElevationsOptions,
|
|
1004
|
+
): RoomWallElevationProjectionResult {
|
|
1005
|
+
if (options !== undefined && !isPlainRecord(options)) {
|
|
1006
|
+
throw new Error('projectRoomWallElevations options must be a plain object.')
|
|
1007
|
+
}
|
|
1008
|
+
const minWallRunM =
|
|
1009
|
+
options?.minWallRunM !== undefined
|
|
1010
|
+
? assertStrictFiniteNumber(options.minWallRunM, 'options.minWallRunM')
|
|
1011
|
+
: FURNISHING_SPATIAL_GROUNDING_DEFAULTS.minWallRunM
|
|
1012
|
+
const wallProximityTolM =
|
|
1013
|
+
options?.wallProximityTolM !== undefined
|
|
1014
|
+
? assertStrictFiniteNumber(options.wallProximityTolM, 'options.wallProximityTolM')
|
|
1015
|
+
: FURNISHING_SPATIAL_GROUNDING_DEFAULTS.wallProximityTolM
|
|
1016
|
+
|
|
1017
|
+
if (minWallRunM < 0 || wallProximityTolM < 0) {
|
|
1018
|
+
throw new Error('Wall elevation tolerances (minWallRunM, wallProximityTolM) must be >= 0.')
|
|
1019
|
+
}
|
|
1020
|
+
const excludeFloorCoverings = options?.excludeFloorCoverings === true
|
|
1021
|
+
|
|
1022
|
+
const { anatomy, room, roomWalls } = resolveTargetRoomAndWalls(
|
|
1023
|
+
nodes,
|
|
1024
|
+
roomIdOrName,
|
|
1025
|
+
options?.levelId,
|
|
1026
|
+
)
|
|
1027
|
+
const roomItems = extractRoomStagedItems(nodes, room, anatomy.rooms, roomWalls)
|
|
1028
|
+
|
|
1029
|
+
const itemsByWallId = new Map<string, RoomWallElevationItem[]>()
|
|
1030
|
+
for (const rw of roomWalls) {
|
|
1031
|
+
itemsByWallId.set(rw.wallId, [])
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
const attributions: RoomWallElevationItem[] = []
|
|
1035
|
+
const unattributedNodeIds: string[] = []
|
|
1036
|
+
|
|
1037
|
+
for (const item of roomItems) {
|
|
1038
|
+
if (excludeFloorCoverings && item.isFloorCovering) {
|
|
1039
|
+
unattributedNodeIds.push(item.nodeId)
|
|
1040
|
+
continue
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
type WallCandidate = {
|
|
1044
|
+
readonly wall: ResolvedRoomWall
|
|
1045
|
+
readonly wallIdx: number
|
|
1046
|
+
readonly u0: number
|
|
1047
|
+
readonly rawRun: number
|
|
1048
|
+
readonly uStartRounded: number
|
|
1049
|
+
readonly runRounded: number
|
|
1050
|
+
readonly cperpRounded: number
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
const candidates: WallCandidate[] = []
|
|
1054
|
+
|
|
1055
|
+
for (let wIdx = 0; wIdx < roomWalls.length; wIdx++) {
|
|
1056
|
+
const wall = roomWalls[wIdx]!
|
|
1057
|
+
const nx = wall.inwardPlanX
|
|
1058
|
+
const ny = wall.inwardPlanY
|
|
1059
|
+
const tx = wall.tangentPlan[0]
|
|
1060
|
+
const ty = wall.tangentPlan[1]
|
|
1061
|
+
const wallOffsetN = wall.startPlan[0] * nx + wall.startPlan[1] * ny
|
|
1062
|
+
const halfThick = wall.thicknessM / 2
|
|
1063
|
+
|
|
1064
|
+
// Clip 4-corner OBB polygon to near-wall slab [-max(0.02, halfThick), halfThick + wallProximityTolM]
|
|
1065
|
+
// along the room-interior normal so `wallProximityTolM` (0.12m) measures room-side distance
|
|
1066
|
+
// from the physical interior wall face while still accepting centerline-referenced test geometry.
|
|
1067
|
+
let bandPoly = clipPolygonHalfPlane(
|
|
1068
|
+
item.cornersPlan,
|
|
1069
|
+
nx,
|
|
1070
|
+
ny,
|
|
1071
|
+
wallOffsetN,
|
|
1072
|
+
halfThick + wallProximityTolM,
|
|
1073
|
+
)
|
|
1074
|
+
bandPoly = clipPolygonHalfPlane(
|
|
1075
|
+
bandPoly,
|
|
1076
|
+
-nx,
|
|
1077
|
+
-ny,
|
|
1078
|
+
-wallOffsetN,
|
|
1079
|
+
Math.max(0.02, halfThick),
|
|
1080
|
+
)
|
|
1081
|
+
if (bandPoly.length === 0) continue
|
|
1082
|
+
|
|
1083
|
+
let minBandU = Number.POSITIVE_INFINITY
|
|
1084
|
+
let maxBandU = Number.NEGATIVE_INFINITY
|
|
1085
|
+
for (const pt of bandPoly) {
|
|
1086
|
+
const u = (pt[0] - wall.startPlan[0]) * tx + (pt[1] - wall.startPlan[1]) * ty
|
|
1087
|
+
if (u < minBandU) minBandU = u
|
|
1088
|
+
if (u > maxBandU) maxBandU = u
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
const u0 = Math.max(0, minBandU)
|
|
1092
|
+
const u1 = Math.min(wall.lengthM, maxBandU)
|
|
1093
|
+
const rawRun = u1 - u0
|
|
1094
|
+
if (rawRun <= 0) continue
|
|
1095
|
+
|
|
1096
|
+
const runRounded = round6(rawRun)
|
|
1097
|
+
if (runRounded < minWallRunM) continue
|
|
1098
|
+
|
|
1099
|
+
const signedCenterDist =
|
|
1100
|
+
(item.centerPlan[0] - wall.startPlan[0]) * nx +
|
|
1101
|
+
(item.centerPlan[1] - wall.startPlan[1]) * ny
|
|
1102
|
+
const centerPerpM = Math.abs(signedCenterDist - halfThick)
|
|
1103
|
+
|
|
1104
|
+
candidates.push({
|
|
1105
|
+
wall,
|
|
1106
|
+
wallIdx: wIdx,
|
|
1107
|
+
u0,
|
|
1108
|
+
rawRun,
|
|
1109
|
+
uStartRounded: round6(u0),
|
|
1110
|
+
runRounded,
|
|
1111
|
+
cperpRounded: round6(centerPerpM),
|
|
1112
|
+
})
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
if (candidates.length === 0) {
|
|
1116
|
+
unattributedNodeIds.push(item.nodeId)
|
|
1117
|
+
continue
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
// Break multi-wall ties by (round6(centerPerpM), -round6(runM))
|
|
1121
|
+
candidates.sort((a, b) => {
|
|
1122
|
+
if (a.cperpRounded !== b.cperpRounded) {
|
|
1123
|
+
return a.cperpRounded - b.cperpRounded
|
|
1124
|
+
}
|
|
1125
|
+
if (a.runRounded !== b.runRounded) {
|
|
1126
|
+
return b.runRounded - a.runRounded
|
|
1127
|
+
}
|
|
1128
|
+
return a.wallIdx - b.wallIdx
|
|
1129
|
+
})
|
|
1130
|
+
|
|
1131
|
+
const win = candidates[0]!
|
|
1132
|
+
const wall = win.wall
|
|
1133
|
+
const viewDir: Vec2 = [-wall.inwardPlanX, -wall.inwardPlanY]
|
|
1134
|
+
const screenRight: Vec2 = [viewDir[1], -viewDir[0]]
|
|
1135
|
+
const dotRight = wall.tangentPlan[0] * screenRight[0] + wall.tangentPlan[1] * screenRight[1]
|
|
1136
|
+
const rawLeft =
|
|
1137
|
+
dotRight < 0
|
|
1138
|
+
? Math.max(0, wall.lengthM - (win.u0 + win.rawRun))
|
|
1139
|
+
: Math.max(0, win.u0)
|
|
1140
|
+
const interiorLeftOffsetM = round6(rawLeft)
|
|
1141
|
+
const interiorRightOffsetM = round6(interiorLeftOffsetM + win.runRounded)
|
|
1142
|
+
|
|
1143
|
+
const projected: RoomWallElevationItem = {
|
|
1144
|
+
nodeId: item.nodeId,
|
|
1145
|
+
nodeType: item.nodeType,
|
|
1146
|
+
kind: item.kind,
|
|
1147
|
+
label: item.label,
|
|
1148
|
+
wallId: wall.wallId,
|
|
1149
|
+
wallUStartM: win.uStartRounded,
|
|
1150
|
+
runM: win.runRounded,
|
|
1151
|
+
centerPerpM: win.cperpRounded,
|
|
1152
|
+
interiorLeftOffsetM,
|
|
1153
|
+
interiorRightOffsetM,
|
|
1154
|
+
elevationM: round6(item.y),
|
|
1155
|
+
heightM: round6(item.heightM),
|
|
1156
|
+
widthM: round6(item.widthM),
|
|
1157
|
+
depthM: round6(item.depthM),
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
attributions.push(projected)
|
|
1161
|
+
itemsByWallId.get(wall.wallId)?.push(projected)
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
const walls: RoomWallElevationSummary[] = roomWalls.map((rw) => {
|
|
1165
|
+
const wallItems = [...(itemsByWallId.get(rw.wallId) ?? [])].sort(
|
|
1166
|
+
(a, b) => a.interiorLeftOffsetM - b.interiorLeftOffsetM || a.elevationM - b.elevationM,
|
|
1167
|
+
)
|
|
1168
|
+
return {
|
|
1169
|
+
wallId: rw.wallId,
|
|
1170
|
+
name: rw.name,
|
|
1171
|
+
startXz: rw.startXz,
|
|
1172
|
+
endXz: rw.endXz,
|
|
1173
|
+
startPlan: rw.startPlan,
|
|
1174
|
+
endPlan: rw.endPlan,
|
|
1175
|
+
lengthM: rw.lengthM,
|
|
1176
|
+
heightM: rw.heightM,
|
|
1177
|
+
thicknessM: rw.thicknessM,
|
|
1178
|
+
tangentPlan: rw.tangentPlan,
|
|
1179
|
+
inwardPlan: rw.inwardPlan,
|
|
1180
|
+
inwardPlanX: rw.inwardPlanX,
|
|
1181
|
+
inwardPlanY: rw.inwardPlanY,
|
|
1182
|
+
isExterior: rw.isExterior,
|
|
1183
|
+
openingIntervals: rw.openingIntervals,
|
|
1184
|
+
items: wallItems,
|
|
1185
|
+
}
|
|
1186
|
+
})
|
|
1187
|
+
|
|
1188
|
+
return {
|
|
1189
|
+
room,
|
|
1190
|
+
roomId: room.id,
|
|
1191
|
+
roomName: room.name,
|
|
1192
|
+
walls,
|
|
1193
|
+
attributions,
|
|
1194
|
+
unattributedNodeIds,
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/**
|
|
1199
|
+
* Compile a spatially grounded architectural render prompt for a specific camera viewpoint
|
|
1200
|
+
* inside a Pascal room:
|
|
1201
|
+
* - Maps `fromXz` and `lookAtXz` into right-handed plan coordinates `[x, -z]`.
|
|
1202
|
+
* - Clips each room perimeter wall segment to the camera front plane `f >= 0` and classifies
|
|
1203
|
+
* visible walls into `sides: { LEFT, AHEAD, RIGHT, BEHIND }`.
|
|
1204
|
+
* - Tracks `solidWallIds` and `visibleWindowWalls`, enforces tight-room `scaleBlock` when
|
|
1205
|
+
* `Math.min(room.widthM, room.depthM) <= tightRoomThresholdM`, and audits `view.scene` prose
|
|
1206
|
+
* for window/daylight contradictions (`sceneConflicts`).
|
|
1207
|
+
*/
|
|
1208
|
+
export function compileRoomRenderPrompt(
|
|
1209
|
+
nodes: Readonly<Record<string, SceneNodeLike>>,
|
|
1210
|
+
roomIdOrName: string,
|
|
1211
|
+
view: RoomCameraViewInput,
|
|
1212
|
+
options?: CompileRoomRenderPromptOptions,
|
|
1213
|
+
): RoomRenderPromptResult {
|
|
1214
|
+
if (!isPlainRecord(view)) {
|
|
1215
|
+
throw new Error('compileRoomRenderPrompt requires a view configuration object.')
|
|
1216
|
+
}
|
|
1217
|
+
if (options !== undefined && !isPlainRecord(options)) {
|
|
1218
|
+
throw new Error('compileRoomRenderPrompt options must be a plain object.')
|
|
1219
|
+
}
|
|
1220
|
+
if (typeof view.id !== 'string' || view.id.trim().length === 0) {
|
|
1221
|
+
throw new Error('view.id must be a non-empty string.')
|
|
1222
|
+
}
|
|
1223
|
+
const viewId = view.id.trim()
|
|
1224
|
+
const fromXz = parseStrictVec2(view.fromXz, 'view.fromXz')
|
|
1225
|
+
const lookAtXz = parseStrictVec2(view.lookAtXz, 'view.lookAtXz')
|
|
1226
|
+
|
|
1227
|
+
const fromPlan = sceneXzToPlan(fromXz[0], fromXz[1])
|
|
1228
|
+
const lookAtPlan = sceneXzToPlan(lookAtXz[0], lookAtXz[1])
|
|
1229
|
+
|
|
1230
|
+
const dx = lookAtPlan[0] - fromPlan[0]
|
|
1231
|
+
const dy = lookAtPlan[1] - fromPlan[1]
|
|
1232
|
+
const lookDist = Math.hypot(dx, dy)
|
|
1233
|
+
if (lookDist <= 1e-6) {
|
|
1234
|
+
throw new Error('view.fromXz and view.lookAtXz must be distinct coordinates.')
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
const tightRoomThresholdM =
|
|
1238
|
+
options?.tightRoomThresholdM !== undefined
|
|
1239
|
+
? assertStrictFiniteNumber(options.tightRoomThresholdM, 'options.tightRoomThresholdM')
|
|
1240
|
+
: FURNISHING_SPATIAL_GROUNDING_DEFAULTS.tightRoomThresholdM
|
|
1241
|
+
if (tightRoomThresholdM <= 0) {
|
|
1242
|
+
throw new Error('options.tightRoomThresholdM must be > 0.')
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
if (options?.mustAppear !== undefined && !Array.isArray(options.mustAppear)) {
|
|
1246
|
+
throw new Error('options.mustAppear must be an array of strings when provided.')
|
|
1247
|
+
}
|
|
1248
|
+
if (options?.shellNotes !== undefined && !Array.isArray(options.shellNotes)) {
|
|
1249
|
+
throw new Error('options.shellNotes must be an array of strings when provided.')
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
const { anatomy, room, roomWalls } = resolveTargetRoomAndWalls(
|
|
1253
|
+
nodes,
|
|
1254
|
+
roomIdOrName,
|
|
1255
|
+
options?.levelId,
|
|
1256
|
+
)
|
|
1257
|
+
|
|
1258
|
+
const forward: Vec2 = [dx / lookDist, dy / lookDist]
|
|
1259
|
+
const screenRight: Vec2 = [forward[1], -forward[0]]
|
|
1260
|
+
|
|
1261
|
+
const leftWalls: string[] = []
|
|
1262
|
+
const aheadWalls: string[] = []
|
|
1263
|
+
const rightWalls: string[] = []
|
|
1264
|
+
const behindWalls: string[] = []
|
|
1265
|
+
const visibleWallBuckets = new Map<string, 'LEFT' | 'AHEAD' | 'RIGHT'>()
|
|
1266
|
+
|
|
1267
|
+
const projectRel = (pt: Vec2): { readonly f: number; readonly r: number } => ({
|
|
1268
|
+
f: (pt[0] - fromPlan[0]) * forward[0] + (pt[1] - fromPlan[1]) * forward[1],
|
|
1269
|
+
r: (pt[0] - fromPlan[0]) * screenRight[0] + (pt[1] - fromPlan[1]) * screenRight[1],
|
|
1270
|
+
})
|
|
1271
|
+
|
|
1272
|
+
for (const wall of roomWalls) {
|
|
1273
|
+
const p0 = wall.startPlan
|
|
1274
|
+
const p1 = wall.endPlan
|
|
1275
|
+
const mid: Vec2 = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2]
|
|
1276
|
+
const pr0 = projectRel(p0)
|
|
1277
|
+
const pr1 = projectRel(p1)
|
|
1278
|
+
const prM = projectRel(mid)
|
|
1279
|
+
const maxF = Math.max(pr0.f, pr1.f, prM.f)
|
|
1280
|
+
|
|
1281
|
+
if (maxF <= 0.05) {
|
|
1282
|
+
behindWalls.push(wall.wallId)
|
|
1283
|
+
continue
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
// Clip wall segment [p0, p1] to camera front plane f >= 0
|
|
1287
|
+
let v0: Vec2 = p0
|
|
1288
|
+
let v1: Vec2 = p1
|
|
1289
|
+
if (pr0.f < 0 && pr1.f >= 0) {
|
|
1290
|
+
const t = pr0.f / (pr0.f - pr1.f)
|
|
1291
|
+
v0 = [p0[0] + t * (p1[0] - p0[0]), p0[1] + t * (p1[1] - p0[1])]
|
|
1292
|
+
} else if (pr1.f < 0 && pr0.f >= 0) {
|
|
1293
|
+
const t = pr0.f / (pr0.f - pr1.f)
|
|
1294
|
+
v1 = [p0[0] + t * (p1[0] - p0[0]), p0[1] + t * (p1[1] - p0[1])]
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
if (Math.hypot(v1[0] - v0[0], v1[1] - v0[1]) <= 0.05) {
|
|
1298
|
+
behindWalls.push(wall.wallId)
|
|
1299
|
+
continue
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
const visMid: Vec2 = [(v0[0] + v1[0]) / 2, (v0[1] + v1[1]) / 2]
|
|
1303
|
+
const vr0 = projectRel(v0)
|
|
1304
|
+
const vr1 = projectRel(v1)
|
|
1305
|
+
const vrM = projectRel(visMid)
|
|
1306
|
+
const straddlesAxis = (vr0.r <= 0.05 && vr1.r >= -0.05) || (vr1.r <= 0.05 && vr0.r >= -0.05)
|
|
1307
|
+
|
|
1308
|
+
let bucket: 'LEFT' | 'AHEAD' | 'RIGHT'
|
|
1309
|
+
if (straddlesAxis || Math.abs(vrM.r) <= vrM.f * 0.55) {
|
|
1310
|
+
bucket = 'AHEAD'
|
|
1311
|
+
aheadWalls.push(wall.wallId)
|
|
1312
|
+
} else if (vrM.r < 0) {
|
|
1313
|
+
bucket = 'LEFT'
|
|
1314
|
+
leftWalls.push(wall.wallId)
|
|
1315
|
+
} else {
|
|
1316
|
+
bucket = 'RIGHT'
|
|
1317
|
+
rightWalls.push(wall.wallId)
|
|
1318
|
+
}
|
|
1319
|
+
visibleWallBuckets.set(wall.wallId, bucket)
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
const sides: RoomCameraWallSides = {
|
|
1323
|
+
LEFT: leftWalls,
|
|
1324
|
+
AHEAD: aheadWalls,
|
|
1325
|
+
RIGHT: rightWalls,
|
|
1326
|
+
BEHIND: behindWalls,
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
const solidWallIds = roomWalls
|
|
1330
|
+
.filter((w) => w.openingIntervals.length === 0)
|
|
1331
|
+
.map((w) => w.wallId)
|
|
1332
|
+
|
|
1333
|
+
const visibleWindowWalls = roomWalls
|
|
1334
|
+
.filter(
|
|
1335
|
+
(w) =>
|
|
1336
|
+
visibleWallBuckets.has(w.wallId) &&
|
|
1337
|
+
w.openingIntervals.some((iv) => iv.kind === 'window'),
|
|
1338
|
+
)
|
|
1339
|
+
.map((w) => w.wallId)
|
|
1340
|
+
|
|
1341
|
+
const narrowDimM = round3(Math.min(room.widthM, room.depthM))
|
|
1342
|
+
const longDimM = round3(Math.max(room.widthM, room.depthM))
|
|
1343
|
+
const ceilingHeightM =
|
|
1344
|
+
roomWalls.length > 0 ? round3(Math.max(...roomWalls.map((w) => w.heightM))) : 2.7
|
|
1345
|
+
const isTightRoom = narrowDimM > 0 && narrowDimM <= tightRoomThresholdM
|
|
1346
|
+
|
|
1347
|
+
const wallSummaries = roomWalls.map((w) => {
|
|
1348
|
+
const doors = w.openingIntervals.filter((iv) => iv.kind === 'door')
|
|
1349
|
+
const windows = w.openingIntervals.filter((iv) => iv.kind === 'window')
|
|
1350
|
+
if (doors.length === 0 && windows.length === 0) {
|
|
1351
|
+
return `- ${w.name} [${w.wallId}] (${w.lengthM.toFixed(2)}m): solid unbroken wall`
|
|
1352
|
+
}
|
|
1353
|
+
const parts: string[] = []
|
|
1354
|
+
if (doors.length > 0) {
|
|
1355
|
+
const spans = doors
|
|
1356
|
+
.map((d) => `${d.widthM.toFixed(2)}m @ ${d.interiorLeftOffsetM.toFixed(2)}m..${d.interiorRightOffsetM.toFixed(2)}m L->R`)
|
|
1357
|
+
.join(', ')
|
|
1358
|
+
parts.push(`${doors.length} door${doors.length > 1 ? 's' : ''} (${spans})`)
|
|
1359
|
+
}
|
|
1360
|
+
if (windows.length > 0) {
|
|
1361
|
+
const spans = windows
|
|
1362
|
+
.map((win) => `${win.widthM.toFixed(2)}m @ ${win.interiorLeftOffsetM.toFixed(2)}m..${win.interiorRightOffsetM.toFixed(2)}m L->R`)
|
|
1363
|
+
.join(', ')
|
|
1364
|
+
parts.push(`${windows.length} window${windows.length > 1 ? 's' : ''} (${spans})`)
|
|
1365
|
+
}
|
|
1366
|
+
return `- ${w.name} [${w.wallId}] (${w.lengthM.toFixed(2)}m): ${parts.join('; ')}`
|
|
1367
|
+
})
|
|
1368
|
+
|
|
1369
|
+
const shellNotes: string[] = []
|
|
1370
|
+
for (const s of options?.shellNotes ?? []) {
|
|
1371
|
+
if (typeof s !== 'string') {
|
|
1372
|
+
throw new Error('Every entry in options.shellNotes must be a string.')
|
|
1373
|
+
}
|
|
1374
|
+
const trimmed = s.trim()
|
|
1375
|
+
if (trimmed.length > 0) shellNotes.push(trimmed)
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
const shellBlock = [
|
|
1379
|
+
`ROOM SHELL (${room.name} [${room.id}]): ${narrowDimM.toFixed(2)}m x ${longDimM.toFixed(2)}m, ceiling ${ceilingHeightM.toFixed(2)}m.`,
|
|
1380
|
+
...wallSummaries,
|
|
1381
|
+
...(shellNotes.length > 0 ? [`Notes: ${shellNotes.join('; ')}`] : []),
|
|
1382
|
+
].join('\n')
|
|
1383
|
+
|
|
1384
|
+
const wallNameMap = new Map<string, string>(roomWalls.map((w) => [w.wallId, w.name]))
|
|
1385
|
+
const solidLabels = solidWallIds.map((id) => `${id} (${wallNameMap.get(id) ?? id})`)
|
|
1386
|
+
const solidClause =
|
|
1387
|
+
solidWallIds.length > 0
|
|
1388
|
+
? `SOLID WALL INVARIANT: Walls [${solidLabels.join(', ')}] have zero openings; do not depict any windows, doors, or alcoves on them.`
|
|
1389
|
+
: 'SOLID WALL INVARIANT: Every wall opening must match its exact compiled position and span.'
|
|
1390
|
+
|
|
1391
|
+
const scaleBlock = isTightRoom
|
|
1392
|
+
? `SCALE LOCK (TIGHT ROOM ${narrowDimM.toFixed(2)}m <= ${tightRoomThresholdM.toFixed(2)}m): Preserve true compact architectural proportions; do not stretch wall spacing or exaggerate room depth with ultra-wide distortion.`
|
|
1393
|
+
: `SCALE LOCK: Maintain true ${narrowDimM.toFixed(2)}m x ${longDimM.toFixed(2)}m floor-plan proportions and ${ceilingHeightM.toFixed(2)}m ceiling height.`
|
|
1394
|
+
|
|
1395
|
+
const cameraLine =
|
|
1396
|
+
typeof view.camera === 'string' && view.camera.trim().length > 0
|
|
1397
|
+
? ` (${view.camera.trim()})`
|
|
1398
|
+
: ''
|
|
1399
|
+
const windowClause =
|
|
1400
|
+
visibleWindowWalls.length > 0
|
|
1401
|
+
? `Visible window walls in frame: [${visibleWindowWalls.join(', ')}].`
|
|
1402
|
+
: 'No windows are visible in this camera orientation (any windows lie behind the camera or room is windowless).'
|
|
1403
|
+
|
|
1404
|
+
const orientationBlock = [
|
|
1405
|
+
`CAMERA ORIENTATION [${viewId}]${cameraLine}: from XZ (${fromXz[0].toFixed(2)}, ${fromXz[1].toFixed(2)}) looking at XZ (${lookAtXz[0].toFixed(2)}, ${lookAtXz[1].toFixed(2)}).`,
|
|
1406
|
+
`AHEAD: [${sides.AHEAD.join(', ') || 'none'}] | LEFT: [${sides.LEFT.join(', ') || 'none'}] | RIGHT: [${sides.RIGHT.join(', ') || 'none'}] | BEHIND (out of frame): [${sides.BEHIND.join(', ') || 'none'}].`,
|
|
1407
|
+
windowClause,
|
|
1408
|
+
].join('\n')
|
|
1409
|
+
|
|
1410
|
+
// Combine explicit `options.mustAppear` + staged retain/hero items inside the room
|
|
1411
|
+
const mustAppearEntries: string[] = []
|
|
1412
|
+
const seenMustAppear = new Set<string>()
|
|
1413
|
+
const pushMustAppear = (raw: string): void => {
|
|
1414
|
+
const clean = raw.trim()
|
|
1415
|
+
if (!clean) return
|
|
1416
|
+
const key = clean.toLowerCase()
|
|
1417
|
+
if (!seenMustAppear.has(key)) {
|
|
1418
|
+
seenMustAppear.add(key)
|
|
1419
|
+
mustAppearEntries.push(clean)
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
for (const entry of options?.mustAppear ?? []) {
|
|
1424
|
+
if (typeof entry !== 'string' || !entry.trim()) {
|
|
1425
|
+
throw new Error('Every entry in options.mustAppear must be a non-empty string.')
|
|
1426
|
+
}
|
|
1427
|
+
pushMustAppear(entry)
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
if (options?.includeStagedItemsInMustAppear !== false) {
|
|
1431
|
+
const roomItems = extractRoomStagedItems(nodes, room, anatomy.rooms, roomWalls)
|
|
1432
|
+
for (const item of roomItems) {
|
|
1433
|
+
if (!item.isRetainOrHero) continue
|
|
1434
|
+
pushMustAppear(`${item.label} (${item.widthM.toFixed(2)}m x ${item.depthM.toFixed(2)}m)`)
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
const mustAppearBlock =
|
|
1439
|
+
mustAppearEntries.length > 0 ? `MUST APPEAR: ${mustAppearEntries.join('; ')}.` : ''
|
|
1440
|
+
|
|
1441
|
+
// Audit `view.scene` prose against compiled camera-relative window visibility & solid walls
|
|
1442
|
+
const sceneText = typeof view.scene === 'string' ? view.scene.trim() : ''
|
|
1443
|
+
const sceneConflicts: string[] = []
|
|
1444
|
+
|
|
1445
|
+
if (sceneText.length > 0) {
|
|
1446
|
+
const deniesWindowRe =
|
|
1447
|
+
/\b(?:no\s+windows?(?:\s+(?:is|are))?(?:\s+visible|\s+in\s+(?:view|frame|sight|shot|this\s+room))?|windowless|without\s+(?:any\s+)?windows?|zero\s+windows?)\b/i
|
|
1448
|
+
|
|
1449
|
+
let mentionsUnnegatedWindow = false
|
|
1450
|
+
for (const m of sceneText.matchAll(/\bwindows?\b/gi)) {
|
|
1451
|
+
const idx = m.index ?? 0
|
|
1452
|
+
const prefix = sceneText.slice(Math.max(0, idx - 32), idx).toLowerCase()
|
|
1453
|
+
const after = sceneText.slice(idx, Math.min(sceneText.length, idx + 36)).toLowerCase()
|
|
1454
|
+
const negatedBefore =
|
|
1455
|
+
/\b(?:no|not|without|zero|lack|lacks|lacking|absent|behind|off-camera)\s+(?:[a-z0-9_-]+\s+){0,3}$/.test(
|
|
1456
|
+
prefix,
|
|
1457
|
+
)
|
|
1458
|
+
const negatedAfter =
|
|
1459
|
+
/^windows?\s+(?:is\s+|are\s+)?(?:out\s+of\s+(?:shot|frame|view)|behind\s+the\s+camera|not\s+(?:in\s+(?:shot|frame|view)|visible))/.test(
|
|
1460
|
+
after,
|
|
1461
|
+
)
|
|
1462
|
+
if (!negatedBefore && !negatedAfter) {
|
|
1463
|
+
mentionsUnnegatedWindow = true
|
|
1464
|
+
break
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
const daylightStream =
|
|
1469
|
+
/\b(?:sunlight|daylight|morning\s+light|afternoon\s+sun|sunbeams?)\s+(?:streams?|streaming|pouring|filtering|flooding|coming|through)\b/i.test(
|
|
1470
|
+
sceneText,
|
|
1471
|
+
) ||
|
|
1472
|
+
/\b(?:streaming|pouring|filtering|flooding)\s+(?:[a-z0-9_-]+\s+){0,2}(?:sunlight|daylight|sunbeams?)\b/i.test(
|
|
1473
|
+
sceneText,
|
|
1474
|
+
)
|
|
1475
|
+
|
|
1476
|
+
if (
|
|
1477
|
+
visibleWindowWalls.length === 0 &&
|
|
1478
|
+
!deniesWindowRe.test(sceneText) &&
|
|
1479
|
+
(mentionsUnnegatedWindow || daylightStream)
|
|
1480
|
+
) {
|
|
1481
|
+
sceneConflicts.push(
|
|
1482
|
+
`View "${viewId}" scene description claims a visible window or streaming window daylight, but visibleWindowWalls is empty for this camera orientation.`,
|
|
1483
|
+
)
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
if (visibleWindowWalls.length > 0 && deniesWindowRe.test(sceneText)) {
|
|
1487
|
+
sceneConflicts.push(
|
|
1488
|
+
`View "${viewId}" scene description claims no windows are visible, contradicting visibleWindowWalls [${visibleWindowWalls.join(', ')}].`,
|
|
1489
|
+
)
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
const solidCardinals = new Set<string>()
|
|
1493
|
+
for (const rw of roomWalls) {
|
|
1494
|
+
if (rw.openingIntervals.length === 0 && rw.cardinalSide) {
|
|
1495
|
+
solidCardinals.add(rw.cardinalSide)
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
for (const cardinal of solidCardinals) {
|
|
1499
|
+
const solidClaimRe = new RegExp(
|
|
1500
|
+
`\\b(?:window|door|doorway|archway)s?\\s+on\\s+the\\s+${cardinal}\\s+wall\\b`,
|
|
1501
|
+
'i',
|
|
1502
|
+
)
|
|
1503
|
+
if (solidClaimRe.test(sceneText)) {
|
|
1504
|
+
sceneConflicts.push(
|
|
1505
|
+
`View "${viewId}" scene description places an opening on the solid ${cardinal} wall.`,
|
|
1506
|
+
)
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
const promptParts = [
|
|
1512
|
+
shellBlock,
|
|
1513
|
+
solidClause,
|
|
1514
|
+
scaleBlock,
|
|
1515
|
+
orientationBlock,
|
|
1516
|
+
...(mustAppearBlock ? [mustAppearBlock] : []),
|
|
1517
|
+
...(sceneText ? [`SCENE: ${sceneText}`] : []),
|
|
1518
|
+
]
|
|
1519
|
+
|
|
1520
|
+
return {
|
|
1521
|
+
viewId,
|
|
1522
|
+
roomId: room.id,
|
|
1523
|
+
roomName: room.name,
|
|
1524
|
+
prompt: promptParts.join('\n\n'),
|
|
1525
|
+
shellBlock,
|
|
1526
|
+
solidClause,
|
|
1527
|
+
scaleBlock,
|
|
1528
|
+
orientationBlock,
|
|
1529
|
+
mustAppearBlock,
|
|
1530
|
+
sides,
|
|
1531
|
+
solidWallIds,
|
|
1532
|
+
visibleWindowWalls,
|
|
1533
|
+
isTightRoom,
|
|
1534
|
+
sceneConflicts,
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
function tokenizeAxisDescription(text: string): ReadonlySet<string> {
|
|
1539
|
+
const matches = text.toLowerCase().match(/[a-z0-9]{2,}/g)
|
|
1540
|
+
return matches ? new Set<string>(matches) : new Set<string>()
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
/**
|
|
1544
|
+
* Evaluate pairwise structural $k$-of-$N$ axis differentiation across interior staging
|
|
1545
|
+
* direction candidates (default `4` of `7` structural axes: `plan`, `ceiling`, `floor`,
|
|
1546
|
+
* `seating`, `storage`, `lighting`, `programme`).
|
|
1547
|
+
*
|
|
1548
|
+
* - Deduplicates custom `options.axes` while preserving declaration order.
|
|
1549
|
+
* - Rejects cosmetic colourway clones via normalized equality + lexical token Jaccard
|
|
1550
|
+
* (`similarityThreshold = 0.72`).
|
|
1551
|
+
* - Flags blank/missing axis entries in `missingAxes` and NEVER counts missing axes as differing.
|
|
1552
|
+
* - Verifies `requiredBudgetTiers` (`'value' | 'mid-tier' | 'designer'`).
|
|
1553
|
+
*/
|
|
1554
|
+
export function evaluateStagingDirectionsDiversity(
|
|
1555
|
+
candidates: readonly StagingDirectionCandidate[],
|
|
1556
|
+
options?: EvaluateStagingDirectionsOptions,
|
|
1557
|
+
): StagingDirectionsDiversityResult {
|
|
1558
|
+
if (!Array.isArray(candidates)) {
|
|
1559
|
+
throw new Error('evaluateStagingDirectionsDiversity requires a candidates array.')
|
|
1560
|
+
}
|
|
1561
|
+
if (options !== undefined && !isPlainRecord(options)) {
|
|
1562
|
+
throw new Error('evaluateStagingDirectionsDiversity options must be a plain object.')
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
let axes: string[]
|
|
1566
|
+
if (options?.axes !== undefined) {
|
|
1567
|
+
if (!Array.isArray(options.axes) || options.axes.length === 0) {
|
|
1568
|
+
throw new Error('options.axes must be a non-empty array of axis names.')
|
|
1569
|
+
}
|
|
1570
|
+
const seenAxes = new Set<string>()
|
|
1571
|
+
axes = []
|
|
1572
|
+
for (let i = 0; i < options.axes.length; i++) {
|
|
1573
|
+
const rawAx = options.axes[i]
|
|
1574
|
+
if (typeof rawAx !== 'string' || rawAx.trim().length === 0) {
|
|
1575
|
+
throw new Error(`options.axes[${i}] must be a non-empty string.`)
|
|
1576
|
+
}
|
|
1577
|
+
const cleanAx = rawAx.trim()
|
|
1578
|
+
if (!seenAxes.has(cleanAx)) {
|
|
1579
|
+
seenAxes.add(cleanAx)
|
|
1580
|
+
axes.push(cleanAx)
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
} else {
|
|
1584
|
+
axes = [...DEFAULT_STAGING_DESIGN_AXES]
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
const minDifferingAxes =
|
|
1588
|
+
options?.minDifferingAxes !== undefined
|
|
1589
|
+
? assertStrictFiniteNumber(options.minDifferingAxes, 'options.minDifferingAxes')
|
|
1590
|
+
: Math.ceil(axes.length / 2)
|
|
1591
|
+
if (!Number.isInteger(minDifferingAxes) || minDifferingAxes < 1 || minDifferingAxes > axes.length) {
|
|
1592
|
+
throw new Error(`options.minDifferingAxes must be an integer between 1 and ${axes.length}.`)
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
const similarityThreshold =
|
|
1596
|
+
options?.similarityThreshold !== undefined
|
|
1597
|
+
? assertStrictFiniteNumber(options.similarityThreshold, 'options.similarityThreshold')
|
|
1598
|
+
: 0.72
|
|
1599
|
+
if (similarityThreshold <= 0 || similarityThreshold > 1) {
|
|
1600
|
+
throw new Error('options.similarityThreshold must be in (0, 1].')
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
const requiredBudgetTiers: BudgetTier[] = []
|
|
1604
|
+
if (options?.requiredBudgetTiers !== undefined) {
|
|
1605
|
+
if (!Array.isArray(options.requiredBudgetTiers)) {
|
|
1606
|
+
throw new Error('options.requiredBudgetTiers must be an array of BudgetTier values.')
|
|
1607
|
+
}
|
|
1608
|
+
const seenReq = new Set<BudgetTier>()
|
|
1609
|
+
for (let i = 0; i < options.requiredBudgetTiers.length; i++) {
|
|
1610
|
+
const rawTier = options.requiredBudgetTiers[i]
|
|
1611
|
+
if (typeof rawTier !== 'string' || !VALID_BUDGET_TIERS.has(rawTier.trim())) {
|
|
1612
|
+
throw new Error(
|
|
1613
|
+
`options.requiredBudgetTiers[${i}] must be one of 'value' | 'mid-tier' | 'designer'.`,
|
|
1614
|
+
)
|
|
1615
|
+
}
|
|
1616
|
+
const cleanTier = rawTier.trim() as BudgetTier
|
|
1617
|
+
if (!seenReq.has(cleanTier)) {
|
|
1618
|
+
seenReq.add(cleanTier)
|
|
1619
|
+
requiredBudgetTiers.push(cleanTier)
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
const missingAxes: StagingDirectionMissingAxis[] = []
|
|
1625
|
+
const presentTiers = new Set<BudgetTier>()
|
|
1626
|
+
const seenCandidateIds = new Set<string>()
|
|
1627
|
+
|
|
1628
|
+
type ParsedAxisEntry = {
|
|
1629
|
+
readonly normalized: string
|
|
1630
|
+
readonly tokens: ReadonlySet<string>
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
const parsedCandidates = candidates.map((cand, idx) => {
|
|
1634
|
+
if (!isPlainRecord(cand) || typeof cand.id !== 'string' || cand.id.trim().length === 0) {
|
|
1635
|
+
throw new Error(`candidates[${idx}] must be an object with a non-empty string "id".`)
|
|
1636
|
+
}
|
|
1637
|
+
const id = cand.id.trim()
|
|
1638
|
+
if (seenCandidateIds.has(id)) {
|
|
1639
|
+
throw new Error(`Duplicate candidate id "${id}".`)
|
|
1640
|
+
}
|
|
1641
|
+
seenCandidateIds.add(id)
|
|
1642
|
+
|
|
1643
|
+
if (cand.budgetTier !== undefined) {
|
|
1644
|
+
if (typeof cand.budgetTier !== 'string' || !VALID_BUDGET_TIERS.has(cand.budgetTier.trim())) {
|
|
1645
|
+
throw new Error(
|
|
1646
|
+
`candidates[${idx}].budgetTier must be one of 'value' | 'mid-tier' | 'designer'.`,
|
|
1647
|
+
)
|
|
1648
|
+
}
|
|
1649
|
+
presentTiers.add(cand.budgetTier.trim() as BudgetTier)
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
if (!isPlainRecord(cand.axes)) {
|
|
1653
|
+
throw new Error(`candidates[${idx}].axes must be a plain object.`)
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
const axisData = new Map<string, ParsedAxisEntry | null>()
|
|
1657
|
+
for (const axis of axes) {
|
|
1658
|
+
const rawVal = Object.hasOwn(cand.axes, axis) ? cand.axes[axis] : undefined
|
|
1659
|
+
if (typeof rawVal !== 'string' || rawVal.trim().length === 0) {
|
|
1660
|
+
missingAxes.push({ id, axis })
|
|
1661
|
+
axisData.set(axis, null)
|
|
1662
|
+
} else {
|
|
1663
|
+
const normalized = rawVal.trim().toLowerCase().replace(/\s+/g, ' ')
|
|
1664
|
+
axisData.set(axis, {
|
|
1665
|
+
normalized,
|
|
1666
|
+
tokens: tokenizeAxisDescription(normalized),
|
|
1667
|
+
})
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
return { id, axisData }
|
|
1671
|
+
})
|
|
1672
|
+
|
|
1673
|
+
const pairResults: StagingDirectionPairResult[] = []
|
|
1674
|
+
const nearDuplicates: StagingDirectionNearDuplicate[] = []
|
|
1675
|
+
|
|
1676
|
+
for (let i = 0; i < parsedCandidates.length; i++) {
|
|
1677
|
+
const cA = parsedCandidates[i]!
|
|
1678
|
+
for (let j = i + 1; j < parsedCandidates.length; j++) {
|
|
1679
|
+
const cB = parsedCandidates[j]!
|
|
1680
|
+
const differingAxes: string[] = []
|
|
1681
|
+
const sharedAxes: string[] = []
|
|
1682
|
+
|
|
1683
|
+
for (const axis of axes) {
|
|
1684
|
+
const entryA = cA.axisData.get(axis) ?? null
|
|
1685
|
+
const entryB = cB.axisData.get(axis) ?? null
|
|
1686
|
+
if (!entryA || !entryB) {
|
|
1687
|
+
// Missing or blank axis entries never count as valid structural differentiation
|
|
1688
|
+
continue
|
|
1689
|
+
}
|
|
1690
|
+
let isSame = entryA.normalized === entryB.normalized
|
|
1691
|
+
if (!isSame && entryA.tokens.size > 0 && entryB.tokens.size > 0) {
|
|
1692
|
+
let inter = 0
|
|
1693
|
+
for (const tok of entryA.tokens) {
|
|
1694
|
+
if (entryB.tokens.has(tok)) inter += 1
|
|
1695
|
+
}
|
|
1696
|
+
const union = entryA.tokens.size + entryB.tokens.size - inter
|
|
1697
|
+
const jaccard = union > 0 ? inter / union : 0
|
|
1698
|
+
if (jaccard >= similarityThreshold) {
|
|
1699
|
+
isSame = true
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
if (isSame) {
|
|
1703
|
+
sharedAxes.push(axis)
|
|
1704
|
+
} else {
|
|
1705
|
+
differingAxes.push(axis)
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
const diffCount = differingAxes.length
|
|
1710
|
+
const distinct = diffCount >= minDifferingAxes
|
|
1711
|
+
pairResults.push({
|
|
1712
|
+
a: cA.id,
|
|
1713
|
+
b: cB.id,
|
|
1714
|
+
differingAxes,
|
|
1715
|
+
sharedAxes,
|
|
1716
|
+
diffCount,
|
|
1717
|
+
distinct,
|
|
1718
|
+
})
|
|
1719
|
+
if (!distinct) {
|
|
1720
|
+
nearDuplicates.push({
|
|
1721
|
+
a: cA.id,
|
|
1722
|
+
b: cB.id,
|
|
1723
|
+
diffCount,
|
|
1724
|
+
sharedAxes: [...sharedAxes],
|
|
1725
|
+
})
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
const missingBudgetTiers = requiredBudgetTiers.filter((tier) => !presentTiers.has(tier))
|
|
1731
|
+
|
|
1732
|
+
const valid =
|
|
1733
|
+
parsedCandidates.length > 0 &&
|
|
1734
|
+
nearDuplicates.length === 0 &&
|
|
1735
|
+
missingAxes.length === 0 &&
|
|
1736
|
+
missingBudgetTiers.length === 0
|
|
1737
|
+
|
|
1738
|
+
const summary = valid
|
|
1739
|
+
? `Staging diversity gate PASSED across ${parsedCandidates.length} candidate(s) (${pairResults.length} pair(s) >= ${minDifferingAxes}/${axes.length} differing axes).`
|
|
1740
|
+
: `Staging diversity gate FAILED: ${nearDuplicates.length} near-duplicate pair(s), ${missingAxes.length} missing axis value(s), ${missingBudgetTiers.length} missing budget tier(s).`
|
|
1741
|
+
|
|
1742
|
+
return {
|
|
1743
|
+
valid,
|
|
1744
|
+
axes,
|
|
1745
|
+
minDifferingAxes,
|
|
1746
|
+
candidateCount: parsedCandidates.length,
|
|
1747
|
+
pairResults,
|
|
1748
|
+
nearDuplicates,
|
|
1749
|
+
missingAxes,
|
|
1750
|
+
missingBudgetTiers,
|
|
1751
|
+
summary,
|
|
1752
|
+
}
|
|
1753
|
+
}
|