@kensnzk/koyu 0.5.0 → 0.13.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 (160) hide show
  1. package/README.ja.md +43 -11
  2. package/README.md +51 -11
  3. package/dist/axo.d.ts +16 -0
  4. package/dist/axo.d.ts.map +1 -0
  5. package/dist/axo.js +211 -0
  6. package/dist/axo.js.map +1 -0
  7. package/dist/check.d.ts +109 -0
  8. package/dist/check.d.ts.map +1 -0
  9. package/dist/check.js +957 -0
  10. package/dist/check.js.map +1 -0
  11. package/dist/cli.d.ts +3 -0
  12. package/dist/cli.d.ts.map +1 -0
  13. package/dist/cli.js +410 -0
  14. package/dist/cli.js.map +1 -0
  15. package/dist/diff.d.ts +105 -0
  16. package/dist/diff.d.ts.map +1 -0
  17. package/dist/diff.js +583 -0
  18. package/dist/diff.js.map +1 -0
  19. package/dist/fabric.d.ts +28 -0
  20. package/dist/fabric.d.ts.map +1 -0
  21. package/dist/fabric.js +105 -0
  22. package/dist/fabric.js.map +1 -0
  23. package/dist/graph.d.ts +118 -0
  24. package/dist/graph.d.ts.map +1 -0
  25. package/dist/graph.js +627 -0
  26. package/dist/graph.js.map +1 -0
  27. package/dist/index.d.ts +12 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +13 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/light.d.ts +15 -0
  32. package/dist/light.d.ts.map +1 -0
  33. package/dist/light.js +53 -0
  34. package/dist/light.js.map +1 -0
  35. package/dist/mcp.d.ts +3 -0
  36. package/dist/mcp.d.ts.map +1 -0
  37. package/dist/mcp.js +361 -0
  38. package/dist/mcp.js.map +1 -0
  39. package/dist/model.d.ts +379 -0
  40. package/dist/model.d.ts.map +1 -0
  41. package/dist/model.js +464 -0
  42. package/dist/model.js.map +1 -0
  43. package/dist/parse-file.d.ts +9 -0
  44. package/dist/parse-file.d.ts.map +1 -0
  45. package/dist/parse-file.js +22 -0
  46. package/dist/parse-file.js.map +1 -0
  47. package/dist/parse.d.ts +16 -0
  48. package/dist/parse.d.ts.map +1 -0
  49. package/dist/parse.js +1040 -0
  50. package/dist/parse.js.map +1 -0
  51. package/dist/plan.d.ts +10 -0
  52. package/dist/plan.d.ts.map +1 -0
  53. package/dist/plan.js +354 -0
  54. package/dist/plan.js.map +1 -0
  55. package/dist/poly.d.ts +78 -0
  56. package/dist/poly.d.ts.map +1 -0
  57. package/dist/poly.js +277 -0
  58. package/dist/poly.js.map +1 -0
  59. package/dist/site.d.ts +24 -0
  60. package/dist/site.d.ts.map +1 -0
  61. package/dist/site.js +54 -0
  62. package/dist/site.js.map +1 -0
  63. package/dist/vertical.d.ts +176 -0
  64. package/dist/vertical.d.ts.map +1 -0
  65. package/dist/vertical.js +669 -0
  66. package/dist/vertical.js.map +1 -0
  67. package/examples/basement/main.muro +84 -0
  68. package/examples/comparison/README.md +64 -1
  69. package/examples/comparison/gen-ifc4.ts +1 -1
  70. package/examples/comparison/gen-ifcx.ts +2 -2
  71. package/examples/comparison/two-rooms.ifcx +1 -1
  72. package/examples/complex/L1.muro +132 -0
  73. package/examples/complex/assets.muro +17 -0
  74. package/examples/complex/basement.muro +40 -0
  75. package/examples/complex/core.muro +40 -0
  76. package/examples/complex/hotel.muro +117 -0
  77. package/examples/complex/main.muro +67 -0
  78. package/examples/complex/office.muro +41 -0
  79. package/examples/complex/plant.muro +34 -0
  80. package/examples/complex/podium.muro +140 -0
  81. package/examples/complex/site.muro +18 -0
  82. package/examples/house/L1.muro +16 -0
  83. package/examples/house/L2.muro +19 -0
  84. package/examples/house/assets.muro +9 -0
  85. package/examples/house/main.muro +27 -0
  86. package/examples/house/site.muro +31 -0
  87. package/examples/house.muro +3 -3
  88. package/examples/mansion.muro +18 -13
  89. package/examples/office.muro +1 -1
  90. package/examples/steps/01-one-room.muro +4 -0
  91. package/examples/steps/02-two-rooms.muro +5 -0
  92. package/examples/steps/03-door.muro +9 -0
  93. package/examples/steps/04-exterior.muro +15 -0
  94. package/examples/steps/05-two-storeys.muro +27 -0
  95. package/examples/steps/06-finished.muro +30 -0
  96. package/examples/steps/README.md +25 -0
  97. package/examples/tower/L1.muro +80 -0
  98. package/examples/tower/L11.muro +49 -0
  99. package/examples/tower/L2.muro +71 -0
  100. package/examples/tower/L3.muro +31 -0
  101. package/examples/tower/assets.muro +14 -0
  102. package/examples/tower/main.muro +37 -0
  103. package/examples/tower/site-geometry.muro +7 -0
  104. package/examples/tower/site.muro +33 -0
  105. package/examples/tower/typical.muro +131 -0
  106. package/examples/two-rooms.canonical.json +30 -3
  107. package/examples/two-rooms.muro +11 -7
  108. package/package.json +29 -2
  109. package/src/axo.ts +258 -0
  110. package/src/check.ts +948 -122
  111. package/src/cli.ts +175 -12
  112. package/src/diff.ts +676 -0
  113. package/src/fabric.ts +123 -0
  114. package/src/graph.ts +451 -61
  115. package/src/index.ts +38 -2
  116. package/src/light.ts +4 -7
  117. package/src/mcp.ts +397 -0
  118. package/src/model.ts +462 -67
  119. package/src/parse-file.ts +28 -0
  120. package/src/parse.ts +682 -45
  121. package/src/plan.ts +152 -14
  122. package/src/poly.ts +295 -0
  123. package/src/site.ts +19 -11
  124. package/src/vertical.ts +884 -0
  125. package/.github/workflows/ci.yml +0 -16
  126. package/.zenodo.json +0 -20
  127. package/CITATION.cff +0 -26
  128. package/docs/decisions/0001-notation-v0.md +0 -29
  129. package/docs/decisions/0002-height-and-offsets.md +0 -27
  130. package/docs/decisions/0003-uncounted-divisions.md +0 -36
  131. package/docs/decisions/0004-typical-floors.md +0 -21
  132. package/docs/decisions/0005-zones-and-unions.md +0 -23
  133. package/docs/decisions/0006-voids-and-light.md +0 -31
  134. package/docs/decisions/0007-semi-outdoor-air.md +0 -27
  135. package/docs/decisions/0008-vocabulary-and-level-attr.md +0 -23
  136. package/docs/decisions/0009-site-and-exterior.md +0 -29
  137. package/docs/ifc-coverage.md +0 -82
  138. package/docs/ifcx-notes.md +0 -25
  139. package/docs/img/house-L1.svg +0 -80
  140. package/docs/img/house-L2.svg +0 -53
  141. package/docs/img/mansion-L1.svg +0 -113
  142. package/docs/img/mansion-L10.svg +0 -111
  143. package/docs/img/mansion-L5.svg +0 -160
  144. package/docs/img/office-L1.svg +0 -116
  145. package/docs/img/office-L2.svg +0 -109
  146. package/docs/img/two-rooms.svg +0 -39
  147. package/docs/log/2026-07-22.md +0 -13
  148. package/docs/log/2026-07-23.md +0 -51
  149. package/docs/roadmap.md +0 -55
  150. package/docs/writing-architecture.md +0 -119
  151. package/spec/notation-v0.md +0 -164
  152. package/spec/vocabulary.md +0 -62
  153. package/test/core.test.ts +0 -171
  154. package/test/design2.test.ts +0 -97
  155. package/test/house.test.ts +0 -74
  156. package/test/mansion.test.ts +0 -99
  157. package/test/office.test.ts +0 -71
  158. package/test/uncounted.test.ts +0 -120
  159. package/test/vertical.test.ts +0 -75
  160. package/tsconfig.json +0 -13
