@expofp/wayfinding-geometry 0.0.0-stage → 3.52.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/README.md CHANGED
@@ -1,3 +1,64 @@
1
- # Temporary Holding Version
1
+ # @expofp/wayfinding-geometry
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Wayfinding geometry over plan data, built on the primitives of `@expofp/geometry`.
4
+
5
+ ## `buildingOutlines(polylines, options?)`
6
+
7
+ The building outlines a layer's walls draw: one closed ring per building.
8
+
9
+ ```ts
10
+ import { buildingOutlines } from '@expofp/wayfinding-geometry';
11
+
12
+ const rings = buildingOutlines(wallLayer.polylines); // flat `x, y, …` lists, largest first
13
+ const indoor = buildingOutlines(wallLayer.polylines, { maxBridge: 30 * unitsPerMeter });
14
+ ```
15
+
16
+ `maxBridge` is the longest gap the outline may bridge — an open corner or an opening (below) — in
17
+ plan units; without it there is no limit. The limit does not change which closure is chosen: where
18
+ the chosen one needs a longer bridge, its walls stay open and draw no building — the outline never
19
+ turns inward round an inner wall to keep under it. The viewer sets it to 30 m for its indoor test —
20
+ no door is wider; the compiler leaves it out, so that it gets at least some of the floor to work on.
21
+
22
+ Walls come in as the plan data carries them — flat `x, y, …` vertex lists in plan coordinates — and
23
+ the rings go out in the same form, first vertex not repeated, largest first and, between equals, in
24
+ the order the walls are drawn. A ring starts where its first-drawn wall starts and runs the way that
25
+ wall is drawn; vertices the ring runs straight on through are left out.
26
+
27
+ The walls need not come as an outline. Each wall can be a separate line, corners can be left a little
28
+ open, and openings — doors, a side left out — stay open in the data. The outline is found like this:
29
+
30
+ 1. **The walls are cut where they meet** — where one crosses another, ends on it or runs along it —
31
+ and joined at the points they share. A piece drawn twice counts once.
32
+ 2. **Corners left open are closed.** Two loose wall ends, each the other's nearest, are joined when
33
+ the gap is shorter than either wall and one of the walls runs into the gap, or the two run past
34
+ each other (a step in the outline). Two walls side by side running the same way — an outline drawn
35
+ twice with a shift — are not joined. A gap in a straight wall shorter than the walls beside it is
36
+ closed here too. Before that every gap in a straight wall is closed, its jamb as short as a quarter
37
+ of it and a vestibule wall behind it nearer than the far jamb: a loose end joins the nearest wall
38
+ end ahead on its line (within 5°) where the wall goes on — up to `maxBridge`, or without it, up to
39
+ 0.6 of the longer piece of wall beside the gap, since a door is narrower than its wall.
40
+ 3. **Openings are closed.** From each loose wall end still on a building's outside, a bridge goes to
41
+ a wall end of the same group of walls, or two bridges join two groups. A closure counts only where
42
+ the walls round it turn at least half a turn: three sides of a box close, a bent wall does not. Of
43
+ the closures, the one that takes more walls inside or onto a building wins, then the one giving the
44
+ larger building — when unsure, the building is the larger one. A wall that runs on from a bridge's
45
+ end along the bridge, off its line by drawing error only (1% of the bridge's length), is part of
46
+ the outline: the bridge stops where the wall ends and spans the gap alone. This repeats until
47
+ nothing more closes.
48
+ 4. **The rings are the outsides** of the groups of walls that enclose an area. A group lying inside
49
+ another building — a room, a wall in a hall — is not a building of its own.
50
+
51
+ A bridge closes the outline only: it is no wall, and a consumer must not treat it as one. An opening
52
+ the outline bridges stays open — to sight in the viewer, to the route network in the compiler.
53
+
54
+ Limits:
55
+
56
+ - A wall that meets the outer walls near an opening's jamb and is longer than its gap to the jamb is
57
+ read as a corner, and the outline follows it inward; the drawing has to close such a wall.
58
+ - Without `maxBridge`, two L-shaped fences facing each other close into one building, however far
59
+ apart they stand: the bridges run across the two open corners.
60
+
61
+ ## Development
62
+
63
+ - Build: `pnpm nx build @expofp/wayfinding-geometry`
64
+ - Test: `pnpm nx test @expofp/wayfinding-geometry`
@@ -0,0 +1,2 @@
1
+ export { buildingOutlines } from './lib/building-outlines.js';
2
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { buildingOutlines } from './lib/building-outlines.js';
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The building outlines a layer's walls draw, one ring per building; the rule is in the README.
3
+ * @param polylines - the layer's walls as the plan data carries them: flat `x, y, …` vertex lists
4
+ * @param options - how the outlines are found
5
+ * @param options.maxBridge - the longest bridge in plan units, unlimited by default; walls whose
6
+ * chosen closure needs a longer one stay open.
7
+ * @returns the rings as flat `x, y, …` lists, first vertex not repeated, largest first; empty when
8
+ * the walls draw no building
9
+ */
10
+ export declare function buildingOutlines(polylines: readonly (readonly number[])[], { maxBridge }?: {
11
+ maxBridge?: number;
12
+ }): number[][];
13
+ //# sourceMappingURL=building-outlines.d.ts.map
@@ -0,0 +1,126 @@
1
+ import { pointDistance } from '@expofp/geometry';
2
+ import { closures, pastWallsAlong } from './closures.js';
3
+ import { closeCorners, closeStraightGaps } from './corners.js';
4
+ import { addBridge, buildGraph, EPS, readWalls, sees } from './wall-graph.js';
5
+ import { groupsOf, markNested } from './wall-groups.js';
6
+ /**
7
+ * The buildings as rings, largest first, then in drawing order; each starts and runs as its
8
+ * first-drawn wall.
9
+ * @param graph - the wall graph
10
+ * @param groups - its groups, nesting marked
11
+ * @returns the rings as flat `x, y, …` lists
12
+ */
13
+ function outlines(graph, groups) {
14
+ const { nodes, edges } = graph;
15
+ return groups
16
+ .filter((group) => group.building && !group.nested)
17
+ .map((group) => {
18
+ let ring = [...group.outer].reverse();
19
+ const next = new Map();
20
+ ring.forEach((node, k) => next.set(`${node}>${ring[(k + 1) % ring.length]}`, k));
21
+ let first = null;
22
+ for (const index of group.edges) {
23
+ const { a, b, drawn } = edges[index];
24
+ if (!drawn)
25
+ continue;
26
+ if (first &&
27
+ (first.at[0] < drawn[0] || (first.at[0] === drawn[0] && first.at[1] <= drawn[1]))) {
28
+ continue;
29
+ }
30
+ const forward = next.get(`${a}>${b}`);
31
+ const backward = next.get(`${b}>${a}`);
32
+ if (forward !== undefined)
33
+ first = { at: drawn, k: forward, forward: true };
34
+ else if (backward !== undefined)
35
+ first = { at: drawn, k: backward, forward: false };
36
+ }
37
+ if (first) {
38
+ // Run the way the first piece is drawn, from its start.
39
+ if (!first.forward) {
40
+ ring = ring.reverse();
41
+ first = { ...first, k: ring.length - 1 - ((first.k + 1) % ring.length) };
42
+ }
43
+ ring = [...ring.slice(first.k), ...ring.slice(0, first.k)];
44
+ }
45
+ return {
46
+ ring: straightened(nodes, ring),
47
+ area: -group.outerSum / 2,
48
+ drawn: first?.at[0] ?? Infinity,
49
+ };
50
+ })
51
+ .sort((a, b) => b.area - a.area || a.drawn - b.drawn)
52
+ .map(({ ring }) => {
53
+ const flat = [];
54
+ for (const node of ring)
55
+ flat.push(nodes[node].x, nodes[node].y);
56
+ return flat;
57
+ });
58
+ }
59
+ /**
60
+ * The ring without the vertices it runs straight on through: where walls were cut, and the like.
61
+ * @param nodes - the graph's nodes
62
+ * @param ring - the ring's nodes
63
+ * @returns the nodes it turns at
64
+ */
65
+ function straightened(nodes, ring) {
66
+ return ring.filter((node, k) => {
67
+ const a = nodes[ring[(k - 1 + ring.length) % ring.length]];
68
+ const b = nodes[node];
69
+ const c = nodes[ring[(k + 1) % ring.length]];
70
+ const ux = b.x - a.x;
71
+ const uy = b.y - a.y;
72
+ const vx = c.x - b.x;
73
+ const vy = c.y - b.y;
74
+ return (Math.abs(ux * vy - uy * vx) > EPS * Math.hypot(ux, uy) * Math.hypot(vx, vy) ||
75
+ ux * vx + uy * vy <= 0);
76
+ });
77
+ }
78
+ /**
79
+ * The building outlines a layer's walls draw, one ring per building; the rule is in the README.
80
+ * @param polylines - the layer's walls as the plan data carries them: flat `x, y, …` vertex lists
81
+ * @param options - how the outlines are found
82
+ * @param options.maxBridge - the longest bridge in plan units, unlimited by default; walls whose
83
+ * chosen closure needs a longer one stay open.
84
+ * @returns the rings as flat `x, y, …` lists, first vertex not repeated, largest first; empty when
85
+ * the walls draw no building
86
+ */
87
+ export function buildingOutlines(polylines, { maxBridge = Infinity } = {}) {
88
+ const graph = buildGraph(readWalls(polylines));
89
+ closeStraightGaps(graph, maxBridge);
90
+ closeCorners(graph, maxBridge);
91
+ for (;;) {
92
+ const { groups, groupOf } = groupsOf(graph);
93
+ markNested(graph, groups);
94
+ const found = closures(graph, groups, groupOf);
95
+ if (!found.length)
96
+ return outlines(graph, groups);
97
+ // Closures touching none of the same groups are made in one pass, best first; once a bridge is
98
+ // in, the next closures' bridges are checked for sight again.
99
+ const touched = new Set();
100
+ let bridged = false;
101
+ for (const closure of found) {
102
+ const ids = [...closure.groups, ...closure.islands];
103
+ if (ids.some((id) => touched.has(id)))
104
+ continue;
105
+ if (bridged && !closure.bridges.every(([a, b]) => sees(graph, a, b)))
106
+ continue;
107
+ for (const id of ids)
108
+ touched.add(id);
109
+ // A wall drawn a little off the bridge line is still the outline: the bridge stops where it is.
110
+ const bridges = closure.bridges.map(([a, b]) => {
111
+ const end = pastWallsAlong(graph, b, a);
112
+ const start = pastWallsAlong(graph, a, end);
113
+ return start !== end && sees(graph, start, end) ? [start, end] : [a, b];
114
+ });
115
+ // The limit does not pick another closure: walls whose best closure is too wide stay open.
116
+ if (bridges.some(([a, b]) => pointDistance(graph.nodes[a], graph.nodes[b]) > maxBridge)) {
117
+ for (const [a, b] of bridges)
118
+ graph.blocked.add(a).add(b);
119
+ continue;
120
+ }
121
+ for (const [a, b] of bridges)
122
+ addBridge(graph, a, b);
123
+ bridged = true;
124
+ }
125
+ }
126
+ }
@@ -0,0 +1,32 @@
1
+ import { type WallGraph } from './wall-graph.js';
2
+ import type { Group } from './wall-groups.js';
3
+ /** What closing an opening gives: the bridges, the walls it takes in, the area and the bridge. */
4
+ interface Closure {
5
+ readonly bridges: readonly (readonly [number, number])[];
6
+ readonly held: number;
7
+ readonly area: number;
8
+ readonly bridged: number;
9
+ /** The groups it closes, and the open groups it takes in: what it changes. */
10
+ readonly groups: readonly number[];
11
+ readonly islands: readonly number[];
12
+ }
13
+ /**
14
+ * The closures worth making, best first: a bridge within a group or a pair between two groups, the
15
+ * walls round it turning at least half a turn.
16
+ * @param graph - the wall graph
17
+ * @param groups - its groups, nesting marked
18
+ * @param groupOf - each node's group
19
+ * @returns the closures, best first
20
+ */
21
+ export declare function closures(graph: WallGraph, groups: readonly Group[], groupOf: readonly number[]): Closure[];
22
+ /**
23
+ * Where a bridge should end instead of `from`: past the walls running on from it along the bridge
24
+ * within drawing error.
25
+ * @param graph - the wall graph
26
+ * @param from - the bridge end to move
27
+ * @param to - the other end
28
+ * @returns the node the bridge ends at; `from` when no wall runs along it
29
+ */
30
+ export declare function pastWallsAlong(graph: WallGraph, from: number, to: number): number;
31
+ export {};
32
+ //# sourceMappingURL=closures.d.ts.map
@@ -0,0 +1,254 @@
1
+ import { Box, lineIntersection, pointDistance, ringContainsPoint, } from '@expofp/geometry';
2
+ import { contentsOf, gainOf, leavesOutward, stretch, stretchSum, turnOf, walkOf, } from './walks.js';
3
+ import { cross, EPS, joined, looseNodes, otherEnd, placeOn, pushTo, sees, } from './wall-graph.js';
4
+ /** How far off a bridge, as a share of its length, a wall still runs along it: drawing error. */
5
+ const ALONG_SHARE = 0.01;
6
+ /**
7
+ * Orders closures best first: more walls taken in, then the larger building, then less bridge.
8
+ * @param a - one closure
9
+ * @param b - the other
10
+ * @returns negative when `a` is better, positive when `b` is, zero for a tie
11
+ */
12
+ const compareClosures = (a, b) => b.held - a.held || b.area - a.area || a.bridged - b.bridged;
13
+ const bridgesCross = (nodes, [a, b], [c, d]) => {
14
+ if (a === c || a === d || b === c || b === d)
15
+ return false;
16
+ const hit = lineIntersection({ p0: nodes[a], p1: nodes[b] }, { p0: nodes[c], p1: nodes[d] });
17
+ return !!hit && hit.t > 0 && hit.t < 1 && hit.u > 0 && hit.u < 1;
18
+ };
19
+ /**
20
+ * The closures worth making, best first: a bridge within a group or a pair between two groups, the
21
+ * walls round it turning at least half a turn.
22
+ * @param graph - the wall graph
23
+ * @param groups - its groups, nesting marked
24
+ * @param groupOf - each node's group
25
+ * @returns the closures, best first
26
+ */
27
+ export function closures(graph, groups, groupOf) {
28
+ const { nodes, wallEnds, blocked } = graph;
29
+ const walks = new Map();
30
+ const walkFor = (group) => {
31
+ let w = walks.get(group.id);
32
+ if (!w) {
33
+ w = walkOf(graph, group);
34
+ walks.set(group.id, w);
35
+ }
36
+ return w;
37
+ };
38
+ const looseBy = new Map();
39
+ const stuck = new Set([...blocked].map((node) => groupOf[node]));
40
+ for (const node of looseNodes(graph)) {
41
+ const group = groups[groupOf[node]];
42
+ if (group.nested || stuck.has(group.id) || !walkFor(group).positions.has(node))
43
+ continue;
44
+ pushTo(looseBy, group.id, node);
45
+ }
46
+ // Open groups a closure takes in when they lie inside it.
47
+ const islands = groups.filter((group) => !group.nested && !group.building);
48
+ const takenIn = (ring, own) => {
49
+ let walls = 0;
50
+ let bridged = 0;
51
+ const ids = [];
52
+ const box = Box.fromPoints(ring);
53
+ for (const island of islands) {
54
+ const point = nodes[island.outer[0]];
55
+ if (own.includes(island.id) || !box.containsPoint(point) || !ringContainsPoint(ring, point)) {
56
+ continue;
57
+ }
58
+ const contents = contentsOf(graph, island);
59
+ walls += contents.walls;
60
+ bridged += contents.bridged;
61
+ ids.push(island.id);
62
+ }
63
+ return { walls, bridged, ids };
64
+ };
65
+ const singles = new Map();
66
+ for (const [id, loose] of looseBy) {
67
+ const w = walkFor(groups[id]);
68
+ const candidates = [];
69
+ for (const u of loose) {
70
+ const i = w.positions.get(u)[0];
71
+ for (const [target, at] of w.positions) {
72
+ if (target === u || !wallEnds.has(target) || joined(graph, u, target))
73
+ continue;
74
+ for (const j of at) {
75
+ if (!leavesOutward(graph, w, j, u))
76
+ continue;
77
+ const sA = stretchSum(w, i, j) + cross(nodes[target], nodes[u]);
78
+ const sB = w.prefix[w.walk.length] - sA;
79
+ const [start, end, sum] = sA >= sB ? [i, j, sA] : [j, i, sB];
80
+ if (sum <= 0)
81
+ continue;
82
+ const path = stretch(w.walk, start, end).map((node) => nodes[node]);
83
+ if (Math.abs(turnOf(path)) < Math.PI - EPS)
84
+ continue;
85
+ const gain = gainOf(w, start, end);
86
+ const inside = takenIn(path, [id]);
87
+ candidates.push({
88
+ bridges: [[u, target]],
89
+ groups: [id],
90
+ islands: inside.ids,
91
+ held: gain.walls + inside.walls,
92
+ area: sum / 2,
93
+ bridged: gain.bridged + inside.bridged + pointDistance(nodes[u], nodes[target]),
94
+ });
95
+ }
96
+ }
97
+ }
98
+ candidates.sort(compareClosures);
99
+ const found = candidates.find(({ bridges: [[u, target]] }) => sees(graph, u, target));
100
+ if (found)
101
+ singles.set(id, found);
102
+ }
103
+ const found = [...singles.values()];
104
+ const open = [...looseBy.keys()];
105
+ for (let x = 0; x < open.length; x++) {
106
+ for (let y = x + 1; y < open.length; y++) {
107
+ const pair = bestPair(graph, walkFor(groups[open[x]]), walkFor(groups[open[y]]), {
108
+ ids: [open[x], open[y]],
109
+ loose: [looseBy.get(open[x]), looseBy.get(open[y])],
110
+ takenIn: (ring) => takenIn(ring, [open[x], open[y]]),
111
+ });
112
+ if (!pair)
113
+ continue;
114
+ // Closing each group on its own may take in as much with a larger building or less bridge.
115
+ const sx = singles.get(open[x]);
116
+ const sy = singles.get(open[y]);
117
+ const both = sx &&
118
+ sy && {
119
+ ...sx,
120
+ held: sx.held + sy.held,
121
+ area: sx.area + sy.area,
122
+ bridged: sx.bridged + sy.bridged,
123
+ };
124
+ if (!both || compareClosures(pair, both) < 0)
125
+ found.push(pair);
126
+ }
127
+ }
128
+ return found.filter(({ held }) => held > 0).sort(compareClosures);
129
+ }
130
+ /**
131
+ * Measures the stretches of a walk on demand, each once.
132
+ * @param nodes - the graph's nodes
133
+ * @param w - the walk
134
+ * @returns the side between two walk positions
135
+ */
136
+ function sidesOf(nodes, w) {
137
+ const sides = new Map();
138
+ return (start, end) => {
139
+ const key = start * w.walk.length + end;
140
+ let side = sides.get(key);
141
+ if (!side) {
142
+ const path = stretch(w.walk, start, end).map((node) => nodes[node]);
143
+ side = { path, turn: turnOf(path), gain: gainOf(w, start, end) };
144
+ sides.set(key, side);
145
+ }
146
+ return side;
147
+ };
148
+ }
149
+ /**
150
+ * The best two bridges joining two open groups into one building.
151
+ * @param graph - the wall graph
152
+ * @param wx - one group's walk
153
+ * @param wy - the other's
154
+ * @param options - the two groups, their loose ends, and what a ring takes in besides them
155
+ * @param options.ids - the two groups
156
+ * @param options.loose - the loose ends of each group
157
+ * @param options.takenIn - the walls and bridge length of open groups inside a ring
158
+ * @returns the bridges, or null
159
+ */
160
+ function bestPair(graph, wx, wy, options) {
161
+ const { nodes } = graph;
162
+ const [lx, ly] = options.loose;
163
+ const { takenIn } = options;
164
+ const sideX = sidesOf(nodes, wx);
165
+ const sideY = sidesOf(nodes, wy);
166
+ const clear = new Map();
167
+ const seesOnce = (a, b) => {
168
+ const key = `${a}>${b}`;
169
+ let found = clear.get(key);
170
+ if (found === undefined) {
171
+ found = sees(graph, a, b);
172
+ clear.set(key, found);
173
+ }
174
+ return found;
175
+ };
176
+ let pair = null;
177
+ for (const u1 of lx) {
178
+ for (const u2 of lx) {
179
+ if (u1 === u2)
180
+ continue;
181
+ const i1 = wx.positions.get(u1)[0];
182
+ const i2 = wx.positions.get(u2)[0];
183
+ for (const v1 of ly) {
184
+ for (const v2 of ly) {
185
+ if (v1 === v2)
186
+ continue;
187
+ const j1 = wy.positions.get(v1)[0];
188
+ const j2 = wy.positions.get(v2)[0];
189
+ const sum = stretchSum(wx, i1, i2) +
190
+ cross(nodes[u2], nodes[v2]) +
191
+ stretchSum(wy, j2, j1) +
192
+ cross(nodes[v1], nodes[u1]);
193
+ if (sum <= 0)
194
+ continue;
195
+ const x = sideX(i1, i2);
196
+ const y = sideY(j2, j1);
197
+ if (Math.abs(x.turn + y.turn) < Math.PI - EPS)
198
+ continue;
199
+ if (!seesOnce(v1, u1) || !seesOnce(u2, v2))
200
+ continue;
201
+ if (bridgesCross(nodes, [v1, u1], [u2, v2]))
202
+ continue;
203
+ const inside = takenIn([...x.path, ...y.path]);
204
+ const closure = {
205
+ bridges: [
206
+ [v1, u1],
207
+ [u2, v2],
208
+ ],
209
+ groups: options.ids,
210
+ islands: inside.ids,
211
+ held: x.gain.walls + y.gain.walls + inside.walls,
212
+ area: sum / 2,
213
+ bridged: x.gain.bridged +
214
+ y.gain.bridged +
215
+ inside.bridged +
216
+ pointDistance(nodes[v1], nodes[u1]) +
217
+ pointDistance(nodes[u2], nodes[v2]),
218
+ };
219
+ if (!pair || compareClosures(closure, pair) < 0)
220
+ pair = closure;
221
+ }
222
+ }
223
+ }
224
+ }
225
+ return pair;
226
+ }
227
+ /**
228
+ * Where a bridge should end instead of `from`: past the walls running on from it along the bridge
229
+ * within drawing error.
230
+ * @param graph - the wall graph
231
+ * @param from - the bridge end to move
232
+ * @param to - the other end
233
+ * @returns the node the bridge ends at; `from` when no wall runs along it
234
+ */
235
+ export function pastWallsAlong(graph, from, to) {
236
+ const { nodes, edges, at } = graph;
237
+ const near = ALONG_SHARE * pointDistance(nodes[from], nodes[to]);
238
+ let node = from;
239
+ let reached = 0;
240
+ for (;;) {
241
+ let next = -1;
242
+ for (const index of at[node]) {
243
+ const other = otherEnd(edges[index], node);
244
+ const { along, off } = placeOn(nodes[from], nodes[to], nodes[other]);
245
+ if (along <= reached || along >= 1 || off > near)
246
+ continue;
247
+ next = other;
248
+ reached = along;
249
+ }
250
+ if (next === -1)
251
+ return node;
252
+ node = next;
253
+ }
254
+ }
@@ -0,0 +1,19 @@
1
+ import { type WallGraph } from './wall-graph.js';
2
+ /**
3
+ * Joins each loose wall end to the nearest node ahead of it on its wall's line where a wall runs on —
4
+ * a door or a gap in a straight wall — within the widest bridge. The walls beside the gap need only
5
+ * be a quarter as long as it: the corner rule asks for longer, and misses a door by a short jamb.
6
+ * With no limit the gap must be well short of the longer wall beside it, or two buildings in line would
7
+ * join.
8
+ * @param graph - the wall graph; the bridges are added to it
9
+ * @param maxBridge - the widest gap
10
+ */
11
+ export declare function closeStraightGaps(graph: WallGraph, maxBridge: number): void;
12
+ /**
13
+ * Joins two loose wall ends, each the other's nearest, across a gap shorter than both walls where one
14
+ * wall runs into the gap or the two run past each other.
15
+ * @param graph - the wall graph; the bridges are added to it
16
+ * @param maxBridge - the widest corner gap
17
+ */
18
+ export declare function closeCorners(graph: WallGraph, maxBridge: number): void;
19
+ //# sourceMappingURL=corners.d.ts.map
@@ -0,0 +1,129 @@
1
+ import { pointDistance } from '@expofp/geometry';
2
+ import { addBridge, edgeKey, EPS, looseNodes, otherEnd, sees, } from './wall-graph.js';
3
+ /** How far a wall's continuation may turn off its line, as the sine of the angle: drawing error. */
4
+ const STRAIGHT_SINE = Math.sin((5 * Math.PI) / 180);
5
+ /** The shortest wall a straight gap is read off, as a share of the gap: a shorter stroke has no line. */
6
+ const MIN_SIDE_SHARE = 0.25;
7
+ /** With no limit, the widest straight gap, as a share of the longer wall beside it: a door is narrower. */
8
+ const MAX_DOOR_SHARE = 0.6;
9
+ /**
10
+ * The direction from one point to another, of length 1.
11
+ * @param from - where it starts
12
+ * @param to - where it points
13
+ * @returns the direction; `null` when the points coincide
14
+ */
15
+ function direction(from, to) {
16
+ const length = pointDistance(from, to);
17
+ return length ? { x: (to.x - from.x) / length, y: (to.y - from.y) / length } : null;
18
+ }
19
+ /**
20
+ * Joins each loose wall end to the nearest node ahead of it on its wall's line where a wall runs on —
21
+ * a door or a gap in a straight wall — within the widest bridge. The walls beside the gap need only
22
+ * be a quarter as long as it: the corner rule asks for longer, and misses a door by a short jamb.
23
+ * With no limit the gap must be well short of the longer wall beside it, or two buildings in line would
24
+ * join.
25
+ * @param graph - the wall graph; the bridges are added to it
26
+ * @param maxBridge - the widest gap
27
+ */
28
+ export function closeStraightGaps(graph, maxBridge) {
29
+ const { nodes, edges, at } = graph;
30
+ const runsOnCosine = Math.sqrt(1 - STRAIGHT_SINE * STRAIGHT_SINE);
31
+ const limited = Number.isFinite(maxBridge);
32
+ for (const u of looseNodes(graph)) {
33
+ if (at[u].length !== 1)
34
+ continue;
35
+ const ahead = direction(nodes[otherEnd(edges[at[u][0]], u)], nodes[u]);
36
+ // The straight piece the gap opens from: a wall drawn there and back measures twice its run.
37
+ const ownWall = edges[at[u][0]].length;
38
+ if (!ahead)
39
+ continue;
40
+ let nearest = -1;
41
+ let nearestGap = maxBridge;
42
+ for (let v = 0; v < nodes.length; v++) {
43
+ const x = nodes[v].x - nodes[u].x;
44
+ const y = nodes[v].y - nodes[u].y;
45
+ const along = x * ahead.x + y * ahead.y;
46
+ if (v === u || along <= EPS || along > nearestGap || ownWall < MIN_SIDE_SHARE * along)
47
+ continue;
48
+ if (Math.abs(x * ahead.y - y * ahead.x) > STRAIGHT_SINE * along)
49
+ continue;
50
+ // The longest piece of wall going on from there along the same line, away from the gap.
51
+ let runsOn = 0;
52
+ for (const index of at[v]) {
53
+ const edge = edges[index];
54
+ const on = !edge.bridge && direction(nodes[v], nodes[otherEnd(edge, v)]);
55
+ if (on && on.x * ahead.x + on.y * ahead.y >= runsOnCosine)
56
+ runsOn = Math.max(runsOn, edge.length);
57
+ }
58
+ if (runsOn < MIN_SIDE_SHARE * along)
59
+ continue;
60
+ // With no limit, a gap as wide as the walls beside it may be the street between two buildings.
61
+ if (!limited && along > MAX_DOOR_SHARE * Math.max(ownWall, runsOn))
62
+ continue;
63
+ if (!sees(graph, u, v))
64
+ continue;
65
+ nearest = v;
66
+ nearestGap = along;
67
+ }
68
+ if (nearest >= 0)
69
+ addBridge(graph, u, nearest);
70
+ }
71
+ }
72
+ /**
73
+ * Joins two loose wall ends, each the other's nearest, across a gap shorter than both walls where one
74
+ * wall runs into the gap or the two run past each other.
75
+ * @param graph - the wall graph; the bridges are added to it
76
+ * @param maxBridge - the widest corner gap
77
+ */
78
+ export function closeCorners(graph, maxBridge) {
79
+ const { nodes, edges, at, wallEnds } = graph;
80
+ const out = (node) => {
81
+ const from = nodes[otherEnd(edges[at[node][0]], node)];
82
+ return { x: nodes[node].x - from.x, y: nodes[node].y - from.y };
83
+ };
84
+ const tried = new Set();
85
+ // Joining only takes ends away, so each end's others are sorted by distance once.
86
+ const initial = looseNodes(graph);
87
+ const byDistance = new Map(initial.map((u) => {
88
+ const distance = new Map(initial.map((v) => [v, pointDistance(nodes[u], nodes[v])]));
89
+ const others = initial
90
+ .filter((v) => v !== u)
91
+ .sort((v, w) => distance.get(v) - distance.get(w) || v - w);
92
+ return [u, others];
93
+ }));
94
+ for (;;) {
95
+ const nearest = new Map();
96
+ for (const u of looseNodes(graph)) {
97
+ const v = byDistance.get(u).find((w) => at[w].length === 1 && sees(graph, u, w));
98
+ if (v !== undefined)
99
+ nearest.set(u, v);
100
+ }
101
+ let added = false;
102
+ for (const [u, v] of nearest) {
103
+ if (u > v || nearest.get(v) !== u || tried.has(edgeKey(u, v)))
104
+ continue;
105
+ tried.add(edgeKey(u, v));
106
+ const gap = pointDistance(nodes[u], nodes[v]);
107
+ if (gap >= (wallEnds.get(u) ?? 0) || gap >= (wallEnds.get(v) ?? 0))
108
+ continue;
109
+ const toward = { x: nodes[v].x - nodes[u].x, y: nodes[v].y - nodes[u].y };
110
+ const fromU = out(u);
111
+ const fromV = out(v);
112
+ const intoGap = fromU.x * toward.x + fromU.y * toward.y > 0 || fromV.x * toward.x + fromV.y * toward.y < 0;
113
+ const pastEachOther = fromU.x * fromV.x + fromU.y * fromV.y < 0;
114
+ // Neither runs into the gap: a step in the outline when they run past each other, else two
115
+ // walls side by side or a bent wall's two ends.
116
+ if (!intoGap && !pastEachOther)
117
+ continue;
118
+ // Too wide for a corner: the walls stay open rather than close some other way.
119
+ if (gap > maxBridge) {
120
+ graph.blocked.add(u).add(v);
121
+ continue;
122
+ }
123
+ addBridge(graph, u, v);
124
+ added = true;
125
+ }
126
+ if (!added)
127
+ return;
128
+ }
129
+ }