Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 138 additions & 7 deletions packages/core/src/services/port-connectivity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ describe('port connectivity — joint follow (stretch vs translate)', () => {
expectPointClose(path[1]!, [3, 0, 1.200025])
})

test('a fitting reached from incompatible collars merges constraints deterministically', () => {
test('a fitting its own collars pull apart cannot follow', () => {
const moved = makeNode('duct-segment', {
path: [
[-0.2, 0, 0],
Expand All @@ -328,12 +328,7 @@ describe('port connectivity — joint follow (stretch vs translate)', () => {
],
} as AnyNode

const updates = resolveConnectivityUpdates(connectivity, preview)

expectPointClose(
(updates.find((u) => u.id === fitting.id)!.data as { position: Point }).position,
[0, 0, 0],
)
expect(resolveConnectivityUpdates(connectivity, preview)).toBeNull()
})

test('an unrelated run not on the fitting is left alone', () => {
Expand Down Expand Up @@ -490,6 +485,142 @@ describe('port connectivity — closed loops', () => {
})
})

/** Largest distance from any port of `after` to its nearest mate, for the
* joints that coincided in `before`. */
function widestJointGap(before: Record<string, AnyNode>, after: Record<string, AnyNode>): number {
const portsOf = (node: AnyNode) =>
nodeRegistry.get(node.type)!.ports!(node as never) as Array<{ id: string; position: Point }>
const distance = (a: Point, b: Point) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2])
let widest = 0
for (const a of Object.values(before)) {
for (const b of Object.values(before)) {
if (a.id >= b.id) continue
for (const pa of portsOf(a)) {
for (const pb of portsOf(b)) {
if (distance(pa.position, pb.position) > 1e-6) continue
const na = portsOf(after[a.id]!).find((p) => p.id === pa.id)!
const nb = portsOf(after[b.id]!).find((p) => p.id === pb.id)!
widest = Math.max(widest, distance(na.position, nb.position))
}
}
}
}
return widest
}

describe('port connectivity — polyline runs between fittings', () => {
const corner = (position: Point) =>
makeNode('test:corner-elbow', {
position,
collars: [
[-0.07, 0, 0],
[0, 0, 0.07],
],
system: 'supply',
})
const run = (path: Point[]) => makeNode('duct-segment', { path, system: 'supply' })

// A straight run, a corner, an L-shaped polyline run, a corner and a tail:
// the far corner only ever follows the L, so it echoes the L's own move.
function chain() {
const south = run([
[0.07, 1, 0],
[3.93, 1, 0],
])
const l = run([
[4, 1, 0.07],
[4, 1, 2],
[6.93, 1, 2],
])
const nodes = sceneOf(
south,
corner([4, 1, 0]),
l,
corner([7, 1, 2]),
run([
[7, 1, 2.07],
[7, 1, 5],
]),
)
return { south, l, nodes }
}

function moved(node: AnyNode, path: Point[]): AnyNode {
return { ...(node as Record<string, unknown>), path } as AnyNode
}

function applied(
nodes: Record<string, AnyNode>,
preview: AnyNode,
updates: { id: AnyNodeId; data: Partial<AnyNode> }[],
): Record<string, AnyNode> {
const after: Record<string, AnyNode> = { ...nodes, [preview.id]: preview }
for (const update of updates) after[update.id] = { ...after[update.id]!, ...update.data }
return after
}

test.each([
[0.3, 0, 0.4],
[0.05, 0, 0.05],
[0.3, 0.2, 0.4],
] as Point[])('a diagonal move (%p, %p, %p) carries the L without stretching it', (...delta) => {
const { south, l, nodes } = chain()
const preview = moved(
south,
(south as unknown as { path: Point[] }).path.map(
(p) => [p[0] + delta[0], p[1] + delta[1], p[2] + delta[2]] as Point,
),
)

const updates = resolveConnectivityUpdates(analyzePortConnectivity(south, nodes), preview)

expect(updates).not.toBeNull()
const after = applied(nodes, preview, updates!)
expect(widestJointGap(nodes, after)).toBeLessThan(1e-6)
const lPath = (after[l.id] as unknown as { path: Point[] }).path
expect(Math.hypot(lPath[2]![0] - lPath[1]![0], lPath[2]![2] - lPath[1]![2])).toBeCloseTo(
2.93,
6,
)
})

test('a loop back to the moved run refuses a drag that would pull its start corner off', () => {
// The run's end corner leads around a U-shaped run back to its start corner.
const looped = run([
[0.07, 1, 0],
[3.93, 1, 0],
])
const nodes = sceneOf(
makeNode('test:corner-elbow', {
position: [0, 1, 0],
collars: [
[0.07, 0, 0],
[0, 0, 0.07],
],
system: 'supply',
}),
looped,
corner([4, 1, 0]),
run([
[4, 1, 0.07],
[4, 1, 2],
[0, 1, 2],
[0, 1, 0.07],
]),
)
const connectivity = analyzePortConnectivity(looped, nodes)
const endAt = (end: Point) => moved(looped, [[0.07, 1, 0], end])

// Across the run, the end corner slides the U's first leg; nothing else moves.
const across = resolveConnectivityUpdates(connectivity, endAt([3.93, 1, 0.3]))
expect(across).not.toBeNull()
expect(widestJointGap(nodes, applied(nodes, endAt([3.93, 1, 0.3]), across!))).toBeLessThan(1e-6)
// Along the run, the U translates whole and would carry the start corner
// off the run's fixed start.
expect(resolveConnectivityUpdates(connectivity, endAt([4.43, 1, 0]))).toBeNull()
})
})

test('kind-owned connectivity keeps fixed neighbors and snapshots custom move followers', () => {
registerNode({
kind: 'test:connected-equipment',
Expand Down
55 changes: 50 additions & 5 deletions packages/core/src/services/port-connectivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ import type { AnyNode, AnyNodeId } from '../schema'
* pushes it receives per port. In a closed loop whose legs split a push
* differently (e.g. one sloped leg), every averaging round re-broadcasts
* through both collars of each fitting, so each joint edge holds only its
* newest pending push and the walk has a fixed step budget.
* newest pending push and the walk has a fixed step budget. A follow that
* still leaves a joint open resolves to `null`, so the edit holds its last
* welded frame instead of committing the split.
*/

type Point = readonly [number, number, number]
Expand All @@ -53,11 +55,16 @@ const COINCIDENT_EPS_M = 0.05
const DELTA_EPS_M = 1e-4
const PROPAGATION_EPS_M = 1e-9

/** Walks allowed per joint edge before the resolver keeps its last averaged
* state. Loops settle within a few walks per edge; this only bounds one whose
* averaging never gets below `PROPAGATION_EPS_M`. */
/** Walk steps per joint edge, pooled across the component. Loops settle within
* a few steps per edge; this only bounds one whose averaging never gets below
* `PROPAGATION_EPS_M`. */
const MAX_WALKS_PER_EDGE = 64

/** Widest a joint may open (meters) and still count as welded: above
* `DELTA_EPS_M`, the residue the walk stops chasing, and well inside
* `COINCIDENT_EPS_M`, so the next edit still finds the joint. */
const WELD_EPS_M = 1e-3

/** A node carried by the edit, plus the snapshot needed to revert it. Kept
* deliberately small: the move tools read only `kind` + `nodeId` and the
* matching start snapshot to revert before the single tracked commit. */
Expand Down Expand Up @@ -368,6 +375,18 @@ function runPathFromPortDeltas(startPath: Point[], portDeltas: Record<string, Po
return startPath.map((p) => add(p, startDelta))
}

// A fitting that follows only this run's far end pushes that end's move
// back. Driving the run from one end alone already satisfies such a push;
// the compromise below would shift the end again, and the fitting would
// echo every shift.
for (const [driven, far] of [
['start', 'end'],
['end', 'start'],
] as const) {
const path = runPathFromSinglePortDelta(startPath, driven, portDeltas[driven]!)
if (nearlyEqual(runEndpointDeltas(startPath, path)[far]!, portDeltas[far]!)) return path
}

const startParts = decompose(startDelta, endpointAxis(startPath, 'start'))
const endParts = decompose(endDelta, endpointAxis(startPath, 'end'))
const commonPerp = average([startParts.perp, endParts.perp])
Expand Down Expand Up @@ -395,11 +414,15 @@ function runPathFromPortDeltas(startPath: Point[], portDeltas: Record<string, Po
* to neighbouring joints. Port-level output guards stop consistent cycles;
* coalesced edge pushes and the step budget bound loops that keep averaging,
* while a looped/shared run still accepts constraints at both endpoints.
*
* Returns `null` when the result would leave any snapshotted joint open by more
* than `WELD_EPS_M` (pushes the followers cannot all satisfy, or a walk that ran
* out of budget). Callers hold their last welded frame or refuse the edit.
*/
export function resolveConnectivityUpdates(
connectivity: PortConnectivity,
previewNode: AnyNode,
): { id: AnyNodeId; data: Partial<AnyNode> }[] {
): { id: AnyNodeId; data: Partial<AnyNode> }[] | null {
if (connectivity.customResolver) return connectivity.customResolver(previewNode)
const { graph, adjacency, startMovedPorts, movedNodeId } = connectivity
if (Object.keys(graph).length === 0) return []
Expand Down Expand Up @@ -506,5 +529,27 @@ export function resolveConnectivityUpdates(
}
}

const portDelta = (nodeId: string, portId: string): Point => {
if (nodeId === movedNodeId) {
const start = startMovedPorts[portId]
const now = newMovedPos[portId]
return start && now ? sub(now, start) : [0, 0, 0]
}
const node = graph[nodeId]
const data = results[nodeId]?.data as { position?: Point; path?: Point[] } | undefined
if (!node || !data) return [0, 0, 0]
if (node.role === 'fitting') return sub(data.position!, node.startPosition!)
return runEndpointDeltas(node.startPath!, data.path!)[portId === 'start' ? 'start' : 'end']!
}
for (const [nodeId, byPort] of Object.entries(adjacency)) {
for (const [portId, mates] of Object.entries(byPort)) {
const delta = portDelta(nodeId, portId)
for (const mate of mates) {
const gap = sub(delta, portDelta(mate.nodeId, mate.portId))
if (lenSq(gap) > WELD_EPS_M * WELD_EPS_M) return null
}
}
}

return Object.values(results)
}
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,83 @@ test.each(['duct-segment', 'pipe-segment'] as const)(
},
)

test.each(['duct-segment', 'pipe-segment'] as const)(
'%s drawn from a collar rises to each panel target without a pointer event',
async (toolName) => {
const previousEditor = useEditor.getState()
const previousScope = useInteractionScope.getState()
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window')
const previousAct = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT')
const keyTarget = Object.assign(new EventTarget(), { closest: () => null })
Object.defineProperty(globalThis, 'window', {
value: keyTarget,
configurable: true,
writable: true,
})
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
value: true,
configurable: true,
writable: true,
})
let tool: ReturnType<typeof useDistributionRunTool> | undefined
const commits: Array<[number, number, number]> = []
let targetElevation = 4
function Host() {
const { gl } = useThree()
gl.domElement.getBoundingClientRect = () =>
({ left: 0, top: 0, width: 100, height: 100 }) as DOMRect
tool = useDistributionRunTool({
active: true,
levelId: 'level_test',
toolName,
routingMode: 'vertical',
elevation: 2,
targetElevation,
initialStart: [1, 2, 0],
getPorts: () => [],
findBody: () => null,
commit: ({ end }) => {
commits.push(end)
return { nextStart: end, nextConnection: { port: null, body: null } }
},
})
return null
}
const pressEnter = () =>
act(async () => {
keyTarget.dispatchEvent(Object.assign(new Event('keydown'), { key: 'Enter' }))
})
let renderer: Awaited<ReturnType<typeof create>> | undefined
try {
useEditor.setState({ snappingModeByContext: { wall: 'off', polygon: 'off', item: 'off' } })
renderer = await create(<Host />)
expect(tool?.cursor).toEqual([1, 4, 0])
targetElevation = 5
await renderer.update(<Host />)
expect(tool?.cursor).toEqual([1, 5, 0])
await pressEnter()
expect(commits).toEqual([[1, 5, 0]])

targetElevation = 3
await renderer.update(<Host />)
expect(tool?.cursor).toEqual([1, 3, 0])
await pressEnter()
expect(commits).toEqual([
[1, 5, 0],
[1, 3, 0],
])
} finally {
await renderer?.unmount()
useEditor.setState(previousEditor)
useInteractionScope.setState(previousScope)
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow)
else Reflect.deleteProperty(globalThis, 'window')
if (previousAct) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', previousAct)
else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT')
}
},
)

test('a sloped horizontal route connects at the height its fall reaches', async () => {
const previousScene = useScene.getState()
const previousEditor = useEditor.getState()
Expand Down
Loading
Loading