@margoengine/loaders 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1198 -3
  4. package/dist/3dm.d.ts +161 -0
  5. package/dist/3dm.js +289 -0
  6. package/dist/3ds.d.ts +124 -0
  7. package/dist/3ds.js +392 -0
  8. package/dist/acclaim.d.ts +90 -0
  9. package/dist/acclaim.js +312 -0
  10. package/dist/amf.d.ts +45 -0
  11. package/dist/amf.js +256 -0
  12. package/dist/babylon.d.ts +197 -0
  13. package/dist/babylon.js +701 -0
  14. package/dist/common.d.ts +7 -0
  15. package/dist/common.js +6 -0
  16. package/dist/dae-animation.d.ts +66 -0
  17. package/dist/dae-animation.js +266 -0
  18. package/dist/dae-common.d.ts +95 -0
  19. package/dist/dae-common.js +226 -0
  20. package/dist/dae-controllers.d.ts +57 -0
  21. package/dist/dae-controllers.js +164 -0
  22. package/dist/dae-pose.d.ts +131 -0
  23. package/dist/dae-pose.js +381 -0
  24. package/dist/dae-scene.d.ts +203 -0
  25. package/dist/dae-scene.js +279 -0
  26. package/dist/dae.d.ts +161 -0
  27. package/dist/dae.js +633 -0
  28. package/dist/detect.d.ts +20 -0
  29. package/dist/detect.js +72 -0
  30. package/dist/dxf.d.ts +81 -0
  31. package/dist/dxf.js +774 -0
  32. package/dist/engine.d.ts +36 -0
  33. package/dist/engine.js +117 -0
  34. package/dist/font-opentype.d.ts +14 -0
  35. package/dist/font-opentype.js +33 -0
  36. package/dist/font-woff.d.ts +23 -0
  37. package/dist/font-woff.js +293 -0
  38. package/dist/font.d.ts +41 -0
  39. package/dist/font.js +26 -0
  40. package/dist/gcode.d.ts +55 -0
  41. package/dist/gcode.js +278 -0
  42. package/dist/geo-model.d.ts +84 -0
  43. package/dist/geo-model.js +220 -0
  44. package/dist/geo-mvt.d.ts +15 -0
  45. package/dist/geo-mvt.js +302 -0
  46. package/dist/geo-shp.d.ts +15 -0
  47. package/dist/geo-shp.js +234 -0
  48. package/dist/geo-xml.d.ts +6 -0
  49. package/dist/geo-xml.js +165 -0
  50. package/dist/geo.d.ts +8 -0
  51. package/dist/geo.js +59 -0
  52. package/dist/geometry.d.ts +60 -0
  53. package/dist/geometry.js +273 -0
  54. package/dist/index.d.ts +54 -0
  55. package/dist/index.js +28 -0
  56. package/dist/kmz.d.ts +78 -0
  57. package/dist/kmz.js +173 -0
  58. package/dist/las.d.ts +92 -0
  59. package/dist/las.js +110 -0
  60. package/dist/ldraw.d.ts +118 -0
  61. package/dist/ldraw.js +474 -0
  62. package/dist/load.d.ts +72 -0
  63. package/dist/load.js +205 -0
  64. package/dist/lottie.d.ts +154 -0
  65. package/dist/lottie.js +893 -0
  66. package/dist/lwo.d.ts +81 -0
  67. package/dist/lwo.js +454 -0
  68. package/dist/lzf.d.ts +13 -0
  69. package/dist/lzf.js +56 -0
  70. package/dist/materialx.d.ts +120 -0
  71. package/dist/materialx.js +563 -0
  72. package/dist/md2.d.ts +52 -0
  73. package/dist/md2.js +112 -0
  74. package/dist/mmcif.d.ts +14 -0
  75. package/dist/mmcif.js +246 -0
  76. package/dist/mmd.d.ts +244 -0
  77. package/dist/mmd.js +958 -0
  78. package/dist/mocap.d.ts +71 -0
  79. package/dist/mocap.js +178 -0
  80. package/dist/molecule-common.d.ts +4 -0
  81. package/dist/molecule-common.js +54 -0
  82. package/dist/mtl.d.ts +120 -0
  83. package/dist/mtl.js +469 -0
  84. package/dist/normals.d.ts +7 -0
  85. package/dist/normals.js +31 -0
  86. package/dist/nrrd.d.ts +63 -0
  87. package/dist/nrrd.js +743 -0
  88. package/dist/nurbs.d.ts +118 -0
  89. package/dist/nurbs.js +265 -0
  90. package/dist/obj.d.ts +143 -0
  91. package/dist/obj.js +456 -0
  92. package/dist/off.d.ts +10 -0
  93. package/dist/off.js +155 -0
  94. package/dist/outline-font.d.ts +87 -0
  95. package/dist/outline-font.js +110 -0
  96. package/dist/outline.d.ts +20 -0
  97. package/dist/outline.js +215 -0
  98. package/dist/pcd.d.ts +34 -0
  99. package/dist/pcd.js +258 -0
  100. package/dist/pdb.d.ts +67 -0
  101. package/dist/pdb.js +126 -0
  102. package/dist/ply.d.ts +35 -0
  103. package/dist/ply.js +392 -0
  104. package/dist/polygon.d.ts +9 -0
  105. package/dist/polygon.js +49 -0
  106. package/dist/prwm.d.ts +24 -0
  107. package/dist/prwm.js +114 -0
  108. package/dist/render.d.ts +27 -0
  109. package/dist/render.js +153 -0
  110. package/dist/sfnt-cff.d.ts +37 -0
  111. package/dist/sfnt-cff.js +749 -0
  112. package/dist/sfnt-layout.d.ts +24 -0
  113. package/dist/sfnt-layout.js +266 -0
  114. package/dist/sfnt-reader.d.ts +28 -0
  115. package/dist/sfnt-reader.js +87 -0
  116. package/dist/sfnt-variation.d.ts +40 -0
  117. package/dist/sfnt-variation.js +318 -0
  118. package/dist/shared/asset-url.js +82 -0
  119. package/dist/shared/crc32.d.ts +2 -0
  120. package/dist/shared/crc32.js +47 -0
  121. package/dist/shared/errors.js +36 -0
  122. package/dist/shared/inflate.js +284 -0
  123. package/dist/shared/normals.js +26 -0
  124. package/dist/shared/scene-scope.js +56 -0
  125. package/dist/shared/trailing-data.js +42 -0
  126. package/dist/stl.d.ts +64 -0
  127. package/dist/stl.js +309 -0
  128. package/dist/svg.d.ts +90 -0
  129. package/dist/svg.js +1007 -0
  130. package/dist/tds.d.ts +2 -0
  131. package/dist/tds.js +2 -0
  132. package/dist/textures.d.ts +42 -0
  133. package/dist/textures.js +53 -0
  134. package/dist/threemf-lattice.d.ts +139 -0
  135. package/dist/threemf-lattice.js +514 -0
  136. package/dist/threemf-materials.d.ts +75 -0
  137. package/dist/threemf-materials.js +314 -0
  138. package/dist/threemf-mesh.d.ts +60 -0
  139. package/dist/threemf-mesh.js +201 -0
  140. package/dist/threemf.d.ts +101 -0
  141. package/dist/threemf.js +415 -0
  142. package/dist/tilt.d.ts +62 -0
  143. package/dist/tilt.js +186 -0
  144. package/dist/tmx.d.ts +151 -0
  145. package/dist/tmx.js +394 -0
  146. package/dist/ttf.d.ts +78 -0
  147. package/dist/ttf.js +568 -0
  148. package/dist/types.d.ts +90 -0
  149. package/dist/types.js +35 -0
  150. package/dist/usd.d.ts +2 -0
  151. package/dist/usd.js +2 -0
  152. package/dist/usd.worker.d.ts +1 -0
  153. package/dist/usdz.d.ts +50 -0
  154. package/dist/usdz.js +646 -0
  155. package/dist/util.d.ts +75 -0
  156. package/dist/util.js +241 -0
  157. package/dist/vdb.d.ts +111 -0
  158. package/dist/vdb.js +663 -0
  159. package/dist/vrml.d.ts +53 -0
  160. package/dist/vrml.js +532 -0
  161. package/dist/vtk-cells.d.ts +29 -0
  162. package/dist/vtk-cells.js +211 -0
  163. package/dist/vtk-legacy.d.ts +57 -0
  164. package/dist/vtk-legacy.js +439 -0
  165. package/dist/vtk-reader.d.ts +19 -0
  166. package/dist/vtk-reader.js +134 -0
  167. package/dist/vtk-xml.d.ts +96 -0
  168. package/dist/vtk-xml.js +578 -0
  169. package/dist/vtk.d.ts +13 -0
  170. package/dist/vtk.js +234 -0
  171. package/dist/woff-glyf.d.ts +17 -0
  172. package/dist/woff-glyf.js +215 -0
  173. package/dist/worker.d.ts +10 -0
  174. package/dist/worker.js +93 -0
  175. package/dist/workers/usd.js +3 -0
  176. package/dist/xfile.d.ts +99 -0
  177. package/dist/xfile.js +706 -0
  178. package/dist/xml.d.ts +107 -0
  179. package/dist/xml.js +843 -0
  180. package/dist/xyz.d.ts +16 -0
  181. package/dist/xyz.js +110 -0
  182. package/dist/zip.d.ts +38 -0
  183. package/dist/zip.js +150 -0
  184. package/package.json +246 -6