package/src/model.ts CHANGED
@@ -2,9 +2,16 @@
2
2
  // 一次要素は空間。壁は二つの空間の「境界」という関係であり、物ではない。
3
3
  // 形はここには無い。形は生成物である。(docs/writing-architecture.md)
4
4
 
5
+ import * as poly from "./poly.js";
6
+
5
7
  export type AttrValue = string | number;
6
8
  export type Attrs = Record<string, AttrValue>;
7
9
 
10
+ /** このツールが受理する言語版 (ADR-0017)。旧版は意味保存の場合のみ受理される (checkが検査する) */
11
+ export const SUPPORTED_LANGUAGE_VERSIONS: readonly string[] = ["0.1", "0.2", "0.3", "0.4", "0.5"];
12
+ /** 版宣言を省略したときの解釈 — 常に最新版の意味論 (省略はツール版を跨いで意味安定ではない) */
13
+ export const DEFAULT_LANGUAGE_VERSION = "0.5";
14
+
8
15
  /** 方位。edge指定は「最初に書いた空間」の矩形から見た辺。N=+Y, S=-Y, E=+X, W=-X */
9
16
  export type Edge = "N" | "E" | "S" | "W";
10
17
 
@@ -16,6 +23,15 @@ export interface Level {
16
23
  h?: number;
17
24
  /** この階の床組み厚 mm (下階の天井面から自階FLまで: スラブ+懐+仕上) */
18
25
  slab?: number;
26
+ /**
27
+ * 地下の宣言 (ADR-0022)。zの負値から推定はしない — 地盤面は敷地の事実であって
28
+ * 座標系の原点の事実ではないため。集計 (地上/地下の床面積) と矩計の表示が読む。
29
+ * 接土境界の語彙は導入しない (物の名は spec 語彙 — 台帳の規則2)
30
+ */
31
+ underground?: boolean;
32
+ /** 宣言の出所 — level 由来の診断 (LVL01/HGT03/VER03) が位置を持てるように (ADR-0028) */
33
+ line: number;
34
+ file?: string;
19
35
  }
20
36
 
