diff --git a/packages/editor/src/lib/glb-export-wall-t-junctions.test.ts b/packages/editor/src/lib/glb-export-wall-t-junctions.test.ts new file mode 100644 index 0000000000..38875b12a9 --- /dev/null +++ b/packages/editor/src/lib/glb-export-wall-t-junctions.test.ts @@ -0,0 +1,203 @@ +import { afterEach, describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + LevelNode, + SiteNode, + sceneRegistry, + useScene, + WallNode, + WindowNode, +} from '@pascal-app/core' +import { runWallBuildFrame } from '@pascal-app/viewer' +import * as THREE from 'three' +import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js' +import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js' +import { prepareSceneForExport } from './glb-export' + +function triangles(geometry: THREE.BufferGeometry): THREE.Vector3[][] { + const position = geometry.getAttribute('position') + const index = geometry.index + const count = index?.count ?? position.count + const out: THREE.Vector3[][] = [] + for (let offset = 0; offset < count; offset += 3) { + out.push( + [0, 1, 2].map((corner) => + new THREE.Vector3().fromBufferAttribute( + position, + index ? index.getX(offset + corner) : offset + corner, + ), + ), + ) + } + return out +} + +function countTJunctions(geometry: THREE.BufferGeometry): number { + const tris = triangles(geometry) + const vertices = tris.flat() + const line = new THREE.Line3() + const closest = new THREE.Vector3() + let count = 0 + for (const tri of tris) { + for (let k = 0; k < 3; k += 1) { + line.set(tri[k]!, tri[(k + 1) % 3]!) + const length = line.distance() + if (length < 1e-4) continue + for (const vertex of vertices) { + const t = line.closestPointToPointParameter(vertex, false) + if (t * length < 1e-4 || (1 - t) * length < 1e-4) continue + line.at(t, closest) + if (closest.distanceTo(vertex) < 1e-6) count += 1 + } + } + } + return count +} + +function area(geometry: THREE.BufferGeometry): number { + return triangles(geometry).reduce( + (sum, [a, b, c]) => sum + new THREE.Triangle(a, b, c).getArea(), + 0, + ) +} + +async function exportGlb(scene: THREE.Object3D): Promise { + const originalFileReader = globalThis.FileReader + class ExportFileReader { + result: ArrayBuffer | null = null + onloadend: (() => void) | null = null + readAsArrayBuffer(blob: Blob) { + void blob.arrayBuffer().then((buffer) => { + this.result = buffer + this.onloadend?.() + }) + } + } + globalThis.FileReader = ExportFileReader as unknown as typeof FileReader + try { + return (await new GLTFExporter().parseAsync(scene, { binary: true })) as ArrayBuffer + } finally { + globalThis.FileReader = originalFileReader + } +} + +async function parseGlb(buffer: ArrayBuffer): Promise { + const gltf = await new GLTFLoader().parseAsync(buffer, '') + return gltf.scene +} + +afterEach(() => { + sceneRegistry.clear() +}) + +describe('deferred wall T-junction repair on export (#1273)', () => { + test('live walls stay deferred while exported GLB repairs T-junctions without touching the live mesh', async () => { + const previousScene = useScene.getState() + const level = LevelNode.parse({ id: 'level_tj', level: 0, parentId: 'building_tj' }) + const windowNode = WindowNode.parse({ + id: 'window_tj', + wallId: 'wall_tj_main', + parentId: 'wall_tj_main', + position: [2.5, 1.4, 0], + width: 1.2, + height: 1.2, + }) + const mainWall = WallNode.parse({ + id: 'wall_tj_main', + parentId: level.id, + children: [windowNode.id], + start: [0, 0], + end: [6, 0], + height: 2.6, + thickness: 0.2, + }) + const crossWall = WallNode.parse({ + id: 'wall_tj_cross', + parentId: level.id, + start: [3, 0], + end: [3, 4], + height: 2.6, + thickness: 0.2, + }) + const building = BuildingNode.parse({ + id: 'building_tj', + parentId: 'site_tj', + children: [level.id], + }) + const site = SiteNode.parse({ + id: 'site_tj', + children: [building.id], + }) + const nodes: Record = { + [site.id]: site, + [building.id]: building, + [level.id]: { ...level, children: [mainWall.id, crossWall.id] }, + [mainWall.id]: mainWall, + [crossWall.id]: crossWall, + [windowNode.id]: windowNode, + } + + const root = new THREE.Group() + const wallMaterial = [ + new THREE.MeshStandardMaterial({ color: '#cccccc', name: 'base' }), + new THREE.MeshStandardMaterial({ color: '#dddddd', name: 'front' }), + new THREE.MeshStandardMaterial({ color: '#eeeeee', name: 'back' }), + ] + const mainMesh = new THREE.Mesh(new THREE.BufferGeometry(), wallMaterial) + mainMesh.name = mainWall.id + const crossMesh = new THREE.Mesh(new THREE.BufferGeometry(), wallMaterial) + crossMesh.name = crossWall.id + root.add(mainMesh, crossMesh) + sceneRegistry.nodes.set(mainWall.id, mainMesh) + sceneRegistry.nodes.set(crossWall.id, crossMesh) + + useScene.setState({ + nodes: nodes as never, + dirtyNodes: new Set([mainWall.id, crossWall.id] as never), + }) + + let prepared: ReturnType | null = null + try { + runWallBuildFrame() + + // Live wall mesh defers T-junction repair. + expect(mainMesh.geometry.userData.wallTJunctions).toBe('deferred') + const liveTJunctions = countTJunctions(mainMesh.geometry) + expect(liveTJunctions).toBeGreaterThan(0) + const liveArea = area(mainMesh.geometry) + + // Export preparation repairs the cloned wall meshes without mutating the live mesh. + prepared = prepareSceneForExport(root, nodes, { onlyVisible: false }) + expect(mainMesh.geometry.userData.wallTJunctions).toBe('deferred') + expect(countTJunctions(mainMesh.geometry)).toBe(liveTJunctions) + + const exportedMain = prepared.scene.getObjectByName(mainWall.id) as THREE.Mesh + expect(exportedMain).toBeDefined() + expect(exportedMain.geometry.userData.wallTJunctions).toBeUndefined() + expect(countTJunctions(exportedMain.geometry)).toBe(0) + expect(area(exportedMain.geometry)).toBeCloseTo(liveArea, 5) + expect(exportedMain.geometry.getAttribute('normal')).toBeDefined() + expect(exportedMain.geometry.getAttribute('uv')).toBeDefined() + expect(exportedMain.geometry.getAttribute('uv2')).toBeDefined() + + // Round-trip through GLTFExporter and GLTFLoader: exported GLB has 0 T-junctions. + const glb = await exportGlb(prepared.scene) + const loaded = await parseGlb(glb) + let loadedMeshCount = 0 + loaded.traverse((obj) => { + if (obj instanceof THREE.Mesh && obj.geometry) { + loadedMeshCount += 1 + expect(countTJunctions(obj.geometry)).toBe(0) + } + }) + expect(loadedMeshCount).toBeGreaterThanOrEqual(2) + } finally { + prepared?.dispose() + mainMesh.geometry.dispose() + crossMesh.geometry.dispose() + for (const m of wallMaterial) m.dispose() + useScene.setState(previousScene) + } + }) +}) diff --git a/packages/editor/src/lib/glb-export.ts b/packages/editor/src/lib/glb-export.ts index a34908c351..863b22bf04 100644 --- a/packages/editor/src/lib/glb-export.ts +++ b/packages/editor/src/lib/glb-export.ts @@ -28,6 +28,7 @@ import { isViewerPresentationTextureBorrowed, poseDoorMovingParts, poseWindowMovingParts, + repairDeferredWallTJunctions, restoreWindowRollerShutter, SCENE_LAYER, snapLevelsToTruePositions, @@ -593,6 +594,27 @@ async function completeSceneExportPreparation( } } +function repairDeferredWallMeshesInScene(scene: THREE.Object3D): void { + const deferredWallMeshes: THREE.Mesh[] = [] + const geometryRefCounts = new Map() + scene.traverse((object) => { + const mesh = object as THREE.Mesh + if (mesh.isMesh !== true || !mesh.geometry) return + geometryRefCounts.set(mesh.geometry, (geometryRefCounts.get(mesh.geometry) ?? 0) + 1) + if (mesh.geometry.userData.wallTJunctions === 'deferred') { + deferredWallMeshes.push(mesh) + } + }) + for (const mesh of deferredWallMeshes) { + const sharedCount = geometryRefCounts.get(mesh.geometry) ?? 1 + if (sharedCount > 1) { + geometryRefCounts.set(mesh.geometry, sharedCount - 1) + mesh.geometry = mesh.geometry.clone() + } + repairDeferredWallTJunctions(mesh) + } +} + function finishSceneExportPreparation(preparation: SceneExportPreparation): GlbExport { const { scene, cloneByOriginal, nodes, options, registryEntries } = preparation const identityNodes = new Set() @@ -602,6 +624,7 @@ function finishSceneExportPreparation(preparation: SceneExportPreparation): GlbE } const warnings = pruneNonRenderableMeshes(scene, identityNodes) + repairDeferredWallMeshesInScene(scene) sanitizeMaterialGroups(scene, identityNodes) convertMaterials(scene, options.textures ?? 'embed', options.purpose ?? 'viewer') diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts index 5dfb9e7ea8..199a4274e8 100644 --- a/packages/viewer/src/index.ts +++ b/packages/viewer/src/index.ts @@ -573,10 +573,12 @@ export { generateExtrudedWall, getPendingWallRebuildCount, isWallInitialBuildActive, + repairDeferredWallTJunctions, runWallBuildFrame, type WallGeometryAdapter, type WallGeometryAdapterContext, WallSystem, + type WallTJunctionMode, } from './systems/wall/wall-system' export { advanceWindowAnimations, diff --git a/packages/viewer/src/systems/wall/wall-system.tsx b/packages/viewer/src/systems/wall/wall-system.tsx index 64bce10975..7a5369d1a2 100644 --- a/packages/viewer/src/systems/wall/wall-system.tsx +++ b/packages/viewer/src/systems/wall/wall-system.tsx @@ -1199,6 +1199,8 @@ function updateWallGeometry( terrainBottomAt, slabSupport.faceDatum, buildWallFinishLayout(node, getCachedLevelZones(node, nodes)), + nodes, + 'deferred', ) const wallAngle = Math.atan2(node.end[1] - node.start[1], node.end[0] - node.start[0]) // World transform the render mesh will apply (position + Y-rotation below). @@ -1232,6 +1234,9 @@ function updateWallGeometry( planeTop, terrainBottomAt, slabSupport.faceDatum, + undefined, + nodes, + 'deferred', ) collisionMesh.geometry.dispose() collisionMesh.geometry = collisionGeo @@ -1508,12 +1513,16 @@ function mergeWallTerrainFill( wall: WallNode, boundaryEdges: TaggedWallBoundaryEdge[], finish: WallFinishContext, + tJunctions: WallTJunctionMode = 'repaired', ): THREE.BufferGeometry { const present = fills.filter((fill): fill is THREE.BufferGeometry => fill !== null) if (present.length === 0) return body const bodyGeometry = body.index ? body.toNonIndexed() : body - if (bodyGeometry !== body) body.dispose() + if (bodyGeometry !== body) { + bodyGeometry.userData = { ...body.userData } + body.dispose() + } // The fill is part of each face below the base: it splits at the same finish bounds. const planes = getWallFinishSplitPlanes(finish) const splitFills = present.map((fill) => splitGeometryAtPlanes(fill, planes.y, planes.x)) @@ -1527,7 +1536,47 @@ function mergeWallTerrainFill( bodyGeometry.dispose() for (const fill of splitFills) fill.dispose() - return finishWallFaces(merged, wall, boundaryEdges, finish) + return finishWallFaces(merged, wall, boundaryEdges, finish, tJunctions) +} + +/** + * `repaired` (default) removes T-junctions on every wall build. `deferred` + * skips the repair during live editing and stamps `userData.wallTJunctions = + * 'deferred'` so export preparation can run it on demand on cloned meshes. + */ +export type WallTJunctionMode = 'repaired' | 'deferred' + +/** + * Runs deferred T-junction repair on a wall mesh marked by + * {@link generateExtrudedWall} with `tJunctions = 'deferred'`, recomputing + * vertex normals and the same level-relative planar UVs as the live build, and + * clears the deferred marker. Returns `true` when triangles were split. + */ +export function repairDeferredWallTJunctions(mesh: THREE.Mesh): boolean { + const geometry = mesh.geometry + if (geometry?.userData.wallTJunctions !== 'deferred') return false + + const { wallTJunctions: _deferred, ...preservedUserData } = geometry.userData + const hadUV = geometry.hasAttribute('uv') + const repaired = repairWallTJunctions(geometry) + if (repaired === geometry) { + delete geometry.userData.wallTJunctions + return false + } + + repaired.computeVertexNormals() + ensureRenderableGeometryAttributes(repaired) + repaired.userData = preservedUserData + + let finalGeometry = repaired + if (hadUV) { + mesh.updateMatrix() + finalGeometry = applyWorldPlanarWallUVs(repaired, mesh.matrix) + } + finalGeometry.computeBoundingBox() + finalGeometry.computeBoundingSphere() + mesh.geometry = finalGeometry + return true } /** @@ -1541,9 +1590,15 @@ function finishWallFaces( wall: WallNode, boundaryEdges: TaggedWallBoundaryEdge[], finish: WallFinishContext, + tJunctions: WallTJunctionMode = 'repaired', ): THREE.BufferGeometry { geometry.computeVertexNormals() assignWallMaterialGroups(geometry, wall, boundaryEdges, finish) + if (tJunctions === 'deferred') { + geometry.userData.wallTJunctions = 'deferred' + ensureRenderableGeometryAttributes(geometry) + return geometry + } const repaired = repairWallTJunctions(geometry) if (repaired !== geometry) repaired.computeVertexNormals() ensureRenderableGeometryAttributes(repaired) @@ -1638,6 +1693,7 @@ export function generateExtrudedWall( faceBase?: { a: readonly WallSlabSupportSegment[]; b: readonly WallSlabSupportSegment[] }, finishLayout: WallFinishLayout = buildWallFinishLayout(wallNode, []), sceneNodes: Readonly> = useScene.getState().nodes, + tJunctions: WallTJunctionMode = 'repaired', ): THREE.BufferGeometry { const wallStart: Point2D = { x: wallNode.start[0], y: wallNode.start[1] } const wallEnd: Point2D = { x: wallNode.end[0], y: wallNode.end[1] } @@ -1906,9 +1962,17 @@ export function generateExtrudedWall( wallNode, boundaryEdges, finish, + tJunctions, ) return withWallFinishData( - mergeWallTerrainFill(splitGeometry, belowBaseFills, wallNode, boundaryEdges, finish), + mergeWallTerrainFill( + splitGeometry, + belowBaseFills, + wallNode, + boundaryEdges, + finish, + tJunctions, + ), finish, ) } @@ -1960,10 +2024,18 @@ export function generateExtrudedWall( wallNode, boundaryEdges, finish, + tJunctions, ) return withWallFinishData( - mergeWallTerrainFill(splitResultGeometry, belowBaseFills, wallNode, boundaryEdges, finish), + mergeWallTerrainFill( + splitResultGeometry, + belowBaseFills, + wallNode, + boundaryEdges, + finish, + tJunctions, + ), finish, ) } diff --git a/packages/viewer/src/systems/wall/wall-t-junctions.test.ts b/packages/viewer/src/systems/wall/wall-t-junctions.test.ts index c9e95a6d43..be5665d2bb 100644 --- a/packages/viewer/src/systems/wall/wall-t-junctions.test.ts +++ b/packages/viewer/src/systems/wall/wall-t-junctions.test.ts @@ -3,7 +3,7 @@ import { describe, expect, test } from 'bun:test' import { calculateLevelMiters, sceneRegistry, WallNode, WindowNode } from '@pascal-app/core' import * as THREE from 'three' -import { generateExtrudedWall } from './wall-system' +import { generateExtrudedWall, repairDeferredWallTJunctions } from './wall-system' import { repairWallTJunctions } from './wall-t-junctions' function triangles(geometry: THREE.BufferGeometry): THREE.Vector3[][] { @@ -94,8 +94,69 @@ describe('wall T-junctions', () => { try { const geometry = generateExtrudedWall(wall, [window], calculateLevelMiters([wall])) expect(countTJunctions(geometry)).toBe(0) + expect(geometry.userData.wallTJunctions).toBeUndefined() } finally { sceneRegistry.nodes.delete(wall.id) } }) + + test('deferred mode skips repair and marks geometry; repairDeferredWallTJunctions finishes it on demand', () => { + const wall = WallNode.parse({ + id: 'wall_t-junction-deferred', + start: [1, 2], + end: [6, 2], + height: 2.5, + thickness: 0.2, + }) + const window = WindowNode.parse({ + id: 'window_t-junction-deferred', + wallId: wall.id, + position: [2.5, 1.4, 0], + width: 1.2, + height: 1.2, + }) + const mesh = new THREE.Mesh() + mesh.position.set(wall.start[0], 0, wall.start[1]) + sceneRegistry.nodes.set(wall.id, mesh) + try { + const deferred = generateExtrudedWall( + wall, + [window], + calculateLevelMiters([wall]), + 0, + 0, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'deferred', + ) + deferred.userData.built = true + expect(deferred.userData.wallTJunctions).toBe('deferred') + expect(countTJunctions(deferred)).toBeGreaterThan(0) + const areaBefore = area(deferred) + const groupsBefore = deferred.groups.map((g) => g.materialIndex) + + mesh.geometry = deferred + const didRepair = repairDeferredWallTJunctions(mesh) + + expect(didRepair).toBe(true) + expect(mesh.geometry.userData.wallTJunctions).toBeUndefined() + expect(mesh.geometry.userData.built).toBe(true) + expect(countTJunctions(mesh.geometry)).toBe(0) + expect(area(mesh.geometry)).toBeCloseTo(areaBefore, 6) + expect(mesh.geometry.groups.map((g) => g.materialIndex)).toEqual(groupsBefore) + expect(mesh.geometry.getAttribute('normal')).toBeDefined() + expect(mesh.geometry.getAttribute('uv')).toBeDefined() + expect(mesh.geometry.getAttribute('uv2')).toBeDefined() + + // Calling a second time is a no-op once the deferred marker is cleared. + expect(repairDeferredWallTJunctions(mesh)).toBe(false) + } finally { + mesh.geometry.dispose() + sceneRegistry.nodes.delete(wall.id) + } + }) })