@es3d/es3d 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 (82) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +86 -3
  3. package/docs/REFERENCE.md +581 -0
  4. package/docs/SPEC.md +417 -0
  5. package/package.json +50 -4
  6. package/scripts/es3d-cli.mjs +377 -0
  7. package/src/cache/geometry-store.js +392 -0
  8. package/src/cache/mesh-bundle.js +123 -0
  9. package/src/cache/sha256.js +73 -0
  10. package/src/format/ast.js +238 -0
  11. package/src/format/colors.js +93 -0
  12. package/src/format/compact-parser.js +171 -0
  13. package/src/format/compact-tokenizer.js +165 -0
  14. package/src/format/errors.js +247 -0
  15. package/src/format/json.js +55 -0
  16. package/src/format/limits.js +14 -0
  17. package/src/format/parse.js +92 -0
  18. package/src/format/schema.js +617 -0
  19. package/src/format/serializer.js +333 -0
  20. package/src/format/validator.js +330 -0
  21. package/src/format/value-error.js +12 -0
  22. package/src/format/value-format.js +314 -0
  23. package/src/format/values.js +459 -0
  24. package/src/format/xml-parser.js +136 -0
  25. package/src/format/xml-tokenizer.js +237 -0
  26. package/src/geometry/contour.js +86 -0
  27. package/src/geometry/extrude.js +175 -0
  28. package/src/geometry/gear.js +85 -0
  29. package/src/geometry/geometry-cache.js +159 -0
  30. package/src/geometry/lod-error.js +178 -0
  31. package/src/geometry/mesh.js +458 -0
  32. package/src/geometry/primitives.js +299 -0
  33. package/src/geometry/registry.js +645 -0
  34. package/src/geometry/revolve.js +136 -0
  35. package/src/geometry/sweep.js +441 -0
  36. package/src/index.js +47 -0
  37. package/src/io/compression.js +67 -0
  38. package/src/io/convert.js +236 -0
  39. package/src/io/download.js +13 -0
  40. package/src/io/external-scene.js +127 -0
  41. package/src/io/file-loader.js +28 -0
  42. package/src/io/gltf.js +630 -0
  43. package/src/io/mesh-import.js +104 -0
  44. package/src/io/obj.js +352 -0
  45. package/src/io/step-brep.js +439 -0
  46. package/src/io/step-exact.js +1149 -0
  47. package/src/io/step.js +1418 -0
  48. package/src/io/stl.js +193 -0
  49. package/src/io/svg-import.js +787 -0
  50. package/src/material/materials.js +154 -0
  51. package/src/math/mat4.js +475 -0
  52. package/src/math/random.js +30 -0
  53. package/src/math/trig.js +65 -0
  54. package/src/math/vec3.js +81 -0
  55. package/src/optimize/optimizer.js +579 -0
  56. package/src/path/path-flatten.js +322 -0
  57. package/src/path/path-parser.js +332 -0
  58. package/src/path/shapes.js +129 -0
  59. package/src/path/triangulate.js +517 -0
  60. package/src/pipeline.js +74 -0
  61. package/src/render/camera.js +168 -0
  62. package/src/render/frame-builder.js +362 -0
  63. package/src/render/geometry-pool.js +149 -0
  64. package/src/render/lighting.js +149 -0
  65. package/src/render/orbit-controls.js +237 -0
  66. package/src/render/renderer.js +249 -0
  67. package/src/render/scroll-timeline.js +104 -0
  68. package/src/render/shaders/glsl.js +285 -0
  69. package/src/render/shaders/wgsl.js +252 -0
  70. package/src/render/stage.js +352 -0
  71. package/src/render/texture-cache.js +40 -0
  72. package/src/render/textures.js +223 -0
  73. package/src/render/webgl2/webgl2-backend.js +532 -0
  74. package/src/render/webgpu/webgpu-backend.js +480 -0
  75. package/src/scene/animation.js +171 -0
  76. package/src/scene/camera-constraints.js +117 -0
  77. package/src/scene/flatten.js +754 -0
  78. package/src/scene/picking.js +161 -0
  79. package/src/scene/scene-graph.js +320 -0
  80. package/src/transform/transform.js +211 -0
  81. package/src/wasm/kernels-binary.js +3 -0
  82. package/src/wasm/kernels.js +385 -0