21
37
  export interface GridAxis {
@@ -62,12 +78,20 @@ export interface Space {
62
78
  level?: string;
63
79
  /** グリッド参照。複数矩形の合併でL字などを表す (rectsと同順) */
64
80
  grids: GridRef[];
65
- /** グリッド解決後のmm矩形の合併。exteriorなどは空 */
81
+ /** グリッド解決後のmm矩形の合併。exteriorなどは空。**書かれた割付** (セル) であって形ではない */
66
82
  rects: Rect[];
83
+ /**
84
+ * 導出された領域 — 凸片の集合 (ADR-0022)。既定は rects をそのまま写したもので、
85
+ * 境界に描かれた線 (line) があればその半平面で切り分けた結果になる。
86
+ * 面積・平面図・立体はこちらを読む。rects は「書かれた綴り」として正準JSONに残る
87
+ */
88
+ pieces: Pt[][];
67
89
  /** 数えない分節 (字下げのarea行) */
68
90
  areas: Area[];
69
91
  attrs: Attrs;
70
92
  line: number;
93
+ /** 合成時の出所ファイル (コンフリクト報告用) */
94
+ file?: string;
71
95
  }
72
96
 
73
97
  /**
@@ -78,6 +102,21 @@ export interface Zone {
78
102
  path: string;
79
103
  attrs: Attrs;
80
104
  line: number;
105
+ /** 合成時の出所ファイル (コンフリクト報告用) */
106
+ file?: string;
107
+ }
108
+
109
+ /**
110
+ * 建具アセット — RevitのFamily、USDのReferenceにあたる型の宣言 (ADR-0010)。
111
+ * `asset SD1 door w:800 style:sliding` と宣言し、開口が `door SD1 ...` で参照する。
112
+ * インスタンス側の属性が上書きする。別ファイル (アセット集) に置いて import できる
113
+ */
114
+ export interface Asset {
115
+ name: string;
116
+ kind: "door" | "window";
117
+ attrs: Attrs;
118
+ line: number;
119
+ file?: string;
81
120
  }
82
121
 
83
122
  /**
@@ -93,12 +132,20 @@ export type BoundaryKind = "wall" | "open" | "stair" | "shaft" | "void";
93
132
 
94
133
  export interface Opening {
95
134
  kind: "door" | "window";
135
+ /** 参照した建具アセット名 (Reference — ADR-0010) */
136
+ ref?: string;
96
137
  /** 幅 mm */
97
138
  w: number;
98
139
  /** 高さ mm */
99
140
  h?: number;
100
- /** 区間上の位置 0..1 (既定 0.5) */
141
+ /** 区間上の位置 0..1 (既定 0.5)。比率指定はクランプされる */
101
142
  at: number;
143
+ /** 明示位置: 書かれた通り参照 (at:X2+450 など) */
144
+ atRef?: string;
145
+ /** 明示位置: 解決済みの絶対座標 mm。はみ出しはエラーになる (クランプしない) */
146
+ atAbs?: number;
147
+ /** 明示位置の軸 (水平線分はX系、垂直線分はY系でなければならない) */
148
+ atAxis?: "X" | "Y";
102
149
  /** 区間が複数あるとき (外部境界など) の辺の指定 */
103
150
  edge?: Edge;
104
151
  /** 開き勝手: 吊元の側 (水平線分ならW/E、垂直線分ならS/N)。既定は始端側 */
@@ -118,16 +165,36 @@ export interface Seg {
118
165
  w: number;
119
166
  /** 区間中心の位置 0..1 (既定 0.5) */
120
167
  at: number;
168
+ /** 明示位置 (開口と同じ流儀 — at:X2+450) */
169
+ atRef?: string;
170
+ atAbs?: number;
171
+ atAxis?: "X" | "Y";
121
172
  edge?: Edge;
122
173
  attrs: Attrs;
123
174
  line: number;
124
175
  }
125
176
 
177
+ /**
178
+ * 描かれた線 (ADR-0022) — 空間を区切る設計の行為そのもの。
179
+ * 端点は通り語 (`X3,Y1` / `X3+600,Y2-900`) で書く。生座標も角度も導入しない。
180
+ * 境界が既定で持つ「隣接から導かれる線分」を、この線が置き換える
181
+ */
182
+ export interface DrawnLine {
183
+ /** 書かれた綴り — 正準JSONと差分が共有する */
184
+ aRef: string;
185
+ bRef: string;
186
+ a: Pt;
187
+ b: Pt;
188
+ line: number;
189
+ }
190
+
126
191
  /** 境界はどちらの空間にも属さない。二つの空間パスを結ぶ第一級の関係 */
127
192
  export interface Boundary {
128
193
  a: string;
129
194
  b: string;
130
195
  kind: BoundaryKind;
196
+ /** 描かれた線 (字下げの line 行)。あれば境界の実現はこの線になる */
197
+ drawn?: DrawnLine;
131
198
  /** 壁厚 mm (通り芯・境界線に対して芯振り分け) */
132
199
  t?: number;
133
200
  /** 遮蔽しない (air:1) — 手すり・柵など、物はあるが外気・光を遮らない。
@@ -141,6 +208,15 @@ export interface Boundary {
141
208
  /** 数えない分節 (字下げのseg行) */
142
209
  segs: Seg[];
143
210
  line: number;
211
+ /** 合成時の出所レイヤー (ADR-0010) */
212
+ file?: string;
213
+ /** 既定境界 (ADR-0014) — 宣言されず、接触から導出された壁。正準JSONには出ない (書かれた構成のみ) */
214
+ derived?: boolean;
215
+ }
216
+
217
+ /** エラー・警告の位置表記 — 合成時はどのレイヤーのことかを言葉にする (ADR-0010) */
218
+ export function srcRef(line: number, file?: string): string {
219
+ return `${file ? `${file}:` : ""}${line}行目`;
144
220
  }
145
221
 
