@margoengine/loaders 0.0.0-stage → 0.1.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 (184) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1198 -3
  4. package/dist/3dm.d.ts +161 -0
  5. package/dist/3dm.js +289 -0
  6. package/dist/3ds.d.ts +124 -0
  7. package/dist/3ds.js +392 -0
  8. package/dist/acclaim.d.ts +90 -0
  9. package/dist/acclaim.js +312 -0
  10. package/dist/amf.d.ts +45 -0
  11. package/dist/amf.js +256 -0
  12. package/dist/babylon.d.ts +197 -0
  13. package/dist/babylon.js +701 -0
  14. package/dist/common.d.ts +7 -0
  15. package/dist/common.js +6 -0
  16. package/dist/dae-animation.d.ts +66 -0
  17. package/dist/dae-animation.js +266 -0
  18. package/dist/dae-common.d.ts +95 -0
  19. package/dist/dae-common.js +226 -0
  20. package/dist/dae-controllers.d.ts +57 -0
  21. package/dist/dae-controllers.js +164 -0
  22. package/dist/dae-pose.d.ts +131 -0
  23. package/dist/dae-pose.js +381 -0
  24. package/dist/dae-scene.d.ts +203 -0
  25. package/dist/dae-scene.js +279 -0
  26. package/dist/dae.d.ts +161 -0
  27. package/dist/dae.js +633 -0
  28. package/dist/detect.d.ts +20 -0
  29. package/dist/detect.js +72 -0
  30. package/dist/dxf.d.ts +81 -0
  31. package/dist/dxf.js +774 -0
  32. package/dist/engine.d.ts +36 -0
  33. package/dist/engine.js +117 -0
  34. package/dist/font-opentype.d.ts +14 -0
  35. package/dist/font-opentype.js +33 -0
  36. package/dist/font-woff.d.ts +23 -0
  37. package/dist/font-woff.js +293 -0
  38. package/dist/font.d.ts +41 -0
  39. package/dist/font.js +26 -0
  40. package/dist/gcode.d.ts +55 -0
  41. package/dist/gcode.js +278 -0
  42. package/dist/geo-model.d.ts +84 -0
  43. package/dist/geo-model.js +220 -0
  44. package/dist/geo-mvt.d.ts +15 -0
  45. package/dist/geo-mvt.js +302 -0
  46. package/dist/geo-shp.d.ts +15 -0
  47. package/dist/geo-shp.js +234 -0
  48. package/dist/geo-xml.d.ts +6 -0
  49. package/dist/geo-xml.js +165 -0
  50. package/dist/geo.d.ts +8 -0
  51. package/dist/geo.js +59 -0
  52. package/dist/geometry.d.ts +60 -0
  53. package/dist/geometry.js +273 -0
  54. package/dist/index.d.ts +54 -0
  55. package/dist/index.js +28 -0
  56. package/dist/kmz.d.ts +78 -0
  57. package/dist/kmz.js +173 -0
  58. package/dist/las.d.ts +92 -0
  59. package/dist/las.js +110 -0
  60. package/dist/ldraw.d.ts +118 -0
  61. package/dist/ldraw.js +474 -0
  62. package/dist/load.d.ts +72 -0
  63. package/dist/load.js +205 -0
  64. package/dist/lottie.d.ts +154 -0
  65. package/dist/lottie.js +893 -0
  66. package/dist/lwo.d.ts +81 -0
  67. package/dist/lwo.js +454 -0
  68. package/dist/lzf.d.ts +13 -0
  69. package/dist/lzf.js +56 -0
  70. package/dist/materialx.d.ts +120 -0
  71. package/dist/materialx.js +563 -0
  72. package/dist/md2.d.ts +52 -0
  73. package/dist/md2.js +112 -0
  74. package/dist/mmcif.d.ts +14 -0
  75. package/dist/mmcif.js +246 -0
  76. package/dist/mmd.d.ts +244 -0
  77. package/dist/mmd.js +958 -0
  78. package/dist/mocap.d.ts +71 -0
  79. package/dist/mocap.js +178 -0
  80. package/dist/molecule-common.d.ts +4 -0
  81. package/dist/molecule-common.js +54 -0
  82. package/dist/mtl.d.ts +120 -0
  83. package/dist/mtl.js +469 -0
  84. package/dist/normals.d.ts +7 -0
  85. package/dist/normals.js +31 -0
  86. package/dist/nrrd.d.ts +63 -0
  87. package/dist/nrrd.js +743 -0
  88. package/dist/nurbs.d.ts +118 -0
  89. package/dist/nurbs.js +265 -0
  90. package/dist/obj.d.ts +143 -0
  91. package/dist/obj.js +456 -0
  92. package/dist/off.d.ts +10 -0
  93. package/dist/off.js +155 -0
  94. package/dist/outline-font.d.ts +87 -0
  95. package/dist/outline-font.js +110 -0
  96. package/dist/outline.d.ts +20 -0
  97. package/dist/outline.js +215 -0
  98. package/dist/pcd.d.ts +34 -0
  99. package/dist/pcd.js +258 -0
  100. package/dist/pdb.d.ts +67 -0
  101. package/dist/pdb.js +126 -0
  102. package/dist/ply.d.ts +35 -0
  103. package/dist/ply.js +392 -0
  104. package/dist/polygon.d.ts +9 -0
  105. package/dist/polygon.js +49 -0
  106. package/dist/prwm.d.ts +24 -0
  107. package/dist/prwm.js +114 -0
  108. package/dist/render.d.ts +27 -0
  109. package/dist/render.js +153 -0
  110. package/dist/sfnt-cff.d.ts +37 -0
  111. package/dist/sfnt-cff.js +749 -0
  112. package/dist/sfnt-layout.d.ts +24 -0
  113. package/dist/sfnt-layout.js +266 -0
  114. package/dist/sfnt-reader.d.ts +28 -0
  115. package/dist/sfnt-reader.js +87 -0
  116. package/dist/sfnt-variation.d.ts +40 -0
  117. package/dist/sfnt-variation.js +318 -0
  118. package/dist/shared/asset-url.js +82 -0
  119. package/dist/shared/crc32.d.ts +2 -0
  120. package/dist/shared/crc32.js +47 -0
  121. package/dist/shared/errors.js +36 -0
  122. package/dist/shared/inflate.js +284 -0
  123. package/dist/shared/normals.js +26 -0
  124. package/dist/shared/scene-scope.js +56 -0
  125. package/dist/shared/trailing-data.js +42 -0
  126. package/dist/stl.d.ts +64 -0
  127. package/dist/stl.js +309 -0
  128. package/dist/svg.d.ts +90 -0
  129. package/dist/svg.js +1007 -0
  130. package/dist/tds.d.ts +2 -0
  131. package/dist/tds.js +2 -0
  132. package/dist/textures.d.ts +42 -0
  133. package/dist/textures.js +53 -0
  134. package/dist/threemf-lattice.d.ts +139 -0
  135. package/dist/threemf-lattice.js +514 -0
  136. package/dist/threemf-materials.d.ts +75 -0
  137. package/dist/threemf-materials.js +314 -0
  138. package/dist/threemf-mesh.d.ts +60 -0
  139. package/dist/threemf-mesh.js +201 -0
  140. package/dist/threemf.d.ts +101 -0
  141. package/dist/threemf.js +415 -0
  142. package/dist/tilt.d.ts +62 -0
  143. package/dist/tilt.js +186 -0
  144. package/dist/tmx.d.ts +151 -0
  145. package/dist/tmx.js +394 -0
  146. package/dist/ttf.d.ts +78 -0
  147. package/dist/ttf.js +568 -0
  148. package/dist/types.d.ts +90 -0
  149. package/dist/types.js +35 -0
  150. package/dist/usd.d.ts +2 -0
  151. package/dist/usd.js +2 -0
  152. package/dist/usd.worker.d.ts +1 -0
  153. package/dist/usdz.d.ts +50 -0
  154. package/dist/usdz.js +646 -0
  155. package/dist/util.d.ts +75 -0
  156. package/dist/util.js +241 -0
  157. package/dist/vdb.d.ts +111 -0
  158. package/dist/vdb.js +663 -0
  159. package/dist/vrml.d.ts +53 -0
  160. package/dist/vrml.js +532 -0
  161. package/dist/vtk-cells.d.ts +29 -0
  162. package/dist/vtk-cells.js +211 -0
  163. package/dist/vtk-legacy.d.ts +57 -0
  164. package/dist/vtk-legacy.js +439 -0
  165. package/dist/vtk-reader.d.ts +19 -0
  166. package/dist/vtk-reader.js +134 -0
  167. package/dist/vtk-xml.d.ts +96 -0
  168. package/dist/vtk-xml.js +578 -0
  169. package/dist/vtk.d.ts +13 -0
  170. package/dist/vtk.js +234 -0
  171. package/dist/woff-glyf.d.ts +17 -0
  172. package/dist/woff-glyf.js +215 -0
  173. package/dist/worker.d.ts +10 -0
  174. package/dist/worker.js +93 -0
  175. package/dist/workers/usd.js +3 -0
  176. package/dist/xfile.d.ts +99 -0
  177. package/dist/xfile.js +706 -0
  178. package/dist/xml.d.ts +107 -0
  179. package/dist/xml.js +843 -0
  180. package/dist/xyz.d.ts +16 -0
  181. package/dist/xyz.js +110 -0
  182. package/dist/zip.d.ts +38 -0
  183. package/dist/zip.js +150 -0
  184. package/package.json +246 -6
