@margoengine/loaders 0.0.0-stage → 1.0.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 (226) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1665 -2
  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/crease.d.ts +7 -0
  17. package/dist/crease.js +67 -0
  18. package/dist/dae-animation.d.ts +66 -0
  19. package/dist/dae-animation.js +266 -0
  20. package/dist/dae-common.d.ts +95 -0
  21. package/dist/dae-common.js +226 -0
  22. package/dist/dae-controllers.d.ts +57 -0
  23. package/dist/dae-controllers.js +164 -0
  24. package/dist/dae-kinematics.d.ts +65 -0
  25. package/dist/dae-kinematics.js +461 -0
  26. package/dist/dae-pose.d.ts +131 -0
  27. package/dist/dae-pose.js +381 -0
  28. package/dist/dae-scene.d.ts +203 -0
  29. package/dist/dae-scene.js +279 -0
  30. package/dist/dae.d.ts +166 -0
  31. package/dist/dae.js +644 -0
  32. package/dist/detect.d.ts +20 -0
  33. package/dist/detect.js +72 -0
  34. package/dist/dxf-hatch.d.ts +8 -0
  35. package/dist/dxf-hatch.js +346 -0
  36. package/dist/dxf-leaders.d.ts +59 -0
  37. package/dist/dxf-leaders.js +258 -0
  38. package/dist/dxf.d.ts +122 -0
  39. package/dist/dxf.js +985 -0
  40. package/dist/engine.d.ts +41 -0
  41. package/dist/engine.js +120 -0
  42. package/dist/font-opentype.d.ts +14 -0
  43. package/dist/font-opentype.js +33 -0
  44. package/dist/font-woff.d.ts +23 -0
  45. package/dist/font-woff.js +293 -0
  46. package/dist/font.d.ts +41 -0
  47. package/dist/font.js +26 -0
  48. package/dist/gcode.d.ts +92 -0
  49. package/dist/gcode.js +369 -0
  50. package/dist/geo-model.d.ts +84 -0
  51. package/dist/geo-model.js +220 -0
  52. package/dist/geo-mvt.d.ts +15 -0
  53. package/dist/geo-mvt.js +302 -0
  54. package/dist/geo-shp.d.ts +15 -0
  55. package/dist/geo-shp.js +234 -0
  56. package/dist/geo-xml.d.ts +6 -0
  57. package/dist/geo-xml.js +165 -0
  58. package/dist/geo.d.ts +8 -0
  59. package/dist/geo.js +59 -0
  60. package/dist/geometry.d.ts +60 -0
  61. package/dist/geometry.js +273 -0
  62. package/dist/index.d.ts +54 -0
  63. package/dist/index.js +28 -0
  64. package/dist/kmz.d.ts +78 -0
  65. package/dist/kmz.js +173 -0
  66. package/dist/las.d.ts +92 -0
  67. package/dist/las.js +110 -0
  68. package/dist/ldraw.d.ts +118 -0
  69. package/dist/ldraw.js +474 -0
  70. package/dist/load.d.ts +72 -0
  71. package/dist/load.js +205 -0
  72. package/dist/lottie.d.ts +154 -0
  73. package/dist/lottie.js +893 -0
  74. package/dist/lwo.d.ts +81 -0
  75. package/dist/lwo.js +454 -0
  76. package/dist/lzf.d.ts +13 -0
  77. package/dist/lzf.js +56 -0
  78. package/dist/materialx.d.ts +120 -0
  79. package/dist/materialx.js +563 -0
  80. package/dist/md2.d.ts +52 -0
  81. package/dist/md2.js +112 -0
  82. package/dist/mmcif.d.ts +14 -0
  83. package/dist/mmcif.js +246 -0
  84. package/dist/mmd.d.ts +244 -0
  85. package/dist/mmd.js +958 -0
  86. package/dist/mocap.d.ts +71 -0
  87. package/dist/mocap.js +178 -0
  88. package/dist/molecule-common.d.ts +4 -0
  89. package/dist/molecule-common.js +54 -0
  90. package/dist/mtl.d.ts +125 -0
  91. package/dist/mtl.js +550 -0
  92. package/dist/normals.d.ts +7 -0
  93. package/dist/normals.js +31 -0
  94. package/dist/nrrd.d.ts +70 -0
  95. package/dist/nrrd.js +785 -0
  96. package/dist/nurbs.d.ts +118 -0
  97. package/dist/nurbs.js +265 -0
  98. package/dist/obj.d.ts +145 -0
  99. package/dist/obj.js +462 -0
  100. package/dist/off.d.ts +10 -0
  101. package/dist/off.js +155 -0
  102. package/dist/outline-font.d.ts +87 -0
  103. package/dist/outline-font.js +110 -0
  104. package/dist/outline.d.ts +20 -0
  105. package/dist/outline.js +215 -0
  106. package/dist/pcd.d.ts +34 -0
  107. package/dist/pcd.js +258 -0
  108. package/dist/pdb.d.ts +67 -0
  109. package/dist/pdb.js +126 -0
  110. package/dist/ply.d.ts +35 -0
  111. package/dist/ply.js +392 -0
  112. package/dist/polygon.d.ts +9 -0
  113. package/dist/polygon.js +49 -0
  114. package/dist/prwm.d.ts +24 -0
  115. package/dist/prwm.js +114 -0
  116. package/dist/render.d.ts +32 -0
  117. package/dist/render.js +181 -0
  118. package/dist/sfnt-cff.d.ts +37 -0
  119. package/dist/sfnt-cff.js +749 -0
  120. package/dist/sfnt-layout.d.ts +24 -0
  121. package/dist/sfnt-layout.js +266 -0
  122. package/dist/sfnt-reader.d.ts +28 -0
  123. package/dist/sfnt-reader.js +87 -0
  124. package/dist/sfnt-variation.d.ts +40 -0
  125. package/dist/sfnt-variation.js +318 -0
  126. package/dist/shared/asset-url.js +82 -0
  127. package/dist/shared/crc32.d.ts +2 -0
  128. package/dist/shared/crc32.js +47 -0
  129. package/dist/shared/errors.js +36 -0
  130. package/dist/shared/inflate.js +284 -0
  131. package/dist/shared/normals.js +26 -0
  132. package/dist/shared/scene-scope.js +56 -0
  133. package/dist/shared/trailing-data.js +45 -0
  134. package/dist/stl.d.ts +64 -0
  135. package/dist/stl.js +309 -0
  136. package/dist/svg.d.ts +90 -0
  137. package/dist/svg.js +1007 -0
  138. package/dist/tds.d.ts +2 -0
  139. package/dist/tds.js +2 -0
  140. package/dist/textures.d.ts +42 -0
  141. package/dist/textures.js +53 -0
  142. package/dist/threemf-beam-reader.d.ts +19 -0
  143. package/dist/threemf-beam-reader.js +165 -0
  144. package/dist/threemf-beams.d.ts +52 -0
  145. package/dist/threemf-beams.js +268 -0
  146. package/dist/threemf-boolean-read.d.ts +10 -0
  147. package/dist/threemf-boolean-read.js +113 -0
  148. package/dist/threemf-boolean.d.ts +59 -0
  149. package/dist/threemf-boolean.js +20 -0
  150. package/dist/threemf-csg.d.ts +14 -0
  151. package/dist/threemf-csg.js +193 -0
  152. package/dist/threemf-displacement-read.d.ts +8 -0
  153. package/dist/threemf-displacement-read.js +213 -0
  154. package/dist/threemf-displacement.d.ts +71 -0
  155. package/dist/threemf-displacement.js +18 -0
  156. package/dist/threemf-evaluate.d.ts +36 -0
  157. package/dist/threemf-evaluate.js +86 -0
  158. package/dist/threemf-functions.d.ts +33 -0
  159. package/dist/threemf-functions.js +359 -0
  160. package/dist/threemf-lattice-mesh.d.ts +9 -0
  161. package/dist/threemf-lattice-mesh.js +115 -0
  162. package/dist/threemf-lattice.d.ts +139 -0
  163. package/dist/threemf-lattice.js +379 -0
  164. package/dist/threemf-levelset.d.ts +23 -0
  165. package/dist/threemf-levelset.js +105 -0
  166. package/dist/threemf-materials.d.ts +162 -0
  167. package/dist/threemf-materials.js +497 -0
  168. package/dist/threemf-mesh.d.ts +75 -0
  169. package/dist/threemf-mesh.js +422 -0
  170. package/dist/threemf-secure.d.ts +50 -0
  171. package/dist/threemf-secure.js +153 -0
  172. package/dist/threemf-tessellate.d.ts +37 -0
  173. package/dist/threemf-tessellate.js +277 -0
  174. package/dist/threemf-volume-colour.d.ts +25 -0
  175. package/dist/threemf-volume-colour.js +233 -0
  176. package/dist/threemf-volume-sample.d.ts +8 -0
  177. package/dist/threemf-volume-sample.js +65 -0
  178. package/dist/threemf-volumetric-read.d.ts +15 -0
  179. package/dist/threemf-volumetric-read.js +539 -0
  180. package/dist/threemf-volumetric.d.ts +177 -0
  181. package/dist/threemf-volumetric.js +28 -0
  182. package/dist/threemf.d.ts +170 -0
  183. package/dist/threemf.js +609 -0
  184. package/dist/tilt.d.ts +62 -0
  185. package/dist/tilt.js +186 -0
  186. package/dist/tmx.d.ts +151 -0
  187. package/dist/tmx.js +394 -0
  188. package/dist/ttf.d.ts +78 -0
  189. package/dist/ttf.js +568 -0
  190. package/dist/types.d.ts +108 -0
  191. package/dist/types.js +35 -0
  192. package/dist/usd.d.ts +2 -0
  193. package/dist/usd.js +2 -0
  194. package/dist/usd.worker.d.ts +1 -0
  195. package/dist/usdz.d.ts +50 -0
  196. package/dist/usdz.js +646 -0
  197. package/dist/util.d.ts +75 -0
  198. package/dist/util.js +241 -0
  199. package/dist/vdb.d.ts +111 -0
  200. package/dist/vdb.js +663 -0
  201. package/dist/vrml.d.ts +53 -0
  202. package/dist/vrml.js +532 -0
  203. package/dist/vtk-cells.d.ts +29 -0
  204. package/dist/vtk-cells.js +211 -0
  205. package/dist/vtk-legacy.d.ts +57 -0
  206. package/dist/vtk-legacy.js +439 -0
  207. package/dist/vtk-reader.d.ts +19 -0
  208. package/dist/vtk-reader.js +134 -0
  209. package/dist/vtk-xml.d.ts +96 -0
  210. package/dist/vtk-xml.js +578 -0
  211. package/dist/vtk.d.ts +13 -0
  212. package/dist/vtk.js +234 -0
  213. package/dist/woff-glyf.d.ts +17 -0
  214. package/dist/woff-glyf.js +215 -0
  215. package/dist/worker.d.ts +10 -0
  216. package/dist/worker.js +93 -0
  217. package/dist/workers/usd.js +3 -0
  218. package/dist/xfile.d.ts +99 -0
  219. package/dist/xfile.js +706 -0
  220. package/dist/xml.d.ts +107 -0
  221. package/dist/xml.js +843 -0
  222. package/dist/xyz.d.ts +16 -0
  223. package/dist/xyz.js +110 -0
  224. package/dist/zip.d.ts +38 -0
  225. package/dist/zip.js +150 -0
  226. package/package.json +289 -4