146
222
  export interface Model {
@@ -151,26 +227,255 @@ export interface Model {
151
227
  levels: Record<string, Level>;
152
228
  spaces: Map<string, Space>;
153
229
  zones: Map<string, Zone>;
230
+ assets: Map<string, Asset>;
154
231
  boundaries: Boundary[];
232
+ /** 敷地形状 — 所与のジオメトリ (ADR-0011)。パス→頂点列 (mm)。
233
+ * 唯一の自由頂点列 — 空間の領域はグリッド参照の矩形として書かれる */
234
+ polygons: Map<string, SitePolygon>;
235
+ /** 柱の宣言 (ADR-0023)。位置は書かれない — 通り芯の交点から導出される */
236
+ columns: ColumnDecl[];
237
+ /** 合成に参加したレイヤー (ローダーのキー、合成順 — entryが先頭)。単一ソースのparseでは空 */
238
+ layers: string[];
239
+ /** koyu版が明示宣言されたか (base層でのみ・一度だけ — ADR-0017の合成規則の管理用) */
240
+ versionDeclared?: boolean;
241
+ }
242
+
243
+ /** 平面上の点 (mm) */
244
+ export interface Pt {
245
+ x: number;
246
+ y: number;
247
+ }
248
+
249
+ /**
250
+ * 柱の宣言 (ADR-0023) — 「どの通りに、どの階に、どの寸法で」だけを書く。
251
+ * **位置は書かない**。通り芯 (共有線) の交点のうち、そのレベルの床のある所に立つ、
252
+ * という規則で導出される。壁が境界から現れるのと同じ構えを、点の要素に適用したもの
253
+ */
254
+ export interface ColumnDecl {
255
+ /** 一辺 mm (角柱)。`d:` があれば矩形断面の奥行 */
256
+ size: number;
257
+ depth?: number;
258
+ /** 展開済みレベル名 (宣言順ではなくz昇順) */
259
+ levels: string[];
260
+ /** 限定する通り名。未指定は全通り */
261
+ xNames?: string[];
262
+ yNames?: string[];
263
+ attrs: Attrs;
264
+ line: number;
265
+ file?: string;
266
+ }
267
+
268
+ /** 導出された柱 — 一本の柱 */
269
+ export interface Column {
270
+ x: number;
271
+ y: number;
272
+ /** X方向の幅 mm / Y方向の奥行 mm */
273
+ w: number;
274
+ d: number;
275
+ level: string;
276
+ /** 立っている通りの名 (X3・Y2 のような組) — 図面の言葉 */
277
+ grid: string;
278
+ /**
279
+ * どの宣言から立ったか (model.columns の添字)。**診断の母集団を宣言に戻すために要る** —
280
+ * これが無いと「この宣言に対して一本も立たない」を問えない (ADR-0028)
281
+ */
282
+ decl: number;
283
+ attrs: Attrs;
155
284
  }
156
285
 
286
+ /** 敷地形状 (ADR-0011) — 測量に由来する所与の多角形。建物の形は生成物のままで、
287
+ * これはゾーン (site:1) に付く入力データ。隔離レイヤー (別ファイル+import) 推奨 */
288
+ export interface SitePolygon {
289
+ path: string;
290
+ points: Pt[];
291
+ line: number;
292
+ file?: string;
293
+ }
294
+
295
+ /** 多角形の面積 ㎡。シューレースの実体は poly.ts にひとつだけある (ADR-0027) */
296
+ export const polygonAreaM2 = (points: Pt[]): number => poly.area(points) / 1e6;
297
+
298
+ /** 線分同士が内部で交差するか (端点・境界上の接触は交差としない、許容誤差eps mm)。交点を返す */
299
+ function properCrossing(a1: Pt, a2: Pt, b1: Pt, b2: Pt, eps = 1): Pt | undefined {
300
+ const d = (a2.x - a1.x) * (b2.y - b1.y) - (a2.y - a1.y) * (b2.x - b1.x);
301
+ if (d === 0) return undefined; // 平行・共線 (共線の重なりは接触扱い — 境界上は内側)
302
+ const t = ((b1.x - a1.x) * (b2.y - b1.y) - (b1.y - a1.y) * (b2.x - b1.x)) / d;
303
+ const u = ((b1.x - a1.x) * (a2.y - a1.y) - (b1.y - a1.y) * (a2.x - a1.x)) / d;
304
+ const la = Math.hypot(a2.x - a1.x, a2.y - a1.y);
305
+ const lb = Math.hypot(b2.x - b1.x, b2.y - b1.y);
306
+ if (la === 0 || lb === 0) return undefined;
307
+ const ea = eps / la;
308
+ const eb = eps / lb;
309
+ if (t <= ea || t >= 1 - ea || u <= eb || u >= 1 - eb) return undefined; // 端点付近は接触
310
+ return { x: a1.x + t * (a2.x - a1.x), y: a1.y + t * (a2.y - a1.y) };
311
+ }
312
+
313
+ /** 多角形の自己交差点 (隣接しない辺同士の内部交差)。なければundefined */
314
+ export function polygonSelfIntersection(poly: Pt[], eps = 1): Pt | undefined {
315
+ const n = poly.length;
316
+ for (let i = 0; i < n; i++) {
317
+ for (let j = i + 2; j < n; j++) {
318
+ if (i === 0 && j === n - 1) continue; // 先頭と末尾の辺は隣接
319
+ const x = properCrossing(poly[i]!, poly[(i + 1) % n]!, poly[j]!, poly[(j + 1) % n]!, eps);
320
+ if (x) return x;
321
+ }
322
+ }
323
+ return undefined;
324
+ }
325
+
326
+ /**
327
+ * 矩形が多角形からはみ出す点 (完全に内側ならundefined)。凹多角形にも正しい:
328
+ * 四隅の内包に加え、多角形の頂点の矩形内への入り込みと、辺同士の内部交差を検査する
329
+ */
330
+ export function rectEscapesPolygon(r: Rect, poly: Pt[], eps = 1): Pt | undefined {
331
+ return shapeEscapesPolygon(rectToPoly(r), poly, eps);
332
+ }
333
+
334
+ /** 凸片が多角形からはみ出す点 (導出された領域を敷地形状と照合する — ADR-0022) */
335
+ export function shapeEscapesPolygon(shape: Pt[], poly: Pt[], eps = 1): Pt | undefined {
336
+ for (const c of shape) if (!pointInPolygon(c, poly, eps)) return c;
337
+ for (const p of poly) {
338
+ // 多角形の頂点が凸片の内部に食い込む (境界上は食い込みではない)
339
+ if (pointInPolygon(p, shape, eps) && !onPolygonEdge(p, shape, eps)) return p;
340
+ }
341
+ for (let i = 0; i < poly.length; i++) {
342
+ const a = poly[i]!;
343
+ const b = poly[(i + 1) % poly.length]!;
344
+ for (let k = 0; k < shape.length; k++) {
345
+ const x = properCrossing(a, b, shape[k]!, shape[(k + 1) % shape.length]!, eps);
346
+ if (x) return x;
347
+ }
348
+ }
349
+ return undefined;
350
+ }
351
+
352
+ /** 点が多角形の辺の上にあるか */
353
+ export const onPolygonEdge = poly.onEdge;
354
+
355
+ /** 点が多角形の内側にあるか (境界上は内側扱い) */
356
+ export const pointInPolygon = poly.pointIn;
357
+
157
358
  export class SourceError extends Error {
158
359
  constructor(
159
360
  public line: number,
160
- message: string,
361
+ /** 位置情報を除いた本文 (合成時のファイル付与に使う) */
362
+ public raw: string,
363
+ /** 出所ファイル (合成時) */
364
+ public file?: string,
161
365
  ) {
162
- super(`${line}行目: ${message}`);
366
+ super(`${file ? `${file}:` : ""}${line}行目: ${raw}`);
163
367
  this.name = "SourceError";
164
368
  }
165
369
  }
166
370
 
167
- /** 面積 (壁芯) m²。複数矩形は合計 (重なりはcheckが禁じる) */
371
+ /**
372
+ * 空間の導出された領域 (ADR-0022 / ADR-0027)。**形を読むときの唯一の入口**。
373
+ * parse の出口で必ず埋まるので、割付への退避は「未parseのModelを手で組んだとき」だけに効く。
374
+ * この式が各所に散っていたことが、rects と pieces の取り違えを四度生んだ根である。
375
+ */
376
+ export const regionOf = (s: Space): Pt[][] =>
377
+ s.pieces.length > 0 ? s.pieces : s.rects.map(poly.rectToPoly);
378
+
379
+ /** 面積 (壁芯) m²。導出された凸片の合計 — 描かれた線で切られていればその形の面積になる */
168
380
  export function areaM2(s: Space): number | undefined {
169
381
  if (s.rects.length === 0) return undefined;
170
- const a = s.rects.reduce((sum, r) => sum + (r.x2 - r.x1) * (r.y2 - r.y1), 0) / 1e6;
382
+ const a = poly.areaOf(regionOf(s)) / 1e6;
171
383
  return Math.round(a * 100) / 100;
172
384
  }
173
385
 
386
+ /** 矩形を頂点列へ (反時計回り) */
387
+ export const rectToPoly = poly.rectToPoly;
388
+
389
+ /** 凸多角形を半平面で切る (Sutherland–Hodgman)。
390
+ * 半平面は有向線分 a→b の左側 (外積>0)。切り落とされて空なら [] */
391
+ export function clipHalfPlane(poly: Pt[], a: Pt, b: Pt, keepLeft: boolean, eps = 1e-6): Pt[] {
392
+ const side = (p: Pt): number => {
393
+ const v = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
394
+ return keepLeft ? v : -v;
395
+ };
396
+ const out: Pt[] = [];
397
+ for (let i = 0; i < poly.length; i++) {
398
+ const p = poly[i]!;
399
+ const q = poly[(i + 1) % poly.length]!;
400
+ const sp = side(p);
401
+ const sq = side(q);
402
+ if (sp >= -eps) out.push(p);
403
+ if ((sp > eps && sq < -eps) || (sp < -eps && sq > eps)) {
404
+ const t = sp / (sp - sq);
405
+ out.push({ x: p.x + t * (q.x - p.x), y: p.y + t * (q.y - p.y) });
406
+ }
407
+ }
408
+ // 退化 (面積ゼロ) は捨てる
409
+ return out.length >= 3 && polygonAreaM2(out) > 1e-9 ? out : [];
410
+ }
411
+
412
+ /** 頂点列の外接矩形 */
413
+ export const polyBounds = poly.bounds;
414
+
415
+ /**
416
+ * 宣言 c がそのレベルで狙う交点のうち、**床の上にあるもの**。先勝ちの規則を適用する前の姿。
417
+ *
418
+ * 「一本も立たない」の理由を二つに割るために要る (ADR-0028) — ここが空なら床が無く、
419
+ * 空でないのに一本も立たないなら先の宣言に取られている。直す手が正反対である。
420
+ */
421
+ export function columnSites(
422
+ model: Model,
423
+ c: ColumnDecl,
424
+ level: string,
425
+ ): Array<{ x: number; y: number; grid: string }> {
426
+ if (!c.levels.includes(level)) return [];
427
+ const floors = [...model.spaces.values()].filter(
428
+ (s) => s.level === level && s.type !== "exterior" && s.type !== "void" && s.rects.length > 0,
429
+ );
430
+ if (floors.length === 0) return [];
431
+ const xs = model.grid.X.names
432
+ .map((n, i) => ({ n, v: model.grid.X.coords[i]! }))
433
+ .filter((g) => !c.xNames || c.xNames.includes(g.n));
434
+ const ys = model.grid.Y.names
435
+ .map((n, i) => ({ n, v: model.grid.Y.coords[i]! }))
436
+ .filter((g) => !c.yNames || c.yNames.includes(g.n));
437
+ const out: Array<{ x: number; y: number; grid: string }> = [];
438
+ for (const gx of xs) {
439
+ for (const gy of ys) {
440
+ const inside = floors.some((s) =>
441
+ (s.pieces.length ? s.pieces : s.rects.map(rectToPoly)).some((p) =>
442
+ pointInPolygon({ x: gx.v, y: gy.v }, p, 1),
443
+ ),
444
+ );
445
+ if (inside) out.push({ x: gx.v, y: gy.v, grid: `${gx.n}・${gy.n}` });
446
+ }
447
+ }
448
+ return out;
449
+ }
450
+
451
+ /**
452
+ * そのレベルに立つ柱を導く (ADR-0023)。
453
+ * 通り芯の交点のうち、床のある空間 (exterior・void を除く) の内側にあるものへ柱を置く。
454
+ * 位置はどこにも書かれていない — 通りと床という既にある事実の交わりから現れる
455
+ */
456
+ export function columnsFor(model: Model, level: string): Column[] {
457
+ const out: Column[] = [];
458
+ const seen = new Set<string>();
459
+ for (let ci = 0; ci < model.columns.length; ci++) {
460
+ const c = model.columns[ci]!;
461
+ for (const site of columnSites(model, c, level)) {
462
+ if (seen.has(site.grid)) continue; // 同じ交点に二本は立たない (先の宣言が勝つ)
463
+ seen.add(site.grid);
464
+ out.push({
465
+ x: site.x,
466
+ y: site.y,
467
+ w: c.size,
468
+ d: c.depth ?? c.size,
469
+ level,
470
+ grid: site.grid,
471
+ decl: ci,
472
+ attrs: c.attrs,
473
+ });
474
+ }
475
+ }
476
+ return out;
477
+ }
478
+
174
479
  /**
175
480
  * 半屋外か — 宣言ではなく導出。外部 (type:exterior) に対して
176
481
  * open または air:1 (手すり等、遮蔽しない物) の境界で接する空間は半屋外である (ADR-0007)
@@ -198,13 +503,7 @@ export function isCoveredAbove(model: Model, s: Space): boolean {
198
503
  if (o === s || o.rects.length === 0 || !o.level) continue;
199
504
  const oz = model.levels[o.level]?.z;
200
505
  if (oz === undefined || oz <= z) continue;
201
- for (const ra of s.rects) {
202
- for (const rb of o.rects) {
203
- const x = Math.min(ra.x2, rb.x2) - Math.max(ra.x1, rb.x1);
204
- const y = Math.min(ra.y2, rb.y2) - Math.max(ra.y1, rb.y1);
205
- if (x > 0.5 && y > 0.5) return true;
206
- }
207
- }
506
+ if (poly.overlaps(regionOf(s), regionOf(o))) return true;
208
507
  }
209
508
  return false;
210
509
  }
@@ -232,13 +531,24 @@ export function zoneAreaM2(model: Model, zonePath: string): number {
232
531
  let sum = 0;
233
532
  for (const s of model.spaces.values()) {
234
533
  if (!s.path.startsWith(zonePath + "/")) continue;
235
- if (s.type === "void") continue;
236
- if (isSemiOutdoor(model, s)) continue;
534
+ if (!isIndoor(model, s)) continue;
237
535
  sum += areaM2(s) ?? 0;
238
536
  }
239
537
  return Math.round(sum * 100) / 100;
240
538
  }
241
539
 
540
+ /**
541
+ * 屋内の床面積に数えるか。**「延べ面積」を問う三箇所 (stats / site / MCP) の唯一の答え**。
542
+ *
543
+ * 判定が散っていたときは、外部そのものが屋内床に入り、しかも「隣に道路を書いたか」で
544
+ * 半屋外に落ちるかどうかが変わっていた。母集団は場所ごとに決めるものではない (ADR-0028)。
545
+ */
546
+ export function isIndoor(model: Model, s: Space): boolean {
547
+ if (s.rects.length === 0) return false;
548
+ if (s.type === "exterior" || s.type === "void") return false;
549
+ return !isSemiOutdoor(model, s);
550
+ }
551
+
242
552
  /** 実効use属性 — 自分に無ければ、最も深いゾーン祖先から継承する */
243
553
  export function effectiveUse(model: Model, s: Space): string | undefined {
244
554
  const own = s.attrs["use"];
@@ -274,69 +584,102 @@ export function displayName(s: Space): string {
274
584
  return typeof n === "string" ? n : (s.path.split("/").pop() ?? s.path);
275
585
  }
276
586
 
587
+ /** 正準JSONの空間エントリ (書かれた表記・正準順)。semantic diff (ADR-0018) が比較基底として共有する */
588
+ export function canonicalSpaceEntry(s: Space): Record<string, unknown> {
589
+ return {
590
+ type: s.type,
591
+ // 明示の level: (パス先頭セグメントと異なる所属 — メゾネット等) は書かれた構成として保存する。
592
+ // これが無いとJSONだけでは所属レベル (垂直検査・集計・既定境界の前提) を復元できない
593
+ ...(s.level !== undefined && s.path.split("/")[1] !== s.level ? { level: s.level } : {}),
594
+ ...(s.grids.length === 1
595
+ ? { at: [s.grids[0]!.xa, s.grids[0]!.ya, s.grids[0]!.xb, s.grids[0]!.yb] }
596
+ : s.grids.length > 1
597
+ ? { at: sortBySerial(s.grids.map((g) => [g.xa, g.ya, g.xb, g.yb])) }
598
+ : {}),
599
+ ...(Object.keys(s.attrs).length ? { attrs: sortObj(s.attrs) } : {}),
600
+ ...(s.areas.length
601
+ ? {
602
+ areas: sortBySerial(
603
+ s.areas.map((a) => ({
604
+ at: [a.grid.xa, a.grid.ya, a.grid.xb, a.grid.yb],
605
+ ...(Object.keys(a.attrs).length ? { attrs: sortObj(a.attrs) } : {}),
606
+ })),
607
+ ),
608
+ }
609
+ : {}),
610
+ };
611
+ }
612
+
613
+ /** 正準JSONの開口エントリ (atRef??at 等の正準表記) — toCanonicalとsemantic diffが共有 */
614
+ export function canonicalOpeningEntry(o: Opening): Record<string, unknown> {
615
+ return {
616
+ kind: o.kind,
617
+ ...(o.ref ? { ref: o.ref } : {}),
618
+ w: o.w,
619
+ ...(o.h !== undefined ? { h: o.h } : {}),
620
+ at: o.atRef ?? o.at,
621
+ ...(o.edge ? { edge: o.edge } : {}),
622
+ ...(o.hinge ? { hinge: o.hinge } : {}),
623
+ ...(o.swing ? { swing: o.swing } : {}),
624
+ ...(Object.keys(o.attrs).length ? { attrs: sortObj(o.attrs) } : {}),
625
+ };
626
+ }
627
+
628
+ /** 正準JSONのsegエントリ — toCanonicalとsemantic diffが共有 */
629
+ export function canonicalSegEntry(g: Seg): Record<string, unknown> {
630
+ return {
631
+ w: g.w,
632
+ at: g.atRef ?? g.at,
633
+ ...(g.edge ? { edge: g.edge } : {}),
634
+ ...(Object.keys(g.attrs).length ? { attrs: sortObj(g.attrs) } : {}),
635
+ };
636
+ }
637
+
638
+ /** 正準JSONの境界エントリ。a/bの向きは書かれた表記 (aキー) として保存する — edge/swingはa側から読む */
639
+ export function canonicalBoundaryEntry(b: Boundary): Record<string, unknown> {
640
+ return {
641
+ between: [b.a, b.b].sort(),
642
+ a: b.a,
643
+ kind: b.kind,
644
+ ...(b.t !== undefined ? { t: b.t } : {}),
645
+ ...(b.air ? { air: true } : {}),
646
+ ...(b.edge ? { edge: b.edge } : {}),
647
+ // 描かれた線は書かれた綴りのまま残す — 頂点座標はビルドの産物であって構成ではない
648
+ // 端点の書き順は図形を変えない (線分は向きを持たない — 導出される凸片は同一) ので、
649
+ // 解決座標の昇順に正準化する。**綴りは保つ** (通り参照のまま — 規則3)
650
+ ...(b.drawn ? { line: canonicalLineEnds(b.drawn) } : {}),
651
+ ...(Object.keys(b.attrs).length ? { attrs: sortObj(b.attrs) } : {}),
652
+ ...(b.openings.length ? { openings: sortBySerial(b.openings.map(canonicalOpeningEntry)) } : {}),
653
+ ...(b.segs.length ? { segs: sortBySerial(b.segs.map(canonicalSegEntry)) } : {}),
654
+ };
655
+ }
656
+
277
657
  /** 正準JSON — 機械形式。差分とレイヤー合成の土台 (キーは安定順) */
278
658
  export function toCanonical(model: Model): string {
279
659
  const spaces: Record<string, unknown> = {};
280
660
  for (const p of [...model.spaces.keys()].sort()) {
281
- const s = model.spaces.get(p)!;
282
- spaces[p] = {
283
- type: s.type,
284
- ...(s.grids.length === 1
285
- ? { at: [s.grids[0]!.xa, s.grids[0]!.ya, s.grids[0]!.xb, s.grids[0]!.yb] }
286
- : s.grids.length > 1
287
- ? { at: s.grids.map((g) => [g.xa, g.ya, g.xb, g.yb]) }
288
- : {}),
289
- ...(Object.keys(s.attrs).length ? { attrs: sortObj(s.attrs) } : {}),
290
- ...(s.areas.length
291
- ? {
292
- areas: s.areas.map((a) => ({
293
- at: [a.grid.xa, a.grid.ya, a.grid.xb, a.grid.yb],
294
- ...(Object.keys(a.attrs).length ? { attrs: sortObj(a.attrs) } : {}),
295
- })),
296
- }
297
- : {}),
298
- };
661
+ spaces[p] = canonicalSpaceEntry(model.spaces.get(p)!);
299
662
  }
300
- const boundaries = [...model.boundaries]
301
- .map((b) => ({
302
- between: [b.a, b.b].sort(),
303
- kind: b.kind,
304
- ...(b.t !== undefined ? { t: b.t } : {}),
305
- ...(b.air ? { air: true } : {}),
306
- ...(b.edge ? { edge: b.edge } : {}),
307
- ...(Object.keys(b.attrs).length ? { attrs: sortObj(b.attrs) } : {}),
308
- ...(b.openings.length
309
- ? {
310
- openings: b.openings.map((o) => ({
311
- kind: o.kind,
312
- w: o.w,
313
- ...(o.h !== undefined ? { h: o.h } : {}),
314
- at: o.at,
315
- ...(o.edge ? { edge: o.edge } : {}),
316
- ...(o.hinge ? { hinge: o.hinge } : {}),
317
- ...(o.swing ? { swing: o.swing } : {}),
318
- ...(Object.keys(o.attrs).length ? { attrs: sortObj(o.attrs) } : {}),
319
- })),
320
- }
321
- : {}),
322
- ...(b.segs.length
323
- ? {
324
- segs: b.segs.map((g) => ({
325
- w: g.w,
326
- at: g.at,
327
- ...(g.edge ? { edge: g.edge } : {}),
328
- ...(Object.keys(g.attrs).length ? { attrs: sortObj(g.attrs) } : {}),
329
- })),
330
- }
331
- : {}),
332
- }))
333
- .sort((x, y) => (x.between.join() < y.between.join() ? -1 : 1));
663
+ // 境界: 宣言順は意味を持たないため、並びは内容の正準順 (betweenの辞書順、同一betweenは直列化順)。
664
+ // 既定境界 (derived — ADR-0014) は出さない: 正準JSONは書かれた構成のみで、意味は導出後のModelが持つ
665
+ const boundaries = sortBySerial(
666
+ [...model.boundaries].filter((b) => !b.derived).map(canonicalBoundaryEntry),
667
+ );
334
668
 
335
669
  const zones: Record<string, unknown> = {};
336
670
  for (const p of [...model.zones.keys()].sort()) {
337
671
  const z = model.zones.get(p)!;
338
672
  zones[p] = Object.keys(z.attrs).length ? { attrs: sortObj(z.attrs) } : {};
339
673
  }
674
+ const assets: Record<string, unknown> = {};
675
+ for (const n of [...model.assets.keys()].sort()) {
676
+ const a = model.assets.get(n)!;
677
+ assets[n] = { kind: a.kind, ...(Object.keys(a.attrs).length ? { attrs: sortObj(a.attrs) } : {}) };
678
+ }
679
+ const polygons: Record<string, number[][]> = {};
680
+ for (const p of [...model.polygons.keys()].sort()) {
681
+ polygons[p] = model.polygons.get(p)!.points.map((pt) => [pt.x, pt.y]);
682
+ }
340
683
 
341
684
  const doc = {
342
685
  koyu: model.version,
@@ -351,10 +694,28 @@ export function toCanonical(model: Model): string {
351
694
  z: v.z,
352
695
  ...(v.h !== undefined ? { h: v.h } : {}),
353
696
  ...(v.slab !== undefined ? { slab: v.slab } : {}),
697
+ ...(v.underground ? { underground: 1 } : {}),
354
698
  },
355
699
  ]),
356
700
  ),
357
701
  ),