package/dist/gcode.js ADDED
@@ -0,0 +1,278 @@
1
+ // RepRap G-code toolpaths: G0 and G1 moves and G2 and G3 arcs with E, grouped by Z into layers of line segments.
2
+ //
3
+ // Arcs follow the RepRap G-code wiki (G2 and G3, G17 to G19) and the LinuxCNC G-code reference (5. G2, G3 Arc Move):
4
+ // I, J and K are the centre's offset from the start in the selected plane, R a radius whose sign picks the arc under
5
+ // 180 degrees (positive) or over it (negative), an arc that ends where it starts is a full circle, P counts turns, and
6
+ // the axis normal to the plane moves linearly (a helix). G2 turns clockwise seen from the positive end of that axis.
7
+ // G90.1 makes I, J and K the centre itself and G91.1 (the default) an offset again (LinuxCNC G-code reference). Marlin's
8
+ // G2 and G3 page (marlinfw.org/docs/gcode/G002-G003.html) gives P as complete circles, read with arcP: 'circles'.
9
+ import { LoaderError } from './types.js';
10
+ import { floats, limits, toText } from './util.js';
11
+ const F = 'G-code';
12
+ /** Largest gap between an arc and its chords, in millimetres; a turn takes at least 16 chords. */
13
+ const ARC_TOLERANCE = 0.002;
14
+ /**
15
+ * Parses RepRap-flavoured G-code: G0 and G1 with X, Y, Z, E; G2 and G3 arcs by centre offsets (I, J, K) or radius (R),
16
+ * with full circles, turns (P, counted as `arcP` says) and helices, in the plane G17, G18 or G19 selects; G90.1 and
17
+ * G91.1 for absolute and incremental arc centres; G90, G91, M82 and M83 for absolute and relative axes; G92 to set a position; G20 and G21 for units; G28 to home. Other commands are skipped. An arc is
18
+ * drawn as chords within 0.002 mm of it, its E spread evenly along them. `maxVertices` counts two per segment.
19
+ *
20
+ * @param input The file's bytes or text.
21
+ * @param options The shared size limits and `arcP`.
22
+ * @returns The layers, filament use and bounds.
23
+ * @throws LoaderError with code `syntax` for a bad number, an arc without its centre or radius, or a G90.1 arc
24
+ * missing one of its plane's two centre words, `range` for an arc
25
+ * whose end is off its circle (past LinuxCNC's tolerance) or whose radius is shorter than half its chord, and `limit`
26
+ * past `maxVertices`.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { parseGCode } from '@margoengine/loaders/gcode';
31
+ *
32
+ * const { layers, filament } = parseGCode('G1 Z0.2\nG1 X10 E1\nG3 X0 Y10 I-10 E2\n');
33
+ * console.log(layers[0].z, layers[0].extrusion.length, filament);
34
+ * ```
35
+ */
36
+ export function parseGCode(input, options = {}) {
37
+ const text = toText(input, F), { maxVertices } = limits(options, F), circles = options.arcP === 'circles';
38
+ if (options.arcP !== undefined && options.arcP !== 'turns' && !circles)
39
+ throw new LoaderError(F, 'range', `arcP must be 'turns' or 'circles', not ${String(options.arcP).slice(0, 40)}`);
40
+ const byZ = new Map(), warnings = [], position = [0, 0, 0, 0], min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
41
+ let pending = floats(), relative = false, relativeE = false,
42
+ // G90.1: I, J and K are the centre itself; G91.1 (the default): its offset from the start.
43
+ absoluteCentre = false, unit = 1, filament = 0, vertices = 0, current,
44
+ // The arc plane's first and second axes and its normal: G17 X Y (Z), G18 Z X (Y), G19 Y Z (X).
45
+ plane = [0, 1, 2], lineNumber = 0;
46
+ const axes = 'XYZE';
47
+ // No exponents: G-code has none, and in G1X1E2 the E is the extruder.
48
+ const word = /([A-Za-z])\s*([+-]?(?:\d+\.?\d*|\.\d+))?/g;
49
+ /** Where a move's words take the tool: each axis absolute or relative by its mode. */
50
+ const target = (words) => position.map((at, a) => {
51
+ const value = words[a];
52
+ return value === undefined ? at : (a === 3 ? relativeE : relative) ? at + value : value;
53
+ });
54
+ /** One straight move, extruding when E rises along it. */
55
+ const segment = (from, to) => {
56
+ const pushed = to[3] - from[3];
57
+ filament += pushed; // A retraction takes back what its recovery pushes again.
58
+ if (to[0] === from[0] && to[1] === from[1] && to[2] === from[2])
59
+ return;
60
+ if ((vertices += 2) > maxVertices)
61
+ throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${maxVertices}`);
62
+ for (let a = 0; a < 3; a++) {
63
+ min[a] = Math.min(min[a], from[a], to[a]);
64
+ max[a] = Math.max(max[a], from[a], to[a]);
65
+ }
66
+ const extruding = pushed > 0;
67
+ if (extruding) {
68
+ current = byZ.get(to[2]);
69
+ if (!current)
70
+ byZ.set(to[2], (current = makeLayer(to[2])));
71
+ // Travel seen since the last extrusion leads into this layer.
72
+ current.travel.reserve(pending.length);
73
+ current.travel.array.set(pending.array.subarray(0, pending.length), current.travel.length);
74
+ current.travel.length += pending.length;
75
+ pending = floats();
76
+ }
77
+ const into = extruding && current ? current.extrusion : pending;
78
+ into.reserve(6);
79
+ into.array.set([from[0], from[1], from[2], to[0], to[1], to[2]], into.length);
80
+ into.length += 6;
81
+ };
82
+ /** G2 (clockwise) or G3 as chords; `words` holds I, J, K, R and P. */
83
+ const arc = (ccw, to, words) => {
84
+ const from = position.slice(), [u, v, w] = plane, radius = words[3],
85
+ // Both readings become the number of whole turns past the first.
86
+ p = words[4] ?? (circles ? 0 : 1), extra = circles ? p : p - 1, su = from[u], sv = from[v], eu = to[u], ev = to[v];
87
+ if (!Number.isInteger(p) || extra < 0)
88
+ throw new LoaderError(F, 'syntax', circles
89
+ ? `P must be a whole number of circles, 0 or more, on line ${lineNumber}`
90
+ : `P must be a whole number of turns on line ${lineNumber}`);
91
+ let cu, cv;
92
+ if (radius !== undefined) {
93
+ // Radius form: the centre is on the chord's bisector, left of the chord for a short G3 or a long G2.
94
+ const chord = Math.hypot(eu - su, ev - sv), r = Math.abs(radius);
95
+ if (!chord)
96
+ throw new LoaderError(F, 'syntax', `an R arc must end away from its start on line ${lineNumber}`);
97
+ if (r < chord / 2 - Math.max(0.005, 1e-3 * r))
98
+ throw new LoaderError(F, 'range', `radius ${r} is shorter than half its chord on line ${lineNumber}`);
99
+ const rise = Math.sqrt(Math.max(0, r * r - (chord * chord) / 4)) / chord, side = (ccw ? 1 : -1) * (radius < 0 ? -1 : 1);
100
+ cu = (su + eu) / 2 - side * rise * (ev - sv);
101
+ cv = (sv + ev) / 2 + side * rise * (eu - su);
102
+ }
103
+ else {
104
+ // The offsets in the plane's own order: I J for G17, K I for G18, J K for G19 (words are I, J, K).
105
+ const du = words[u], dv = words[v];
106
+ if (absoluteCentre) {
107
+ // LinuxCNC: with G90.1 both of the plane's centre words must be given.
108
+ if (du === undefined || dv === undefined)
109
+ throw new LoaderError(F, 'syntax', `a G90.1 arc needs both centre words of its plane or R on line ${lineNumber}`);
110
+ cu = du;
111
+ cv = dv;
112
+ }
113
+ else {
114
+ if (du === undefined && dv === undefined)
115
+ throw new LoaderError(F, 'syntax', `an arc needs centre offsets in its plane or R on line ${lineNumber}`);
116
+ cu = su + (du ?? 0);
117
+ cv = sv + (dv ?? 0);
118
+ }
119
+ }
120
+ const r0 = Math.hypot(su - cu, sv - cv), r1 = Math.hypot(eu - cu, ev - cv), off = Math.abs(r1 - r0);
121
+ // LinuxCNC: the end may miss the circle by at most 0.5 mm, and by at most 0.005 mm or 0.1% of the radius.
122
+ if (off > 0.5 || (off > 0.005 && off > 1e-3 * r0))
123
+ throw new LoaderError(F, 'range', `the arc's end is ${off} mm off its circle on line ${lineNumber}`);
124
+ const a0 = Math.atan2(sv - cv, su - cu);
125
+ let sweep = eu === su && ev === sv ? 0 : Math.atan2(ev - cv, eu - cu) - a0;
126
+ // Turn the long way round to keep the direction; an arc that ends where it starts is a full circle.
127
+ if (ccw ? sweep <= 0 : sweep >= 0)
128
+ sweep += ccw ? 2 * Math.PI : -2 * Math.PI;
129
+ sweep += (ccw ? 2 : -2) * Math.PI * extra;
130
+ const step = r0 > ARC_TOLERANCE ? 2 * Math.acos(1 - ARC_TOLERANCE / r0) : Math.PI, chords = Math.max(1, Math.ceil(Math.abs(sweep) / Math.min(step, Math.PI / 8)));
131
+ if (vertices + chords * 2 > maxVertices)
132
+ throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${maxVertices}`);
133
+ let last = from;
134
+ for (let c = 1; c <= chords; c++) {
135
+ const t = c / chords, point = to.slice();
136
+ if (c < chords) {
137
+ const angle = a0 + sweep * t, r = r0 + (r1 - r0) * t;
138
+ point[u] = cu + r * Math.cos(angle);
139
+ point[v] = cv + r * Math.sin(angle);
140
+ point[w] = from[w] + (to[w] - from[w]) * t;
141
+ point[3] = from[3] + (to[3] - from[3]) * t;
142
+ }
143
+ segment(last, point);
144
+ last = point;
145
+ }
146
+ };
147
+ for (let start = 0; start < text.length;) {
148
+ let end = text.indexOf('\n', start);
149
+ if (end < 0)
150
+ end = text.length;
151
+ const line = text.slice(start, end).replace(/\(.*?\)/g, '');
152
+ start = end + 1;
153
+ lineNumber++;
154
+ const semicolon = line.indexOf(';');
155
+ let body = semicolon >= 0 ? line.slice(0, semicolon) : line;
156
+ const star = body.indexOf('*');
157
+ if (star >= 0)
158
+ body = body.slice(0, star);
159
+ let command = '';
160
+ const values = [undefined, undefined, undefined, undefined],
161
+ // I, J, K, R and P of an arc.
162
+ arcWords = [undefined, undefined, undefined, undefined, undefined];
163
+ word.lastIndex = 0;
164
+ for (let match = word.exec(body); match; match = word.exec(body)) {
165
+ const letter = match[1].toUpperCase();
166
+ if (letter === 'N' && !command)
167
+ continue;
168
+ if (!command) {
169
+ if (match[2] === undefined)
170
+ throw new LoaderError(F, 'syntax', `command without a number on line ${lineNumber}`);
171
+ command = letter + Number(match[2]);
172
+ continue;
173
+ }
174
+ const axis = axes.indexOf(letter);
175
+ if (axis < 0) {
176
+ const at = 'IJKRP'.indexOf(letter);
177
+ if (at < 0 || (command !== 'G2' && command !== 'G3'))
178
+ continue;
179
+ if (match[2] === undefined)
180
+ throw new LoaderError(F, 'syntax', `${letter} has no number on line ${lineNumber}`);
181
+ arcWords[at] = Number(match[2]) * (letter === 'P' ? 1 : unit);
182
+ continue;
183
+ }
184
+ if (match[2] === undefined) {
185
+ if (command === 'G28')
186
+ values[axis] = 0;
187
+ else if (command !== 'G92')
188
+ throw new LoaderError(F, 'syntax', `${letter} has no number on line ${lineNumber}`);
189
+ else
190
+ values[axis] = 0;
191
+ }
192
+ else
193
+ values[axis] = Number(match[2]) * unit;
194
+ }
195
+ switch (command) {
196
+ case 'G90':
197
+ relative = relativeE = false;
198
+ break;
199
+ case 'G91':
200
+ relative = relativeE = true;
201
+ break;
202
+ case 'G90.1':
203
+ absoluteCentre = true;
204
+ break;
205
+ case 'G91.1':
206
+ absoluteCentre = false;
207
+ break;
208
+ case 'M82':
209
+ relativeE = false;
210
+ break;
211
+ case 'M83':
212
+ relativeE = true;
213
+ break;
214
+ case 'G20':
215
+ unit = 25.4;
216
+ break;
217
+ case 'G21':
218
+ unit = 1;
219
+ break;
220
+ case 'G17':
221
+ plane = [0, 1, 2];
222
+ break;
223
+ case 'G18':
224
+ plane = [2, 0, 1];
225
+ break;
226
+ case 'G19':
227
+ plane = [1, 2, 0];
228
+ break;
229
+ case 'G92':
230
+ for (let a = 0; a < 4; a++)
231
+ position[a] = values[a] ?? (values.every((v) => v === undefined) ? 0 : position[a]);
232
+ break;
233
+ case 'G28':
234
+ for (let a = 0; a < 3; a++)
235
+ if (values[a] !== undefined || values.every((v) => v === undefined))
236
+ position[a] = 0;
237
+ break;
238
+ case 'G2':
239
+ case 'G3': {
240
+ const to = target(values);
241
+ arc(command === 'G3', to, arcWords);
242
+ position.splice(0, 4, ...to);
243
+ break;
244
+ }
245
+ case 'G0':
246
+ case 'G1': {
247
+ const from = position.slice();
248
+ position.splice(0, 4, ...target(values));
249
+ segment(from, position);
250
+ break;
251
+ }
252
+ default:
253
+ }
254
+ }
255
+ if (pending.length) {
256
+ const last = current ?? makeLayer(position[2]);
257
+ if (!current)
258
+ byZ.set(position[2], last);
259
+ last.travel.reserve(pending.length);
260
+ last.travel.array.set(pending.array.subarray(0, pending.length), last.travel.length);
261
+ last.travel.length += pending.length;
262
+ }
263
+ const layers = [...byZ.values()]
264
+ .sort((a, b) => a.z - b.z)
265
+ .map((layer) => ({
266
+ z: layer.z,
267
+ extrusion: layer.extrusion.array.slice(0, layer.extrusion.length),
268
+ travel: layer.travel.array.slice(0, layer.travel.length),
269
+ }));
270
+ if (!vertices) {
271
+ min.fill(0);
272
+ max.fill(0);
273
+ }
274
+ return { layers, filament, min, max, warnings };
275
+ }
276
+ function makeLayer(z) {
277
+ return { z, extrusion: floats(), travel: floats() };
278
+ }
@@ -0,0 +1,84 @@
1
+ import { type LoadedGeometry, type ParseLimits } from './types.js';
2
+ import type { XMLExternalOptions } from './xml.js';
3
+ /** A source coordinate; z is optional and extra ordinates remain in source geometry. */
4
+ export type GeoPosition = number[];
5
+ /** GeoJSON-compatible geometry shared by every vector reader. */
6
+ export type GeoGeometry = {
7
+ type: 'Point';
8
+ coordinates: GeoPosition;
9
+ } | {
10
+ type: 'MultiPoint' | 'LineString';
11
+ coordinates: GeoPosition[];
12
+ } | {
13
+ type: 'MultiLineString' | 'Polygon';
14
+ coordinates: GeoPosition[][];
15
+ } | {
16
+ type: 'MultiPolygon';
17
+ coordinates: GeoPosition[][][];
18
+ } | {
19
+ type: 'GeometryCollection';
20
+ geometries: GeoGeometry[];
21
+ };
22
+ /** One source feature and its attributes. */
23
+ export interface GeoFeature {
24
+ type: 'Feature';
25
+ id?: string | number;
26
+ properties: Record<string, unknown> | null;
27
+ geometry: GeoGeometry | null;
28
+ /** MVT source layer name, if present. */
29
+ layer?: string;
30
+ /** MVT layer extent, if present. */
31
+ extent?: number;
32
+ }
33
+ /** Parse and tessellation bounds for vector data. */
34
+ export interface GeoOptions extends ParseLimits, XMLExternalOptions {
35
+ /** Maximum source features. Default 100,000. */
36
+ maxFeatures?: number;
37
+ /** Maximum input bytes. Default 256 MiB. */
38
+ maxBytes?: number;
39
+ /** Geometry collection nesting limit. Default 64. */
40
+ maxDepth?: number;
41
+ /** Cancellation checked at feature and primitive boundaries. */
42
+ signal?: AbortSignal;
43
+ }
44
+ /** One polygon: index rings, with outer ring first and holes following. */
45
+ export interface GeoPolygon {
46
+ feature: number;
47
+ rings: Uint32Array[];
48
+ }
49
+ /** Mixed vector primitives with source precision and renderable triangles. */
50
+ export interface GeoResult {
51
+ features: GeoFeature[];
52
+ /** Owned xyz coordinates in source units, retaining double precision. */
53
+ positions: Float64Array;
54
+ /** Explicit point indices. */
55
+ points: Uint32Array;
56
+ /** Source feature per point. */
57
+ pointFeatures: Uint32Array;
58
+ /** Two indices per line segment, including polygon boundaries. */
59
+ lines: Uint32Array;
60
+ /** Source feature per segment. */
61
+ lineFeatures: Uint32Array;
62
+ /** Source feature per triangle in mesh.indices. */
63
+ triangleFeatures: Uint32Array;
64
+ /** Source polygon boundaries, without the repeated closing vertex. */
65
+ polygons: GeoPolygon[];
66
+ /** Triangles and float32 coordinates for createMeshes/toGeometry; groups address source features. */
67
+ mesh: LoadedGeometry;
68
+ /** Coordinate reference system label. No implicit projection is applied. */
69
+ crs: string;
70
+ }
71
+ export declare const GEO = "Geo";
72
+ export declare function geoLimit(options: GeoOptions, key: 'maxFeatures' | 'maxBytes' | 'maxDepth', fallback: number): number;
73
+ export declare function geoText(input: string | Uint8Array, options: GeoOptions): string;
74
+ export declare function area(ring: GeoPosition[]): number;
75
+ export declare function inside(p: GeoPosition, ring: GeoPosition[]): boolean;
76
+ /**
77
+ * The two ordinates a ring is triangulated in: x and y, the plane of every map polygon, unless the ring stands
78
+ * vertical (a MultiPatch wall), where its x/y outline has no area; then the plane its Newell normal faces.
79
+ */
80
+ export declare function planeAxes(ring: GeoPosition[]): [number, number];
81
+ /** Internal containment grouping, independent of source ring winding or part ordering. */
82
+ export declare function ringPolygons(rings: GeoPosition[][]): GeoPosition[][][];
83
+ /** Internal normalization and tessellation shared by all vector formats. */
84
+ export declare function buildGeo(features: GeoFeature[], options?: GeoOptions, crs?: string): GeoResult;
@@ -0,0 +1,220 @@
1
+ import { triangulate } from '@margoengine/geometry/triangulate';
2
+ import { LoaderError } from './types.js';
3
+ import { limits, throwIfAborted } from './util.js';
4
+ export const GEO = 'Geo';
5
+ export function geoLimit(options, key, fallback) {
6
+ const value = options[key] ?? fallback;
7
+ if (!Number.isSafeInteger(value) || value < 1)
8
+ throw new LoaderError(GEO, 'limit', `${key} must be a positive safe integer`);
9
+ return value;
10
+ }
11
+ export function geoText(input, options) {
12
+ throwIfAborted(options.signal, GEO);
13
+ const max = geoLimit(options, 'maxBytes', 256 << 20);
14
+ if ((typeof input === 'string' ? new TextEncoder().encode(input).length : input.length) > max)
15
+ throw new LoaderError(GEO, 'limit', `input exceeds ${max} bytes`);
16
+ return typeof input === 'string' ? input : new TextDecoder().decode(input);
17
+ }
18
+ export function area(ring) {
19
+ let sum = 0;
20
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++)
21
+ sum += ring[j][0] * ring[i][1] - ring[i][0] * ring[j][1];
22
+ return sum / 2;
23
+ }
24
+ export function inside(p, ring) {
25
+ let result = false;
26
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
27
+ const a = ring[i], b = ring[j];
28
+ if (a[1] > p[1] !== b[1] > p[1] && p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0])
29
+ result = !result;
30
+ }
31
+ return result;
32
+ }
33
+ /**
34
+ * The two ordinates a ring is triangulated in: x and y, the plane of every map polygon, unless the ring stands
35
+ * vertical (a MultiPatch wall), where its x/y outline has no area; then the plane its Newell normal faces.
36
+ */
37
+ export function planeAxes(ring) {
38
+ let nx = 0, ny = 0, nz = 0;
39
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
40
+ const a = ring[j], b = ring[i], az = a[2] ?? 0, bz = b[2] ?? 0;
41
+ nx += (a[1] - b[1]) * (az + bz);
42
+ ny += (az - bz) * (a[0] + b[0]);
43
+ nz += (a[0] - b[0]) * (a[1] + b[1]);
44
+ }
45
+ const x = Math.abs(nx), y = Math.abs(ny), z = Math.abs(nz);
46
+ // Kept in x/y unless that projection is degenerate, so lon/lat polygons with metre heights never change plane.
47
+ if (z > Math.hypot(x, y, z) * 1e-9 || (x === 0 && y === 0))
48
+ return [0, 1];
49
+ return x >= y ? [1, 2] : [2, 0];
50
+ }
51
+ /** Internal containment grouping, independent of source ring winding or part ordering. */
52
+ export function ringPolygons(rings) {
53
+ const ordered = rings
54
+ .map((ring, i) => ({ ring, i, area: Math.abs(area(ring)), parent: -1, depth: 0 }))
55
+ .sort((a, b) => b.area - a.area);
56
+ const polygons = [], owner = new Map();
57
+ for (let i = 0; i < ordered.length; i++) {
58
+ const entry = ordered[i];
59
+ for (let j = i - 1; j >= 0; j--)
60
+ if (inside(entry.ring[0], ordered[j].ring)) {
61
+ entry.parent = j;
62
+ entry.depth = ordered[j].depth + 1;
63
+ break;
64
+ }
65
+ if (!(entry.depth % 2)) {
66
+ const polygon = [entry.ring];
67
+ polygons.push(polygon);
68
+ owner.set(i, polygon);
69
+ }
70
+ else {
71
+ let parent = entry.parent;
72
+ while (parent >= 0 && !owner.has(parent))
73
+ parent = ordered[parent].parent;
74
+ owner.get(parent).push(entry.ring);
75
+ }
76
+ }
77
+ return polygons;
78
+ }
79
+ /** Internal normalization and tessellation shared by all vector formats. */
80
+ export function buildGeo(features, options = {}, crs = 'OGC:CRS84') {
81
+ throwIfAborted(options.signal, GEO);
82
+ const limit = limits(options, GEO), maxFeatures = geoLimit(options, 'maxFeatures', 100000), maxDepth = geoLimit(options, 'maxDepth', 64);
83
+ if (features.length > maxFeatures)
84
+ throw new LoaderError(GEO, 'limit', `features exceed ${maxFeatures}`);
85
+ const positions = [], points = [], pointFeatures = [], lines = [], lineFeatures = [], indices = [], triangleFeatures = [], polygons = [];
86
+ const groups = [];
87
+ const vertex = (p) => {
88
+ if (!Array.isArray(p) || p.length < 2 || p.some((v) => typeof v !== 'number' || !Number.isFinite(v)))
89
+ throw new LoaderError(GEO, 'syntax', 'positions need finite x/y and optional z');
90
+ if (positions.length / 3 >= limit.maxVertices)
91
+ throw new LoaderError(GEO, 'limit', `vertices exceed ${limit.maxVertices}`);
92
+ const index = positions.length / 3;
93
+ positions.push(p[0], p[1], p[2] ?? 0);
94
+ return index;
95
+ };
96
+ const path = (coords, feature, closed = false) => {
97
+ throwIfAborted(options.signal, GEO);
98
+ if (Array.isArray(coords) && coords.length === 0 && !closed)
99
+ return [];
100
+ if (!Array.isArray(coords) || coords.length < (closed ? 4 : 2))
101
+ throw new LoaderError(GEO, 'syntax', closed ? 'polygon rings need four closed coordinates' : 'lines need two positions');
102
+ let source = coords;
103
+ if (closed) {
104
+ const a = coords[0], b = coords.at(-1);
105
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length || a.some((v, i) => v !== b[i]))
106
+ throw new LoaderError(GEO, 'syntax', 'polygon rings must be closed');
107
+ source = coords.slice(0, -1);
108
+ }
109
+ const result = source.map(vertex);
110
+ for (let i = 0; i + 1 < result.length; i++) {
111
+ lines.push(result[i], result[i + 1]);
112
+ lineFeatures.push(feature);
113
+ }
114
+ if (closed) {
115
+ lines.push(result.at(-1), result[0]);
116
+ lineFeatures.push(feature);
117
+ }
118
+ return result;
119
+ };
120
+ const geometry = (g, feature, depth = 0) => {
121
+ if (depth > maxDepth)
122
+ throw new LoaderError(GEO, 'limit', `geometry collections exceed ${maxDepth}`);
123
+ if (!g || typeof g !== 'object')
124
+ throw new LoaderError(GEO, 'syntax', 'expected a geometry object');
125
+ switch (g.type) {
126
+ case 'Point':
127
+ points.push(vertex(g.coordinates));
128
+ pointFeatures.push(feature);
129
+ break;
130
+ case 'MultiPoint':
131
+ if (!Array.isArray(g.coordinates))
132
+ throw new LoaderError(GEO, 'syntax', 'MultiPoint needs coordinates');
133
+ for (const p of g.coordinates) {
134
+ points.push(vertex(p));
135
+ pointFeatures.push(feature);
136
+ }
137
+ break;
138
+ case 'LineString':
139
+ path(g.coordinates, feature);
140
+ break;
141
+ case 'MultiLineString':
142
+ if (!Array.isArray(g.coordinates))
143
+ throw new LoaderError(GEO, 'syntax', 'MultiLineString needs coordinates');
144
+ for (const line of g.coordinates)
145
+ path(line, feature);
146
+ break;
147
+ case 'Polygon': {
148
+ if (!Array.isArray(g.coordinates))
149
+ throw new LoaderError(GEO, 'syntax', 'Polygon needs coordinate rings');
150
+ if (!g.coordinates.length)
151
+ break;
152
+ const rings = g.coordinates.map((r) => path(r, feature, true)), [u, w] = planeAxes(g.coordinates[0]), flat = [], mapping = [], holes = [];
153
+ for (let r = 0; r < rings.length; r++) {
154
+ if (r)
155
+ holes.push(mapping.length);
156
+ for (const v of rings[r]) {
157
+ mapping.push(v);
158
+ flat.push(positions[v * 3 + u], positions[v * 3 + w]);
159
+ }
160
+ }
161
+ const triangles = triangulate(flat, holes, 2);
162
+ if (indices.length / 3 + triangles.length / 3 > limit.maxTriangles)
163
+ throw new LoaderError(GEO, 'limit', `triangles exceed ${limit.maxTriangles}`);
164
+ for (const index of triangles)
165
+ indices.push(mapping[index]);
166
+ for (let t = 0; t < triangles.length; t += 3)
167
+ triangleFeatures.push(feature);
168
+ polygons.push({ feature, rings: rings.map((r) => Uint32Array.from(r)) });
169
+ break;
170
+ }
171
+ case 'MultiPolygon':
172
+ if (!Array.isArray(g.coordinates))
173
+ throw new LoaderError(GEO, 'syntax', 'MultiPolygon needs coordinates');
174
+ for (const polygon of g.coordinates)
175
+ geometry({ type: 'Polygon', coordinates: polygon }, feature, depth);
176
+ break;
177
+ case 'GeometryCollection':
178
+ if (!Array.isArray(g.geometries))
179
+ throw new LoaderError(GEO, 'syntax', 'GeometryCollection needs geometries');
180
+ for (const child of g.geometries)
181
+ geometry(child, feature, depth + 1);
182
+ break;
183
+ default:
184
+ throw new LoaderError(GEO, 'unsupported', `unknown geometry type ${g.type}`);
185
+ }
186
+ };
187
+ for (let f = 0; f < features.length; f++) {
188
+ throwIfAborted(options.signal, GEO);
189
+ const feature = features[f];
190
+ const start = indices.length;
191
+ if (feature.geometry)
192
+ geometry(feature.geometry, f);
193
+ if (indices.length > start)
194
+ groups.push({
195
+ start,
196
+ count: indices.length - start,
197
+ objectId: String(feature.id ?? f),
198
+ name: typeof feature.properties?.name === 'string' ? feature.properties.name : undefined,
199
+ });
200
+ }
201
+ const mesh = { kind: indices.length ? 'mesh' : 'points', positions: Float32Array.from(positions) };
202
+ if (mesh.positions.some((v) => !Number.isFinite(v)))
203
+ throw new LoaderError(GEO, 'range', 'render coordinates exceed float32 range');
204
+ if (indices.length) {
205
+ mesh.indices = Uint32Array.from(indices);
206
+ mesh.groups = groups;
207
+ }
208
+ return {
209
+ features,
210
+ positions: Float64Array.from(positions),
211
+ points: Uint32Array.from(points),
212
+ pointFeatures: Uint32Array.from(pointFeatures),
213
+ lines: Uint32Array.from(lines),
214
+ lineFeatures: Uint32Array.from(lineFeatures),
215
+ triangleFeatures: Uint32Array.from(triangleFeatures),
216
+ polygons,
217
+ mesh,
218
+ crs,
219
+ };
220
+ }
@@ -0,0 +1,15 @@
1
+ import { type BinaryInput } from './util.js';
2
+ import { type GeoOptions, type GeoResult } from './geo-model.js';
3
+ /** Vector tile coordinates and optional layer selection. */
4
+ export interface MVTOptions extends GeoOptions {
5
+ /** With a tile address, return WGS84 lon/lat; otherwise retain local tile coordinates (y down). */
6
+ tile?: {
7
+ x: number;
8
+ y: number;
9
+ z: number;
10
+ };
11
+ /** Read only these named layers. Default all. */
12
+ layers?: readonly string[];
13
+ }
14
+ /** Reads MVT 1/2 protobuf vector tiles, preserving layers, tags, IDs, multipart lines and polygon holes. */
15
+ export declare function parseMVT(input: BinaryInput, options?: MVTOptions): GeoResult;