@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/tds.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { parse3DS as parseTDS } from './3ds.js';
2
+ export type { ThreeDSCamera, ThreeDSGroup, ThreeDSKey, ThreeDSKeyframes, ThreeDSLight, ThreeDSMaterial, ThreeDSNode, ThreeDSOptions, ThreeDSResult, ThreeDSTrack, } from './3ds.js';
package/dist/tds.js ADDED
@@ -0,0 +1,2 @@
1
+ // A .tds file is the same 3D Studio format under another extension, so this entry is the 3DS reader's other name.
2
+ export { parse3DS as parseTDS } from './3ds.js';
@@ -0,0 +1,42 @@
1
+ import type { AssetResolver } from './types.js';
2
+ /** Options of {@link loadTextures}. */
3
+ export interface LoadTexturesOptions {
4
+ /** Stops the reads; the promise then rejects with a `LoaderError` code `aborted`. */
5
+ signal?: AbortSignal;
6
+ }
7
+ /** What {@link loadTextures} returns. */
8
+ export interface LoadedTextures {
9
+ /** Each file's bytes, by the path as the model wrote it. */
10
+ textures: Map<string, Uint8Array>;
11
+ /** The paths no spelling of which could be read, with the resolver's last error. */
12
+ missing: {
13
+ path: string;
14
+ error: unknown;
15
+ }[];
16
+ }
17
+ /**
18
+ * Reads the texture files a model names (`materials[i].texture` of `parse3DS`, `images` of `parseLWO`, `skins` of
19
+ * `parseMD2`) through `resolve`, asking for each path as written, then with forward slashes, in lower case, and by its
20
+ * base name. A file that cannot be read is listed in `missing`, so one lost skin does not lose the model.
21
+ *
22
+ * Decode the bytes with what fits: `createImageBitmap` for PNG, JPEG and BMP, `parseTGA` from
23
+ * `@margoengine/decoders/tga`, and `parsePCX` from `@margoengine/decoders/pcx` for Quake skins.
24
+ *
25
+ * @param paths The paths, each read once.
26
+ * @param resolve Reads one path; `resolveFromURL` from `@margoengine/loaders/ldraw` makes one for a hosted folder.
27
+ * @param options An AbortSignal.
28
+ * @returns The bytes by path, and what is missing.
29
+ * @throws LoaderError with code `aborted`.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * import { resolveFromURL } from '@margoengine/loaders/ldraw';
34
+ * import { parseMD2 } from '@margoengine/loaders/md2';
35
+ * import { loadTextures } from '@margoengine/loaders/textures';
36
+ *
37
+ * const model = parseMD2(await (await fetch('/models/tank.md2')).arrayBuffer());
38
+ * const { textures, missing } = await loadTextures(model.skins, resolveFromURL('/models/'));
39
+ * console.log(textures.size, missing);
40
+ * ```
41
+ */
42
+ export declare function loadTextures(paths: Iterable<string>, resolve: AssetResolver, { signal }?: LoadTexturesOptions): Promise<LoadedTextures>;
@@ -0,0 +1,53 @@
1
+ import { throwIfAborted } from './util.js';
2
+ /** Old tools wrote upper-case 8.3 names, folders of their own PC and `Images:wall.jpg` volumes: the spellings to ask for, in order. */
3
+ function spellings(path) {
4
+ const clean = path.replaceAll('\\', '/'), base = clean.slice(Math.max(clean.lastIndexOf('/'), clean.lastIndexOf(':')) + 1);
5
+ return [...new Set([path, clean, clean.toLowerCase(), base, base.toLowerCase()])];
6
+ }
7
+ /**
8
+ * Reads the texture files a model names (`materials[i].texture` of `parse3DS`, `images` of `parseLWO`, `skins` of
9
+ * `parseMD2`) through `resolve`, asking for each path as written, then with forward slashes, in lower case, and by its
10
+ * base name. A file that cannot be read is listed in `missing`, so one lost skin does not lose the model.
11
+ *
12
+ * Decode the bytes with what fits: `createImageBitmap` for PNG, JPEG and BMP, `parseTGA` from
13
+ * `@margoengine/decoders/tga`, and `parsePCX` from `@margoengine/decoders/pcx` for Quake skins.
14
+ *
15
+ * @param paths The paths, each read once.
16
+ * @param resolve Reads one path; `resolveFromURL` from `@margoengine/loaders/ldraw` makes one for a hosted folder.
17
+ * @param options An AbortSignal.
18
+ * @returns The bytes by path, and what is missing.
19
+ * @throws LoaderError with code `aborted`.
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * import { resolveFromURL } from '@margoengine/loaders/ldraw';
24
+ * import { parseMD2 } from '@margoengine/loaders/md2';
25
+ * import { loadTextures } from '@margoengine/loaders/textures';
26
+ *
27
+ * const model = parseMD2(await (await fetch('/models/tank.md2')).arrayBuffer());
28
+ * const { textures, missing } = await loadTextures(model.skins, resolveFromURL('/models/'));
29
+ * console.log(textures.size, missing);
30
+ * ```
31
+ */
32
+ export async function loadTextures(paths, resolve, { signal } = {}) {
33
+ const textures = new Map(), missing = [];
34
+ for (const path of new Set(paths)) {
35
+ let error;
36
+ for (const name of spellings(path)) {
37
+ throwIfAborted(signal, 'textures');
38
+ try {
39
+ const read = await resolve(name);
40
+ textures.set(path, typeof read === 'string' ? new TextEncoder().encode(read) : read);
41
+ break;
42
+ }
43
+ catch (failure) {
44
+ // The next spelling may be the one the folder holds; the last failure is reported in `missing`.
45
+ error = failure;
46
+ }
47
+ }
48
+ throwIfAborted(signal, 'textures');
49
+ if (!textures.has(path))
50
+ missing.push({ path, error });
51
+ }
52
+ return { textures, missing };
53
+ }
@@ -0,0 +1,19 @@
1
+ import type { ThreeMFBeamLattice } from './threemf-lattice.js';
2
+ export declare const attribute: (a: Record<string, string>, name: string) => string | undefined;
3
+ export declare function number(value: string | undefined, name: string, fallback?: number): number;
4
+ export declare function index(value: string | undefined, name: string): number;
5
+ export declare function choice<T extends string>(value: string | undefined, values: readonly T[], fallback: T): T;
6
+ /** The lattices of one package, element by element, under one count of beams, balls and set references. */
7
+ export declare function beamReader(maxBeams: number): {
8
+ /** A `<beamlattice>` of the mesh object `owner` is reading; `pid` and `property` are the object's own. */
9
+ begin(owner: object, a: Record<string, string>, pid?: string, property?: number): ThreeMFBeamLattice;
10
+ /** One element inside a lattice; other names are left alone. */
11
+ element(owner: object, name: string, a: Record<string, string>): void;
12
+ close(owner: object, name: string): void;
13
+ };
14
+ /**
15
+ * Checks a finished lattice against its mesh's vertices and fills `activeBeams` and `effectiveBalls`: beams shorter
16
+ * than `minlength` are ignored, and the ball mode decides which beam ends get a ball. `property` checks a property
17
+ * reference.
18
+ */
19
+ export declare function finishLattice(l: ThreeMFBeamLattice, vertices: ArrayLike<number>, property: (pid: string | undefined, p: number | undefined) => void): void;
@@ -0,0 +1,165 @@
1
+ // Reads the elements of a 3MF beam lattice (https://github.com/3MFConsortium/spec_beamlattice, chapter 2), for the
2
+ // lattice entry and for the readers that evaluate one.
3
+ import { LoaderError } from './types.js';
4
+ const F = '3MF';
5
+ export const attribute = (a, name) => a[name] ?? Object.entries(a).find(([key]) => key.endsWith(':' + name))?.[1];
6
+ export function number(value, name, fallback) {
7
+ const n = value === undefined ? fallback : Number(value);
8
+ if (n === undefined || !Number.isFinite(n))
9
+ throw new LoaderError(F, 'syntax', `${name} must be a finite number`);
10
+ return n;
11
+ }
12
+ export function index(value, name) {
13
+ const n = number(value, name);
14
+ if (!Number.isSafeInteger(n) || n < 0 || n >= 2147483648)
15
+ throw new LoaderError(F, 'range', `${name} must be a nonnegative 31-bit index`);
16
+ return n;
17
+ }
18
+ function positive(value, name, fallback) {
19
+ const n = number(value, name, fallback);
20
+ if (n <= 0)
21
+ throw new LoaderError(F, 'range', `${name} must be positive`);
22
+ return n;
23
+ }
24
+ export function choice(value, values, fallback) {
25
+ if (value === undefined)
26
+ return fallback;
27
+ if (!values.includes(value))
28
+ throw new LoaderError(F, 'range', `expected ${values.join(', ')}; got ${value}`);
29
+ return value;
30
+ }
31
+ const cap = (value) => choice(value, ['sphere', 'hemisphere', 'butt'], 'sphere');
32
+ /** The lattices of one package, element by element, under one count of beams, balls and set references. */
33
+ export function beamReader(maxBeams) {
34
+ let beams = 0, balls = 0, references = 0;
35
+ const open = new WeakMap();
36
+ return {
37
+ /** A `<beamlattice>` of the mesh object `owner` is reading; `pid` and `property` are the object's own. */
38
+ begin(owner, a, pid, property) {
39
+ const lattice = {
40
+ radius: positive(a.radius, 'radius'),
41
+ minLength: positive(a.minlength, 'minlength'),
42
+ cap: cap(a.cap),
43
+ ballMode: choice(attribute(a, 'ballmode'), ['none', 'mixed', 'all'], 'none'),
44
+ clippingMode: choice(a.clippingmode, ['none', 'inside', 'outside'], 'none'),
45
+ clippingMesh: a.clippingmesh,
46
+ representationMesh: a.representationmesh,
47
+ pid: a.pid ?? pid,
48
+ property: a.pindex === undefined ? property : index(a.pindex, 'pindex'),
49
+ beams: [],
50
+ balls: [],
51
+ sets: [],
52
+ activeBeams: new Uint32Array(),
53
+ effectiveBalls: [],
54
+ };
55
+ const radius = attribute(a, 'ballradius');
56
+ if (radius !== undefined)
57
+ lattice.ballRadius = positive(radius, 'ballradius');
58
+ if (lattice.ballMode !== 'none' && lattice.ballRadius === undefined)
59
+ throw new LoaderError(F, 'syntax', 'ballmode needs ballradius');
60
+ open.set(owner, { lattice });
61
+ return lattice;
62
+ },
63
+ /** One element inside a lattice; other names are left alone. */
64
+ element(owner, name, a) {
65
+ const state = open.get(owner), l = state?.lattice;
66
+ if (name === 'beam') {
67
+ if (!l)
68
+ throw new LoaderError(F, 'syntax', 'beam outside beamlattice');
69
+ if (++beams > maxBeams)
70
+ throw new LoaderError(F, 'limit', 'beam count exceeds maxBeams');
71
+ if (a.r2 !== undefined && a.r1 === undefined)
72
+ throw new LoaderError(F, 'syntax', 'r2 requires r1');
73
+ const r1 = positive(a.r1, 'r1', l.radius);
74
+ l.beams.push({
75
+ v1: index(a.v1, 'v1'),
76
+ v2: index(a.v2, 'v2'),
77
+ r1,
78
+ r2: positive(a.r2, 'r2', r1),
79
+ cap1: a.cap1 === undefined ? l.cap : cap(a.cap1),
80
+ cap2: a.cap2 === undefined ? l.cap : cap(a.cap2),
81
+ pid: a.pid ?? l.pid,
82
+ p1: a.p1 === undefined ? l.property : index(a.p1, 'p1'),
83
+ p2: a.p2 === undefined ? l.property : index(a.p2, 'p2'),
84
+ });
85
+ }
86
+ else if (name === 'ball') {
87
+ if (!l)
88
+ throw new LoaderError(F, 'syntax', 'ball outside beamlattice');
89
+ if (++balls > maxBeams)
90
+ throw new LoaderError(F, 'limit', 'ball count exceeds maxBeams');
91
+ l.balls.push({
92
+ vertex: index(a.vindex, 'vindex'),
93
+ radius: positive(a.r, 'ball radius', l.ballRadius),
94
+ pid: a.pid ?? l.pid,
95
+ property: a.p === undefined ? l.property : index(a.p, 'ball property'),
96
+ });
97
+ }
98
+ else if (name === 'beamset') {
99
+ if (!state || state.set)
100
+ throw new LoaderError(F, 'syntax', 'invalid beamset nesting');
101
+ state.set = { name: a.name, identifier: a.identifier, beams: [], balls: [] };
102
+ }
103
+ else if ((name === 'ref' || name === 'ballref') && state?.set) {
104
+ if (++references > maxBeams * 2)
105
+ throw new LoaderError(F, 'limit', 'beamset references exceed the native primitive budget');
106
+ state.set[name === 'ref' ? 'beams' : 'balls'].push(index(a.index, name === 'ref' ? 'beam ref' : 'ball ref'));
107
+ }
108
+ },
109
+ close(owner, name) {
110
+ const state = open.get(owner);
111
+ if (!state)
112
+ return;
113
+ if (name === 'beamlattice')
114
+ open.delete(owner);
115
+ else if (name === 'beamset' && state.set) {
116
+ state.lattice.sets.push({
117
+ ...state.set,
118
+ beams: Uint32Array.from(state.set.beams),
119
+ balls: Uint32Array.from(state.set.balls),
120
+ });
121
+ state.set = undefined;
122
+ }
123
+ },
124
+ };
125
+ }
126
+ /**
127
+ * Checks a finished lattice against its mesh's vertices and fills `activeBeams` and `effectiveBalls`: beams shorter
128
+ * than `minlength` are ignored, and the ball mode decides which beam ends get a ball. `property` checks a property
129
+ * reference.
130
+ */
131
+ export function finishLattice(l, vertices, property) {
132
+ if (!l.beams.length)
133
+ throw new LoaderError(F, 'syntax', 'beamlattice requires at least one beam');
134
+ const pointCount = vertices.length / 3, active = [], ends = new Set();
135
+ l.beams.forEach((beam, i) => {
136
+ if (beam.v1 === beam.v2 || beam.v1 >= pointCount || beam.v2 >= pointCount)
137
+ throw new LoaderError(F, 'range', 'invalid beam endpoints');
138
+ property(beam.pid, beam.p1);
139
+ property(beam.pid, beam.p2);
140
+ const a = beam.v1 * 3, b = beam.v2 * 3;
141
+ if (Math.hypot(vertices[a] - vertices[b], vertices[a + 1] - vertices[b + 1], vertices[a + 2] - vertices[b + 2]) >=
142
+ l.minLength) {
143
+ active.push(i);
144
+ ends.add(beam.v1);
145
+ ends.add(beam.v2);
146
+ }
147
+ });
148
+ l.activeBeams = Uint32Array.from(active);
149
+ const explicit = new Map();
150
+ for (const ball of l.balls) {
151
+ if (ball.vertex >= pointCount || explicit.has(ball.vertex))
152
+ throw new LoaderError(F, 'range', 'invalid or repeated ball vertex');
153
+ property(ball.pid, ball.property);
154
+ explicit.set(ball.vertex, ball);
155
+ }
156
+ l.effectiveBalls = [];
157
+ if (l.ballMode !== 'none')
158
+ for (const vertex of ends) {
159
+ const ball = explicit.get(vertex);
160
+ if (ball)
161
+ l.effectiveBalls.push({ ...ball });
162
+ else if (l.ballMode === 'all')
163
+ l.effectiveBalls.push({ vertex, radius: l.ballRadius, pid: l.pid, property: l.property });
164
+ }
165
+ }
@@ -0,0 +1,52 @@
1
+ import type { ThreeMFBall, ThreeMFBeam } from './threemf-lattice.js';
2
+ /** The parts of a `ThreeMFBeamLattice` that make its surface, as `parse3MFLattice` gives them. */
3
+ export interface ThreeMFBeamGeometry {
4
+ beams: readonly ThreeMFBeam[];
5
+ /** Indices of the beams to make: those no shorter than `minlength`. Every beam when absent. */
6
+ activeBeams?: ArrayLike<number>;
7
+ /** The balls to make, after the ball mode. */
8
+ effectiveBalls?: readonly ThreeMFBall[];
9
+ }
10
+ /** Options of {@link mesh3MFBeamLattice}. */
11
+ export interface ThreeMFBeamMeshOptions {
12
+ /** Triangles' sides around an axis and around a full circle of a cap: 3 to 256, default 16. */
13
+ segments?: number;
14
+ /** The most triangles to make. Default 4,000,000. */
15
+ maxTriangles?: number;
16
+ }
17
+ /** The triangles one beam or ball made. */
18
+ export interface ThreeMFBeamPart {
19
+ kind: 'beam' | 'ball';
20
+ /** The index in `beams`, or in `effectiveBalls`. */
21
+ index: number;
22
+ triangleStart: number;
23
+ triangleCount: number;
24
+ }
25
+ /** A lattice's surface: one closed, outward shell for each beam and ball, which may overlap. */
26
+ export interface ThreeMFBeamMesh {
27
+ /** In the vertices' own coordinates. */
28
+ positions: Float32Array;
29
+ indices: Uint32Array;
30
+ /** For each vertex, where its nearest point of the axis lies from the beam's `v1` (0) to its `v2` (1). */
31
+ along: Float32Array;
32
+ parts: ThreeMFBeamPart[];
33
+ }
34
+ /**
35
+ * The surface of a lattice in the vertices' coordinates: one closed, outward triangle shell for each active beam, in
36
+ * their order, then one for each effective ball. The shells overlap where the lattice joins, which the 3MF positive
37
+ * fill rule reads as their union; `batchBooleanMeshes` of `@margoengine/mesh-edit` unions them where one surface is
38
+ * needed. A clipping mesh is not applied here (`parse3MFEvaluated` applies it).
39
+ *
40
+ * @throws LoaderError for a vertex index outside the vertices, a beam without length or radius, a bad option, or more
41
+ * triangles than `maxTriangles`.
42
+ */
43
+ export declare function mesh3MFBeamLattice(vertices: ArrayLike<number>, lattice: ThreeMFBeamGeometry, options?: ThreeMFBeamMeshOptions): ThreeMFBeamMesh;
44
+ /**
45
+ * The signed distance to a lattice's beams and balls, negative inside. It is exact outside the lattice and its sign is
46
+ * exact everywhere; inside, where beams overlap, it is the distance to the surface of the beam or ball the point lies
47
+ * deepest in, which is never more than the distance to the lattice's surface. Infinite for a lattice with nothing in
48
+ * it. A clipping mesh is not applied here.
49
+ *
50
+ * @throws LoaderError for a vertex index outside the vertices or a beam without length or radius.
51
+ */
52
+ export declare function threeMFBeamDistance(vertices: ArrayLike<number>, lattice: ThreeMFBeamGeometry): (x: number, y: number, z: number) => number;
@@ -0,0 +1,268 @@
1
+ import { LoaderError } from './types.js';
2
+ const F = '3MF';
3
+ const arc = (c, radius, from, to) => ({
4
+ from,
5
+ to,
6
+ c,
7
+ radius,
8
+ at: (z) => Math.sqrt(Math.max(0, radius * radius - (z - c) * (z - c))),
9
+ });
10
+ /** The upper envelope of the sources over their spans, which touch or overlap, closed to the axis at both ends. */
11
+ function envelope(sources, frustum) {
12
+ const low = Math.min(...sources.map((s) => s.from)), high = Math.max(...sources.map((s) => s.to)), size = Math.max(high - low, ...sources.map((s) => Math.max(s.at(s.from), s.at(s.to), s.radius ?? 0))), tiny = size * 1e-9, heights = sources.flatMap((s) => [s.from, s.to]), arcs = sources.filter((s) => s.radius !== undefined);
13
+ // Where two curves cross, the envelope changes from one to the other.
14
+ for (const [i, a] of arcs.entries()) {
15
+ if (frustum) {
16
+ const { slope: k, r0 } = frustum, c = a.c, qa = 1 + k * k, qb = 2 * (r0 * k - c), qc = r0 * r0 + c * c - a.radius * a.radius, d = qb * qb - 4 * qa * qc;
17
+ if (d >= 0)
18
+ heights.push((-qb - Math.sqrt(d)) / (2 * qa), (-qb + Math.sqrt(d)) / (2 * qa));
19
+ }
20
+ for (const b of arcs.slice(i + 1))
21
+ if (a.c !== b.c)
22
+ heights.push((a.c * a.c - b.c * b.c - a.radius ** 2 + b.radius ** 2) / (2 * (a.c - b.c)));
23
+ }
24
+ const cuts = heights
25
+ .filter((z) => z >= low && z <= high)
26
+ .sort((a, b) => a - b)
27
+ .filter((z, i, all) => !i || z - all[i - 1] > tiny);
28
+ if (high - cuts[cuts.length - 1] > 0)
29
+ cuts[cuts.length - 1] = high;
30
+ const pieces = [];
31
+ let previous, end = 0;
32
+ for (let i = 0; i + 1 < cuts.length; i++) {
33
+ const z0 = cuts[i], z1 = cuts[i + 1], middle = (z0 + z1) / 2;
34
+ let top;
35
+ for (const s of sources)
36
+ if (s.from <= middle && s.to >= middle && (!top || s.at(middle) > top.at(middle)))
37
+ top = s;
38
+ if (!top)
39
+ continue;
40
+ const r0 = top.at(z0), r1 = top.at(z1), last = pieces[pieces.length - 1];
41
+ // A step of the radius at a height is a flat ring.
42
+ if (Math.abs(r0 - end) > tiny)
43
+ pieces.push({ z0, r0: end, z1: z0, r1: r0 });
44
+ if (top === previous && last.z1 === z0 && Math.abs(r0 - end) <= tiny) {
45
+ last.z1 = z1;
46
+ last.r1 = r1;
47
+ }
48
+ else
49
+ pieces.push({ z0, r0, z1, r1, ...(top.radius === undefined ? {} : { c: top.c, radius: top.radius }) });
50
+ previous = top;
51
+ end = r1;
52
+ }
53
+ if (end > tiny)
54
+ pieces.push({ z0: high, r0: end, z1: high, r1: 0 });
55
+ return pieces;
56
+ }
57
+ function solid(origin, axis, length, sources, frustum) {
58
+ const profile = envelope(sources, frustum), low = [Infinity, Infinity, Infinity], high = [-Infinity, -Infinity, -Infinity];
59
+ let from = Infinity, to = -Infinity, reach = 0;
60
+ for (const s of sources) {
61
+ from = Math.min(from, s.from);
62
+ to = Math.max(to, s.to);
63
+ reach = Math.max(reach, s.radius ?? Math.max(s.at(s.from), s.at(s.to)));
64
+ }
65
+ for (let k = 0; k < 3; k++)
66
+ for (const z of [from, to]) {
67
+ low[k] = Math.min(low[k], origin[k] + axis[k] * z - reach);
68
+ high[k] = Math.max(high[k], origin[k] + axis[k] * z + reach);
69
+ }
70
+ return { origin, axis, length, profile, low, high };
71
+ }
72
+ const point = (vertices, v) => {
73
+ if (!(Number.isInteger(v) && v >= 0 && v * 3 + 2 < vertices.length))
74
+ throw new LoaderError(F, 'range', `lattice vertex ${v} is outside 0..${vertices.length / 3 - 1}`);
75
+ return [vertices[v * 3], vertices[v * 3 + 1], vertices[v * 3 + 2]];
76
+ };
77
+ /** Every beam and ball of a lattice as a solid of revolution. */
78
+ function solidsOf(vertices, lattice) {
79
+ const parts = [];
80
+ const active = lattice.activeBeams ?? lattice.beams.map((_, i) => i);
81
+ for (let n = 0; n < active.length; n++) {
82
+ const at = active[n], beam = lattice.beams[at], a = point(vertices, beam.v1), b = point(vertices, beam.v2), d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], length = Math.hypot(d[0], d[1], d[2]), { r1, r2, cap1, cap2 } = beam;
83
+ if (!(length > 0 && r1 > 0 && r2 > 0))
84
+ throw new LoaderError(F, 'range', `beam ${at} needs two distinct ends and positive radii`);
85
+ const slope = (r2 - r1) / length, sources = [{ from: 0, to: length, at: (z) => r1 + slope * z }];
86
+ if (cap1 !== 'butt')
87
+ sources.push(arc(0, r1, -r1, cap1 === 'sphere' ? r1 : 0));
88
+ if (cap2 !== 'butt')
89
+ sources.push(arc(length, r2, cap2 === 'sphere' ? length - r2 : length, length + r2));
90
+ parts.push({
91
+ kind: 'beam',
92
+ index: at,
93
+ solid: solid(a, d.map((v) => v / length), length, sources, { slope, r0: r1 }),
94
+ });
95
+ }
96
+ for (const [at, ball] of (lattice.effectiveBalls ?? []).entries()) {
97
+ if (!(ball.radius > 0))
98
+ throw new LoaderError(F, 'range', `ball ${at} needs a positive radius`);
99
+ parts.push({
100
+ kind: 'ball',
101
+ index: at,
102
+ solid: solid(point(vertices, ball.vertex), [0, 0, 1], 0, [arc(0, ball.radius, -ball.radius, ball.radius)]),
103
+ });
104
+ }
105
+ return parts;
106
+ }
107
+ /**
108
+ * The surface of a lattice in the vertices' coordinates: one closed, outward triangle shell for each active beam, in
109
+ * their order, then one for each effective ball. The shells overlap where the lattice joins, which the 3MF positive
110
+ * fill rule reads as their union; `batchBooleanMeshes` of `@margoengine/mesh-edit` unions them where one surface is
111
+ * needed. A clipping mesh is not applied here (`parse3MFEvaluated` applies it).
112
+ *
113
+ * @throws LoaderError for a vertex index outside the vertices, a beam without length or radius, a bad option, or more
114
+ * triangles than `maxTriangles`.
115
+ */
116
+ export function mesh3MFBeamLattice(vertices, lattice, options = {}) {
117
+ const { segments = 16, maxTriangles = 4_000_000 } = options;
118
+ if (!(Number.isInteger(segments) && segments >= 3 && segments <= 256))
119
+ throw new LoaderError(F, 'range', 'segments must be an integer from 3 to 256');
120
+ if (!(Number.isSafeInteger(maxTriangles) && maxTriangles > 0))
121
+ throw new LoaderError(F, 'range', 'maxTriangles must be a positive integer');
122
+ const turn = Array.from({ length: segments }, (_, j) => {
123
+ const angle = (2 * Math.PI * j) / segments;
124
+ return [Math.cos(angle), Math.sin(angle)];
125
+ }), positions = [], along = [], indices = [], parts = [];
126
+ for (const part of solidsOf(vertices, lattice)) {
127
+ const { origin, axis, length, profile } = part.solid,
128
+ // A unit vector across the axis, from the world axis it leans on least.
129
+ least = [0, 1, 2].reduce((m, k) => (Math.abs(axis[k]) < Math.abs(axis[m]) ? k : m), 0), e = [0, 0, 0];
130
+ e[least] = 1;
131
+ const dot = axis[least], e1 = e.map((v, k) => v - dot * axis[k]), size = Math.hypot(e1[0], e1[1], e1[2]);
132
+ for (let k = 0; k < 3; k++)
133
+ e1[k] /= size;
134
+ const e2 = [
135
+ axis[1] * e1[2] - axis[2] * e1[1],
136
+ axis[2] * e1[0] - axis[0] * e1[2],
137
+ axis[0] * e1[1] - axis[1] * e1[0],
138
+ ];
139
+ // The profile as points of height and radius.
140
+ const widest = Math.max(...profile.map((p) => p.radius ?? Math.max(p.r0, p.r1))), tiny = widest * 1e-6, line = [];
141
+ const add = (z, r) => {
142
+ const radius = r > tiny ? r : 0, last = line[line.length - 1];
143
+ if (last && Math.abs(last[0] - z) <= tiny && Math.abs(last[1] - radius) <= tiny)
144
+ return;
145
+ line.push([z, radius]);
146
+ };
147
+ add(profile[0].z0, 0);
148
+ for (const { z0, r0, z1, r1, c, radius } of profile) {
149
+ add(z0, r0);
150
+ if (radius !== undefined) {
151
+ const angle = (z, r) => Math.atan2(r, z - c), from = angle(z0, r0), to = angle(z1, r1), steps = Math.max(1, Math.ceil((Math.abs(from - to) / (2 * Math.PI)) * segments - 1e-6));
152
+ for (let i = 1; i < steps; i++) {
153
+ const t = from + ((to - from) * i) / steps;
154
+ add(c + radius * Math.cos(t), radius * Math.sin(t));
155
+ }
156
+ }
157
+ add(z1, r1);
158
+ }
159
+ add(profile[profile.length - 1].z1, 0);
160
+ const triangleStart = indices.length / 3, rings = [];
161
+ for (const [z, r] of line) {
162
+ const ring = [];
163
+ for (let j = 0; j < (r ? segments : 1); j++) {
164
+ ring.push(positions.length / 3);
165
+ for (let k = 0; k < 3; k++)
166
+ positions.push(origin[k] + axis[k] * z + r * (turn[j][0] * e1[k] + turn[j][1] * e2[k]));
167
+ along.push(length ? Math.min(1, Math.max(0, z / length)) : 0);
168
+ }
169
+ rings.push(ring);
170
+ }
171
+ for (let i = 0; i + 1 < rings.length; i++) {
172
+ const a = rings[i], b = rings[i + 1];
173
+ if (a.length === 1 && b.length === 1)
174
+ continue;
175
+ for (let j = 0; j < segments; j++) {
176
+ const k = (j + 1) % segments;
177
+ if (a.length > 1)
178
+ indices.push(a[j], a[k], b[b.length > 1 ? k : 0]);
179
+ if (b.length > 1)
180
+ indices.push(a[a.length > 1 ? j : 0], b[k], b[j]);
181
+ }
182
+ if (indices.length / 3 > maxTriangles)
183
+ throw new LoaderError(F, 'limit', `the beam lattice exceeds ${maxTriangles} triangles; lower segments`);
184
+ }
185
+ parts.push({
186
+ kind: part.kind,
187
+ index: part.index,
188
+ triangleStart,
189
+ triangleCount: indices.length / 3 - triangleStart,
190
+ });
191
+ }
192
+ return {
193
+ positions: Float32Array.from(positions),
194
+ indices: Uint32Array.from(indices),
195
+ along: Float32Array.from(along),
196
+ parts,
197
+ };
198
+ }
199
+ /** The signed distance from a point to one solid of revolution, negative inside. */
200
+ function distanceTo({ origin, axis, profile }, x, y, z) {
201
+ const dx = x - origin[0], dy = y - origin[1], dz = z - origin[2], h = dx * axis[0] + dy * axis[1] + dz * axis[2], r = Math.hypot(dx - h * axis[0], dy - h * axis[1], dz - h * axis[2]);
202
+ let best = Infinity, top = -1;
203
+ for (const { z0, r0, z1, r1, c, radius } of profile) {
204
+ if (radius === undefined) {
205
+ const ez = z1 - z0, er = r1 - r0, t = Math.min(1, Math.max(0, ((h - z0) * ez + (r - r0) * er) / (ez * ez + er * er || 1)));
206
+ best = Math.min(best, Math.hypot(h - z0 - t * ez, r - r0 - t * er));
207
+ if (h >= z0 && h <= z1 && ez > 0)
208
+ top = Math.max(top, r0 + (er * (h - z0)) / ez);
209
+ }
210
+ else {
211
+ const away = Math.hypot(h - c, r),
212
+ // The nearest point of the circle, when it lies on this arc.
213
+ on = away > 0 ? c + ((h - c) * radius) / away : c;
214
+ if (on >= z0 && on <= z1)
215
+ best = Math.min(best, Math.abs(away - radius));
216
+ else
217
+ best = Math.min(best, Math.hypot(h - z0, r - r0), Math.hypot(h - z1, r - r1));
218
+ if (h >= z0 && h <= z1)
219
+ top = Math.max(top, Math.sqrt(Math.max(0, radius * radius - (h - c) ** 2)));
220
+ }
221
+ }
222
+ return r <= top ? -best : best;
223
+ }
224
+ function tree(solids) {
225
+ const low = [0, 1, 2].map((k) => solids.reduce((m, s) => Math.min(m, s.low[k]), Infinity)), high = [0, 1, 2].map((k) => solids.reduce((m, s) => Math.max(m, s.high[k]), -Infinity));
226
+ if (solids.length === 1)
227
+ return { low, high, solid: solids[0] };
228
+ const k = [0, 1, 2].reduce((m, i) => (high[i] - low[i] > high[m] - low[m] ? i : m), 0), sorted = [...solids].sort((a, b) => a.low[k] + a.high[k] - b.low[k] - b.high[k]), half = sorted.length >> 1;
229
+ return { low, high, left: tree(sorted.slice(0, half)), right: tree(sorted.slice(half)) };
230
+ }
231
+ /**
232
+ * The signed distance to a lattice's beams and balls, negative inside. It is exact outside the lattice and its sign is
233
+ * exact everywhere; inside, where beams overlap, it is the distance to the surface of the beam or ball the point lies
234
+ * deepest in, which is never more than the distance to the lattice's surface. Infinite for a lattice with nothing in
235
+ * it. A clipping mesh is not applied here.
236
+ *
237
+ * @throws LoaderError for a vertex index outside the vertices or a beam without length or radius.
238
+ */
239
+ export function threeMFBeamDistance(vertices, lattice) {
240
+ const solids = solidsOf(vertices, lattice).map((p) => p.solid);
241
+ if (!solids.length)
242
+ return () => Infinity;
243
+ const root = tree(solids);
244
+ const away = ({ low, high }, x, y, z) => Math.hypot(Math.max(low[0] - x, 0, x - high[0]), Math.max(low[1] - y, 0, y - high[1]), Math.max(low[2] - z, 0, z - high[2]));
245
+ return (x, y, z) => {
246
+ let best = Infinity;
247
+ const visit = (node, near) => {
248
+ // A solid is no nearer than its box; one whose box holds the point may be deeper than the best so far.
249
+ if (near > 0 && near >= best)
250
+ return;
251
+ if (node.solid) {
252
+ best = Math.min(best, distanceTo(node.solid, x, y, z));
253
+ return;
254
+ }
255
+ const a = away(node.left, x, y, z), b = away(node.right, x, y, z);
256
+ if (a <= b) {
257
+ visit(node.left, a);
258
+ visit(node.right, b);
259
+ }
260
+ else {
261
+ visit(node.right, b);
262
+ visit(node.left, a);
263
+ }
264
+ };
265
+ visit(root, away(root, x, y, z));
266
+ return best;
267
+ };
268
+ }
@@ -0,0 +1,10 @@
1
+ import type { ThreeMFBooleanOptions, ThreeMFBooleanShape } from './threemf-boolean.js';
2
+ import type { ThreeMFExtension } from './threemf.js';
3
+ /**
4
+ * The boolean reader's hooks. `others` says that hooks before these turn displacement meshes, level sets and lattices
5
+ * into triangles, so such an object may be a base.
6
+ */
7
+ export declare function booleanStage(options: ThreeMFBooleanOptions, others?: boolean): {
8
+ hooks: ThreeMFExtension;
9
+ shapes: ThreeMFBooleanShape[];
10
+ };