702
+ ...(Object.keys(assets).length ? { assets } : {}),
703
+ ...(Object.keys(polygons).length ? { polygons } : {}),
704
+ // **柱の宣言順は意味である。**同じ交点に二本は立たず、先の宣言が勝つ (ADR-0023) ので、
705
+ // 並べ替えると別の建物が同一のJSONになる。並べ替えてよいのは宣言の**中**の、
706
+ // 順序に意味の無い通り名の列だけである (ADR-0029)
707
+ ...(model.columns.length
708
+ ? {
709
+ columns: model.columns.map((c) => ({
710
+ size: c.size,
711
+ ...(c.depth !== undefined ? { d: c.depth } : {}),
712
+ levels: c.levels,
713
+ ...(c.xNames ? { x: sortGridNames(model.grid.X.names, c.xNames) } : {}),
714
+ ...(c.yNames ? { y: sortGridNames(model.grid.Y.names, c.yNames) } : {}),
715
+ ...(Object.keys(c.attrs).length ? { attrs: sortObj(c.attrs) } : {}),
716
+ })),
717
+ }
718
+ : {}),
358
719
  ...(Object.keys(zones).length ? { zones } : {}),
359
720
  spaces,
360
721
  boundaries,
@@ -362,6 +723,40 @@ export function toCanonical(model: Model): string {
362
723
  return JSON.stringify(doc, null, 2) + "\n";
363
724
  }