@@ -0,0 +1,236 @@
1
+ // File conversion to and from ES3D, shared by the website's converter and
2
+ // the command-line tool. Works in browsers and in Node.
3
+ //
4
+ // const r = await importFiles([{ name: 'logo.svg', bytes }]); // → ES3D markup in r.text
5
+ // const out = exportFormat(r.text, 'glb', { baseName: 'logo' }); // → { files: [{ name, data, mime }] }
6
+
7
+ import { isGzip, gunzip } from './compression.js';
8
+ import { parse } from '../format/parse.js';
9
+ import { serialize } from '../format/serializer.js';
10
+ import { isGLB, glbToScene, gltfToScene, exportGLB } from './gltf.js';
11
+ import { objToScene, exportOBJ } from './obj.js';
12
+ import { isBinarySTL, isAsciiSTL, stlToScene, exportSTL } from './stl.js';
13
+ import { isSTEP, stepToScene, exportSTEP } from './step.js';
14
+ import { stepToExact } from './step-exact.js';
15
+ import { svgToES3D } from './svg-import.js';
16
+ import { sceneToMeshDocument } from './mesh-import.js';
17
+ import { compile } from '../pipeline.js';
18
+ import { exportableInstances } from './external-scene.js';
19
+
20
+ /** OBJ and STL repeat every copy's triangles; beyond this the file gets too large for a browser tab. */
21
+ const OBJ_TRIANGLE_LIMIT = 4e6;
22
+
23
+ export const INPUT_KINDS = {
24
+ es3d: 'ES3D text',
25
+ svg: 'SVG drawing',
26
+ obj: 'Wavefront OBJ',
27
+ stl: 'STL',
28
+ gltf: 'glTF (JSON)',
29
+ glb: 'glTF binary (GLB)',
30
+ step: 'STEP',
31
+ };
32
+
33
+ export const OUTPUT_FORMATS = {
34
+ es3d: { label: 'ES3D markup (.es3d)', ext: '.es3d', mime: 'model/vnd.es3d', text: true },
35
+ 'es3d-min': { label: 'ES3D markup, minified (.es3d)', ext: '.es3d', mime: 'model/vnd.es3d', text: true },
36
+ 'es3d-compact': { label: 'ES3D compact syntax (.es3d)', ext: '.es3d', mime: 'model/vnd.es3d', text: true },
37
+ glb: { label: 'glTF binary (.glb)', ext: '.glb', mime: 'model/gltf-binary' },
38
+ obj: { label: 'Wavefront OBJ + MTL (.obj)', ext: '.obj', mime: 'model/obj', text: true },
39
+ stl: { label: 'STL for 3D printing (.stl)', ext: '.stl', mime: 'model/stl' },
40
+ step: { label: 'STEP, tessellated (.step)', ext: '.step', mime: 'model/step', text: true },
41
+ };
42
+
43
+ /** Files that only accompany a main file (OBJ materials, glTF buffers and textures). */
44
+ const COMPANION = /\.(mtl|bin|png|jpe?g|webp|gif|ktx2|dds|tga|bmp)$/i;
45
+
46
+ const decode = (bytes) => new TextDecoder('utf-8').decode(bytes).replace(/^/, '');
47
+
48
+ /**
49
+ * The kind of a file, from its content first and its extension second.
50
+ * @returns {keyof INPUT_KINDS | null}
51
+ */
52
+ export function detectKind(name, bytes) {
53
+ if (isGLB(bytes)) return 'glb';
54
+ const ext = ((/\.([a-z0-9]+)$/i.exec(name) || [])[1] || '').toLowerCase();
55
+ const head = decode(bytes.subarray(0, 4096));
56
+ if (isSTEP(head)) return 'step';
57
+ if (isBinarySTL(bytes) && !['es3d', 'svg', 'obj', 'gltf'].includes(ext)) return 'stl';
58
+ const es3dText = /^\s*(<\?xml[^>]*\?>\s*)?(<!--[\s\S]*?-->\s*)*<es3d[\s>/]/.test(head) || /^\s*((\/\/[^\n]*|\/\*[\s\S]*?\*\/)\s*)*es3d\b/.test(head);
59
+ if (ext === 'es3d' || es3dText) return 'es3d';
60
+ if (ext === 'svg' || /<svg[\s>/]/.test(head)) return 'svg';
61
+ if (ext === 'stl' || isAsciiSTL(bytes)) return 'stl';
62
+ if (ext === 'gltf' || /^\s*\{[\s\S]*"asset"\s*:/.test(head)) return 'gltf';
63
+ if (ext === 'obj' || /^\s*(#[^\n]*\n\s*)*(mtllib|o|g|v|vt|vn|f|usemtl|s)\s/.test(head)) return 'obj';
64
+ if (ext === 'step' || ext === 'stp' || ext === 'p21') return 'step';
65
+ return null;
66
+ }
67
+
68
+ /** Options of the importers, with their defaults. */
69
+ export const IMPORT_DEFAULTS = {
70
+ svg: { size: 10, depth: 0.04, bevel: 0, strokes: true, base: false },
71
+ mesh: { precision: 'auto', normals: 'auto', uvs: true, smooth: 30 },
72
+ stl: { up: 'z' },
73
+ };
74
+
75
+ /**
76
+ * Convert input files into an ES3D document.
77
+ * @param {{name: string, bytes: Uint8Array}[]} files the main file plus companions (.mtl, .bin)
78
+ * @param {{svg?: object, mesh?: object, stl?: object}} [opts] see IMPORT_DEFAULTS
79
+ * @returns {Promise<{kind: string, name: string, title: string, text: string, warnings: string[], notes: string[]}>}
80
+ */
81
+ export async function importFiles(files, opts = {}) {
82
+ if (!files.length) throw new Error('No file was given.');
83
+ const list = [];
84
+ for (const f of files) {
85
+ let bytes = f.bytes instanceof Uint8Array ? f.bytes : new Uint8Array(f.bytes);
86
+ let name = f.name || 'untitled';
87
+ if (isGzip(bytes)) {
88
+ bytes = await gunzip(bytes);
89
+ name = name.replace(/\.svgz$/i, '.svg').replace(/\.gz$/i, '');
90
+ }
91
+ list.push({ name, bytes });
92
+ }
93
+ const main = list.find((f) => !COMPANION.test(f.name)) || list[0];
94
+ const companions = list.filter((f) => f !== main);
95
+ const kind = detectKind(main.name, main.bytes);
96
+ if (!kind) throw new Error(`${main.name}: unknown file type. The converter reads SVG, OBJ, STL, STEP (.step, .stp) and glTF (.gltf, .glb) and ES3D (.es3d) files.`);
97
+ const title = main.name.replace(/\.[^.]+$/, '') || 'untitled';
98
+ const svgOpts = { ...IMPORT_DEFAULTS.svg, ...(opts.svg || {}) };
99
+ const meshOpts = { ...IMPORT_DEFAULTS.mesh, ...(opts.mesh || {}) };
100
+ const stlOpts = { ...IMPORT_DEFAULTS.stl, ...(opts.stl || {}) };
101
+ const warnings = [];
102
+ const notes = [];
103
+ const meshDocument = (s, sourceHasNormals) => {
104
+ const normals = meshOpts.normals === 'auto' ? sourceHasNormals : !!meshOpts.normals;
105
+ const digits = meshOpts.precision === 'exact' ? null : meshOpts.precision;
106
+ if (!normals) notes.push(`Normals are not stored; viewers compute them with a ${meshOpts.smooth}° crease angle.`);
107
+ return sceneToMeshDocument(s.scene, s.meshOf, title, { digits, normals, uvs: meshOpts.uvs ? 'auto' : false, smooth: meshOpts.smooth });
108
+ };
109
+ let text;
110
+ switch (kind) {
111
+ case 'es3d':
112
+ text = decode(main.bytes);
113
+ break;
114
+ case 'svg': {
115
+ const r = svgToES3D(decode(main.bytes), { name: main.name, ...svgOpts });
116
+ text = r.text;
117
+ warnings.push(...r.warnings);
118
+ notes.push(`${r.stats.fills} filled shape${r.stats.fills === 1 ? '' : 's'} extruded, ${r.stats.strokes} stroke${r.stats.strokes === 1 ? '' : 's'} turned into tubes, ${r.stats.materials} material${r.stats.materials === 1 ? '' : 's'}.`);
119
+ break;
120
+ }
121
+ case 'obj': {
122
+ const objText = decode(main.bytes);
123
+ const lib = (/^mtllib\s+(.+?)\s*$/m.exec(objText) || [])[1];
124
+ const mtlFile = companions.find((f) => /\.mtl$/i.test(f.name) && (!lib || f.name.toLowerCase() === lib.split(/[\\/]/).pop().toLowerCase())) || companions.find((f) => /\.mtl$/i.test(f.name));
125
+ if (lib && !mtlFile) warnings.push(`The material library ${lib} was not given; default colors are used. Select the .obj and .mtl files together to keep the materials.`);
126
+ if (companions.some((f) => /\.(png|jpe?g|webp|gif|tga|bmp)$/i.test(f.name)) || /^\s*map_/m.test(mtlFile ? decode(mtlFile.bytes) : '')) warnings.push('Textures are not converted; the materials keep their base colors.');
127
+ const s = objToScene(objText, mtlFile ? decode(mtlFile.bytes) : '');
128
+ const hasNormals = /^vn\s/m.test(objText);
129
+ text = meshDocument(s, hasNormals);
130
+ break;
131
+ }
132
+ case 'stl': {
133
+ const s = stlToScene(main.bytes, { up: stlOpts.up, smooth: meshOpts.smooth });
134
+ if (s.info.degenerate) warnings.push(`${s.info.degenerate} degenerate triangle${s.info.degenerate === 1 ? '' : 's'} (with two identical corners) ${s.info.degenerate === 1 ? 'was' : 'were'} dropped.`);
135
+ notes.push(`${s.info.format === 'binary' ? 'Binary' : 'ASCII'} STL with ${s.info.triangles.toLocaleString('en-US')} triangles, welded to ${s.info.vertices.toLocaleString('en-US')} vertices${stlOpts.up === 'z' ? '; turned from Z-up to Y-up' : ''}.`);
136
+ text = meshDocument(s, false);
137
+ break;
138
+ }
139
+ case 'step': {
140
+ // a B-rep (what CAD tools export) becomes ES3D shapes; tessellated STEP stays a mesh
141
+ const exact = stepToExact(main.bytes, { up: stlOpts.up, name: title });
142
+ if (exact) {
143
+ notes.push(exact.note);
144
+ text = exact.text;
145
+ break;
146
+ }
147
+ const s = stepToScene(main.bytes, { up: stlOpts.up, smooth: meshOpts.smooth });
148
+ if (s.info.curved) warnings.push(`${s.info.curved} curved face${s.info.curved === 1 ? '' : 's'} skipped. ES3D tessellates planar faces, circles and cylinders; re-export other curved solids as tessellated STEP or STL to keep them.`);
149
+ const unit = s.info.unit ? ` Coordinates are in ${s.info.unit} and were not rescaled.` : ' The file does not name a length unit; coordinates were used as written.';
150
+ notes.push(`STEP with ${s.info.triangles.toLocaleString('en-US')} triangles in ${s.info.meshes} mesh${s.info.meshes === 1 ? '' : 'es'}${stlOpts.up === 'z' ? '; turned from Z-up to Y-up' : ''}.${unit}`);
151
+ text = meshDocument(s, false);
152
+ break;
153
+ }
154
+ case 'gltf':
155
+ case 'glb': {
156
+ const resources = Object.fromEntries(companions.map((f) => [f.name, f.bytes]));
157
+ const s = kind === 'glb' ? glbToScene(main.bytes) : gltfToScene(decode(main.bytes), resources);
158
+ if (s.skipped.textures) warnings.push(`Textures are not converted (${s.skipped.textures} textured material${s.skipped.textures === 1 ? '' : 's'}); the materials keep their base colors.`);
159
+ if (s.skipped.points) warnings.push(`${s.skipped.points} point cloud primitive${s.skipped.points === 1 ? ' was' : 's were'} skipped.`);
160
+ const lines = s.scene.geometries.filter((g) => g.kind === 'lines').length;
161
+ if (lines) warnings.push(`${lines} line primitive${lines === 1 ? ' was' : 's were'} skipped (ES3D meshes hold triangles).`);
162
+ if ((s.json.skins || []).length || (s.json.animations || []).length) warnings.push('Skins and animations are not converted; the model is shown in its rest pose.');
163
+ if (s.json.extensionsRequired && s.json.extensionsRequired.length) warnings.push(`The file requires extensions that are not supported: ${s.json.extensionsRequired.join(', ')}.`);
164
+ const hasNormals = (s.json.meshes || []).some((m) => m.primitives.some((p) => p.attributes && p.attributes.NORMAL !== undefined));
165
+ text = meshDocument(s, hasNormals);
166
+ break;
167
+ }
168
+ }
169
+ return { kind, name: main.name, title, text, warnings, notes };
170
+ }
171
+
172
+ /** Parse and validate ES3D text; throws with the first diagnostics on errors. */
173
+ function validDocument(source) {
174
+ const doc = parse(source);
175
+ if (!doc.ok) throw new Error(describeErrors(doc.diagnostics, doc.lineIndex));
176
+ return doc;
177
+ }
178
+
179
+ function describeErrors(diagnostics, lineIndex) {
180
+ const errors = diagnostics.filter((d) => d.severity === 'error');
181
+ const shown = errors.slice(0, 3).map((d) => d.format(lineIndex)).join('\n\n');
182
+ return `The ES3D document has ${errors.length} error${errors.length === 1 ? '' : 's'}:\n\n${shown}${errors.length > 3 ? `\n\n… and ${errors.length - 3} more` : ''}`;
183
+ }
184
+
185
+ /**
186
+ * Write an ES3D document in another format.
187
+ * @param {string|Uint8Array} source ES3D text
188
+ * @param {keyof OUTPUT_FORMATS} format
189
+ * @param {{baseName?: string, lod?: number, compiled?: object, instancing?: boolean}} [opts]
190
+ * compiled: an existing compile() result for the same source (saves compiling twice)
191
+ * @returns {{files: {name: string, data: Uint8Array|string, mime: string}[], triangles?: number}}
192
+ */
193
+ export function exportFormat(source, format, { baseName = 'scene', lod = 0, compiled = null, instancing = true } = {}) {
194
+ const spec = OUTPUT_FORMATS[format];
195
+ if (!spec) throw new Error(`Unknown output format ${format}.`);
196
+ const name = baseName + spec.ext;
197
+ const one = (data) => ({ files: [{ name, data, mime: spec.mime }] });
198
+ switch (format) {
199
+ case 'es3d':
200
+ return one(serialize(validDocument(source), { syntax: 'xml', pretty: true, comments: true }));
201
+ case 'es3d-min':
202
+ return one(serialize(validDocument(source), { syntax: 'xml', pretty: false }));
203
+ case 'es3d-compact':
204
+ return one(serialize(validDocument(source), { syntax: 'compact', pretty: true, comments: true }));
205
+ default: {
206
+ const r = compiled || compile(source);
207
+ if (!r.ok) throw new Error(describeErrors(r.diagnostics, r.doc && r.doc.lineIndex));
208
+ const meshOf = (e, l) => r.cache.mesh(e, Math.min(l, e.lods - 1));
209
+ if (format === 'glb') return one(exportGLB(r.scene, meshOf, { lod, instancing }));
210
+ if (format === 'obj') {
211
+ let triangles = 0;
212
+ for (const i of exportableInstances(r.scene)) {
213
+ const m = meshOf(r.scene.geometries[r.scene.geom[i]], lod);
214
+ if (m.kind === 'triangles') triangles += m.primitiveCount;
215
+ }
216
+ if (triangles > OBJ_TRIANGLE_LIMIT) throw new Error(`At this level of detail the scene has ${triangles.toLocaleString('en-US')} triangles, too many for an OBJ file (limit ${OBJ_TRIANGLE_LIMIT.toLocaleString('en-US')}). Choose a coarser detail, or glTF, which stores repeated shapes once.`);
217
+ }
218
+ if (format === 'stl') {
219
+ const s = exportSTL(r.scene, meshOf, { lod, name: baseName, maxTriangles: OBJ_TRIANGLE_LIMIT });
220
+ return { ...one(s.data), triangles: s.triangles };
221
+ }
222
+ if (format === 'step') {
223
+ const s = exportSTEP(r.scene, meshOf, { lod, name: baseName, maxTriangles: OBJ_TRIANGLE_LIMIT });
224
+ return { ...one(s.data), triangles: s.triangles };
225
+ }
226
+ const o = exportOBJ(r.scene, meshOf, { lod, name: baseName });
227
+ return {
228
+ files: [
229
+ { name, data: o.obj, mime: spec.mime },
230
+ { name: `${baseName}.mtl`, data: o.mtl, mime: 'text/plain' },
231
+ ],
232
+ triangles: o.triangles,
233
+ };
234
+ }
235
+ }
236
+ }
@@ -0,0 +1,13 @@
1
+ // Browser download helper.
2
+
3
+ export function download(name, data, mime = 'application/octet-stream') {
4
+ const blob = data instanceof Blob ? data : new Blob([data], { type: mime });
5
+ const url = URL.createObjectURL(blob);
6
+ const a = document.createElement('a');
7
+ a.href = url;
8
+ a.download = name;
9
+ document.body.appendChild(a);
10
+ a.click();
11
+ a.remove();
12
+ setTimeout(() => URL.revokeObjectURL(url), 2000);
13
+ }
@@ -0,0 +1,127 @@
1
+ // Shared helpers for exporters and importers of conventional mesh formats.
2
+
3
+ import { RenderScene } from '../scene/flatten.js';
4
+ import { Material, DEFAULT_MATERIAL_PARAMS } from '../material/materials.js';
5
+
6
+ /**
7
+ * Instances that a static exporter should write: every instance outside <lod>
8
+ * switches, and the most detailed alternative (child 0) inside them.
9
+ */
10
+ export function exportableInstances(scene) {
11
+ const sw = scene.lodSwitches;
12
+ const visible = new Uint8Array(sw.length);
13
+ for (let s = 0; s < sw.length; s++) {
14
+ const w = sw[s];
15
+ visible[s] = w.parent < 0 ? 1 : visible[w.parent] && w.parentChild === 0 ? 1 : 0;
16
+ }
17
+ const out = [];
18
+ for (let i = 0; i < scene.count; i++) {
19
+ const ln = scene.lodNode[i];
20
+ if (ln >= 0 && !(visible[ln] && scene.lodChild[i] === 0)) continue;
21
+ out.push(i);
22
+ }
23
+ return out;
24
+ }
25
+
26
+ /**
27
+ * Geometry indices that are drawn with a textured material. Exporters write
28
+ * texture coordinates only for these (with `uvs: 'auto'`): UVs of untextured
29
+ * procedural geometry are dead weight in a mesh file.
30
+ */
31
+ export function texturedGeometries(scene) {
32
+ const out = new Set();
33
+ for (let i = 0; i < scene.count; i++) {
34
+ const m = scene.materials[scene.mat[i]];
35
+ if (m && (m.map || m.normalMap)) out.add(scene.geom[i]);
36
+ }
37
+ return out;
38
+ }
39
+
40
+ /** Stable, unique names for materials (OBJ usemtl / glTF material names). */
41
+ export function materialNames(materials) {
42
+ const used = new Set();
43
+ return materials.map((m, i) => {
44
+ let base = String(m.name || `material${i}`).replace(/[^A-Za-z0-9_.-]/g, '_') || `material${i}`;
45
+ let name = base;
46
+ let k = 1;
47
+ while (used.has(name)) name = `${base}_${k++}`;
48
+ used.add(name);
49
+ return name;
50
+ });
51
+ }
52
+
53
+ /** Growable flat instance table (no per-instance allocations for large imports). */
54
+ export class InstanceTable {
55
+ constructor(capacity = 64) {
56
+ this.count = 0;
57
+ this.geom = new Int32Array(capacity);
58
+ this.mat = new Int32Array(capacity);
59
+ this.matrices = new Float64Array(capacity * 16);
60
+ }
61
+
62
+ push(geom, mat, matrix) {
63
+ if (this.count === this.geom.length) {
64
+ const cap = this.geom.length * 2;
65
+ const g = new Int32Array(cap), m = new Int32Array(cap), x = new Float64Array(cap * 16);
66
+ g.set(this.geom);
67
+ m.set(this.mat);
68
+ x.set(this.matrices);
69
+ this.geom = g;
70
+ this.mat = m;
71
+ this.matrices = x;
72
+ }
73
+ const i = this.count++;
74
+ this.geom[i] = geom;
75
+ this.mat[i] = mat;
76
+ const o = i * 16, x = this.matrices;
77
+ for (let k = 0; k < 16; k++) x[o + k] = matrix[k];
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Build a RenderScene from already tessellated meshes (OBJ / glTF imports).
83
+ * @param {{geometries: {mesh: import('../geometry/mesh.js').Mesh, key?: string}[],
84
+ * materials: object[], instances: InstanceTable}} data
85
+ * materials are parameter objects in the ES3D material model (sRGB colors)
86
+ */
87
+ export function buildExternalScene(data) {
88
+ const table = data.instances;
89
+ const scene = new RenderScene(Math.max(16, table.count));
90
+ scene.environment = { background: [0.09, 0.1, 0.12, 1], sky: [0.8, 0.86, 0.95, 1], ground: [0.25, 0.22, 0.2, 1], intensity: 0.5, exposure: 1 };
91
+ scene.materials = data.materials.map((p, i) => new Material({ ...DEFAULT_MATERIAL_PARAMS, ...p }, i, p.name || `material${i}`));
92
+ if (!scene.materials.length) scene.materials.push(new Material({ ...DEFAULT_MATERIAL_PARAMS }, 0, 'default'));
93
+ const entries = data.geometries.map((g, i) => ({
94
+ id: i + 1,
95
+ key: g.key || `external:${i}`,
96
+ kind: g.mesh.kind,
97
+ lods: 1,
98
+ doubleSided: false,
99
+ bounds: g.mesh.bounds,
100
+ meshes: [g.mesh],
101
+ }));
102
+ const gIndex = entries.map((e) => scene.geometryIndex(e));
103
+ const lastMat = scene.materials.length - 1;
104
+ const world = new Float64Array(16);
105
+ for (let i = 0; i < table.count; i++) {
106
+ for (let k = 0; k < 16; k++) world[k] = table.matrices[i * 16 + k];
107
+ scene.setInstance(i, gIndex[table.geom[i]], Math.min(table.mat[i], lastMat), world, 0, -1, 0);
108
+ }
109
+ scene.count = table.count;
110
+ if (!(scene.bounds.min[0] <= scene.bounds.max[0])) scene.bounds = { min: [-1, -1, -1], max: [1, 1, 1] };
111
+ scene.version++;
112
+ return { scene, meshOf: (entry) => entry.meshes[0] };
113
+ }
114
+
115
+ /** Trimmed fixed-point number formatting (used by text exporters). */
116
+ export function fixed(v, digits) {
117
+ if (!Number.isFinite(v)) return '0';
118
+ let s = v.toFixed(digits);
119
+ if (s.indexOf('.') >= 0) {
120
+ let e = s.length;
121
+ while (s.charCodeAt(e - 1) === 48) e--;
122
+ if (s.charCodeAt(e - 1) === 46) e--;
123
+ s = s.slice(0, e);
124
+ }
125
+ if (s === '-0') return '0';
126
+ return s;
127
+ }
@@ -0,0 +1,28 @@
1
+ // File loading for ES3D Studio: detects the content type from magic bytes and
2
+ // extension, transparently decompresses gzip, and converts foreign formats
3
+ // (SVG, OBJ, STL, STEP, glTF) into ES3D text with the same importers as the
4
+ // converter page, so they can be inspected and edited like any other document.
5
+
6
+ import { isGzip, gunzip } from './compression.js';
7
+ import { detectKind, importFiles, INPUT_KINDS } from './convert.js';
8
+
9
+ /**
10
+ * @param {File|{name:string, arrayBuffer:()=>Promise<ArrayBuffer>}} file
11
+ * @returns {Promise<{name:string, kind:string, text?:string, bytes:Uint8Array, originalSize:number, note?:string}>}
12
+ */
13
+ export async function loadFile(file) {
14
+ let bytes = new Uint8Array(await file.arrayBuffer());
15
+ const originalSize = bytes.length;
16
+ let name = file.name || 'untitled.es3d';
17
+ let note = '';
18
+ if (isGzip(bytes)) {
19
+ bytes = await gunzip(bytes);
20
+ name = name.replace(/\.svgz$/i, '.svg').replace(/\.gz$/i, '');
21
+ note = `decompressed from ${originalSize.toLocaleString('en-US')} gzip bytes`;
22
+ }
23
+ const kind = detectKind(name, bytes) || 'es3d';
24
+ if (kind === 'es3d') return { name, kind, text: new TextDecoder('utf-8').decode(bytes), bytes, originalSize, note };
25
+ const r = await importFiles([{ name, bytes }]);
26
+ const warn = r.warnings.length ? ` (${r.warnings.join(' ')})` : '';
27
+ return { name, kind, bytes, originalSize, text: r.text, note: (note ? note + '; ' : '') + `converted from ${INPUT_KINDS[kind]} to ES3D${warn}` };
28
+ }