@kensnzk/koyu 0.22.0 → 0.23.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.
Files changed (54) hide show
  1. package/dist/cli.js +51 -2
  2. package/dist/cli.js.map +1 -1
  3. package/dist/core/model.d.ts +20 -1
  4. package/dist/core/model.d.ts.map +1 -1
  5. package/dist/core/model.js +27 -1
  6. package/dist/core/model.js.map +1 -1
  7. package/dist/core/parse.d.ts.map +1 -1
  8. package/dist/core/parse.js +11 -13
  9. package/dist/core/parse.js.map +1 -1
  10. package/dist/core/poly.d.ts +35 -0
  11. package/dist/core/poly.d.ts.map +1 -1
  12. package/dist/core/poly.js +67 -0
  13. package/dist/core/poly.js.map +1 -1
  14. package/dist/core/section.d.ts +88 -0
  15. package/dist/core/section.d.ts.map +1 -0
  16. package/dist/core/section.js +289 -0
  17. package/dist/core/section.js.map +1 -0
  18. package/dist/draw/axo.d.ts.map +1 -1
  19. package/dist/draw/axo.js +13 -31
  20. package/dist/draw/axo.js.map +1 -1
  21. package/dist/draw/index.d.ts +1 -0
  22. package/dist/draw/index.d.ts.map +1 -1
  23. package/dist/draw/index.js +1 -0
  24. package/dist/draw/index.js.map +1 -1
  25. package/dist/draw/plan.d.ts.map +1 -1
  26. package/dist/draw/plan.js +15 -16
  27. package/dist/draw/plan.js.map +1 -1
  28. package/dist/draw/section.d.ts +23 -0
  29. package/dist/draw/section.d.ts.map +1 -0
  30. package/dist/draw/section.js +168 -0
  31. package/dist/draw/section.js.map +1 -0
  32. package/dist/draw/sheet.d.ts +40 -0
  33. package/dist/draw/sheet.d.ts.map +1 -0
  34. package/dist/draw/sheet.js +93 -0
  35. package/dist/draw/sheet.js.map +1 -0
  36. package/dist/form.d.ts +1 -0
  37. package/dist/form.d.ts.map +1 -1
  38. package/dist/form.js +4 -0
  39. package/dist/form.js.map +1 -1
  40. package/dist/mcp.js +67 -3
  41. package/dist/mcp.js.map +1 -1
  42. package/package.json +1 -1
  43. package/src/cli.ts +57 -1
  44. package/src/core/model.ts +32 -1
  45. package/src/core/parse.ts +13 -12
  46. package/src/core/poly.ts +76 -0
  47. package/src/core/section.ts +360 -0
  48. package/src/draw/axo.ts +13 -29
  49. package/src/draw/index.ts +1 -0
  50. package/src/draw/plan.ts +14 -22
  51. package/src/draw/section.ts +224 -0
  52. package/src/draw/sheet.ts +102 -0
  53. package/src/form.ts +18 -0
  54. package/src/mcp.ts +75 -2
package/src/cli.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  // npm run koyu -- check examples/office.muro # --json で構造化診断、--strict で警告も終了コード1
4
4
  // npm run koyu -- diff before.muro after.muro # 構成の言葉の差分 (--json で ModelDiff)
5
5
  // npm run koyu -- plan examples/office.muro -l L2 -o out/office-L2.svg
6
+ // npm run koyu -- section examples/office.muro --at X2+900 # the cut is named by a grid line
7
+ // npm run koyu -- elevation examples/office.muro --face S
6
8
  // npm run koyu -- doors examples/office.muro /L2/office /out
7
9
  // npm run koyu -- graph examples/office.muro
8
10
  // npm run koyu -- stats examples/office.muro
