@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/3dm.d.ts ADDED
@@ -0,0 +1,161 @@
1
+ import { type NurbsSurfaceOptions } from './nurbs.js';
2
+ import { type LoadedGeometry, type LoadedGroup, type ParseLimits } from './types.js';
3
+ import { type BinaryInput } from './util.js';
4
+ interface Disposable {
5
+ delete?(): void;
6
+ }
7
+ interface IndexedList<T> extends Disposable {
8
+ count: number;
9
+ get(index: number): T;
10
+ }
11
+ interface RhinoColor {
12
+ r: number;
13
+ g: number;
14
+ b: number;
15
+ a: number;
16
+ }
17
+ /** The part of a rhino3dm mesh this entry reads. */
18
+ export interface RhinoMesh extends Disposable {
19
+ vertices(): IndexedList<number[]>;
20
+ faces(): IndexedList<number[]>;
21
+ normals?(): IndexedList<number[]>;
22
+ textureCoordinates?(): IndexedList<number[]>;
23
+ vertexColors?(): IndexedList<RhinoColor>;
24
+ }
25
+ /** The part of a rhino3dm NURBS surface this entry reads. */
26
+ export interface RhinoNurbsSurface extends Disposable {
27
+ degree(direction: number): number;
28
+ knotsU(): IndexedList<number>;
29
+ knotsV(): IndexedList<number>;
30
+ points(): Disposable & {
31
+ countU: number;
32
+ countV: number;
33
+ /** Control point `[x * w, y * w, z * w, w]`. */
34
+ get(u: number, v: number): number[];
35
+ /** Control point `[x, y, z]`. */
36
+ getPoint(u: number, v: number): number[];
37
+ };
38
+ }
39
+ /** The part of a rhino3dm solid's face this entry reads. */
40
+ export interface RhinoFace extends Disposable {
41
+ getMesh(type: unknown): RhinoMesh | null | undefined;
42
+ underlyingSurface?(): Disposable & {
43
+ toNurbsSurface(): RhinoNurbsSurface | null | undefined;
44
+ };
45
+ orientationIsReversed?: boolean;
46
+ }
47
+ /** What an object's geometry may offer. Anything with no mesh and no untrimmed surface is counted in `skipped`. */
48
+ export interface RhinoGeometry extends Disposable {
49
+ vertices?: RhinoMesh['vertices'];
50
+ vertexColors?: RhinoMesh['vertexColors'];
51
+ getMesh?(type: unknown): RhinoMesh | null | undefined;
52
+ faces?(): IndexedList<RhinoFace>;
53
+ /** True on a solid that is one face with no trims of its own. */
54
+ isSurface?: boolean;
55
+ /** Only a surface object has these. */
56
+ knotsU?: RhinoNurbsSurface['knotsU'];
57
+ degree?: RhinoNurbsSurface['degree'];
58
+ }
59
+ /** The part of a rhino3dm object's attributes this entry reads. */
60
+ export interface RhinoAttributes extends Disposable {
61
+ name?: string;
62
+ id?: string;
63
+ layerIndex?: number;
64
+ materialIndex?: number;
65
+ visible?: boolean;
66
+ drawColor?(document: unknown): RhinoColor;
67
+ getUserStrings?(): [string, string][];
68
+ }
69
+ /** The part of a rhino3dm layer this entry reads. */
70
+ export interface RhinoLayer extends Disposable {
71
+ name?: string;
72
+ fullPath?: string;
73
+ color?: RhinoColor;
74
+ visible?: boolean;
75
+ }
76
+ /** The part of a rhino3dm file this entry reads. */
77
+ export interface RhinoDocument extends Disposable {
78
+ objects(): IndexedList<{
79
+ geometry(): RhinoGeometry;
80
+ attributes(): RhinoAttributes;
81
+ } & Disposable>;
82
+ layers(): IndexedList<RhinoLayer>;
83
+ settings?(): {
84
+ modelUnitSystem?: {
85
+ value?: number;
86
+ } | number;
87
+ } & Disposable;
88
+ }
89
+ /** A loaded rhino3dm module: `await rhino3dm()`. The caller owns it and its Wasm file. */
90
+ export interface RhinoRuntime {
91
+ File3dm: {
92
+ fromByteArray(bytes: Uint8Array): RhinoDocument | null | undefined;
93
+ };
94
+ MeshType?: {
95
+ Any?: unknown;
96
+ };
97
+ }
98
+ /** Options of {@link parse3DM}. */
99
+ export interface ThreeDMOptions extends ParseLimits, Pick<NurbsSurfaceOptions, 'segmentsU' | 'segmentsV'> {
100
+ /** `'meters'` (default) scales by the file's unit when it has one; `'file'` keeps the file's own units. */
101
+ units?: 'meters' | 'file';
102
+ /** Read objects that are hidden, or on a hidden layer. Default false. */
103
+ hidden?: boolean;
104
+ }
105
+ /** One layer of a {@link ThreeDMResult}. */
106
+ export interface ThreeDMLayer {
107
+ name: string;
108
+ /** The name with its parents, `Parent::Child`, when the file has one. */
109
+ path: string;
110
+ /** sRGB `[r, g, b, a]` in [0,1]. */
111
+ color: [number, number, number, number];
112
+ visible: boolean;
113
+ }
114
+ /** One object read into a {@link ThreeDMResult}: a range of `indices` with what the file says about it. */
115
+ export interface ThreeDMGroup extends LoadedGroup {
116
+ /** The object's id. */
117
+ id?: string;
118
+ /** Index into `layers`. */
119
+ layer?: number;
120
+ /** The file's material index, -1 for none. */
121
+ material?: number;
122
+ /** Key and value text the object carries. Null prototype. */
123
+ userStrings: Record<string, string>;
124
+ }
125
+ /** What {@link parse3DM} returns: one merged mesh, with a group per object. */
126
+ export interface ThreeDMResult extends LoadedGeometry {
127
+ groups: ThreeDMGroup[];
128
+ layers: ThreeDMLayer[];
129
+ /** Metres per file unit, when the file names a unit. */
130
+ metersPerUnit?: number;
131
+ /** Objects without a mesh or an untrimmed surface, such as curves, points and solids saved without their render mesh. */
132
+ skipped: number;
133
+ /** Objects drawn from their NURBS surface, because the file saved no render mesh for them. */
134
+ surfaces: number;
135
+ }
136
+ /**
137
+ * Reads the meshes, layers and attributes of a Rhino `.3dm` file through a rhino3dm runtime you load and own, the same
138
+ * pattern as `parseIFC`, so its Wasm file is never part of this package. Each object becomes a group of one merged mesh:
139
+ * a mesh as it is, and any other surface object through the render mesh saved in the file. Objects without one are
140
+ * counted in `skipped`; the runtime meshes nothing on its own.
141
+ *
142
+ * @param rhino The loaded module.
143
+ * @param input The file's bytes.
144
+ * @param options The shared size limits, units and whether hidden objects load.
145
+ * @returns The mesh, with a group per object, and the file's layers.
146
+ * @throws LoaderError with code `header` for a file the runtime cannot read, `limit`, `range` or `syntax`.
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * import { parse3DM, type RhinoRuntime } from '@margoengine/loaders/3dm';
151
+ *
152
+ * // `rhino` is `await rhino3dm()`, from the rhino3dm package you install and host.
153
+ * export async function loadChair(rhino: RhinoRuntime) {
154
+ * const bytes = await (await fetch('/models/chair.3dm')).arrayBuffer();
155
+ * const { groups, layers } = parse3DM(rhino, bytes);
156
+ * console.log(groups[0].name, layers[groups[0].layer ?? 0].name);
157
+ * }
158
+ * ```
159
+ */
160
+ export declare function parse3DM(rhino: RhinoRuntime, input: BinaryInput, options?: ThreeDMOptions): ThreeDMResult;
161
+ export {};
package/dist/3dm.js ADDED
@@ -0,0 +1,289 @@
1
+ // Rhino 3DM files through a caller-owned rhino3dm runtime: meshes, untrimmed surfaces, layers and object attributes.
2
+ import { tessellateNurbsSurface } from './nurbs.js';
3
+ import { LoaderError } from './types.js';
4
+ import { floats, limits, toBytes, uints } from './util.js';
5
+ const F = '3DM';
6
+ const AU = 149597870700;
7
+ /**
8
+ * Metres per unit, by the file's unit system number (RhinoCommon `UnitSystem`). 0 None and 11 CustomUnits name no
9
+ * metre factor, so they are left out.
10
+ */
11
+ const UNITS = {
12
+ 1: 1e-6,
13
+ 2: 1e-3,
14
+ 3: 1e-2,
15
+ 4: 1,
16
+ 5: 1e3,
17
+ 6: 2.54e-8,
18
+ 7: 2.54e-5,
19
+ 8: 0.0254,
20
+ 9: 0.3048,
21
+ 10: 1609.344,
22
+ 12: 1e-10,
23
+ 13: 1e-9,
24
+ 14: 0.1,
25
+ 15: 10,
26
+ 16: 100,
27
+ 17: 1e6,
28
+ 18: 1e9,
29
+ 19: 0.9144,
30
+ 20: 0.0254 / 72,
31
+ 21: 0.0254 / 6,
32
+ 22: 1852,
33
+ 23: AU,
34
+ 24: 9460730472580800,
35
+ 25: (648000 / Math.PI) * AU,
36
+ };
37
+ const unit = (color) => color ? [color.r / 255, color.g / 255, color.b / 255, color.a === undefined ? 1 : color.a / 255] : [1, 1, 1, 1];
38
+ /**
39
+ * Frees a rhino3dm object. The runtime's tables, such as `File3dmLayerTable`, have a method of their own called `delete`
40
+ * that removes an entry by id, which hides the handle's `delete`, so the free comes from the handle's base prototype,
41
+ * the one that owns `isDeleted`. A plain object without that base has only its own `delete`.
42
+ */
43
+ function free(value) {
44
+ let owner = value;
45
+ while (owner && !Object.hasOwn(owner, 'isDeleted'))
46
+ owner = Object.getPrototypeOf(owner);
47
+ (owner ?? value).delete?.call(value);
48
+ }
49
+ /** Runs `use` on a rhino3dm object and frees it, because its memory is outside JavaScript's reach. */
50
+ function using(value, use) {
51
+ try {
52
+ return use(value);
53
+ }
54
+ finally {
55
+ free(value);
56
+ }
57
+ }
58
+ /**
59
+ * Reads the meshes, layers and attributes of a Rhino `.3dm` file through a rhino3dm runtime you load and own, the same
60
+ * pattern as `parseIFC`, so its Wasm file is never part of this package. Each object becomes a group of one merged mesh:
61
+ * a mesh as it is, and any other surface object through the render mesh saved in the file. Objects without one are
62
+ * counted in `skipped`; the runtime meshes nothing on its own.
63
+ *
64
+ * @param rhino The loaded module.
65
+ * @param input The file's bytes.
66
+ * @param options The shared size limits, units and whether hidden objects load.
67
+ * @returns The mesh, with a group per object, and the file's layers.
68
+ * @throws LoaderError with code `header` for a file the runtime cannot read, `limit`, `range` or `syntax`.
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * import { parse3DM, type RhinoRuntime } from '@margoengine/loaders/3dm';
73
+ *
74
+ * // `rhino` is `await rhino3dm()`, from the rhino3dm package you install and host.
75
+ * export async function loadChair(rhino: RhinoRuntime) {
76
+ * const bytes = await (await fetch('/models/chair.3dm')).arrayBuffer();
77
+ * const { groups, layers } = parse3DM(rhino, bytes);
78
+ * console.log(groups[0].name, layers[groups[0].layer ?? 0].name);
79
+ * }
80
+ * ```
81
+ */
82
+ export function parse3DM(rhino, input, options = {}) {
83
+ const bytes = toBytes(input, F), { maxVertices, maxTriangles } = limits(options, F);
84
+ if (options.units !== undefined && options.units !== 'meters' && options.units !== 'file')
85
+ throw new LoaderError(F, 'range', 'units must be "meters" or "file"');
86
+ if (typeof rhino?.File3dm?.fromByteArray !== 'function')
87
+ throw new LoaderError(F, 'range', 'pass a loaded rhino3dm module: await rhino3dm()');
88
+ const document = rhino.File3dm.fromByteArray(bytes);
89
+ if (!document)
90
+ throw new LoaderError(F, 'header', 'rhino3dm cannot read this file');
91
+ return using(document, () => read(rhino, document, options, maxVertices, maxTriangles));
92
+ }
93
+ function read(rhino, document, options, maxVertices, maxTriangles) {
94
+ const positions = floats(), normals = floats(), uvs = floats(), colors = floats(), indices = uints(), groups = [], meshType = rhino.MeshType?.Any;
95
+ let hasNormals = false, hasUVs = false, hasColors = false, skipped = 0, surfaces = 0;
96
+ const layers = using(document.layers(), (table) => {
97
+ const out = [];
98
+ for (let i = 0; i < table.count; i++)
99
+ using(table.get(i), (layer) => {
100
+ const name = layer.name ?? '';
101
+ out.push({ name, path: layer.fullPath ?? name, color: unit(layer.color), visible: layer.visible !== false });
102
+ });
103
+ return out;
104
+ });
105
+ let scale = 1, metersPerUnit;
106
+ if (document.settings)
107
+ using(document.settings(), (settings) => {
108
+ const system = settings.modelUnitSystem, value = typeof system === 'number' ? system : system?.value;
109
+ metersPerUnit = value === undefined ? undefined : UNITS[value];
110
+ });
111
+ if (metersPerUnit !== undefined && options.units !== 'file')
112
+ scale = metersPerUnit;
113
+ const addMesh = (mesh) => {
114
+ const base = positions.length / 3;
115
+ const count = using(mesh.vertices(), (vertices) => {
116
+ if (base + vertices.count > maxVertices)
117
+ throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${maxVertices}`);
118
+ for (let i = 0; i < vertices.count; i++) {
119
+ const [x, y, z] = vertices.get(i);
120
+ positions.push3(x * scale, y * scale, z * scale);
121
+ }
122
+ return vertices.count;
123
+ });
124
+ using(mesh.faces(), (faces) => {
125
+ for (let i = 0; i < faces.count; i++) {
126
+ const [a, b, c, d] = faces.get(i), quad = d !== undefined && d !== c;
127
+ if (indices.length / 3 + (quad ? 2 : 1) > maxTriangles)
128
+ throw new LoaderError(F, 'limit', `triangle count exceeds the limit of ${maxTriangles}`);
129
+ for (const corner of quad ? [a, b, c, d] : [a, b, c])
130
+ if (!(corner >= 0 && corner < count))
131
+ throw new LoaderError(F, 'range', `face index ${corner} is outside 0..${count - 1}`);
132
+ indices.push3(base + a, base + b, base + c);
133
+ if (quad)
134
+ indices.push3(base + a, base + c, base + d);
135
+ }
136
+ });
137
+ // Each optional array has one entry per vertex or none; a mesh without one takes neutral values, so all stay aligned.
138
+ const list = (table, each, fill) => {
139
+ const complete = table?.count === count;
140
+ for (let i = 0; i < count; i++)
141
+ if (complete)
142
+ each(table.get(i));
143
+ else
144
+ fill();
145
+ if (table)
146
+ free(table);
147
+ return complete;
148
+ };
149
+ if (list(mesh.normals?.(), ([x, y, z]) => normals.push3(x, y, z), () => normals.push3(0, 0, 0)))
150
+ hasNormals = true;
151
+ const uv = (u, v) => {
152
+ uvs.push(u);
153
+ uvs.push(v);
154
+ };
155
+ if (list(mesh.textureCoordinates?.(), ([u, v]) => uv(u, 1 - v), () => uv(0, 0)))
156
+ hasUVs = true;
157
+ if (list(mesh.vertexColors?.(), (c) => colors.push3(c.r / 255, c.g / 255, c.b / 255), () => colors.push3(1, 1, 1)))
158
+ hasColors = true;
159
+ };
160
+ /** Adds a whole surface through the one NURBS evaluator: the runtime meshes nothing, and it has no trims to apply. */
161
+ const addSurface = (surface, reversed) => {
162
+ const knots = (list) => using(list, (table) => Array.from({ length: table.count }, (_, i) => table.get(i)));
163
+ const grid = using(surface.points(), (list) => {
164
+ const { countU, countV } = list, points = [], weights = [];
165
+ for (let u = 0; u < countU; u++)
166
+ for (let v = 0; v < countV; v++) {
167
+ points.push(...list.getPoint(u, v));
168
+ weights.push(list.get(u, v)[3]);
169
+ }
170
+ return { countU, countV, points, weights };
171
+ }), base = positions.length / 3, { positions: at, normals: facing, uvs: coordinates, indices: order, } = tessellateNurbsSurface({
172
+ degreeU: surface.degree(0),
173
+ degreeV: surface.degree(1),
174
+ knotsU: knots(surface.knotsU()),
175
+ knotsV: knots(surface.knotsV()),
176
+ ...grid,
177
+ }, {
178
+ segmentsU: options.segmentsU,
179
+ segmentsV: options.segmentsV,
180
+ maxVertices: maxVertices - base,
181
+ maxTriangles: maxTriangles - indices.length / 3,
182
+ }), flip = reversed ? -1 : 1;
183
+ for (let i = 0; i < at.length; i += 3) {
184
+ positions.push3(at[i] * scale, at[i + 1] * scale, at[i + 2] * scale);
185
+ normals.push3(facing[i] * flip, facing[i + 1] * flip, facing[i + 2] * flip);
186
+ colors.push3(1, 1, 1);
187
+ }
188
+ for (let i = 0; i < coordinates.length; i++)
189
+ uvs.push(coordinates[i]);
190
+ for (let i = 0; i < order.length; i += 3)
191
+ if (reversed)
192
+ indices.push3(base + order[i], base + order[i + 2], base + order[i + 1]);
193
+ else
194
+ indices.push3(base + order[i], base + order[i + 1], base + order[i + 2]);
195
+ hasNormals = hasUVs = true;
196
+ surfaces++;
197
+ };
198
+ /** Adds the object's meshes and says whether it had any. */
199
+ const addGeometry = (geometry) => {
200
+ if (geometry.knotsU && geometry.degree) {
201
+ addSurface(geometry, false);
202
+ return true;
203
+ }
204
+ // A solid has `vertices` and `faces` too, of another kind; only a mesh has vertex colours.
205
+ if (geometry.vertices && geometry.vertexColors) {
206
+ addMesh(geometry);
207
+ return true;
208
+ }
209
+ if (geometry.getMesh) {
210
+ const mesh = geometry.getMesh(meshType);
211
+ if (!mesh)
212
+ return false;
213
+ using(mesh, addMesh);
214
+ return true;
215
+ }
216
+ if (!geometry.faces)
217
+ return false;
218
+ return using(geometry.faces(), (faces) => {
219
+ let any = false;
220
+ for (let i = 0; i < faces.count; i++)
221
+ using(faces.get(i), (face) => {
222
+ const mesh = face.getMesh(meshType);
223
+ if (!mesh)
224
+ return;
225
+ using(mesh, addMesh);
226
+ any = true;
227
+ });
228
+ // A face of a solid can be trimmed, and the runtime gives no trim curves: only a solid it calls one plain surface
229
+ // draws from its surface, so nothing shows past a trim.
230
+ if (!any && geometry.isSurface && faces.count === 1)
231
+ using(faces.get(0), (face) => {
232
+ const nurbs = face.underlyingSurface && using(face.underlyingSurface(), (surface) => surface.toNurbsSurface());
233
+ if (!nurbs)
234
+ return;
235
+ using(nurbs, (surface) => addSurface(surface, face.orientationIsReversed === true));
236
+ any = true;
237
+ });
238
+ return any;
239
+ });
240
+ };
241
+ using(document.objects(), (table) => {
242
+ for (let i = 0; i < table.count; i++)
243
+ using(table.get(i), (object) => using(object.attributes(), (attributes) => {
244
+ const layer = attributes.layerIndex, onLayer = layer === undefined ? undefined : layers[layer];
245
+ if (!options.hidden && (attributes.visible === false || onLayer?.visible === false))
246
+ return;
247
+ const start = indices.length;
248
+ const added = using(object.geometry(), addGeometry);
249
+ if (!added) {
250
+ skipped++;
251
+ return;
252
+ }
253
+ const userStrings = Object.create(null);
254
+ for (const [key, value] of attributes.getUserStrings?.() ?? [])
255
+ userStrings[key] = value;
256
+ const group = { start, count: indices.length - start, userStrings };
257
+ if (attributes.name)
258
+ group.name = attributes.name;
259
+ if (attributes.id)
260
+ group.id = attributes.id;
261
+ if (layer !== undefined)
262
+ group.layer = layer;
263
+ if (attributes.materialIndex !== undefined)
264
+ group.material = attributes.materialIndex;
265
+ const drawn = attributes.drawColor?.(document) ?? onLayer?.color;
266
+ if (drawn)
267
+ group.color = Array.isArray(drawn) ? [...drawn] : unit(drawn);
268
+ groups.push(group);
269
+ }));
270
+ });
271
+ const result = {
272
+ kind: 'mesh',
273
+ positions: positions.result(),
274
+ indices: indices.result(),
275
+ groups,
276
+ layers,
277
+ skipped,
278
+ surfaces,
279
+ };
280
+ if (hasNormals)
281
+ result.normals = normals.result();
282
+ if (hasUVs)
283
+ result.uvs = uvs.result();
284
+ if (hasColors)
285
+ result.colors = colors.result();
286
+ if (metersPerUnit !== undefined)
287
+ result.metersPerUnit = metersPerUnit;
288
+ return result;
289
+ }
package/dist/3ds.d.ts ADDED
@@ -0,0 +1,124 @@
1
+ import { type LoadedGeometry, type LoadedGroup, type ParseLimits } from './types.js';
2
+ import { type BinaryInput } from './util.js';
3
+ /** Options of {@link parse3DS}: the shared size limits. */
4
+ export interface ThreeDSOptions extends ParseLimits {
5
+ }
6
+ /** One material of a {@link ThreeDSResult}. Colours are sRGB in [0,1]. */
7
+ export interface ThreeDSMaterial {
8
+ name: string;
9
+ /** `[r, g, b, a]`, the alpha from the file's transparency. */
10
+ color: [number, number, number, number];
11
+ /** The diffuse map's file name, as written. */
12
+ texture?: string;
13
+ }
14
+ /** A group of a {@link ThreeDSResult}: the faces of one object in one material. */
15
+ export interface ThreeDSGroup extends LoadedGroup {
16
+ /** Index into `materials`. */
17
+ material?: number;
18
+ }
19
+ /** A camera of a {@link ThreeDSResult}. */
20
+ export interface ThreeDSCamera {
21
+ name: string;
22
+ position: [number, number, number];
23
+ /** The point it looks at. */
24
+ target: [number, number, number];
25
+ /** Bank about the view direction, in degrees. */
26
+ roll: number;
27
+ /** Lens focal length in millimetres, on 3D Studio's 35 mm film. */
28
+ lens: number;
29
+ }
30
+ /** A light of a {@link ThreeDSResult}. A light with no `spot` shines every way from `position`. */
31
+ export interface ThreeDSLight {
32
+ name: string;
33
+ position: [number, number, number];
34
+ /** Linear `[r, g, b]`, as the file gives it. */
35
+ color: [number, number, number];
36
+ /** False when the file has the light switched off. */
37
+ on: boolean;
38
+ /** The file's multiplier, 1 when it has none. */
39
+ multiplier: number;
40
+ /** Spotlight data: the point aimed at and the two cone angles in degrees. */
41
+ spot?: {
42
+ target: [number, number, number];
43
+ hotspot: number;
44
+ falloff: number;
45
+ };
46
+ }
47
+ /** One key of a {@link ThreeDSTrack}. The spline values are there only when the file stores them. */
48
+ export interface ThreeDSKey {
49
+ frame: number;
50
+ /** The track's value: xyz for `position` and `scale`, `[radians, x, y, z]` for `rotation`, rgb for `color`, else one number. */
51
+ value: number[];
52
+ tension?: number;
53
+ continuity?: number;
54
+ bias?: number;
55
+ easeTo?: number;
56
+ easeFrom?: number;
57
+ }
58
+ /** A keyframe track of a {@link ThreeDSNode}, in the order of its frames. */
59
+ export interface ThreeDSTrack {
60
+ /** The file's track flags: bits 0 and 1 are 2 for a repeating track, 3 for a looping one. */
61
+ flags: number;
62
+ keys: ThreeDSKey[];
63
+ }
64
+ /** One node of the keyframer. Rotation keys are axis and angle, each relative to the key before it, as 3D Studio saves them. */
65
+ export interface ThreeDSNode {
66
+ /** The file's node id, or the node's position in the list when it has none. */
67
+ id: number;
68
+ kind: 'ambient' | 'object' | 'camera' | 'cameraTarget' | 'light' | 'spotTarget' | 'spot';
69
+ /** The object, camera or light this node animates. `$$$DUMMY` is a dummy node, and `$AMBIENT$` the ambient light. */
70
+ name: string;
71
+ /** The instance name a dummy or a repeated object has. */
72
+ instance?: string;
73
+ /** The `id` of the parent node, -1 at the root. */
74
+ parent: number;
75
+ /** The pivot, in the object's coordinates. */
76
+ pivot: [number, number, number];
77
+ tracks: {
78
+ [K in 'position' | 'rotation' | 'scale' | 'fov' | 'roll' | 'color' | 'hotspot' | 'falloff']?: ThreeDSTrack;
79
+ };
80
+ }
81
+ /** The keyframer's data of a {@link ThreeDSResult}. */
82
+ export interface ThreeDSKeyframes {
83
+ /** The first and last frame of the active segment. */
84
+ start: number;
85
+ end: number;
86
+ /** Frames in the whole animation. */
87
+ length: number;
88
+ nodes: ThreeDSNode[];
89
+ }
90
+ /** What {@link parse3DS} returns. Coordinates are the file's: no unit, Z up, as 3D Studio saved them. */
91
+ export interface ThreeDSResult extends LoadedGeometry {
92
+ kind: 'mesh';
93
+ groups: ThreeDSGroup[];
94
+ materials: ThreeDSMaterial[];
95
+ /** The file's master scale, 1 when it has none. */
96
+ masterScale: number;
97
+ cameras: ThreeDSCamera[];
98
+ lights: ThreeDSLight[];
99
+ /** The ambient light's linear `[r, g, b]`, when the file sets one. */
100
+ ambient?: [number, number, number];
101
+ /** The keyframer's data, when the file has any. */
102
+ keyframes?: ThreeDSKeyframes;
103
+ }
104
+ /**
105
+ * Reads a 3D Studio `.3ds` file: every triangle mesh with its UVs, one group per object and material, the materials'
106
+ * colours, transparency and diffuse map names, the cameras and lights, and the keyframer's nodes and tracks. Vertices are
107
+ * saved in world space, so no transform applies. Cameras, lights and keyframes are returned as the file holds them, in
108
+ * its coordinates. `loadTextures` from `@margoengine/loaders/textures` reads the maps the materials name.
109
+ *
110
+ * @param input The file's bytes.
111
+ * @param options The shared size limits.
112
+ * @returns The merged mesh, its materials, the master scale, cameras, lights and keyframes.
113
+ * @throws LoaderError with code `header`, `truncated`, `range`, `limit` or `syntax` (no mesh in the file).
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * import { parse3DS } from '@margoengine/loaders/3ds';
118
+ *
119
+ * const bytes = await (await fetch('/models/teapot.3ds')).arrayBuffer();
120
+ * const { groups, materials, cameras, keyframes } = parse3DS(bytes);
121
+ * console.log(groups.length, materials[0]?.texture, cameras[0]?.lens, keyframes?.nodes.length);
122
+ * ```
123
+ */
124
+ export declare function parse3DS(input: BinaryInput, options?: ThreeDSOptions): ThreeDSResult;