package/dist/stl.js ADDED
@@ -0,0 +1,309 @@
1
+ import { LoaderError } from './types.js';
2
+ import { computeVertexNormals } from './normals.js';
3
+ import { latin1, limits, TextScanner, throwIfAborted, toBytes } from './util.js';
4
+ const F = 'STL';
5
+ /** How many triangles are read between two checks of the abort signal (a power of two). */
6
+ const ABORT_STEP = 16384;
7
+ /** Reads `key` and the RGBA bytes after it from the 80-byte header, or undefined when absent or cut off. */
8
+ function headerColors(bytes, key, count, from = 0) {
9
+ const header = latin1(bytes, 0, 80), at = header.indexOf(key, from);
10
+ if (at < 0 || at + key.length + 4 * count > 80)
11
+ return undefined;
12
+ const out = [];
13
+ for (let c = 0, i = at + key.length; c < count; c++, i += 4)
14
+ out.push([bytes[i] / 255, bytes[i + 1] / 255, bytes[i + 2] / 255, bytes[i + 3] / 255]);
15
+ return out;
16
+ }
17
+ /** Writes the flat normal of the triangle at `positions[at..at+8]` onto its three corners, (0, 0, 1) if degenerate. */
18
+ function flatNormal(positions, normals, at) {
19
+ const ux = positions[at + 3] - positions[at], uy = positions[at + 4] - positions[at + 1], uz = positions[at + 5] - positions[at + 2];
20
+ const vx = positions[at + 6] - positions[at], vy = positions[at + 7] - positions[at + 1], vz = positions[at + 8] - positions[at + 2];
21
+ let nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
22
+ const length = Math.sqrt(nx * nx + ny * ny + nz * nz);
23
+ if (length > 0 && length < Infinity) {
24
+ const scale = 1 / length;
25
+ nx *= scale;
26
+ ny *= scale;
27
+ nz *= scale;
28
+ }
29
+ else {
30
+ nx = 0;
31
+ ny = 0;
32
+ nz = 1;
33
+ }
34
+ normals[at] = normals[at + 3] = normals[at + 6] = nx;
35
+ normals[at + 1] = normals[at + 4] = normals[at + 7] = ny;
36
+ normals[at + 2] = normals[at + 5] = normals[at + 8] = nz;
37
+ }
38
+ /** True when a facet normal read from the file is usable: finite and not (0, 0, 0). */
39
+ const usable = (x, y, z) => Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z) && (x !== 0 || y !== 0 || z !== 0);
40
+ /** Stores the stored facet normal on the triangle's corners, or computes the flat one when it is unusable. */
41
+ function setNormal(positions, normals, at, nx, ny, nz) {
42
+ if (!usable(nx, ny, nz))
43
+ return flatNormal(positions, normals, at);
44
+ for (let c = 0; c < 9; c += 3) {
45
+ normals[at + c] = nx;
46
+ normals[at + c + 1] = ny;
47
+ normals[at + c + 2] = nz;
48
+ }
49
+ }
50
+ function parseBinary(bytes, count, options) {
51
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
52
+ const positions = new Float32Array(count * 9), normals = new Float32Array(count * 9);
53
+ const variant = options.colorVariant ?? 'auto';
54
+ // Materialise Magics: "COLOR=" and four RGBA bytes, then ",MATERIAL=" and diffuse, specular and ambient RGBA.
55
+ const color = headerColors(bytes, 'COLOR=', 1)?.[0];
56
+ const materialise = variant === 'materialise' || (variant === 'auto' && color !== undefined);
57
+ let header;
58
+ if (materialise) {
59
+ header = {};
60
+ if (color)
61
+ header.color = color;
62
+ const material = headerColors(bytes, 'MATERIAL=', 3);
63
+ if (material)
64
+ [header.diffuse, header.specular, header.ambient] = material;
65
+ }
66
+ const part = header?.diffuse ?? header?.color;
67
+ let colors = part && fillColors(count, part);
68
+ for (let t = 0, offset = 84; t < count; t++, offset += 50) {
69
+ if ((t & (ABORT_STEP - 1)) === 0)
70
+ throwIfAborted(options.signal, F);
71
+ const at = t * 9;
72
+ const ax = view.getFloat32(offset + 12, true), ay = view.getFloat32(offset + 16, true), az = view.getFloat32(offset + 20, true), bx = view.getFloat32(offset + 24, true), by = view.getFloat32(offset + 28, true), bz = view.getFloat32(offset + 32, true), cx = view.getFloat32(offset + 36, true), cy = view.getFloat32(offset + 40, true), cz = view.getFloat32(offset + 44, true);
73
+ positions[at] = ax;
74
+ positions[at + 1] = ay;
75
+ positions[at + 2] = az;
76
+ positions[at + 3] = bx;
77
+ positions[at + 4] = by;
78
+ positions[at + 5] = bz;
79
+ positions[at + 6] = cx;
80
+ positions[at + 7] = cy;
81
+ positions[at + 8] = cz;
82
+ let nx = view.getFloat32(offset, true), ny = view.getFloat32(offset + 4, true), nz = view.getFloat32(offset + 8, true);
83
+ if (!usable(nx, ny, nz)) {
84
+ // The same sums as flatNormal, on the corners already in hand.
85
+ const ux = bx - ax, uy = by - ay, uz = bz - az, vx = cx - ax, vy = cy - ay, vz = cz - az;
86
+ nx = uy * vz - uz * vy;
87
+ ny = uz * vx - ux * vz;
88
+ nz = ux * vy - uy * vx;
89
+ const length = Math.sqrt(nx * nx + ny * ny + nz * nz);
90
+ if (length > 0 && length < Infinity) {
91
+ const scale = 1 / length;
92
+ nx *= scale;
93
+ ny *= scale;
94
+ nz *= scale;
95
+ }
96
+ else {
97
+ nx = 0;
98
+ ny = 0;
99
+ nz = 1;
100
+ }
101
+ }
102
+ normals[at] = normals[at + 3] = normals[at + 6] = nx;
103
+ normals[at + 1] = normals[at + 4] = normals[at + 7] = ny;
104
+ normals[at + 2] = normals[at + 5] = normals[at + 8] = nz;
105
+ // VisCAM / SolidView: bit 15 set means a facet colour, red bits 10-14, green 5-9, blue 0-4. Materialise Magics:
106
+ // bit 15 clear means a facet colour, red bits 0-4, green 5-9, blue 10-14; set takes the part colour already filled.
107
+ const attribute = view.getUint16(offset + 48, true);
108
+ if (materialise ? (attribute & 0x8000) === 0 : attribute & 0x8000) {
109
+ colors ??= fillColors(count, [0.8, 0.8, 0.8, 1]);
110
+ const low = (attribute & 31) / 31, g = ((attribute >> 5) & 31) / 31, high = ((attribute >> 10) & 31) / 31, r = materialise ? low : high, b = materialise ? high : low;
111
+ for (let c = 0; c < 9; c += 3) {
112
+ colors[at + c] = r;
113
+ colors[at + c + 1] = g;
114
+ colors[at + c + 2] = b;
115
+ }
116
+ }
117
+ }
118
+ const result = finish(positions, normals, colors, options);
119
+ if (header)
120
+ result.materialise = header;
121
+ return result;
122
+ }
123
+ /** A colour per corner for `count` triangles, all `rgb`. */
124
+ function fillColors(count, rgb) {
125
+ const colors = new Float32Array(count * 9);
126
+ for (let i = 0; i < colors.length; i += 3) {
127
+ colors[i] = rgb[0];
128
+ colors[i + 1] = rgb[1];
129
+ colors[i + 2] = rgb[2];
130
+ }
131
+ return colors;
132
+ }
133
+ function parseASCII(bytes, options, limit) {
134
+ const scanner = new TextScanner(latin1(bytes), F);
135
+ let capacity = Math.max(16, Math.min(limit.maxTriangles, Math.ceil(bytes.length / 250)));
136
+ let positions = new Float32Array(capacity * 9), normals = new Float32Array(capacity * 9);
137
+ let facets = 0, corners = 0, inFacet = false, nx = 0, ny = 0, nz = 0;
138
+ const grow = () => {
139
+ capacity *= 2;
140
+ const p = new Float32Array(capacity * 9), n = new Float32Array(capacity * 9);
141
+ p.set(positions);
142
+ n.set(normals);
143
+ positions = p;
144
+ normals = n;
145
+ };
146
+ for (let word = scanner.token(); word !== null; word = scanner.token()) {
147
+ const key = word.toLowerCase();
148
+ if (key === 'facet') {
149
+ if (inFacet)
150
+ throw new LoaderError(F, 'syntax', `facet ${facets + 1} is not closed with "endfacet"`);
151
+ if (facets >= limit.maxTriangles || facets * 3 >= limit.maxVertices)
152
+ throw new LoaderError(F, 'limit', `the file has more than ${limit.maxTriangles} triangles or ${limit.maxVertices} vertices; pass a larger maxTriangles and maxVertices`);
153
+ if (facets === capacity)
154
+ grow();
155
+ if ((facets & (ABORT_STEP - 1)) === 0)
156
+ throwIfAborted(options.signal, F);
157
+ const what = `the normal of facet ${facets + 1}`;
158
+ if (scanner.token()?.toLowerCase() !== 'normal')
159
+ throw new LoaderError(F, 'syntax', `facet ${facets + 1} must read "facet normal nx ny nz"`);
160
+ nx = scanner.number(what);
161
+ ny = scanner.number(what);
162
+ nz = scanner.number(what);
163
+ inFacet = true;
164
+ corners = 0;
165
+ }
166
+ else if (key === 'vertex') {
167
+ if (!inFacet || corners === 3)
168
+ throw new LoaderError(F, 'syntax', `facet ${facets + 1} has a "vertex" where none belongs (a triangle has 3)`);
169
+ const at = facets * 9 + corners * 3, what = `a vertex of facet ${facets + 1}`;
170
+ positions[at] = scanner.number(what);
171
+ positions[at + 1] = scanner.number(what);
172
+ positions[at + 2] = scanner.number(what);
173
+ corners++;
174
+ }
175
+ else if (key === 'endfacet') {
176
+ if (!inFacet || corners !== 3)
177
+ throw new LoaderError(F, 'syntax', `facet ${facets + 1} has ${corners} vertices, expected 3`);
178
+ setNormal(positions, normals, facets * 9, nx, ny, nz);
179
+ facets++;
180
+ inFacet = false;
181
+ }
182
+ else if (key === 'solid' || key === 'endsolid') {
183
+ scanner.line(); // the solid's name is the rest of the line and may hold anything
184
+ }
185
+ }
186
+ if (inFacet)
187
+ throw new LoaderError(F, 'truncated', `the file ends inside facet ${facets + 1}`);
188
+ if (!facets)
189
+ throw new LoaderError(F, 'syntax', 'the ASCII file has no "facet normal" blocks');
190
+ return finish(positions.slice(0, facets * 9), normals.slice(0, facets * 9), undefined, options);
191
+ }
192
+ /** Builds the result: identity indices, or a position (and color) weld with smooth normals. */
193
+ function finish(positions, normals, colors, options) {
194
+ const corners = positions.length / 3;
195
+ if (!options.weld) {
196
+ const indices = new Uint32Array(corners);
197
+ for (let i = 0; i < corners; i++)
198
+ indices[i] = i;
199
+ const result = { kind: 'mesh', positions, normals, indices };
200
+ if (colors)
201
+ result.colors = colors;
202
+ return result;
203
+ }
204
+ for (let i = 0; i < positions.length; i++)
205
+ positions[i] += 0; // -0 becomes +0, so equal positions have equal bits
206
+ const bits = new Uint32Array(positions.buffer, positions.byteOffset, positions.length), colorBits = colors && new Uint32Array(colors.buffer, colors.byteOffset, colors.length);
207
+ let size = 16;
208
+ while (size < corners * 2)
209
+ size *= 2;
210
+ const mask = size - 1, table = new Int32Array(size).fill(-1), indices = new Uint32Array(corners), first = new Uint32Array(corners); // the source corner of each welded vertex
211
+ let count = 0;
212
+ for (let corner = 0; corner < corners; corner++) {
213
+ if ((corner & (ABORT_STEP * 4 - 1)) === 0)
214
+ throwIfAborted(options.signal, F);
215
+ const i = corner * 3;
216
+ let h = Math.imul(bits[i], 0x9e3779b1) ^ Math.imul(bits[i + 1], 0x85ebca6b) ^ Math.imul(bits[i + 2], 0xc2b2ae35);
217
+ if (colorBits)
218
+ h ^= Math.imul(colorBits[i] ^ (colorBits[i + 1] << 7) ^ (colorBits[i + 2] << 13), 0x27d4eb2f);
219
+ h ^= h >>> 15;
220
+ let slot = h & mask, found = -1;
221
+ for (let v = table[slot]; v !== -1; v = table[slot]) {
222
+ const j = first[v] * 3;
223
+ if (bits[j] === bits[i] &&
224
+ bits[j + 1] === bits[i + 1] &&
225
+ bits[j + 2] === bits[i + 2] &&
226
+ (!colorBits ||
227
+ (colorBits[j] === colorBits[i] &&
228
+ colorBits[j + 1] === colorBits[i + 1] &&
229
+ colorBits[j + 2] === colorBits[i + 2]))) {
230
+ found = v;
231
+ break;
232
+ }
233
+ slot = (slot + 1) & mask;
234
+ }
235
+ if (found < 0) {
236
+ found = count;
237
+ first[count++] = corner;
238
+ table[slot] = found;
239
+ }
240
+ indices[corner] = found;
241
+ }
242
+ const welded = new Float32Array(count * 3), weldedColors = colors && new Float32Array(count * 3);
243
+ for (let v = 0; v < count; v++) {
244
+ const i = first[v] * 3;
245
+ for (let a = 0; a < 3; a++) {
246
+ welded[v * 3 + a] = positions[i + a];
247
+ if (weldedColors && colors)
248
+ weldedColors[v * 3 + a] = colors[i + a];
249
+ }
250
+ }
251
+ const result = {
252
+ kind: 'mesh',
253
+ positions: welded,
254
+ normals: computeVertexNormals(welded, indices),
255
+ indices,
256
+ };
257
+ if (weldedColors)
258
+ result.colors = weldedColors;
259
+ return result;
260
+ }
261
+ /**
262
+ * Parses a binary or ASCII STL file into plain typed arrays, the way a basic STL loader does: no GPU objects, no
263
+ * parts, no normal smoothing. The flavor is detected from the data: a file whose length is exactly
264
+ * `84 + 50 * triangles` is binary even when it starts with `solid`; otherwise text starting with `solid` and holding
265
+ * facets is ASCII.
266
+ *
267
+ * - `positions`: three vertices per triangle, in file order (Float32).
268
+ * - `normals`: the facet normal from the file repeated on the triangle's corners; a facet whose stored normal is zero
269
+ * or not finite (many writers leave it zero) gets the flat normal computed from its corners.
270
+ * - `colors`: for binary files using a colour extension, as sRGB 0 to 1. VisCAM / SolidView (bit 15 of the 16-bit
271
+ * attribute set marks a facet colour; facets without one get 0.8 gray) or Materialise Magics, read when the header
272
+ * holds `COLOR=` or `colorVariant` says so (bit 15 clear marks a facet colour; the others take the header's part
273
+ * colour, the `,MATERIAL=` diffuse before `COLOR=`, or 0.8 gray). ASCII files and uncolored binary files have none.
274
+ * - `materialise`: the header's `COLOR=` and `,MATERIAL=` colours (RGBA 0 to 1) of a Materialise file.
275
+ * - `indices`: 0, 1, 2, ... (or the weld's indices with `weld: true`).
276
+ *
277
+ * @throws LoaderError with code `'header'` (too short to be STL), `'truncated'` (binary data shorter than its
278
+ * triangle count, or an ASCII file cut inside a facet), `'syntax'` (a malformed ASCII facet or number), `'limit'`
279
+ * (past `maxTriangles` or `maxVertices`; raise them) or `'aborted'` (the `signal` fired); `'range'` for a bad limit or
280
+ * `colorVariant`.
281
+ * @example
282
+ * const mesh = parseSTL(await (await fetch('/part.stl')).arrayBuffer());
283
+ * mesh.positions.length / 9; // triangles
284
+ */
285
+ export function parseSTL(input, options = {}) {
286
+ const bytes = toBytes(input, F), limit = limits(options, F), variant = options.colorVariant;
287
+ if (variant !== undefined && variant !== 'auto' && variant !== 'viscam' && variant !== 'materialise')
288
+ throw new LoaderError(F, 'range', `colorVariant must be 'auto', 'viscam' or 'materialise', not ${String(variant).slice(0, 40)}`);
289
+ throwIfAborted(options.signal, F);
290
+ if (bytes.length < 15)
291
+ throw new LoaderError(F, 'header', `${bytes.length} bytes is too short for an STL file; pass the whole file (a binary header alone is 84 bytes)`);
292
+ const declared = bytes.length >= 84 ? new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(80, true) : -1;
293
+ const exactBinary = declared >= 0 && bytes.length === 84 + 50 * declared;
294
+ if (!exactBinary) {
295
+ const head = latin1(bytes, 0, Math.min(bytes.length, 1024));
296
+ if (/^\s*solid/i.test(head) && /facet|endsolid/i.test(head))
297
+ return parseASCII(bytes, options, limit);
298
+ if (declared < 0)
299
+ throw new LoaderError(F, 'header', 'the data is neither ASCII STL (it must start with "solid" and hold "facet" blocks) nor a binary file with its 84-byte header');
300
+ if (bytes.length < 84 + 50 * declared)
301
+ throw new LoaderError(F, 'truncated', `the header declares ${declared} triangles (${84 + 50 * declared} bytes) but the data has ${bytes.length}; pass the whole file`);
302
+ }
303
+ // Longer than declared: the extra bytes are ignored.
304
+ if (declared > limit.maxTriangles)
305
+ throw new LoaderError(F, 'limit', `triangle count ${declared} exceeds the limit of ${limit.maxTriangles}; pass a larger maxTriangles`);
306
+ if (declared * 3 > limit.maxVertices)
307
+ throw new LoaderError(F, 'limit', `vertex count ${declared * 3} exceeds the limit of ${limit.maxVertices}; pass a larger maxVertices (it applies before welding)`);
308
+ return parseBinary(bytes, declared, options);
309
+ }
package/dist/svg.d.ts ADDED
@@ -0,0 +1,90 @@
1
+ import type { Shape } from '@margoengine/geometry/shapes';
2
+ import { type GeometryData } from '@margoengine/geometry/utils';
3
+ import { type OutlineCommand, type OutlineFillRule } from './outline.js';
4
+ import { type BinaryInput } from './util.js';
5
+ import { type XMLExternalOptions } from './xml.js';
6
+ export type { OutlineCommand, OutlineFillRule } from './outline.js';
7
+ /** Options of {@link SVGPath.toShapes}. */
8
+ export interface SVGShapeOptions {
9
+ /** Negate y so the drawing is upright in a y-up world (SVG's y axis points down). Default false. */
10
+ flipY?: boolean;
11
+ }
12
+ /** Options of {@link SVGPath.toStrokeGeometry}. */
13
+ export interface SVGStrokeOptions extends SVGShapeOptions {
14
+ /** Stroke width in the element's own (pre-transform) units. Default: the path's `strokeWidth`. */
15
+ width?: number;
16
+ /** Straight pieces per curve segment, and per quarter turn of a round join or cap. Default 12. */
17
+ divisions?: number;
18
+ }
19
+ /** One drawn element (path, rect, circle, ellipse, line, polyline or polygon) with its computed style. */
20
+ export interface SVGPath {
21
+ /** Element name, for example `'rect'`. */
22
+ element: string;
23
+ /** The element's own `id`, when it has one. Copies drawn through `<use>` keep the referenced element's id. */
24
+ id?: string;
25
+ /** Outline in root user units (every transform and nested viewport applied), y down. */
26
+ commands: OutlineCommand[];
27
+ /** Fill colour, sRGB 0..1, or null for none or an unusable paint. */
28
+ fill: [number, number, number] | null;
29
+ /** Group opacity x `fill-opacity` x the paint's alpha, 0..1. */
30
+ fillOpacity: number;
31
+ /** `'evenodd'` or `'nonzero'` (the default). */
32
+ fillRule: OutlineFillRule;
33
+ /** Stroke colour, sRGB 0..1, or null for no stroke (the default). */
34
+ stroke: [number, number, number] | null;
35
+ /** Group opacity x `stroke-opacity` x the paint's alpha, 0..1. */
36
+ strokeOpacity: number;
37
+ /** Stroke width in the element's own units. Default 1, never negative. */
38
+ strokeWidth: number;
39
+ /** `stroke-linejoin`; values other than round and bevel are drawn as miter. */
40
+ strokeLineJoin: 'miter' | 'round' | 'bevel';
41
+ /** `stroke-linecap`. */
42
+ strokeLineCap: 'butt' | 'round' | 'square';
43
+ /** `stroke-miterlimit`, 1 or more. Default 4. */
44
+ strokeMiterLimit: number;
45
+ /** Filled shapes, with holes decided by containment and the fill rule. Open subpaths fill as if closed. */
46
+ toShapes(options?: SVGShapeOptions): Shape[];
47
+ /**
48
+ * The stroke as flat triangles on z = 0, wound counter-clockwise, with normals +z and UVs equal to x and y. The
49
+ * outline is built in the element's own units with its joins, caps and miter limit and then transformed, so
50
+ * non-uniform scales and skews shape it as SVG does. Joins are trimmed on their inner side where the neighbouring
51
+ * segments are long enough, so most pieces do not overlap; where they cannot be trimmed they overlap, which is fine
52
+ * when opaque. Dashes are not applied. A width of 0 gives an empty geometry.
53
+ *
54
+ * @throws RangeError when the width is not a finite number of 0 or more, or `divisions` is not an integer of 1 or
55
+ * more.
56
+ */
57
+ toStrokeGeometry(options?: SVGStrokeOptions): GeometryData;
58
+ }
59
+ /** Result of {@link parseSVG}. */
60
+ export interface LoadedSVG {
61
+ /** Drawn elements in document order. */
62
+ paths: SVGPath[];
63
+ /** The root `viewBox`, when it holds exactly four numbers. */
64
+ viewBox?: [number, number, number, number];
65
+ /** Root width in px, when the attribute is present. */
66
+ width?: number;
67
+ /** Root height in px, when the attribute is present. */
68
+ height?: number;
69
+ /** Everything that was skipped or approximated, one line each, without repeats. */
70
+ warnings: string[];
71
+ }
72
+ /**
73
+ * Reads an SVG document into drawn paths with their computed styles.
74
+ *
75
+ * Supported: `path`, `rect`, `circle`, `ellipse`, `line`, `polyline` and `polygon`, inside `g`, `a`, `switch` (only
76
+ * its first child whose conditions hold) and nested `svg` viewports, plus `use` of elements and `symbol`s.
77
+ * Transforms, presentation attributes, `<style>` rules with type, class and id selectors, and the `style` attribute
78
+ * are applied. {@link SVGPath.toShapes} gives filled shapes with holes from the fill rule, and
79
+ * {@link SVGPath.toStrokeGeometry} gives the stroke as triangles. Coordinates are root user units (the root viewBox
80
+ * is not applied), y down.
81
+ *
82
+ * Not drawn: text, images, clipping, masks, markers, filters and dashes; each is noted in `warnings`. Gradients are
83
+ * drawn as their average stop colour. Bad path data keeps everything before the error. Everything lenient adds a
84
+ * warning instead of throwing.
85
+ *
86
+ * @param input - SVG text, or its bytes (UTF-8, or UTF-16 with a byte order mark).
87
+ * @throws LoaderError `'syntax'` for malformed XML, `'header'` when there is no `<svg>` root, and `'limit'` when one
88
+ * path or the whole document has more than 4,000,000 commands.
89
+ */
90
+ export declare function parseSVG(input: string | BinaryInput, options?: XMLExternalOptions): LoadedSVG;