package/dist/mtl.js ADDED
@@ -0,0 +1,469 @@
1
+ import { Material, createMesh, loadTexture as loadMaterialTexture, } from '@margoengine/materials';
2
+ import { SRGBToLinear } from '@margoengine/math/color';
3
+ import { DEFAULT_MAX_BYTES, fetchBytes } from './load.js';
4
+ import { assetURL } from './shared/asset-url.js';
5
+ import { captureScene } from './shared/scene-scope.js';
6
+ import { DEFAULT_MAX_MATERIAL_BYTES, parseOBJ, } from './obj.js';
7
+ import { LoaderError } from './types.js';
8
+ import { resolvePath } from './util.js';
9
+ const F = 'MTL';
10
+ /** Map statements with a material slot; every other map key is reported as unused. */
11
+ const SLOTTED_MAPS = new Set(['map_Kd', 'map_Ke', 'map_d', 'bump']);
12
+ /** PBR-extension statements read from `extras` (compared in lower case); other extras are reported as unused. */
13
+ const READ_EXTRAS = new Set(['norm', 'pr', 'pm']);
14
+ const clamp01 = (v) => Math.min(1, Math.max(0, v));
15
+ /** One sRGB channel as written in the file to linear light: non-finite becomes 0, then clamped to [0, 1]. */
16
+ const linear = (v) => SRGBToLinear(Number.isFinite(v) ? clamp01(v) : 0);
17
+ const linear3 = (c) => [linear(c[0]), linear(c[1]), linear(c[2])];
18
+ /** Value of the first extension statement named `keyword` (any case), or undefined. */
19
+ function extra(m, keyword) {
20
+ return m.extras?.find((s) => s.keyword.toLowerCase() === keyword)?.value;
21
+ }
22
+ /** First number of an extension statement's value, or NaN. */
23
+ function extraNumber(m, keyword) {
24
+ const value = extra(m, keyword);
25
+ return value === undefined ? Number.NaN : Number(value.trim().split(/\s+/)[0]);
26
+ }
27
+ /**
28
+ * Roughness from the Phong exponent Ns. Walter, Marschner, Li and Torrance, "Microfacet Models for Refraction
29
+ * through Rough Surfaces" (EGSR 2007) §5.2 match Blinn-Phong exponent Ns to a Beckmann width alpha with
30
+ * alpha^2 = 2 / (Ns + 2); glTF 2.0 metallic-roughness uses alpha = roughness^2, so roughness = (2 / (Ns + 2))^(1/4).
31
+ * Ns 0 gives 1, 10 about 0.64, 100 about 0.37, 1000 about 0.21.
32
+ */
33
+ const roughnessFromNs = (ns) => clamp01((2 / (Math.max(0, ns) + 2)) ** 0.25);
34
+ /** The folder of the material's library, recovered from a map whose resolved path ends with its file name. */
35
+ function libraryFolder(m) {
36
+ for (const map of Object.values(m.maps ?? {})) {
37
+ const file = resolvePath('_', map.file);
38
+ if (file && map.path.endsWith(file))
39
+ return map.path.slice(0, map.path.length - file.length);
40
+ }
41
+ return '';
42
+ }
43
+ /** Reads a `norm` statement like a map statement: `-bm n`, `-o u [v [w]]`, `-s u [v [w]]`, `-clamp on|off`, file. */
44
+ function parseNorm(value) {
45
+ const tokens = value.trim().split(/\s+/).filter(Boolean), options = {};
46
+ let i = 0;
47
+ const numbers = (fill) => {
48
+ const out = [fill, fill, fill];
49
+ for (let k = 0; k < 3 && i < tokens.length && Number.isFinite(Number(tokens[i])); k++)
50
+ out[k] = Number(tokens[i++]);
51
+ return out;
52
+ };
53
+ while (i < tokens.length && tokens[i].startsWith('-')) {
54
+ const option = tokens[i++];
55
+ if (option === '-bm')
56
+ options.bm = Number(tokens[i++]);
57
+ else if (option === '-o')
58
+ options.o = numbers(0);
59
+ else if (option === '-s')
60
+ options.s = numbers(1);
61
+ else if (option === '-clamp')
62
+ options.clamp = tokens[i++] === 'on';
63
+ else
64
+ i++; // an option this reader does not use: skip its value
65
+ }
66
+ return { file: tokens.slice(i).join(' '), options };
67
+ }
68
+ /** The `new Material` options of one MTL material (section "MTL material format", illumination models included). */
69
+ function materialOptions(m, doubleSided) {
70
+ const unlit = m.illum === 0, options = { doubleSided };
71
+ if (unlit)
72
+ options.shading = 'basic';
73
+ options.color = m.Kd ? linear3(m.Kd) : [1, 1, 1];
74
+ const written = m.d !== undefined ? m.d : m.Tr !== undefined ? 1 - m.Tr : 1, opacity = Number.isFinite(written) ? clamp01(written) : 1;
75
+ options.opacity = opacity;
76
+ if (opacity < 1 || m.maps?.map_d)
77
+ options.transparent = true;
78
+ if (unlit)
79
+ return options;
80
+ const emit = m.Ke ? [...m.Ke] : m.maps?.map_Ke ? [1, 1, 1] : undefined;
81
+ if (emit) {
82
+ const peak = Math.max(emit[0], emit[1], emit[2]);
83
+ if (peak > 1) {
84
+ for (let k = 0; k < 3; k++)
85
+ emit[k] /= peak;
86
+ options.emissive = linear3(emit);
87
+ options.emissiveIntensity = peak;
88
+ }
89
+ else
90
+ options.emissive = linear3(emit);
91
+ }
92
+ const pr = extraNumber(m, 'pr');
93
+ if (Number.isFinite(pr))
94
+ options.roughness = clamp01(pr);
95
+ else if (m.illum === 1 || (m.Ks && m.Ks.every((c) => c <= 0)) || m.Ns === undefined || !Number.isFinite(m.Ns))
96
+ options.roughness = 1;
97
+ else
98
+ options.roughness = roughnessFromNs(m.Ns);
99
+ const pm = extraNumber(m, 'pm');
100
+ options.metalness = Number.isFinite(pm) ? clamp01(pm) : 0;
101
+ return options;
102
+ }
103
+ /** The maps a material uses, in slot (and load) order: map, alphaMap, emissiveMap, bump or normal, norm. */
104
+ function mapUses(m, bump) {
105
+ const maps = m.maps ?? {}, uses = [];
106
+ const add = (slot, map, colorSpace) => {
107
+ if (map)
108
+ uses.push({ slot, path: map.path, options: map.options ?? {}, colorSpace });
109
+ };
110
+ add('map', maps.map_Kd, 'srgb');
111
+ add('alphaMap', maps.map_d, 'linear');
112
+ if (m.illum === 0)
113
+ return uses;
114
+ add('emissiveMap', maps.map_Ke, 'srgb');
115
+ add(bump === 'normal' ? 'normalMap' : 'bumpMap', maps.bump, 'linear');
116
+ const norm = extra(m, 'norm');
117
+ if (norm !== undefined) {
118
+ const { file, options } = parseNorm(norm);
119
+ if (file)
120
+ add('normalMap', { path: resolvePath(`${libraryFolder(m)}_`, file), options }, 'linear');
121
+ }
122
+ return uses;
123
+ }
124
+ /** What a material says that Margo materials cannot show, as warnings. */
125
+ function unusedWarnings(m) {
126
+ const out = [];
127
+ for (const key of Object.keys(m.maps ?? {}))
128
+ if (!SLOTTED_MAPS.has(key))
129
+ out.push(`${key} has no Margo material slot; it is not used`);
130
+ for (const s of m.extras ?? [])
131
+ if (!READ_EXTRAS.has(s.keyword.toLowerCase()))
132
+ out.push(`${s.keyword} has no Margo material equivalent; it is not used`);
133
+ if (m.Ka)
134
+ out.push('Ka (ambient colour) has no Margo material equivalent; it is not used');
135
+ if (m.Ks && m.Ks.some((c) => c > 0) && m.illum !== 0)
136
+ out.push('Ks (specular colour) only sets whether there is a highlight; roughness comes from Ns');
137
+ return out;
138
+ }
139
+ /**
140
+ * Builds one materials `Material` per `newmtl` of `parseMTL` output (or `parseOBJ`'s `materials`), mapped to
141
+ * metallic-roughness: `Kd` is the base colour (sRGB in the file, linear in the material), `d` (else 1 - `Tr`) the
142
+ * opacity, `Ke` the emission (a peak above 1 moves into `emissiveIntensity`), and roughness comes from the Phong
143
+ * exponent `Ns` as (2 / (Ns + 2))^(1/4) (Walter et al. 2007's Blinn-Phong to Beckmann match with glTF's
144
+ * alpha = roughness^2). The PBR extension's `Pr`, `Pm` and `norm` are read when present. `illum 0` is unlit.
145
+ * `map_Kd`, `map_d`, `map_Ke`, `bump` and `norm` load as textures, each (file, colour space, wrap) once; their `-o`
146
+ * and `-s` become the slot's UV transform and `-clamp on` a clamped wrap. A map that fails to load is a warning.
147
+ * Rejects with `TypeError` / `RangeError` for bad arguments and with a `LoaderError` (code `'aborted'`) when
148
+ * `signal` aborts; whatever was built is disposed first.
149
+ */
150
+ export async function createMTLMaterials(mtl, options = {}) {
151
+ if (!Array.isArray(mtl))
152
+ throw new TypeError('createMTLMaterials mtl is not an array of materials; pass parseMTL output or obj.materials');
153
+ const opts = options ?? {}, bump = opts.bump ?? 'height';
154
+ if (bump !== 'height' && bump !== 'normal')
155
+ throw new RangeError(`createMTLMaterials bump ${JSON.stringify(bump)} is not 'height' or 'normal'; pass one of them`);
156
+ if (opts.loadTexture !== undefined && typeof opts.loadTexture !== 'function')
157
+ throw new TypeError('createMTLMaterials loadTexture is not a function; pass (url, options) => Promise<Texture>');
158
+ const load = opts.loadTexture ?? loadMaterialTexture, signal = opts.signal, get = opts.fetch, doubleSided = opts.doubleSided ?? false;
159
+ const materials = new Map(), warnings = [], arrived = [];
160
+ let disposed = false;
161
+ const warn = (message) => {
162
+ if (!warnings.includes(message))
163
+ warnings.push(message);
164
+ };
165
+ const set = {
166
+ materials,
167
+ textures: [],
168
+ warnings,
169
+ dispose() {
170
+ disposed = true;
171
+ for (const material of materials.values())
172
+ material.dispose();
173
+ for (const texture of arrived)
174
+ texture.dispose();
175
+ },
176
+ };
177
+ const abortError = () => new LoaderError(F, 'aborted', 'aborted while loading textures');
178
+ let base;
179
+ /** The URL of a map path, or undefined (with a warning) when the URL policy refuses it. */
180
+ const urlOf = (path) => {
181
+ if (base === undefined) {
182
+ const from = opts.baseUrl ?? globalThis.location?.href;
183
+ try {
184
+ base = new URL(String(from)).href;
185
+ }
186
+ catch {
187
+ throw new TypeError(`createMTLMaterials baseUrl ${JSON.stringify(String(from))} is not an absolute URL; pass the .mtl (or .obj) URL to resolve maps against`);
188
+ }
189
+ }
190
+ // data: URIs make no request; everything else must stay inside the base's directory or an allowed prefix.
191
+ if (/^data:/i.test(path))
192
+ return path;
193
+ try {
194
+ return assetURL(path, base, opts.allowedURLs, 'MTL texture').href;
195
+ }
196
+ catch (error) {
197
+ warn(`${error.message}; its maps are left out`);
198
+ return undefined;
199
+ }
200
+ };
201
+ // One request per (colour space, wrap, URL), in first-use order.
202
+ const requests = new Map(), assignments = [];
203
+ const request = (url, colorSpace, wrap) => {
204
+ const key = `${colorSpace} ${wrap} ${url}`;
205
+ if (requests.has(key))
206
+ return key;
207
+ const entry = {
208
+ promise: Promise.resolve()
209
+ .then(() => load(url, { colorSpace, wrapS: wrap, wrapT: wrap, signal, ...(get ? { fetch: get } : {}) }))
210
+ .then((texture) => {
211
+ if (disposed) {
212
+ texture.dispose();
213
+ return undefined;
214
+ }
215
+ arrived.push(texture);
216
+ entry.texture = texture;
217
+ return texture;
218
+ }, (error) => {
219
+ if (signal?.aborted)
220
+ throw abortError();
221
+ warn(`texture ${url} could not be loaded (${error?.message ?? error}); its maps are left out`);
222
+ return undefined;
223
+ }),
224
+ };
225
+ requests.set(key, entry);
226
+ return key;
227
+ };
228
+ let stopListening = () => { };
229
+ try {
230
+ for (const m of mtl) {
231
+ if (!m || typeof m.name !== 'string' || materials.has(m.name))
232
+ continue;
233
+ const material = new Material(materialOptions(m, doubleSided));
234
+ materials.set(m.name, material);
235
+ for (const message of unusedWarnings(m))
236
+ warn(message);
237
+ for (const use of mapUses(m, bump)) {
238
+ const wrap = use.options.clamp ? 'clamp' : 'repeat', url = urlOf(use.path);
239
+ if (url === undefined)
240
+ continue;
241
+ assignments.push({ material, slot: use.slot, key: request(url, use.colorSpace, wrap) });
242
+ if (use.slot === 'bumpMap' && Number.isFinite(use.options.bm))
243
+ material.bumpScale = use.options.bm;
244
+ const [ou = 0, ov = 0] = use.options.o ?? [], [su = 1, sv = 1] = use.options.s ?? [];
245
+ if (ou !== 0 || ov !== 0 || su !== 1 || sv !== 1)
246
+ material.setUVTransform({ offset: [ou, ov], scale: [su, sv] }, use.slot);
247
+ }
248
+ }
249
+ const all = Promise.all([...requests.values()].map((r) => r.promise));
250
+ if (signal) {
251
+ const aborted = new Promise((_, reject) => {
252
+ const onAbort = () => reject(abortError());
253
+ if (signal.aborted)
254
+ onAbort();
255
+ else {
256
+ signal.addEventListener('abort', onAbort, { once: true });
257
+ stopListening = () => signal.removeEventListener('abort', onAbort);
258
+ }
259
+ });
260
+ all.catch(() => { });
261
+ await Promise.race([all, aborted]);
262
+ }
263
+ else
264
+ await all;
265
+ for (const { material, slot, key } of assignments) {
266
+ const texture = requests.get(key)?.texture;
267
+ if (texture)
268
+ material[slot] = texture;
269
+ }
270
+ set.textures = [...requests.values()].flatMap((r) => (r.texture ? [r.texture] : []));
271
+ return set;
272
+ }
273
+ catch (error) {
274
+ set.dispose();
275
+ throw error;
276
+ }
277
+ finally {
278
+ stopListening();
279
+ }
280
+ }
281
+ /** A unit normal, or +z for a zero or non-finite one (materials meshes reject zero normals). */
282
+ function unit(out, at, x, y, z) {
283
+ const length = Math.hypot(x, y, z);
284
+ if (length > 0 && Number.isFinite(length)) {
285
+ out[at] = x / length;
286
+ out[at + 1] = y / length;
287
+ out[at + 2] = z / length;
288
+ }
289
+ else {
290
+ out[at] = 0;
291
+ out[at + 1] = 0;
292
+ out[at + 2] = 1;
293
+ }
294
+ }
295
+ /**
296
+ * Smooth vertex normals per OBJ position: each triangle's area-weighted face normal is summed into the positions its
297
+ * corners came from, so corners split by UV seams share one normal.
298
+ */
299
+ function smoothNormals(positions, indices, origin) {
300
+ const vertices = positions.length / 3, from = (v) => (origin ? origin[v] : v);
301
+ let slots = 0;
302
+ for (let v = 0; v < vertices; v++)
303
+ slots = Math.max(slots, from(v) + 1);
304
+ const sums = new Float64Array(slots * 3);
305
+ for (let t = 0; t + 2 < indices.length; t += 3) {
306
+ const a = indices[t] * 3, b = indices[t + 1] * 3, c = indices[t + 2] * 3, e1x = positions[b] - positions[a], e1y = positions[b + 1] - positions[a + 1], e1z = positions[b + 2] - positions[a + 2], e2x = positions[c] - positions[a], e2y = positions[c + 1] - positions[a + 1], e2z = positions[c + 2] - positions[a + 2], nx = e1y * e2z - e1z * e2y, ny = e1z * e2x - e1x * e2z, nz = e1x * e2y - e1y * e2x;
307
+ for (const corner of [indices[t], indices[t + 1], indices[t + 2]]) {
308
+ const s = from(corner) * 3;
309
+ sums[s] += nx;
310
+ sums[s + 1] += ny;
311
+ sums[s + 2] += nz;
312
+ }
313
+ }
314
+ const normals = new Float32Array(vertices * 3);
315
+ for (let v = 0; v < vertices; v++) {
316
+ const s = from(v) * 3;
317
+ unit(normals, v * 3, sums[s], sums[s + 1], sums[s + 2]);
318
+ }
319
+ return normals;
320
+ }
321
+ /**
322
+ * Turns a parsed OBJ and its materials into materials-ready geometry plus one material per slot, without a GPU:
323
+ * groups map to materials by their `usemtl` name. Positions and indices are the OBJ's own arrays. Normals are the
324
+ * OBJ's (normalised) or, without them, smooth normals shared across UV seams; zero normals become +z. UVs go back to
325
+ * OBJ's v-up orientation for flipY textures, and vertex colours from sRGB to linear. Throws a `LoaderError` (code
326
+ * `'unsupported'`) for an OBJ without faces and `TypeError` when `materials` is neither a Map nor a set.
327
+ */
328
+ export function prepareOBJMesh(obj, materials, options = {}) {
329
+ if (!obj || obj.kind !== 'mesh' || !obj.indices)
330
+ throw new LoaderError('OBJ', 'unsupported', 'the OBJ has no faces to draw as a mesh; draw its points with pointsToGeometry instead');
331
+ const lookup = materials instanceof Map
332
+ ? materials
333
+ : materials && materials.materials instanceof Map
334
+ ? materials.materials
335
+ : undefined;
336
+ if (!lookup)
337
+ throw new TypeError('prepareOBJMesh materials is not a Map or material set; pass createMTLMaterials output');
338
+ const { positions, indices } = obj, vertices = positions.length / 3;
339
+ let normals;
340
+ if (obj.normals) {
341
+ normals = new Float32Array(vertices * 3);
342
+ for (let v = 0; v < vertices; v++)
343
+ unit(normals, v * 3, obj.normals[v * 3], obj.normals[v * 3 + 1], obj.normals[v * 3 + 2]);
344
+ }
345
+ else
346
+ normals = smoothNormals(positions, indices, obj.positionIndices);
347
+ const geometry = { positions, normals, indices };
348
+ if (obj.uvs) {
349
+ const uvs = Float32Array.from(obj.uvs);
350
+ for (let i = 1; i < uvs.length; i += 2)
351
+ uvs[i] = 1 - uvs[i];
352
+ geometry.uvs = uvs;
353
+ }
354
+ if (obj.colors)
355
+ geometry.colors = obj.colors.map((c) => linear(c));
356
+ const slots = [], slotOf = new Map(), groups = [];
357
+ let fallback = options?.fallback;
358
+ const source = obj.groups?.length ? obj.groups : [{ start: 0, count: indices.length, material: undefined }];
359
+ for (const group of source) {
360
+ if (!group.count)
361
+ continue;
362
+ let material = group.material === undefined ? undefined : lookup.get(group.material);
363
+ if (!material)
364
+ material = fallback ??= new Material();
365
+ let index = slotOf.get(material);
366
+ if (index === undefined) {
367
+ index = slots.push(material) - 1;
368
+ slotOf.set(material, index);
369
+ }
370
+ groups.push({ start: group.start, count: group.count, materialIndex: index });
371
+ }
372
+ geometry.groups = groups;
373
+ return { geometry, materials: slots };
374
+ }
375
+ /**
376
+ * `prepareOBJMesh`, then materials' `createMesh` with one material slot per OBJ material. Dispose the mesh with
377
+ * `destroy()`; the materials stay owned by their set.
378
+ */
379
+ export function createOBJMesh(engine, obj, materials, options = {}) {
380
+ const prepared = prepareOBJMesh(obj, materials, options);
381
+ return createMesh(engine, prepared.geometry, prepared.materials, { renderOrder: options?.renderOrder ?? 0 });
382
+ }
383
+ /**
384
+ * Loads a textured OBJ in one call: fetches the OBJ, then each `mtllib` relative to it, builds the materials with
385
+ * `createMTLMaterials` (textures relative to their library) and the mesh with `createOBJMesh`. A library that cannot
386
+ * be read is a warning. The OBJ is untrusted: its `mtllib` files and textures load only from the OBJ's directory or
387
+ * an `allowedURLs` prefix (a library elsewhere throws a `LoaderError` with code `'url'`, a texture elsewhere is a
388
+ * warning), `init` (headers, credentials) goes only to the OBJ's own origin, and the libraries share the
389
+ * `maxMaterialLibraries` and `maxMaterialBytes` budget (code `'limit'`). Throws `TypeError` when `url` is not absolute
390
+ * and there is no page URL, and the `LoaderError` of a failed fetch or parse. When the mesh cannot be built,
391
+ * everything loaded is disposed first.
392
+ */
393
+ export async function loadOBJ(engine, url, options = {}) {
394
+ const opts = options ?? {};
395
+ let objUrl;
396
+ try {
397
+ objUrl = new URL(String(url), globalThis.location?.href).href;
398
+ }
399
+ catch {
400
+ throw new TypeError(`loadOBJ url ${JSON.stringify(String(url))} is not an absolute URL; pass the full .obj URL`);
401
+ }
402
+ const fetchOptions = {
403
+ signal: opts.signal,
404
+ maxBytes: opts.maxBytes,
405
+ fetch: opts.fetch,
406
+ init: opts.init,
407
+ };
408
+ // The mesh is made after the awaits below: it goes in the scene this call started in.
409
+ const scope = captureScene(engine), bytes = await fetchBytes(objUrl, fetchOptions);
410
+ const origin = new URL(objUrl).origin, perFile = opts.maxBytes ?? DEFAULT_MAX_BYTES, budget = opts.maxMaterialBytes ?? DEFAULT_MAX_MATERIAL_BYTES;
411
+ let spent = 0;
412
+ const obj = await parseOBJ(bytes, {
413
+ resolve: async (path) => {
414
+ let library;
415
+ try {
416
+ library = assetURL(path, objUrl, opts.allowedURLs, 'OBJ mtllib');
417
+ }
418
+ catch (error) {
419
+ throw new LoaderError('OBJ', 'url', error.message);
420
+ }
421
+ // Headers and credentials are the caller's for the OBJ's own origin; an allowed library elsewhere gets none.
422
+ // The fetch stops at whatever is left of the libraries' shared budget.
423
+ const content = await fetchBytes(library, {
424
+ ...fetchOptions,
425
+ init: library.origin === origin ? opts.init : undefined,
426
+ maxBytes: Math.max(0, Math.min(perFile, budget - spent)),
427
+ });
428
+ spent += content.length;
429
+ return content;
430
+ },
431
+ signal: opts.signal,
432
+ maxVertices: opts.maxVertices,
433
+ maxTriangles: opts.maxTriangles,
434
+ maxMaterialLibraries: opts.maxMaterialLibraries,
435
+ maxMaterialBytes: opts.maxMaterialBytes,
436
+ });
437
+ const set = await createMTLMaterials(obj.materials, { ...opts, baseUrl: objUrl });
438
+ const ownFallback = opts.fallback ? undefined : new Material(), fallback = opts.fallback ?? ownFallback;
439
+ let mesh;
440
+ try {
441
+ mesh = scope.run(() => createOBJMesh(engine, obj, set, { fallback, renderOrder: opts.renderOrder ?? 0 }));
442
+ }
443
+ catch (error) {
444
+ set.dispose();
445
+ ownFallback?.dispose();
446
+ throw error;
447
+ }
448
+ // The materials, textures and fallback made here go with the mesh, also when its scene removes it (removePlugin,
449
+ // scene or engine disposal) before dispose() is called.
450
+ let released = false;
451
+ const release = () => {
452
+ if (released)
453
+ return;
454
+ released = true;
455
+ set.dispose();
456
+ ownFallback?.dispose();
457
+ };
458
+ mesh.onDispose(release);
459
+ return {
460
+ mesh,
461
+ obj,
462
+ materials: set,
463
+ warnings: [...obj.warnings, ...set.warnings],
464
+ dispose() {
465
+ mesh.destroy();
466
+ release();
467
+ },
468
+ };
469
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Area-weighted smooth vertex normals for an indexed triangle list. Vertices touched by no
3
+ * non-degenerate triangle get (0, 0, 1).
4
+ */
5
+ export declare function computeVertexNormals(positions: ArrayLike<number>, indices: ArrayLike<number>): Float32Array;
6
+ /** Unit face normal of triangle `a, b, c` (vertex indices), or (0, 0, 1) when degenerate. */
7
+ export declare function faceNormal(positions: ArrayLike<number>, a: number, b: number, c: number): [number, number, number];
@@ -0,0 +1,31 @@
1
+ import { accumulateNormals } from './shared/normals.js';
2
+ /**
3
+ * Area-weighted smooth vertex normals for an indexed triangle list. Vertices touched by no
4
+ * non-degenerate triangle get (0, 0, 1).
5
+ */
6
+ export function computeVertexNormals(positions, indices) {
7
+ const normals = accumulateNormals(positions, indices, new Float64Array(positions.length));
8
+ const out = new Float32Array(positions.length);
9
+ for (let v = 0; v < out.length; v += 3) {
10
+ const length = Math.hypot(normals[v], normals[v + 1], normals[v + 2]);
11
+ if (length > 0 && Number.isFinite(length)) {
12
+ out[v] = normals[v] / length;
13
+ out[v + 1] = normals[v + 1] / length;
14
+ out[v + 2] = normals[v + 2] / length;
15
+ }
16
+ else
17
+ out[v + 2] = 1;
18
+ }
19
+ return out;
20
+ }
21
+ /** Unit face normal of triangle `a, b, c` (vertex indices), or (0, 0, 1) when degenerate. */
22
+ export function faceNormal(positions, a, b, c) {
23
+ a *= 3;
24
+ b *= 3;
25
+ c *= 3;
26
+ const ux = positions[b] - positions[a], uy = positions[b + 1] - positions[a + 1], uz = positions[b + 2] - positions[a + 2];
27
+ const vx = positions[c] - positions[a], vy = positions[c + 1] - positions[a + 1], vz = positions[c + 2] - positions[a + 2];
28
+ const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
29
+ const length = Math.hypot(nx, ny, nz);
30
+ return length > 0 && Number.isFinite(length) ? [nx / length, ny / length, nz / length] : [0, 0, 1];
31
+ }
package/dist/nrrd.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ import { type AssetResolver } from './types.js';
2
+ import { type BinaryInput } from './util.js';
3
+ /** A sample type of a NRRD file, with the C spellings folded to one name. */
4
+ export type NRRDType = 'int8' | 'uint8' | 'int16' | 'uint16' | 'int32' | 'uint32' | 'int64' | 'uint64' | 'float32' | 'float64';
5
+ /** Samples in the file's own type; 64-bit integers arrive as `Float64Array`, exact up to 2^53. */
6
+ export type NRRDData = Int8Array<ArrayBuffer> | Uint8Array<ArrayBuffer> | Int16Array<ArrayBuffer> | Uint16Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | Float32Array<ArrayBuffer> | Float64Array<ArrayBuffer>;
7
+ /** Options of {@link parseNRRD}. */
8
+ export interface NRRDOptions {
9
+ /** Reads a detached `data file`, by the path written in the header. A `.nhdr` file needs this. Default none. */
10
+ resolve?: AssetResolver;
11
+ /** Maximum samples in the whole array. Default 536,870,912. */
12
+ maxSamples?: number;
13
+ signal?: AbortSignal;
14
+ }
15
+ /** What {@link parseNRRD} returns. Pass `data`, `dims` and `bounds` to `fig.volume()` of `@margoengine/sciviz`. */
16
+ export interface NRRDVolume {
17
+ /** Every sample, the first axis fastest. */
18
+ data: NRRDData;
19
+ type: NRRDType;
20
+ /** The size of every axis in the file, the fastest first. */
21
+ sizes: number[];
22
+ /** Grid size `[nx, ny, nz]` of the spatial axes, padded with 1 for a 1D or 2D file. */
23
+ dims: [number, number, number];
24
+ /** Samples per voxel: the product of the leading non-spatial axes, such as an RGB axis. 1 for a scalar volume. */
25
+ components: number;
26
+ /** Volumes in the file: the product of the axes after the spatial ones, such as time. 1 for one volume. */
27
+ frames: number;
28
+ /** Distance between samples along each spatial axis; 1 where the file gives none. */
29
+ spacing: [number, number, number];
30
+ /** `[0, (nx - 1) * sx, 0, (ny - 1) * sy, 0, (nz - 1) * sz]`: the true proportions, in `spacing` units. */
31
+ bounds: [number, number, number, number, number, number];
32
+ /** Column-major 4x4 from voxel index to `space` coordinates, with the file's origin, rotation and flips. */
33
+ matrix: Float64Array<ArrayBuffer>;
34
+ /** The `space` field, such as `left-posterior-superior`, when the file names one. */
35
+ space?: string;
36
+ /** Every header field by lower-case name, as written. Null prototype. */
37
+ fields: Record<string, string>;
38
+ /** `key:=value` pairs with their escapes undone. Null prototype. */
39
+ meta: Record<string, string>;
40
+ }
41
+ /**
42
+ * Reads a NRRD volume from a `.nrrd` file, or a `.nhdr` header with its detached data through `resolve`. Encodings are
43
+ * raw, ascii, hex, gzip and bzip2, with either byte order, `line skip` and `byte skip` (-1 for the end of a raw file)
44
+ * and one or many data files (a printf pattern or a `LIST`, with `subdim`). Data past what the header needs is
45
+ * ignored, and gzip decoding stops there. `space directions`, `space origin`, `spacings` and `kinds` set `dims`, `spacing`, `bounds` and
46
+ * `matrix`; a leading non-spatial axis is `components` and trailing ones are `frames`.
47
+ *
48
+ * @param input The file's bytes.
49
+ * @param options A resolver for detached data, the sample limit and an AbortSignal.
50
+ * @returns The samples in the file's own type and where they sit.
51
+ * @throws LoaderError with code `header`, `syntax`, `truncated`, `range`, `limit`, `aborted`, `zip` or `unsupported` (
52
+ * the block type, or detached data without `resolve`).
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { parseNRRD } from '@margoengine/loaders/nrrd';
57
+ *
58
+ * const header = 'NRRD0004\ntype: uint8\ndimension: 3\nsizes: 2 1 1\nspacings: 2 1 1\nencoding: ascii\n\n';
59
+ * const { data, dims, bounds } = await parseNRRD(new TextEncoder().encode(`${header}10 20\n`));
60
+ * console.log(data, dims, bounds);
61
+ * ```
62
+ */
63
+ export declare function parseNRRD(input: BinaryInput, options?: NRRDOptions): Promise<NRRDVolume>;