@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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1198 -3
- package/dist/3dm.d.ts +161 -0
- package/dist/3dm.js +289 -0
- package/dist/3ds.d.ts +124 -0
- package/dist/3ds.js +392 -0
- package/dist/acclaim.d.ts +90 -0
- package/dist/acclaim.js +312 -0
- package/dist/amf.d.ts +45 -0
- package/dist/amf.js +256 -0
- package/dist/babylon.d.ts +197 -0
- package/dist/babylon.js +701 -0
- package/dist/common.d.ts +7 -0
- package/dist/common.js +6 -0
- package/dist/dae-animation.d.ts +66 -0
- package/dist/dae-animation.js +266 -0
- package/dist/dae-common.d.ts +95 -0
- package/dist/dae-common.js +226 -0
- package/dist/dae-controllers.d.ts +57 -0
- package/dist/dae-controllers.js +164 -0
- package/dist/dae-pose.d.ts +131 -0
- package/dist/dae-pose.js +381 -0
- package/dist/dae-scene.d.ts +203 -0
- package/dist/dae-scene.js +279 -0
- package/dist/dae.d.ts +161 -0
- package/dist/dae.js +633 -0
- package/dist/detect.d.ts +20 -0
- package/dist/detect.js +72 -0
- package/dist/dxf.d.ts +81 -0
- package/dist/dxf.js +774 -0
- package/dist/engine.d.ts +36 -0
- package/dist/engine.js +117 -0
- package/dist/font-opentype.d.ts +14 -0
- package/dist/font-opentype.js +33 -0
- package/dist/font-woff.d.ts +23 -0
- package/dist/font-woff.js +293 -0
- package/dist/font.d.ts +41 -0
- package/dist/font.js +26 -0
- package/dist/gcode.d.ts +55 -0
- package/dist/gcode.js +278 -0
- package/dist/geo-model.d.ts +84 -0
- package/dist/geo-model.js +220 -0
- package/dist/geo-mvt.d.ts +15 -0
- package/dist/geo-mvt.js +302 -0
- package/dist/geo-shp.d.ts +15 -0
- package/dist/geo-shp.js +234 -0
- package/dist/geo-xml.d.ts +6 -0
- package/dist/geo-xml.js +165 -0
- package/dist/geo.d.ts +8 -0
- package/dist/geo.js +59 -0
- package/dist/geometry.d.ts +60 -0
- package/dist/geometry.js +273 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.js +28 -0
- package/dist/kmz.d.ts +78 -0
- package/dist/kmz.js +173 -0
- package/dist/las.d.ts +92 -0
- package/dist/las.js +110 -0
- package/dist/ldraw.d.ts +118 -0
- package/dist/ldraw.js +474 -0
- package/dist/load.d.ts +72 -0
- package/dist/load.js +205 -0
- package/dist/lottie.d.ts +154 -0
- package/dist/lottie.js +893 -0
- package/dist/lwo.d.ts +81 -0
- package/dist/lwo.js +454 -0
- package/dist/lzf.d.ts +13 -0
- package/dist/lzf.js +56 -0
- package/dist/materialx.d.ts +120 -0
- package/dist/materialx.js +563 -0
- package/dist/md2.d.ts +52 -0
- package/dist/md2.js +112 -0
- package/dist/mmcif.d.ts +14 -0
- package/dist/mmcif.js +246 -0
- package/dist/mmd.d.ts +244 -0
- package/dist/mmd.js +958 -0
- package/dist/mocap.d.ts +71 -0
- package/dist/mocap.js +178 -0
- package/dist/molecule-common.d.ts +4 -0
- package/dist/molecule-common.js +54 -0
- package/dist/mtl.d.ts +120 -0
- package/dist/mtl.js +469 -0
- package/dist/normals.d.ts +7 -0
- package/dist/normals.js +31 -0
- package/dist/nrrd.d.ts +63 -0
- package/dist/nrrd.js +743 -0
- package/dist/nurbs.d.ts +118 -0
- package/dist/nurbs.js +265 -0
- package/dist/obj.d.ts +143 -0
- package/dist/obj.js +456 -0
- package/dist/off.d.ts +10 -0
- package/dist/off.js +155 -0
- package/dist/outline-font.d.ts +87 -0
- package/dist/outline-font.js +110 -0
- package/dist/outline.d.ts +20 -0
- package/dist/outline.js +215 -0
- package/dist/pcd.d.ts +34 -0
- package/dist/pcd.js +258 -0
- package/dist/pdb.d.ts +67 -0
- package/dist/pdb.js +126 -0
- package/dist/ply.d.ts +35 -0
- package/dist/ply.js +392 -0
- package/dist/polygon.d.ts +9 -0
- package/dist/polygon.js +49 -0
- package/dist/prwm.d.ts +24 -0
- package/dist/prwm.js +114 -0
- package/dist/render.d.ts +27 -0
- package/dist/render.js +153 -0
- package/dist/sfnt-cff.d.ts +37 -0
- package/dist/sfnt-cff.js +749 -0
- package/dist/sfnt-layout.d.ts +24 -0
- package/dist/sfnt-layout.js +266 -0
- package/dist/sfnt-reader.d.ts +28 -0
- package/dist/sfnt-reader.js +87 -0
- package/dist/sfnt-variation.d.ts +40 -0
- package/dist/sfnt-variation.js +318 -0
- package/dist/shared/asset-url.js +82 -0
- package/dist/shared/crc32.d.ts +2 -0
- package/dist/shared/crc32.js +47 -0
- package/dist/shared/errors.js +36 -0
- package/dist/shared/inflate.js +284 -0
- package/dist/shared/normals.js +26 -0
- package/dist/shared/scene-scope.js +56 -0
- package/dist/shared/trailing-data.js +42 -0
- package/dist/stl.d.ts +64 -0
- package/dist/stl.js +309 -0
- package/dist/svg.d.ts +90 -0
- package/dist/svg.js +1007 -0
- package/dist/tds.d.ts +2 -0
- package/dist/tds.js +2 -0
- package/dist/textures.d.ts +42 -0
- package/dist/textures.js +53 -0
- package/dist/threemf-lattice.d.ts +139 -0
- package/dist/threemf-lattice.js +514 -0
- package/dist/threemf-materials.d.ts +75 -0
- package/dist/threemf-materials.js +314 -0
- package/dist/threemf-mesh.d.ts +60 -0
- package/dist/threemf-mesh.js +201 -0
- package/dist/threemf.d.ts +101 -0
- package/dist/threemf.js +415 -0
- package/dist/tilt.d.ts +62 -0
- package/dist/tilt.js +186 -0
- package/dist/tmx.d.ts +151 -0
- package/dist/tmx.js +394 -0
- package/dist/ttf.d.ts +78 -0
- package/dist/ttf.js +568 -0
- package/dist/types.d.ts +90 -0
- package/dist/types.js +35 -0
- package/dist/usd.d.ts +2 -0
- package/dist/usd.js +2 -0
- package/dist/usd.worker.d.ts +1 -0
- package/dist/usdz.d.ts +50 -0
- package/dist/usdz.js +646 -0
- package/dist/util.d.ts +75 -0
- package/dist/util.js +241 -0
- package/dist/vdb.d.ts +111 -0
- package/dist/vdb.js +663 -0
- package/dist/vrml.d.ts +53 -0
- package/dist/vrml.js +532 -0
- package/dist/vtk-cells.d.ts +29 -0
- package/dist/vtk-cells.js +211 -0
- package/dist/vtk-legacy.d.ts +57 -0
- package/dist/vtk-legacy.js +439 -0
- package/dist/vtk-reader.d.ts +19 -0
- package/dist/vtk-reader.js +134 -0
- package/dist/vtk-xml.d.ts +96 -0
- package/dist/vtk-xml.js +578 -0
- package/dist/vtk.d.ts +13 -0
- package/dist/vtk.js +234 -0
- package/dist/woff-glyf.d.ts +17 -0
- package/dist/woff-glyf.js +215 -0
- package/dist/worker.d.ts +10 -0
- package/dist/worker.js +93 -0
- package/dist/workers/usd.js +3 -0
- package/dist/xfile.d.ts +99 -0
- package/dist/xfile.js +706 -0
- package/dist/xml.d.ts +107 -0
- package/dist/xml.js +843 -0
- package/dist/xyz.d.ts +16 -0
- package/dist/xyz.js +110 -0
- package/dist/zip.d.ts +38 -0
- package/dist/zip.js +150 -0
- package/package.json +246 -6
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { type LoadedGeometry, type LoadedGroup, type ParseLimits } from './types.js';
|
|
2
|
+
import { type BinaryInput, type Growable } from './util.js';
|
|
3
|
+
import { type ZipOptions } from './zip.js';
|
|
4
|
+
import { type XMLExternalOptions } from './xml.js';
|
|
5
|
+
/** Meters per 3MF unit. */
|
|
6
|
+
export declare const THREEMF_UNITS: Readonly<Record<string, number>>;
|
|
7
|
+
/**
|
|
8
|
+
* Options of parse3MF: size limits, zip limits, the unit handling, the component nesting depth and an AbortSignal.
|
|
9
|
+
*/
|
|
10
|
+
export interface ThreeMFOptions extends ParseLimits, XMLExternalOptions, Pick<ZipOptions, 'maxEntries' | 'maxEntryBytes' | 'maxRatio'> {
|
|
11
|
+
/** `'meters'` (default) scales by the model unit; `'file'` keeps the file's own units. */
|
|
12
|
+
units?: 'meters' | 'file';
|
|
13
|
+
/** Component nesting limit. Default 32. */
|
|
14
|
+
maxDepth?: number;
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
}
|
|
17
|
+
/** 3MF result: the merged triangle mesh plus the model unit and metadata. */
|
|
18
|
+
export interface ThreeMFResult extends LoadedGeometry {
|
|
19
|
+
kind: 'mesh';
|
|
20
|
+
unit: string;
|
|
21
|
+
/** `<metadata>` entries by name, in a null-prototype object (names come from the file). */
|
|
22
|
+
metadata: Record<string, string>;
|
|
23
|
+
}
|
|
24
|
+
type Color = [number, number, number, number];
|
|
25
|
+
interface MeshData {
|
|
26
|
+
vertices: Growable<Float32Array>;
|
|
27
|
+
triangles: Growable<Uint32Array>;
|
|
28
|
+
pid: Growable<Uint32Array>;
|
|
29
|
+
p: Growable<Uint32Array>;
|
|
30
|
+
}
|
|
31
|
+
interface ObjectData {
|
|
32
|
+
id: string;
|
|
33
|
+
name?: string;
|
|
34
|
+
type: string;
|
|
35
|
+
pid?: string;
|
|
36
|
+
pindex?: number;
|
|
37
|
+
mesh?: MeshData;
|
|
38
|
+
components: {
|
|
39
|
+
objectId: string;
|
|
40
|
+
path?: string;
|
|
41
|
+
transform: Float64Array;
|
|
42
|
+
}[];
|
|
43
|
+
}
|
|
44
|
+
interface Model {
|
|
45
|
+
unit: string;
|
|
46
|
+
objects: Map<string, ObjectData>;
|
|
47
|
+
properties: Map<string, Color[]>;
|
|
48
|
+
propertyIds: string[];
|
|
49
|
+
items: {
|
|
50
|
+
objectId: string;
|
|
51
|
+
path?: string;
|
|
52
|
+
transform: Float64Array;
|
|
53
|
+
}[];
|
|
54
|
+
metadata: Record<string, string>;
|
|
55
|
+
}
|
|
56
|
+
/** A parsed model part, as an extension of the 3MF reader sees it. */
|
|
57
|
+
export type ThreeMFModel = Model;
|
|
58
|
+
/** Package-part access for optional 3MF extensions that reference additional model streams. */
|
|
59
|
+
export interface ThreeMFReadContext {
|
|
60
|
+
models: ReadonlyMap<string, ThreeMFModel>;
|
|
61
|
+
loadModelPart(path: string): Promise<ThreeMFModel>;
|
|
62
|
+
}
|
|
63
|
+
/** What the materials entry adds to the 3MF reader: more elements, and one call per written triangle corner. */
|
|
64
|
+
export interface ThreeMFExtension {
|
|
65
|
+
/** Observe any element; returning true consumes it before the core-format reader (for 2D slice vertices). */
|
|
66
|
+
element?(model: ThreeMFModel, name: string, attributes: Record<string, string>): boolean | void;
|
|
67
|
+
/** One built object with its composed row-vector affine transform and output unit scale. */
|
|
68
|
+
instance?(model: ThreeMFModel, object: ObjectData, transform: Float64Array, scale: number, depth: number): void;
|
|
69
|
+
/** True only when a built native primitive provides geometry despite an empty triangle fallback. */
|
|
70
|
+
hasGeometry?(): boolean;
|
|
71
|
+
/** An element the reader does not know, with its attributes. */
|
|
72
|
+
open?(model: ThreeMFModel, name: string, attributes: Record<string, string>): void;
|
|
73
|
+
/** The end of any element. */
|
|
74
|
+
close?(model: ThreeMFModel, name: string): void;
|
|
75
|
+
/** Every model part is parsed; `read` returns a package part's bytes. */
|
|
76
|
+
ready?(read: (path: string) => Promise<Uint8Array>, context: ThreeMFReadContext): Promise<void>;
|
|
77
|
+
/** Extra text for a triangle's group key: triangles with different keys get different groups. */
|
|
78
|
+
bucket(model: ThreeMFModel, object: ObjectData, mesh: MeshData, triangle: number): string;
|
|
79
|
+
/** Corner `corner` of `triangle` has just been written as the next vertex. */
|
|
80
|
+
corner(model: ThreeMFModel, object: ObjectData, mesh: MeshData, triangle: number, corner: number): void;
|
|
81
|
+
/** A group is finished; `triangle` is its first triangle. */
|
|
82
|
+
group(group: LoadedGroup, model: ThreeMFModel, object: ObjectData, mesh: MeshData, triangle: number): void;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The property a triangle corner names: the triangle's own `pid`, else its object's, and the corner's index, else the
|
|
86
|
+
* triangle's first, else the object's `pindex`.
|
|
87
|
+
*/
|
|
88
|
+
export declare function cornerProperty(model: ThreeMFModel, object: ObjectData, mesh: MeshData, triangle: number, corner: number): {
|
|
89
|
+
id: string;
|
|
90
|
+
index: number;
|
|
91
|
+
} | undefined;
|
|
92
|
+
/**
|
|
93
|
+
* Parses a 3MF package (core specification, plus basematerials and the materials extension colorgroup, and
|
|
94
|
+
* production extension `p:path` components). Build item and component
|
|
95
|
+
* transforms are baked into the positions, which are converted to meters by default. The result has one
|
|
96
|
+
* group per build item object and color; `colors` is present only when some triangle has per-corner colors.
|
|
97
|
+
*/
|
|
98
|
+
export declare function parse3MF(input: BinaryInput, options?: ThreeMFOptions): Promise<ThreeMFResult>;
|
|
99
|
+
/** The reader behind {@link parse3MF}, with the hooks `@margoengine/loaders/threemf-materials` uses. */
|
|
100
|
+
export declare function read3MF(input: BinaryInput, options: ThreeMFOptions, extension?: ThreeMFExtension): Promise<ThreeMFResult>;
|
|
101
|
+
export {};
|
package/dist/threemf.js
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
import { LoaderError } from './types.js';
|
|
2
|
+
import { floats, limits, throwIfAborted, toBytes, uints } from './util.js';
|
|
3
|
+
import { readZipDirectory, readZipEntry } from './zip.js';
|
|
4
|
+
import { decodeXML, readXML } from './xml.js';
|
|
5
|
+
import { hexColor } from '@margoengine/math/color';
|
|
6
|
+
const F = '3MF';
|
|
7
|
+
const NONE = 0xffffffff;
|
|
8
|
+
// The per-file part cap shared by every loader that makes one mesh per part (docs/limits.md).
|
|
9
|
+
const MAX_INSTANCES = 100_000;
|
|
10
|
+
/** Meters per 3MF unit. */
|
|
11
|
+
export const THREEMF_UNITS = {
|
|
12
|
+
micron: 1e-6,
|
|
13
|
+
millimeter: 1e-3,
|
|
14
|
+
centimeter: 1e-2,
|
|
15
|
+
inch: 0.0254,
|
|
16
|
+
foot: 0.3048,
|
|
17
|
+
meter: 1,
|
|
18
|
+
};
|
|
19
|
+
const IDENTITY = new Float64Array([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]);
|
|
20
|
+
function parseColor(value) {
|
|
21
|
+
const rgba = hexColor(value?.trim() ?? '');
|
|
22
|
+
if (!rgba)
|
|
23
|
+
throw new LoaderError(F, 'syntax', `invalid color "${String(value).slice(0, 16)}"`);
|
|
24
|
+
return rgba;
|
|
25
|
+
}
|
|
26
|
+
function parseTransform(value) {
|
|
27
|
+
if (value === undefined)
|
|
28
|
+
return IDENTITY;
|
|
29
|
+
const parts = value.trim().split(/\s+/).map(Number);
|
|
30
|
+
if (parts.length !== 12 || !parts.every(Number.isFinite))
|
|
31
|
+
throw new LoaderError(F, 'syntax', `invalid transform "${value.slice(0, 64)}"`);
|
|
32
|
+
return new Float64Array(parts);
|
|
33
|
+
}
|
|
34
|
+
/** Row-vector composition: apply `a`, then `b`. */
|
|
35
|
+
function compose(a, b) {
|
|
36
|
+
const out = new Float64Array(12);
|
|
37
|
+
for (let r = 0; r < 4; r++)
|
|
38
|
+
for (let c = 0; c < 3; c++) {
|
|
39
|
+
let sum = r === 3 ? b[9 + c] : 0;
|
|
40
|
+
for (let k = 0; k < 3; k++)
|
|
41
|
+
sum += a[r * 3 + k] * b[k * 3 + c];
|
|
42
|
+
out[r * 3 + c] = sum;
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
const determinant = (m) => m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]);
|
|
47
|
+
function index(value, what) {
|
|
48
|
+
if (value === undefined)
|
|
49
|
+
return NONE;
|
|
50
|
+
const number = Number(value);
|
|
51
|
+
if (!Number.isSafeInteger(number) || number < 0 || number >= NONE)
|
|
52
|
+
throw new LoaderError(F, 'range', `invalid ${what} "${value.slice(0, 32)}"`);
|
|
53
|
+
return number;
|
|
54
|
+
}
|
|
55
|
+
function parseModel(xml, limit, extension, external) {
|
|
56
|
+
const model = {
|
|
57
|
+
unit: 'millimeter',
|
|
58
|
+
objects: new Map(),
|
|
59
|
+
properties: new Map(),
|
|
60
|
+
propertyIds: [],
|
|
61
|
+
items: [],
|
|
62
|
+
// Null prototype: <metadata name="..."> comes from the file (`__proto__`, `constructor`, `hasOwnProperty`).
|
|
63
|
+
metadata: Object.create(null),
|
|
64
|
+
};
|
|
65
|
+
const propertyIds = model.propertyIds;
|
|
66
|
+
let object, colors, metadataName, metadataText = '',
|
|
67
|
+
// 3MF Core 1.4 section 4.1: <metadata> inside an object's or item's <metadatagroup> describes that element, not
|
|
68
|
+
// the model, so only top-level entries reach the model metadata.
|
|
69
|
+
metadataGroups = 0;
|
|
70
|
+
let vertexCount = 0, triangleCount = 0, sawModel = false;
|
|
71
|
+
readXML(xml, {
|
|
72
|
+
open(name, a) {
|
|
73
|
+
if (extension?.element?.(model, name, a))
|
|
74
|
+
return;
|
|
75
|
+
switch (name) {
|
|
76
|
+
case 'model':
|
|
77
|
+
if (sawModel)
|
|
78
|
+
throw new LoaderError(F, 'syntax', 'nested <model>');
|
|
79
|
+
sawModel = true;
|
|
80
|
+
model.unit = a.unit ?? 'millimeter';
|
|
81
|
+
if (!Object.hasOwn(THREEMF_UNITS, model.unit))
|
|
82
|
+
throw new LoaderError(F, 'unsupported', `unknown unit "${model.unit.slice(0, 32)}"`);
|
|
83
|
+
break;
|
|
84
|
+
case 'metadatagroup':
|
|
85
|
+
metadataGroups++;
|
|
86
|
+
break;
|
|
87
|
+
case 'metadata':
|
|
88
|
+
metadataName = metadataGroups ? undefined : a.name;
|
|
89
|
+
metadataText = '';
|
|
90
|
+
break;
|
|
91
|
+
case 'basematerials':
|
|
92
|
+
case 'colorgroup':
|
|
93
|
+
if (!a.id)
|
|
94
|
+
throw new LoaderError(F, 'syntax', `<${name}> without id`);
|
|
95
|
+
colors = [];
|
|
96
|
+
model.properties.set(a.id, colors);
|
|
97
|
+
propertyIds.push(a.id);
|
|
98
|
+
break;
|
|
99
|
+
case 'base':
|
|
100
|
+
if (colors)
|
|
101
|
+
colors.push(a.displaycolor ? parseColor(a.displaycolor) : [1, 1, 1, 1]);
|
|
102
|
+
break;
|
|
103
|
+
case 'color':
|
|
104
|
+
if (colors)
|
|
105
|
+
colors.push(parseColor(a.color));
|
|
106
|
+
break;
|
|
107
|
+
case 'object': {
|
|
108
|
+
if (!a.id)
|
|
109
|
+
throw new LoaderError(F, 'syntax', '<object> without id');
|
|
110
|
+
if (model.objects.has(a.id))
|
|
111
|
+
throw new LoaderError(F, 'syntax', `duplicate object id ${a.id}`);
|
|
112
|
+
object = {
|
|
113
|
+
id: a.id,
|
|
114
|
+
name: a.name,
|
|
115
|
+
type: a.type ?? 'model',
|
|
116
|
+
pid: a.pid,
|
|
117
|
+
pindex: a.pindex === undefined ? undefined : index(a.pindex, 'pindex'),
|
|
118
|
+
components: [],
|
|
119
|
+
};
|
|
120
|
+
model.objects.set(a.id, object);
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
case 'mesh':
|
|
124
|
+
if (!object)
|
|
125
|
+
throw new LoaderError(F, 'syntax', '<mesh> outside <object>');
|
|
126
|
+
object.mesh = { vertices: floats(), triangles: uints(), pid: uints(), p: uints() };
|
|
127
|
+
break;
|
|
128
|
+
case 'vertex': {
|
|
129
|
+
const mesh = object?.mesh;
|
|
130
|
+
if (!mesh)
|
|
131
|
+
throw new LoaderError(F, 'syntax', '<vertex> outside <mesh>');
|
|
132
|
+
if (++vertexCount > limit.maxVertices)
|
|
133
|
+
throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${limit.maxVertices}`);
|
|
134
|
+
const x = Number(a.x), y = Number(a.y), z = Number(a.z);
|
|
135
|
+
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z))
|
|
136
|
+
throw new LoaderError(F, 'syntax', `vertex ${mesh.vertices.length / 3} of object ${object.id} has an invalid coordinate`);
|
|
137
|
+
mesh.vertices.push3(x, y, z);
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
case 'triangle': {
|
|
141
|
+
const mesh = object?.mesh;
|
|
142
|
+
if (!mesh)
|
|
143
|
+
throw new LoaderError(F, 'syntax', '<triangle> outside <mesh>');
|
|
144
|
+
if (++triangleCount > limit.maxTriangles)
|
|
145
|
+
throw new LoaderError(F, 'limit', `triangle count exceeds the limit of ${limit.maxTriangles}`);
|
|
146
|
+
const v1 = index(a.v1, 'v1'), v2 = index(a.v2, 'v2'), v3 = index(a.v3, 'v3');
|
|
147
|
+
if (v1 === NONE || v2 === NONE || v3 === NONE)
|
|
148
|
+
throw new LoaderError(F, 'syntax', `triangle ${mesh.triangles.length / 3} of object ${object.id} is missing v1, v2 or v3`);
|
|
149
|
+
mesh.triangles.push3(v1, v2, v3);
|
|
150
|
+
let pid = NONE;
|
|
151
|
+
if (a.pid !== undefined) {
|
|
152
|
+
pid = propertyIds.indexOf(a.pid);
|
|
153
|
+
if (pid < 0)
|
|
154
|
+
pid = NONE - 1;
|
|
155
|
+
}
|
|
156
|
+
mesh.pid.push(pid);
|
|
157
|
+
mesh.p.push3(index(a.p1, 'p1'), index(a.p2, 'p2'), index(a.p3, 'p3'));
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
case 'component': {
|
|
161
|
+
if (!object)
|
|
162
|
+
throw new LoaderError(F, 'syntax', '<component> outside <object>');
|
|
163
|
+
if (!a.objectid)
|
|
164
|
+
throw new LoaderError(F, 'syntax', '<component> without objectid');
|
|
165
|
+
object.components.push({ objectId: a.objectid, path: a['p:path'], transform: parseTransform(a.transform) });
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
case 'item':
|
|
169
|
+
if (!a.objectid)
|
|
170
|
+
throw new LoaderError(F, 'syntax', '<item> without objectid');
|
|
171
|
+
model.items.push({ objectId: a.objectid, path: a['p:path'], transform: parseTransform(a.transform) });
|
|
172
|
+
break;
|
|
173
|
+
default:
|
|
174
|
+
extension?.open?.(model, name, a);
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
close(name) {
|
|
178
|
+
extension?.close?.(model, name);
|
|
179
|
+
if (name === 'object')
|
|
180
|
+
object = undefined;
|
|
181
|
+
else if (name === 'basematerials' || name === 'colorgroup')
|
|
182
|
+
colors = undefined;
|
|
183
|
+
else if (name === 'metadatagroup')
|
|
184
|
+
metadataGroups--;
|
|
185
|
+
else if (name === 'metadata' && metadataName) {
|
|
186
|
+
model.metadata[metadataName] = metadataText.trim();
|
|
187
|
+
metadataName = undefined;
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
text(text) {
|
|
191
|
+
if (metadataName)
|
|
192
|
+
metadataText += text;
|
|
193
|
+
},
|
|
194
|
+
}, F, { external });
|
|
195
|
+
if (!sawModel)
|
|
196
|
+
throw new LoaderError(F, 'syntax', 'no <model> element');
|
|
197
|
+
return model;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* The property a triangle corner names: the triangle's own `pid`, else its object's, and the corner's index, else the
|
|
201
|
+
* triangle's first, else the object's `pindex`.
|
|
202
|
+
*/
|
|
203
|
+
export function cornerProperty(model, object, mesh, triangle, corner) {
|
|
204
|
+
const pid = mesh.pid.array[triangle], id = pid === NONE ? object.pid : pid === NONE - 1 ? undefined : model.propertyIds[pid];
|
|
205
|
+
if (id === undefined)
|
|
206
|
+
return undefined;
|
|
207
|
+
const first = mesh.p.array[triangle * 3], fallback = first !== NONE ? first : (object.pindex ?? NONE), own = mesh.p.array[triangle * 3 + corner], index = own === NONE ? fallback : own;
|
|
208
|
+
return index === NONE ? undefined : { id, index };
|
|
209
|
+
}
|
|
210
|
+
const normalizePath = (path) => path.replace(/\\/g, '/').replace(/^\/+/, '').toLowerCase();
|
|
211
|
+
/**
|
|
212
|
+
* Parses a 3MF package (core specification, plus basematerials and the materials extension colorgroup, and
|
|
213
|
+
* production extension `p:path` components). Build item and component
|
|
214
|
+
* transforms are baked into the positions, which are converted to meters by default. The result has one
|
|
215
|
+
* group per build item object and color; `colors` is present only when some triangle has per-corner colors.
|
|
216
|
+
*/
|
|
217
|
+
export async function parse3MF(input, options = {}) {
|
|
218
|
+
return read3MF(input, options);
|
|
219
|
+
}
|
|
220
|
+
/** The reader behind {@link parse3MF}, with the hooks `@margoengine/loaders/threemf-materials` uses. */
|
|
221
|
+
export async function read3MF(input, options, extension) {
|
|
222
|
+
const bytes = toBytes(input, F), limit = limits(options, F), maxDepth = options.maxDepth ?? 32;
|
|
223
|
+
if (!Number.isSafeInteger(maxDepth) || maxDepth < 0)
|
|
224
|
+
throw new LoaderError(F, 'range', 'maxDepth must be a non-negative integer');
|
|
225
|
+
if (options.units !== undefined && options.units !== 'meters' && options.units !== 'file')
|
|
226
|
+
throw new LoaderError(F, 'range', `units must be "meters" or "file"`);
|
|
227
|
+
if (bytes.length < 4 || bytes[0] !== 0x50 || bytes[1] !== 0x4b)
|
|
228
|
+
throw new LoaderError(F, 'header', 'not a ZIP package (missing PK signature)');
|
|
229
|
+
const entries = readZipDirectory(bytes, options);
|
|
230
|
+
const byPath = new Map();
|
|
231
|
+
for (const entry of entries)
|
|
232
|
+
byPath.set(normalizePath(entry.name), entry);
|
|
233
|
+
const read = async (path) => {
|
|
234
|
+
throwIfAborted(options.signal, F);
|
|
235
|
+
const entry = byPath.get(normalizePath(path));
|
|
236
|
+
if (!entry)
|
|
237
|
+
throw new LoaderError(F, 'syntax', `package part "${path.slice(0, 128)}" is missing`);
|
|
238
|
+
return readZipEntry(bytes, entry, options);
|
|
239
|
+
};
|
|
240
|
+
let rootPath = '3D/3dmodel.model';
|
|
241
|
+
if (byPath.has('_rels/.rels')) {
|
|
242
|
+
readXML(decodeXML(await read('_rels/.rels')), {
|
|
243
|
+
open(name, a) {
|
|
244
|
+
if (name === 'Relationship' && a.Type?.endsWith('/3dmodel') && a.Target)
|
|
245
|
+
rootPath = a.Target;
|
|
246
|
+
},
|
|
247
|
+
close() { },
|
|
248
|
+
}, F);
|
|
249
|
+
}
|
|
250
|
+
const models = new Map();
|
|
251
|
+
const load = async (path) => {
|
|
252
|
+
const key = normalizePath(path);
|
|
253
|
+
let model = models.get(key);
|
|
254
|
+
if (!model) {
|
|
255
|
+
if (models.size >= 1024)
|
|
256
|
+
throw new LoaderError(F, 'limit', 'too many model parts');
|
|
257
|
+
model = parseModel(decodeXML(await read(path)), limit, extension, options.external);
|
|
258
|
+
models.set(key, model);
|
|
259
|
+
}
|
|
260
|
+
return model;
|
|
261
|
+
};
|
|
262
|
+
const root = await load(rootPath);
|
|
263
|
+
// Load every model part referenced through p:path before the synchronous build walk.
|
|
264
|
+
const pending = [root];
|
|
265
|
+
while (pending.length) {
|
|
266
|
+
const model = pending.pop();
|
|
267
|
+
const paths = [
|
|
268
|
+
...model.items.map((i) => i.path),
|
|
269
|
+
...[...model.objects.values()].flatMap((o) => o.components.map((c) => c.path)),
|
|
270
|
+
];
|
|
271
|
+
for (const path of paths)
|
|
272
|
+
if (path && !models.has(normalizePath(path)))
|
|
273
|
+
pending.push(await load(path));
|
|
274
|
+
}
|
|
275
|
+
await extension?.ready?.(read, { models, loadModelPart: load });
|
|
276
|
+
throwIfAborted(options.signal, F);
|
|
277
|
+
const scale = options.units === 'file' ? 1 : THREEMF_UNITS[root.unit];
|
|
278
|
+
const resolveColors = (model, object, mesh, t) => [0, 1, 2].map((k) => {
|
|
279
|
+
const property = cornerProperty(model, object, mesh, t, k), group = property && model.properties.get(property.id);
|
|
280
|
+
if (!group)
|
|
281
|
+
return undefined;
|
|
282
|
+
if (property.index >= group.length)
|
|
283
|
+
throw new LoaderError(F, 'range', `property index ${property.index} is outside property group ${property.id} (${group.length} entries)`);
|
|
284
|
+
return group[property.index];
|
|
285
|
+
});
|
|
286
|
+
const object = (model, id, path) => {
|
|
287
|
+
const owner = path ? models.get(normalizePath(path)) : model;
|
|
288
|
+
const found = owner.objects.get(id);
|
|
289
|
+
if (!found)
|
|
290
|
+
throw new LoaderError(F, 'syntax', `object ${id.slice(0, 32)} is not defined${path ? ` in ${path.slice(0, 128)}` : ''}`);
|
|
291
|
+
return [owner, found];
|
|
292
|
+
};
|
|
293
|
+
// Pass 1: does any referenced triangle need per-corner colors?
|
|
294
|
+
let vertexColors = false;
|
|
295
|
+
for (const model of models.values())
|
|
296
|
+
for (const o of model.objects.values()) {
|
|
297
|
+
if (!o.mesh || vertexColors)
|
|
298
|
+
continue;
|
|
299
|
+
for (let t = 0; t < o.mesh.triangles.length / 3 && !vertexColors; t++) {
|
|
300
|
+
const [a, b, c] = resolveColors(model, o, o.mesh, t);
|
|
301
|
+
vertexColors = a !== b || b !== c;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
const positions = floats(), indices = uints(), colors = vertexColors ? floats() : undefined, groups = [];
|
|
305
|
+
const emitMesh = (model, o, mesh, m) => {
|
|
306
|
+
const vertexCount = mesh.vertices.length / 3, triangleCount = mesh.triangles.length / 3;
|
|
307
|
+
if (!vertexCount && !triangleCount)
|
|
308
|
+
return; // an empty mesh adds nothing; skip the per-instance bookkeeping
|
|
309
|
+
const tri = mesh.triangles.array, source = mesh.vertices.array;
|
|
310
|
+
for (let i = 0; i < tri.length && i < triangleCount * 3; i++)
|
|
311
|
+
if (tri[i] >= vertexCount)
|
|
312
|
+
throw new LoaderError(F, 'range', `triangle index ${tri[i]} of object ${o.id} is outside 0..${vertexCount - 1}`);
|
|
313
|
+
const corner = (v) => {
|
|
314
|
+
const x = source[v * 3], y = source[v * 3 + 1], z = source[v * 3 + 2];
|
|
315
|
+
return [
|
|
316
|
+
(x * m[0] + y * m[3] + z * m[6] + m[9]) * scale,
|
|
317
|
+
(x * m[1] + y * m[4] + z * m[7] + m[10]) * scale,
|
|
318
|
+
(x * m[2] + y * m[5] + z * m[8] + m[11]) * scale,
|
|
319
|
+
];
|
|
320
|
+
};
|
|
321
|
+
const flip = determinant(m) < 0;
|
|
322
|
+
// Bucket triangles by their first-corner color so each group has one uniform color.
|
|
323
|
+
const buckets = new Map(), suffix = (t) => (extension ? `|${extension.bucket(model, o, mesh, t)}` : '');
|
|
324
|
+
const triangleColors = [];
|
|
325
|
+
let colored = false;
|
|
326
|
+
for (let t = 0; t < triangleCount; t++) {
|
|
327
|
+
const c = resolveColors(model, o, mesh, t);
|
|
328
|
+
triangleColors.push(c);
|
|
329
|
+
if (c[0])
|
|
330
|
+
colored = true;
|
|
331
|
+
const key = (c[0] ? c[0].join(',') : '') + suffix(t);
|
|
332
|
+
let bucket = buckets.get(key);
|
|
333
|
+
if (!bucket)
|
|
334
|
+
buckets.set(key, (bucket = { color: c[0], triangles: [] }));
|
|
335
|
+
bucket.triangles.push(t);
|
|
336
|
+
}
|
|
337
|
+
const unweld = (!!colors && colored) || !!extension;
|
|
338
|
+
const base = positions.length / 3;
|
|
339
|
+
if (base + (unweld ? triangleCount * 3 : vertexCount) > limit.maxVertices)
|
|
340
|
+
throw new LoaderError(F, 'limit', `vertex count after instancing exceeds the limit of ${limit.maxVertices}`);
|
|
341
|
+
if (indices.length / 3 + triangleCount > limit.maxTriangles)
|
|
342
|
+
throw new LoaderError(F, 'limit', `triangle count after instancing exceeds the limit of ${limit.maxTriangles}`);
|
|
343
|
+
if (!unweld)
|
|
344
|
+
for (let v = 0; v < vertexCount; v++) {
|
|
345
|
+
positions.push3(...corner(v));
|
|
346
|
+
colors?.push3(1, 1, 1);
|
|
347
|
+
}
|
|
348
|
+
for (const bucket of buckets.values()) {
|
|
349
|
+
const start = indices.length;
|
|
350
|
+
for (const t of bucket.triangles) {
|
|
351
|
+
const order = flip ? [0, 2, 1] : [0, 1, 2];
|
|
352
|
+
for (const k of order) {
|
|
353
|
+
const v = tri[t * 3 + k];
|
|
354
|
+
if (unweld) {
|
|
355
|
+
indices.push(positions.length / 3);
|
|
356
|
+
positions.push3(...corner(v));
|
|
357
|
+
const color = triangleColors[t][k] ?? [1, 1, 1, 1];
|
|
358
|
+
colors?.push3(color[0], color[1], color[2]);
|
|
359
|
+
extension?.corner(model, o, mesh, t, k);
|
|
360
|
+
}
|
|
361
|
+
else
|
|
362
|
+
indices.push(base + v);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
const group = { start, count: indices.length - start, objectId: o.id };
|
|
366
|
+
if (o.name)
|
|
367
|
+
group.name = o.name;
|
|
368
|
+
if (bucket.color)
|
|
369
|
+
group.color = [...bucket.color];
|
|
370
|
+
extension?.group(group, model, o, mesh, bucket.triangles[0]);
|
|
371
|
+
groups.push(group);
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
const visiting = new Set();
|
|
375
|
+
// Components may reuse an object many times per level: bound the expanded instances, not just the depth, or
|
|
376
|
+
// fan-out^depth references to an empty object never finish (meshes are also bounded by the vertex limits).
|
|
377
|
+
let instances = 0;
|
|
378
|
+
const emit = (model, id, path, m, depth) => {
|
|
379
|
+
if (depth > maxDepth)
|
|
380
|
+
throw new LoaderError(F, 'limit', `components nest deeper than ${maxDepth}`);
|
|
381
|
+
if (++instances > MAX_INSTANCES)
|
|
382
|
+
throw new LoaderError(F, 'limit', `the build expands to more than ${MAX_INSTANCES} object instances`);
|
|
383
|
+
const [owner, o] = object(model, id, path);
|
|
384
|
+
if (visiting.has(o))
|
|
385
|
+
throw new LoaderError(F, 'syntax', `object ${id.slice(0, 32)} references itself through its components`);
|
|
386
|
+
if (o.mesh && o.components.length)
|
|
387
|
+
throw new LoaderError(F, 'syntax', `object ${id.slice(0, 32)} has both a mesh and components`);
|
|
388
|
+
visiting.add(o);
|
|
389
|
+
extension?.instance?.(owner, o, m, scale, depth);
|
|
390
|
+
if (o.mesh)
|
|
391
|
+
emitMesh(owner, o, o.mesh, m);
|
|
392
|
+
for (const component of o.components)
|
|
393
|
+
emit(owner, component.objectId, component.path, compose(component.transform, m), depth + 1);
|
|
394
|
+
visiting.delete(o);
|
|
395
|
+
};
|
|
396
|
+
for (const item of root.items) {
|
|
397
|
+
const [, o] = object(root, item.objectId, item.path);
|
|
398
|
+
if (o.type === 'other')
|
|
399
|
+
continue;
|
|
400
|
+
emit(root, item.objectId, item.path, item.transform, 0);
|
|
401
|
+
}
|
|
402
|
+
if (!indices.length && !extension?.hasGeometry?.())
|
|
403
|
+
throw new LoaderError(F, 'syntax', 'the build contains no triangles');
|
|
404
|
+
const result = {
|
|
405
|
+
kind: 'mesh',
|
|
406
|
+
positions: positions.result(),
|
|
407
|
+
indices: indices.result(),
|
|
408
|
+
groups,
|
|
409
|
+
unit: root.unit,
|
|
410
|
+
metadata: root.metadata,
|
|
411
|
+
};
|
|
412
|
+
if (colors)
|
|
413
|
+
result.colors = colors.result();
|
|
414
|
+
return result;
|
|
415
|
+
}
|
package/dist/tilt.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type LoadedGeometry, type ParseLimits } from './types.js';
|
|
2
|
+
import { type BinaryInput } from './util.js';
|
|
3
|
+
import { type ZipOptions } from './zip.js';
|
|
4
|
+
/** Options of {@link parseTilt}. */
|
|
5
|
+
export interface TiltOptions extends ParseLimits, Pick<ZipOptions, 'maxEntries' | 'maxEntryBytes' | 'maxRatio'> {
|
|
6
|
+
/**
|
|
7
|
+
* Metres per sketch unit. Default 0.1: Tilt Brush sketches are drawn in decimetres. The brush size scales with it.
|
|
8
|
+
*/
|
|
9
|
+
scale?: number;
|
|
10
|
+
/**
|
|
11
|
+
* Convert from Tilt Brush's left-handed Y-up space to the right-handed Y-up space of glTF and the engine, by
|
|
12
|
+
* mirroring Z and reversing the triangle winding to match. Default true.
|
|
13
|
+
*/
|
|
14
|
+
rightHanded?: boolean;
|
|
15
|
+
/** Ribbon width multiplier, over `brushSize * pressure`. Default 1. */
|
|
16
|
+
widthScale?: number;
|
|
17
|
+
/** Skip strokes with fewer control points than this. Default 2. */
|
|
18
|
+
minControlPoints?: number;
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
}
|
|
21
|
+
/** One stroke of a sketch, as stored. */
|
|
22
|
+
export interface TiltStroke {
|
|
23
|
+
/** Index into {@link LoadedTilt.brushes}. */
|
|
24
|
+
brushIndex: number;
|
|
25
|
+
/** The brush GUID from `metadata.json`'s `BrushIndex`, when the file has one. */
|
|
26
|
+
brush?: string;
|
|
27
|
+
/** RGBA in [0,1]. */
|
|
28
|
+
color: [number, number, number, number];
|
|
29
|
+
/** Brush size in sketch units. */
|
|
30
|
+
size: number;
|
|
31
|
+
/** Control points: position xyz, orientation quaternion xyzw (the controller's), pressure (1 when absent) and timestamp in ms (0 when absent). */
|
|
32
|
+
points: {
|
|
33
|
+
position: [number, number, number];
|
|
34
|
+
orientation: [number, number, number, number];
|
|
35
|
+
pressure: number;
|
|
36
|
+
timestamp: number;
|
|
37
|
+
}[];
|
|
38
|
+
}
|
|
39
|
+
/** The result of {@link parseTilt}. */
|
|
40
|
+
export interface LoadedTilt {
|
|
41
|
+
/** All strokes as flat ribbons: one group per drawn stroke, with the stroke's colour and `properties.brushIndex`. Draw it double-sided. */
|
|
42
|
+
geometry: LoadedGeometry;
|
|
43
|
+
/** Every stroke as stored, in sketch space, before scale and handedness. */
|
|
44
|
+
strokes: TiltStroke[];
|
|
45
|
+
/** The `BrushIndex` GUIDs of `metadata.json`, empty when absent. */
|
|
46
|
+
brushes: string[];
|
|
47
|
+
/** The parsed `metadata.json`, when the archive has one. */
|
|
48
|
+
metadata?: Record<string, unknown>;
|
|
49
|
+
/** The `data.sketch` version. */
|
|
50
|
+
version: number;
|
|
51
|
+
}
|
|
52
|
+
/** Reads `data.sketch` itself (the stroke stream), for callers that already unzipped the `.tilt`. */
|
|
53
|
+
export declare function parseTiltSketch(input: BinaryInput, options?: TiltOptions): {
|
|
54
|
+
strokes: TiltStroke[];
|
|
55
|
+
version: number;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Parses a `.tilt` file (a zip with a 16-byte header in front: `data.sketch` and `metadata.json`) into ribbons.
|
|
59
|
+
* A ribbon runs along a stroke's control points; its width is `size * pressure * widthScale` along the controller's
|
|
60
|
+
* local X axis, its normal is across it, and every vertex carries the stroke colour.
|
|
61
|
+
*/
|
|
62
|
+
export declare function parseTilt(input: BinaryInput, options?: TiltOptions): Promise<LoadedTilt>;
|