364
725
 
726
+ /**
727
+ * 描かれた線の端点の対を、解決座標の昇順に並べる。
728
+ * 線分は向きを持たない — 端点をどちらから書いても導出される凸片は同一なので、
729
+ * 書き順は綴りの揺れである (規則1)。綴り自体は通り参照のまま保つ (規則3)
730
+ */
731
+ function canonicalLineEnds(d: DrawnLine): [string, string] {
732
+ const forward = d.a.x < d.b.x || (d.a.x === d.b.x && d.a.y <= d.b.y);
733
+ return forward ? [d.aRef, d.bRef] : [d.bRef, d.aRef];
734
+ }
735
+
736
+ /** 通り名の列を通りの並び順に整える — `x:X2,X1` と `x:X1,X2` は同じ構成である */
737
+ function sortGridNames(axis: string[], names: string[]): string[] {
738
+ return [...names].sort((p, q) => {
739
+ const ip = axis.indexOf(p);
740
+ const iq = axis.indexOf(q);
741
+ if (ip < 0 || iq < 0) return p < q ? -1 : p > q ? 1 : 0; // 未宣言の通りは辞書順で安定させる
742
+ return ip - iq;
743
+ });
744
+ }
745
+
365
746
  function sortObj<T>(o: Record<string, T>): Record<string, T> {
366
747
  return Object.fromEntries(Object.entries(o).sort(([a], [b]) => (a < b ? -1 : 1)));
367
748
  }
749
+
750
+ /**
751
+ * 宣言順に意味の無い集合を、直列化したJSONの辞書順に並べる — 正準順の土台 (diffも同じ順で比べる)。
752
+ *
753
+ * **掛ける前に問う: この配列の順序を入れ替えたら別の構成になるか。**なるなら掛けてはならない。
754
+ * 並べ替えは整形ではなく「順序に意味が無い」ことの表明である。柱 (columns) は先勝ちの規則を
755
+ * 持つので掛けない — 掛けていたとき、別の建物が同一バイトの正準JSONになっていた (ADR-0029)
756
+ */
757
+ export function sortBySerial<T>(items: T[]): T[] {
758
+ return items
759
+ .map((it) => [JSON.stringify(it), it] as const)
760
+ .sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0))
761
+ .map(([, it]) => it);
762
+ }