@@ -26,6 +28,7 @@ import {
26
28
  areaM2,
27
29
  displayName,
28
30
  effectiveAttr,
31
+ gridRef,
29
32
  heff,
30
33
  isSemiOutdoor,
31
34
  levelsSorted,
@@ -41,6 +44,8 @@ import {
41
44
  import { parseFile } from "./parse-file.js";
42
45
  import { svgPlan } from "./draw/plan.js";
43
46
  import { svgAxo } from "./draw/axo.js";
47
+ import { svgElevation, svgSection } from "./draw/section.js";
48
+ import { axisOf } from "./core/section.js";
44
49
  import { slopeText, verticalRuns } from "./core/vertical.js";
45
50
 
46
51
  function load(file: string): Model {
@@ -223,7 +228,7 @@ function main(argv: string[]): number {
223
228
  }
224
229
  if (!cmd || !file) {
225
230
  console.log(
226
- "Usage: koyu <check|validate|layers|diff|plan|axo|doors|graph|stats|levels|runs|light|site|json> <file.muro> [args...]\n" +
231
+ "Usage: koyu <check|validate|layers|diff|plan|axo|section|elevation|doors|graph|stats|levels|runs|light|site|json> <file.muro> [args...]\n" +
227
232
  " check: --json (emit Diagnostic[] as JSON) / --strict (exit 1 if there are warnings) — structural consistency only\n" +
228
233
  " validate: --profile <id> --as-of <YYYY-MM-DD> [--json] — architectural judgement (not what check guarantees)\n" +
229
234
  " layers: the layers that took part in composition, weakest first. --attrs for the provenance of each attribute\n" +
@@ -596,6 +601,57 @@ function main(argv: string[]): number {
596
601
  console.log(`Generated the axonometric: ${outPath}`);
597
602
  return 0;
598
603
  }
604
+ case "section": {
605
+ // The section. **The cut is named by a grid line**, because the notation writes no
606
+ // coordinate directly (docs/reference/muro/positions.md) and a plane is a position too
607
+ const at = opt(rest, "--at");
608
+ if (!at) {
609
+ console.log(
610
+ "Usage: koyu section <file.muro> --at <X3|X3+450|Y2-600> [--look N|E|S|W] [-s <scale>] [-o <out.svg>]",
611
+ );
612
+ return 2;
613
+ }
614
+ const g = gridRef(model, at);
615
+ if (!g) {
616
+ die(
617
+ `Undefined grid reference: ${at} (declared: ${model.grid.X.names.join(" ")} ${model.grid.Y.names.join(" ")})`,
618
+ );
619
+ }
620
+ const chosen = enumOpt(rest, ["N", "E", "S", "W"] as const, "--look");
621
+ if (chosen && axisOf(chosen) !== g.axis) {
622
+ die(
623
+ `--look ${chosen} runs along ${at} rather than across it (an X reference is looked at from E or W, a Y reference from N or S)`,
624
+ );
625
+ }
626
+ const sc = numOpt(rest, "-s", "--scale");
627
+ const outPath = opt(rest, "-o", "--out") ?? `out/section-${at}.svg`;
628
+ const svg = svgSection(model, {
629
+ axis: g.axis,
630
+ at: g.coord,
631
+ atRef: at,
632
+ ...(chosen ? { look: chosen } : {}),
633
+ ...(sc !== undefined ? { scale: sc } : {}),
634
+ });
635
+ mkdirSync(dirname(outPath), { recursive: true });
636
+ writeFileSync(outPath, svg);
637
+ console.log(`Generated the section: ${outPath}`);
638
+ return 0;
639
+ }
640
+ case "elevation": {
641
+ // The elevation — a section whose plane stands outside the mass. Where that plane goes is
642
+ // derived, so naming one is a calling mistake rather than something to ignore
643
+ if (rest.includes("--at")) {
644
+ die("elevation takes no --at (the plane is placed outside the mass; koyu section takes a cut)");
645
+ }
646
+ const face = enumOpt(rest, ["N", "E", "S", "W"] as const, "-f", "--face") ?? "S";
647
+ const sc = numOpt(rest, "-s", "--scale");
648
+ const outPath = opt(rest, "-o", "--out") ?? `out/elevation-${face}.svg`;
649
+ const svg = svgElevation(model, { face, ...(sc !== undefined ? { scale: sc } : {}) });
650
+ mkdirSync(dirname(outPath), { recursive: true });
651
+ writeFileSync(outPath, svg);
652
+ console.log(`Generated the elevation: ${outPath}`);
653
+ return 0;
654
+ }
599
655
 
600
656
  case "runs": {
601
657
  // 縦動線 (ADR-0021): 段数も踏面も勾配も原本には書かれていない。全て導出値である
package/src/core/model.ts CHANGED
@@ -73,7 +73,7 @@ export const LAST_KOYU_SPELLED_VERSION = "1.1";
73
73
  * `since` column is written in this vocabulary, and every surface that answers "which muro
74
74
  * does this build speak" needs both halves at once.
75
75
  */
76
- export const KOYU_VERSION = "0.22.0";
76
+ export const KOYU_VERSION = "0.23.0";
77
77
 
78
78
  /**
79
79
  * Whether `a` names a later language version than `b`.
@@ -241,6 +241,37 @@ export interface GridAxis {
241
241
  coords: number[];
242
242
  }
243
243
 
244
+ /** A grid reference resolved: which axis names it, and where it sits in mm. */
245
+ export interface GridPosition {
246
+ axis: "X" | "Y";
247
+ coord: number;
248
+ }
249
+
250
+ /**
251
+ * A grid reference — `X2`, `X2+600`, `Y3-150` — resolved to an axis and a coordinate in mm.
252
+ * `undefined` when the spelling is not a grid reference, or names no declared line.
253
+ *
254
+ * **This is the one place the spelling is read.** The notation writes no coordinate directly
255
+ * (docs/reference/muro/positions.md), so every position in a source is a reference in this form:
256
+ * an opening's `at:`, a `seg`'s, the endpoints of a drawn line. A caller outside the parser — the
257
+ * `--at` of a section, say — resolves through here rather than through a second copy of the
258
+ * pattern, because two copies is how `--at X3+450` and `at:X3+450` come to disagree.
259
+ *
260
+ * The names are machine-generated (`X1`, `Y2`, …), never written by the author, so the pattern is
261
+ * the whole grammar: an axis letter, a line number, and at most one signed whole-millimetre offset.
262
+ */
263
+ export function gridRef(model: Model, token: string): GridPosition | undefined {
264
+ const m = /^([XY]\d+)([+-]\d+)?$/.exec(token);
265
+ if (!m) return undefined;
266
+ const offset = m[2] ? Number(m[2]) : 0;
267
+ for (const axis of ["X", "Y"] as const) {
268
+ const g = model.grid[axis];
269
+ const i = g.names.indexOf(m[1]!);
270
+ if (i >= 0) return { axis, coord: g.coords[i]! + offset };
271
+ }
272
+ return undefined;
273
+ }
274
+
244
275
  /** mm矩形 (x1<x2, y1<y2) */
245
276
  export interface Rect {
246
277
  x1: number;
package/src/core/parse.ts CHANGED
@@ -11,6 +11,8 @@ import {
11
11
  type Boundary,
12
12
  DEFAULT_LANGUAGE_VERSION,
13
13
  type Edge,
14
+ gridRef,
15
+ type GridPosition,
14
16
  isNewerVersion,
15
17
  KOYU_VERSION,
16
18
  LAST_KOYU_SPELLED_VERSION,
@@ -1202,18 +1204,17 @@ function expandSpan(model: Model, paths: string[], ln: number): string[][] {
1202
1204
  );
1203
1205
  }
1204
1206
 
1205
- /** 通り参照 (X2, X2+600, Y3-150 など) を軸と座標mmに解決する */
1206
- function resolveRef(model: Model, token: string, ln: number): { axis: "X" | "Y"; coord: number } {
1207
- const m = /^([XY]\d+)([+-]\d+)?$/.exec(token);
1208
- if (!m) throw new SourceError(ln, `Undefined grid line name: ${token}`);
1209
- const name = m[1]!;
1210
- const offset = m[2] ? Number(m[2]) : 0;
1211
- for (const axis of ["X", "Y"] as const) {
1212
- const g = model.grid[axis];
1213
- const i = g.names.indexOf(name);
1214
- if (i >= 0) return { axis, coord: g.coords[i]! + offset };
1215
- }
1216
- throw new SourceError(ln, `Undefined grid line name: ${token}`);
1207
+ /**
1208
+ * 通り参照 (X2, X2+600, Y3-150 など) を軸と座標mmに解決する。
1209
+ *
1210
+ * The grammar itself is `gridRef` in model.ts — **one copy**, so that a position named from
1211
+ * outside the source (a section's `--at`) cannot resolve differently from one written in it.
1212
+ * What this adds is the source's own failure: the line it was written on.
1213
+ */
1214
+ function resolveRef(model: Model, token: string, ln: number): GridPosition {
1215
+ const r = gridRef(model, token);
1216
+ if (!r) throw new SourceError(ln, `Undefined grid line name: ${token}`);
1217
+ return r;
1217
1218
  }
1218
1219
 
1219
1220
  function parseBoundary(rest: string[], ln: number): Boundary {
package/src/core/poly.ts CHANGED
@@ -165,6 +165,82 @@ export function unionArea(pieces: Pt[][]): number {
165
165
  return total;
166
166
  }
167
167
 
168
+ /** Where an axis-parallel line meets the boundary of a piece. */
169
+ export interface Crossing {
170
+ /** the coordinate along the line — y for a line `x = at`, x for a line `y = at` */
171
+ at: number;
172
+ /** the edge it sits on: `poly[edge]` → `poly[(edge + 1) % n]` */
173
+ edge: number;
174
+ /** how far along that edge, 0..1 */
175
+ t: number;
176
+ }
177
+
178
+ /**
179
+ * Where the axis-parallel line at `at` crosses a ring — the two extreme crossings, ascending.
180
+ *
181
+ * `axis:"X"` means the line `x = at`. **A convex ring meets a line in exactly one interval**, which
182
+ * is what makes two crossings a whole answer rather than a first one, and every ring in a `Form` is
183
+ * convex (ADR-0022). Handed a ring that is not, it returns the outermost pair, which spans the true
184
+ * answer and is never less than it.
185
+ *
186
+ * **The edge and the parameter come back with the coordinate** because the caller usually holds a
187
+ * value per vertex — the top and bottom z of a prism — and has to read it at the crossing. Handing
188
+ * back the coordinate alone would leave that caller re-deriving where on the ring it was.
189
+ *
190
+ * A vertex on the line counts, so an edge lying along the line is returned as itself. Touching a
191
+ * single corner is not being crossed, and comes back `undefined`.
192
+ */
193
+ export function crossing(poly: Pt[], axis: "X" | "Y", at: number): [Crossing, Crossing] | undefined {
194
+ /** across the line */
195
+ const c = (p: Pt): number => (axis === "X" ? p.x : p.y);
196
+ /** along the line */
197
+ const o = (p: Pt): number => (axis === "X" ? p.y : p.x);
198
+ const found: Crossing[] = [];
199
+ for (let i = 0; i < poly.length; i++) {
200
+ const p = poly[i]!;
201
+ const q = poly[(i + 1) % poly.length]!;
202
+ const dp = c(p) - at;
203
+ const dq = c(q) - at;
204
+ if (Math.abs(dp) <= EPS) found.push({ at: o(p), edge: i, t: 0 });
205
+ if ((dp > EPS && dq < -EPS) || (dp < -EPS && dq > EPS)) {
206
+ const t = dp / (dp - dq);
207
+ found.push({ at: o(p) + t * (o(q) - o(p)), edge: i, t });
208
+ }
209
+ }
210
+ if (found.length < 2) return undefined;
211
+ found.sort((a, b) => a.at - b.at);
212
+ const lo = found[0]!;
213
+ const hi = found[found.length - 1]!;
214
+ return hi.at - lo.at > EPS ? [lo, hi] : undefined;
215
+ }
216
+
217
+ /**
218
+ * The convex hull of a set of points, counter-clockwise (Andrew's monotone chain).
219
+ *
220
+ * **The projection of a convex solid is the hull of its projected vertices**, which is why this is
221
+ * here: a body in a `Form` is a prism over a convex ring whose top and bottom vary linearly, so it
222
+ * is convex, and its silhouette is exact rather than approximate.
223
+ *
224
+ * Collinear points are dropped, so the result carries no vertex that is not a corner.
225
+ */
226
+ export function hull(points: Pt[]): Pt[] {
227
+ if (points.length < 3) return [...points];
228
+ const pts = [...points].sort((a, b) => a.x - b.x || a.y - b.y);
229
+ const cross = (o: Pt, a: Pt, b: Pt): number =>
230
+ (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
231
+ const half = (src: Pt[]): Pt[] => {
232
+ const out: Pt[] = [];
233
+ for (const p of src) {
234
+ while (out.length >= 2 && cross(out[out.length - 2]!, out[out.length - 1]!, p) <= 0) out.pop();
235
+ out.push(p);
236
+ }
237
+ out.pop();
238
+ return out;
239
+ };
240
+ const ring = [...half(pts), ...half([...pts].reverse())];
241
+ return ring.length >= 3 ? ring : [];
242
+ }
243
+
168
244
  // ---- 窓 (どの範囲で測り、どの範囲を切るか) ----
169
245
 
170
246
  /**
@@ -0,0 +1,360 @@
1
+ // koyu — the section and the elevation (ADR-0064)
2
+ //
3
+ // **This reads a `Form` and nothing else.** Every body it cuts was already raised by `derive`, and
4
+ // the constructors it calls to raise the rest (`band` / `columnRect` / `runPrism`) are the
5
+ // published ones. It composes no matter; it re-frames what came out of the one entry point to
6
+ // shape, which is what `planOf` does for a horizontal plane and this does for a vertical one.
7
+ //
8
+ // **Why it is here and not in `src/draw/`.** Everything a section needs is public on `Form`, so a
9
+ // renderer could compute one without tripping a single import gate. What forbids it is not a test
10
+ // but docs/why/plan-is-not-a-section.md: "this is a section, this is a projection" is decided by
11
+ // comparing a range against a plane, and left to the drawing side the thresholds differ per
12
+ // implementation, so one source yields two drawings. The comparison here is the same one, turned
13
+ // on its side.
14
+ //
15
+ // **What a vertical plane needs that a slice does not give.** A slice hands back flat pieces at
16
+ // one x and an empty background. A section is mostly what stands *behind* the plane — the far wall
17
+ // with its windows, the stair beyond the cut — and none of that falls out of cutting. Nor does the
18
+ // decision to throw the near half away, which is a choice of viewpoint and has to be an input.
19
+
20
+ import { band, columnRect, runPrism, type Form } from "./derive.js";
21
+ import type { Edge, Pt } from "./model.js";
22
+ import { crossing, hull, signedArea } from "./poly.js";
23
+ import { EPS } from "./tolerance.js";
24
+
25
+ /** Which axis names the plane. `"X"` means the plane `x = at`. */
26
+ export type SectionAxis = "X" | "Y";
27
+
28
+ /**
29
+ * What a vertical plane divides the mass into. **Two, where a plan has five.**
30
+ *
31
+ * A plan is looked at from above, so it carries what is below the cut, what is above it dropped
32
+ * back down, and the symbols of movement. A section is looked at from the side: what the plane
33
+ * crossed, and what stands behind it. What stands in front is not hidden by convention — it is
34
+ * behind the viewer — so it is not produced at all, and saying so here is what stops each
35
+ * consumer deciding it.
36
+ */
37
+ export type SectionClass = "cut" | "beyond";
38
+
39
+ export type SectionSubject = "space" | "boundary" | "opening" | "column" | "slab" | "run";
40
+
41
+ /** A point on the section. **Not a plan coordinate** — `u` runs across the sheet, `z` is height. */
42
+ export interface SectionPt {
43
+ u: number;
44
+ z: number;
45
+ }
46
+
47
+ /** The plane, and the direction it is looked at from. */
48
+ export interface SectionSpec {
49
+ axis: SectionAxis;
50
+ /** where the plane sits along `axis`, world mm */
51
+ at: number;
52
+ /** the grid reference it was named by, when it was named by one */
53
+ atRef?: string;
54
+ /** the direction of view. `W`/`E` across an X plane, `N`/`S` across a Y plane */
55
+ look: Edge;
56
+ }
57
+
58
+ export interface SectionEntity {
59
+ class: SectionClass;
60
+ of: SectionSubject;
61
+ /** identity of the subject, in the spelling the rest of `Form` uses */
62
+ ref: string;
63
+ /** what the subject already says it is — a slab's face, an opening's leaf, a run's device */
64
+ kind?: string;
65
+ /** counter-clockwise in (u, z), like every outline `Form` returns */
66
+ polygon: SectionPt[];
67
+ /**
68
+ * How far behind the plane the nearest point of the body stands, mm. `0` for anything the plane
69
+ * crossed. **It is a distance, not a draw order** — `Form` holds no draw order, and whether to
70
+ * sort by this, fade by it or ignore it is the drawing's business.
71
+ */
72
+ depth: number;
73
+ }
74
+
75
+ export interface FormSection {
76
+ axis: SectionAxis;
77
+ at: number;
78
+ atRef?: string;
79
+ look: Edge;
80
+ entities: SectionEntity[];
81
+ }
82
+
83
+ /** A body of the `Form`, in the one shape every body reduces to. */
84
+ interface Body {
85
+ of: SectionSubject;
86
+ ref: string;
87
+ kind?: string;
88
+ poly: Pt[];
89
+ bottom: number[];
90
+ top: number[];
91
+ }
92
+
93
+ /** The direction of view as a unit vector in plan. */
94
+ function look(edge: Edge): Pt {
95
+ return edge === "N"
96
+ ? { x: 0, y: 1 }
97
+ : edge === "S"
98
+ ? { x: 0, y: -1 }
99
+ : edge === "E"
100
+ ? { x: 1, y: 0 }
101
+ : { x: -1, y: 0 };
102
+ }
103
+
104
+ /**
105
+ * The axis a direction of view crosses. Looking east or west crosses an X plane.
106
+ *
107
+ * A `look` that runs along the plane rather than across it draws nothing, so it is refused rather
108
+ * than answered — the same treatment `svgPlan` gives a level that was never declared.
109
+ */
110
+ export function axisOf(edge: Edge): SectionAxis {
111
+ return edge === "E" || edge === "W" ? "X" : "Y";
112
+ }
113
+
114
+ /**
115
+ * The direction a section is looked at from when nobody said.
116
+ *
117
+ * The rule is statable rather than conventional: **on the default, `u` is the world coordinate
118
+ * along the cut line**, so a dimension taken off the plan carries into the section without being
119
+ * reversed. Looking the other way mirrors the sheet, which is why it has to be asked for.
120
+ */
121
+ export function defaultLook(axis: SectionAxis): Edge {
122
+ return axis === "X" ? "W" : "N";
123
+ }
124
+
125
+ /**
126
+ * Where the sheet's `u` axis points, in plan. **It is the viewer's right hand**: `u = d × ẑ`.
127
+ *
128
+ * Facing north, east is on your right; facing east, south is. Fixing it here is what makes one
129
+ * spec give one drawing — a renderer that guessed would mirror the building and no test would
130
+ * catch it.
131
+ */
132
+ function rightOf(d: Pt): Pt {
133
+ return { x: d.y, y: -d.x };
134
+ }
135
+
136
+ /** Every body of the Form, in canonical order. **The order is inherited, never re-established.** */
137
+ function bodiesOf(form: Form): Body[] {
138
+ const out: Body[] = [];
139
+ const flat = (poly: Pt[], z0: number, z1: number): Pick<Body, "poly" | "bottom" | "top"> => ({
140
+ poly,
141
+ bottom: poly.map(() => z0),
142
+ top: poly.map(() => z1),
143
+ });
144
+
145
+ // Spaces come first because space is the primary element. A space is a void: the plane opens it,
146
+ // but from outside you see the matter that bounds it, never the void itself — so a space that
147
+ // stands wholly beyond the plane is dropped rather than painted (see `entitiesOf`).
148
+ for (const s of form.spaces) {
149
+ if (s.z0 === undefined || s.z1 === undefined) continue; // no ceiling height, no volume (SUF01)
150
+ // **Outside and semi-outdoor spaces have no volume to cut.** A storey's ceiling height reaches
151
+ // them, so they carry a z range, but no ceiling is derived over them (fabric.ts excludes both)
152
+ // and there is nothing above them to bound the air. Cutting one paints a garden as a room.
153
+ if (s.outside || s.semiOutdoor) continue;
154
+ for (const piece of s.outline) {
155
+ out.push({ of: "space", ref: s.path, ...(s.type ? { kind: s.type } : {}), ...flat(piece, s.z0, s.z1) });
156
+ }
157
+ }
158
+ for (const b of form.boundaries) {
159
+ if (!b.material) continue; // type:open — a relation with no matter to cut
160
+ for (const p of b.material.panels) {
161
+ out.push({ of: "boundary", ref: b.ref, kind: b.kind, ...flat(p.footprint, p.z0, p.z1) });
162
+ }
163
+ }
164
+ for (const o of form.openings) {
165
+ out.push({
166
+ of: "opening",
167
+ ref: o.ref,
168
+ kind: o.kind,
169
+ ...flat(band(o.segment, o.cx, o.cy, o.w, o.t), o.z0, o.z1),
170
+ });
171
+ }
172
+ for (const c of form.columns) {
173
+ out.push({ of: "column", ref: c.ref, ...flat(columnRect(c), c.z0, c.z1) });
174
+ }
175
+ for (const sl of form.slabs) {
176
+ out.push({ of: "slab", ref: sl.space, kind: sl.kind, ...flat(sl.outline, sl.z0, sl.z1) });
177
+ }
178
+ for (const run of form.runs) {
179
+ for (const s of run.solids) {
180
+ const pr = runPrism(s);
181
+ out.push({ of: "run", ref: run.path, kind: run.device, poly: pr.poly, bottom: pr.bottom, top: pr.top });
182
+ }
183
+ }
184
+ return out;
185
+ }
186
+
187
+ /** The polygon a body leaves on the plane, or `undefined` where the plane only grazes a corner. */
188
+ function cutOf(body: Body, axis: SectionAxis, at: number, u: (p: Pt) => number): SectionPt[] | undefined {
189
+ const met = crossing(body.poly, axis, at);
190
+ if (!met) return undefined;
191
+ const n = body.poly.length;
192
+ // The height at a crossing, read off the edge it sits on. **This is exact, not sampled** — a
193
+ // per-vertex height means the height is linear along each edge, which is all the reading assumes.
194
+ const at01 = (v: number[], c: { edge: number; t: number }): number =>
195
+ v[c.edge]! + c.t * (v[(c.edge + 1) % n]! - v[c.edge]!);
196
+ const ends = met.map((c) => ({
197
+ u: u(body.poly[c.edge]!) + c.t * (u(body.poly[(c.edge + 1) % n]!) - u(body.poly[c.edge]!)),
198
+ z0: at01(body.bottom, c),
199
+ z1: at01(body.top, c),
200
+ }));
201
+ const [a, b] = ends[0]!.u <= ends[1]!.u ? [ends[0]!, ends[1]!] : [ends[1]!, ends[0]!];
202
+ if (b.u - a.u <= EPS) return undefined;
203
+ // Bottom-left, bottom-right, top-right, top-left — counter-clockwise with z up.
204
+ return [
205
+ { u: a.u, z: a.z0 },
206
+ { u: b.u, z: b.z0 },
207
+ { u: b.u, z: b.z1 },
208
+ { u: a.u, z: a.z1 },
209
+ ];
210
+ }
211
+
212
+ /**
213
+ * The shape a body throws onto the plane, seen head-on.
214
+ *
215
+ * A body of the `Form` is a prism over a convex ring whose top and bottom vary linearly, so it is
216
+ * a convex solid and **its shadow is the hull of its projected vertices** — exact, not an outline
217
+ * fitted to it. Where the top and bottom do not vary (everything but a ramp or an escalator) that
218
+ * hull is a rectangle, and it is taken directly.
219
+ */
220
+ function shadowOf(body: Body, u: (p: Pt) => number): SectionPt[] | undefined {
221
+ let uLo = Infinity;
222
+ let uHi = -Infinity;
223
+ let zLo = Infinity;
224
+ let zHi = -Infinity;
225
+ let level = true;
226
+ for (let i = 0; i < body.poly.length; i++) {
227
+ const v = u(body.poly[i]!);
228
+ if (v < uLo) uLo = v;
229
+ if (v > uHi) uHi = v;
230
+ const b = body.bottom[i]!;
231
+ const t = body.top[i]!;
232
+ if (b < zLo) zLo = b;
233
+ if (t > zHi) zHi = t;
234
+ if (b !== body.bottom[0] || t !== body.top[0]) level = false;
235
+ }
236
+ if (uHi - uLo <= EPS || zHi - zLo <= EPS) return undefined;
237
+ if (level) {
238
+ return [
239
+ { u: uLo, z: zLo },
240
+ { u: uHi, z: zLo },
241
+ { u: uHi, z: zHi },
242
+ { u: uLo, z: zHi },
243
+ ];
244
+ }
245
+ const pts: Pt[] = [];
246
+ for (let i = 0; i < body.poly.length; i++) {
247
+ const v = u(body.poly[i]!);
248
+ pts.push({ x: v, y: body.bottom[i]! }, { x: v, y: body.top[i]! });
249
+ }
250
+ const ring = hull(pts);
251
+ return ring.length >= 3 ? ring.map((p) => ({ u: p.x, z: p.y })) : undefined;
252
+ }
253
+
254
+ function entitiesOf(bodies: Body[], spec: SectionSpec): SectionEntity[] {
255
+ const d = look(spec.look);
256
+ const r = rightOf(d);
257
+ const u = (p: Pt): number => p.x * r.x + p.y * r.y;
258
+ /** How far behind the plane a point stands. Positive is away from the viewer. */
259
+ const behind = (p: Pt): number => (spec.axis === "X" ? (p.x - spec.at) * d.x : (p.y - spec.at) * d.y);
260
+
261
+ const out: SectionEntity[] = [];
262
+ for (const body of bodies) {
263
+ let lo = Infinity;
264
+ let hi = -Infinity;
265
+ for (const p of body.poly) {
266
+ const f = behind(p);
267
+ if (f < lo) lo = f;
268
+ if (f > hi) hi = f;
269
+ }
270
+ // **The body is asked which side it is wholly on, not how far it reaches past the plane.**
271
+ // Asking the second question needs the body to extend more than the tolerance on both sides,
272
+ // which a body no wider than the tolerance itself can never do — a `t:1` wall standing on the
273
+ // plane reaches −0.5 and +0.5, and would be reported as standing behind a plane that goes
274
+ // straight through it.
275
+ const wholly = { behind: lo >= -EPS && hi > EPS, front: hi <= EPS && lo < -EPS };
276
+ if (!wholly.behind && !wholly.front) {
277
+ // It reaches both sides: the plane crossed it.
278
+ const polygon = cutOf(body, spec.axis, spec.at, u);
279
+ if (polygon) {
280
+ out.push({ class: "cut", of: body.of, ref: body.ref, ...(body.kind ? { kind: body.kind } : {}), polygon, depth: 0 });
281
+ }
282
+ continue;
283
+ }
284
+ // Wholly at or behind the plane. A space is a void — from outside there is nothing to see.
285
+ if (wholly.behind && body.of !== "space") {
286
+ const polygon = shadowOf(body, u);
287
+ if (polygon) {
288
+ out.push({
289
+ class: "beyond",
290
+ of: body.of,
291
+ ref: body.ref,
292
+ ...(body.kind ? { kind: body.kind } : {}),
293
+ polygon,
294
+ // A face within the tolerance of the plane counts as on it, so the nearest point can
295
+ // measure a hair negative. `depth` is a distance behind the plane and never less than 0.
296
+ depth: Math.max(0, lo),
297
+ });
298
+ }
299
+ }
300
+ // Otherwise it stands in front of the plane, behind the viewer, and is not produced.
301
+ }
302
+ return out;
303
+ }
304
+
305
+ /**
306
+ * The section a vertical plane makes of a `Form`.
307
+ *
308
+ * The plane is named by an axis and a coordinate; `look` says which way it is faced, and must
309
+ * cross the plane rather than run along it.
310
+ */
311
+ export function sectionForm(form: Form, spec: SectionSpec): FormSection {
312
+ if (axisOf(spec.look) !== spec.axis) {
313
+ throw new Error(
314
+ `Looking ${spec.look} runs along the ${spec.axis} plane rather than across it (an X plane is looked at from E or W, a Y plane from N or S)`,
315
+ );
316
+ }
317
+ return {
318
+ axis: spec.axis,
319
+ at: spec.at,
320
+ ...(spec.atRef !== undefined ? { atRef: spec.atRef } : {}),
321
+ look: spec.look,
322
+ entities: entitiesOf(bodiesOf(form), spec),
323
+ };
324
+ }
325
+
326
+ /**
327
+ * The elevation of one face — **a section whose plane misses the mass.**
328
+ *
329
+ * `face` names the side the viewer stands on: `S` is the south elevation, seen from the south.
330
+ * The plane is put at the extreme of the mass along the line of sight, so **nothing can straddle
331
+ * it and `cut` comes back empty by construction** rather than by a branch in the code. Where
332
+ * exactly it goes is free: the projection is orthographic, so moving the plane further back
333
+ * changes no `u` and no `z`, only the datum that `depth` is counted from.
334
+ */
335
+ export function elevationForm(form: Form, face: Edge): FormSection {
336
+ // Standing to the south means looking north.
337
+ const from: Edge = face === "N" ? "S" : face === "S" ? "N" : face === "E" ? "W" : "E";
338
+ const axis = axisOf(from);
339
+ const d = look(from);
340
+ const bodies = bodiesOf(form);
341
+ // The near extreme along the line of sight: looking towards the larger coordinate puts the plane
342
+ // at the smallest, and looking towards the smaller puts it at the largest.
343
+ const towardsLarger = (axis === "X" ? d.x : d.y) > 0;
344
+ let at = 0;
345
+ let seen = false;
346
+ for (const body of bodies) {
347
+ for (const p of body.poly) {
348
+ const c = axis === "X" ? p.x : p.y;
349
+ if (!seen || (towardsLarger ? c < at : c > at)) at = c;
350
+ seen = true;
351
+ }
352
+ }
353
+ const spec: SectionSpec = { axis, at, look: from };
354
+ return { axis, at, look: from, entities: entitiesOf(bodies, spec) };
355
+ }
356
+
357
+ /** The area of a section polygon, mm². Used by the tests that hold the cut against the Form. */
358
+ export function sectionArea(polygon: SectionPt[]): number {
359
+ return Math.abs(signedArea(polygon.map((p) => ({ x: p.u, y: p.z }))));
360
+ }