@margoengine/loaders 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1665 -2
- 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/crease.d.ts +7 -0
- package/dist/crease.js +67 -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-kinematics.d.ts +65 -0
- package/dist/dae-kinematics.js +461 -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 +166 -0
- package/dist/dae.js +644 -0
- package/dist/detect.d.ts +20 -0
- package/dist/detect.js +72 -0
- package/dist/dxf-hatch.d.ts +8 -0
- package/dist/dxf-hatch.js +346 -0
- package/dist/dxf-leaders.d.ts +59 -0
- package/dist/dxf-leaders.js +258 -0
- package/dist/dxf.d.ts +122 -0
- package/dist/dxf.js +985 -0
- package/dist/engine.d.ts +41 -0
- package/dist/engine.js +120 -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 +92 -0
- package/dist/gcode.js +369 -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 +125 -0
- package/dist/mtl.js +550 -0
- package/dist/normals.d.ts +7 -0
- package/dist/normals.js +31 -0
- package/dist/nrrd.d.ts +70 -0
- package/dist/nrrd.js +785 -0
- package/dist/nurbs.d.ts +118 -0
- package/dist/nurbs.js +265 -0
- package/dist/obj.d.ts +145 -0
- package/dist/obj.js +462 -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 +32 -0
- package/dist/render.js +181 -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 +45 -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-beam-reader.d.ts +19 -0
- package/dist/threemf-beam-reader.js +165 -0
- package/dist/threemf-beams.d.ts +52 -0
- package/dist/threemf-beams.js +268 -0
- package/dist/threemf-boolean-read.d.ts +10 -0
- package/dist/threemf-boolean-read.js +113 -0
- package/dist/threemf-boolean.d.ts +59 -0
- package/dist/threemf-boolean.js +20 -0
- package/dist/threemf-csg.d.ts +14 -0
- package/dist/threemf-csg.js +193 -0
- package/dist/threemf-displacement-read.d.ts +8 -0
- package/dist/threemf-displacement-read.js +213 -0
- package/dist/threemf-displacement.d.ts +71 -0
- package/dist/threemf-displacement.js +18 -0
- package/dist/threemf-evaluate.d.ts +36 -0
- package/dist/threemf-evaluate.js +86 -0
- package/dist/threemf-functions.d.ts +33 -0
- package/dist/threemf-functions.js +359 -0
- package/dist/threemf-lattice-mesh.d.ts +9 -0
- package/dist/threemf-lattice-mesh.js +115 -0
- package/dist/threemf-lattice.d.ts +139 -0
- package/dist/threemf-lattice.js +379 -0
- package/dist/threemf-levelset.d.ts +23 -0
- package/dist/threemf-levelset.js +105 -0
- package/dist/threemf-materials.d.ts +162 -0
- package/dist/threemf-materials.js +497 -0
- package/dist/threemf-mesh.d.ts +75 -0
- package/dist/threemf-mesh.js +422 -0
- package/dist/threemf-secure.d.ts +50 -0
- package/dist/threemf-secure.js +153 -0
- package/dist/threemf-tessellate.d.ts +37 -0
- package/dist/threemf-tessellate.js +277 -0
- package/dist/threemf-volume-colour.d.ts +25 -0
- package/dist/threemf-volume-colour.js +233 -0
- package/dist/threemf-volume-sample.d.ts +8 -0
- package/dist/threemf-volume-sample.js +65 -0
- package/dist/threemf-volumetric-read.d.ts +15 -0
- package/dist/threemf-volumetric-read.js +539 -0
- package/dist/threemf-volumetric.d.ts +177 -0
- package/dist/threemf-volumetric.js +28 -0
- package/dist/threemf.d.ts +170 -0
- package/dist/threemf.js +609 -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 +108 -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 +289 -4
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
import { Material, Texture, createMesh, } from '@margoengine/materials';
|
|
2
|
+
import { layered } from '@margoengine/materials/layered';
|
|
3
|
+
import { creasedNormals } from '@margoengine/geometry/utils';
|
|
4
|
+
import { SRGBToLinear } from '@margoengine/math/color';
|
|
5
|
+
import { computeVertexNormals } from './normals.js';
|
|
6
|
+
import { LoaderError } from './types.js';
|
|
7
|
+
import { throwIfAborted } from './util.js';
|
|
8
|
+
const F = '3MF';
|
|
9
|
+
const wrap = (style) => style === 'mirror' ? 'mirror' : style === 'clamp' || style === 'none' ? 'clamp' : 'repeat';
|
|
10
|
+
async function decode(texture, signal) {
|
|
11
|
+
// Pixels as stored: the spec reads colour as sRGB and alpha as linear, unpremultiplied.
|
|
12
|
+
const image = await createImageBitmap(new Blob([texture.data.slice()], { type: texture.contentType }), {
|
|
13
|
+
colorSpaceConversion: 'none',
|
|
14
|
+
premultiplyAlpha: 'none',
|
|
15
|
+
});
|
|
16
|
+
throwIfAborted(signal, F);
|
|
17
|
+
const nearest = texture.filter === 'nearest', filter = nearest ? 'nearest' : 'linear';
|
|
18
|
+
return new Texture(image, {
|
|
19
|
+
wrapS: wrap(texture.tileStyleU),
|
|
20
|
+
wrapT: wrap(texture.tileStyleV),
|
|
21
|
+
minFilter: filter,
|
|
22
|
+
magFilter: filter,
|
|
23
|
+
mipmaps: !nearest,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The roughness and metalness maps of one group as the single glTF-layout map a material reads (roughness in green,
|
|
28
|
+
* metalness in blue); a channel left out stays white, so the material's number stands alone. Both samplers of the
|
|
29
|
+
* extension are read texel by texel with `addressing`, the colour texture's; images of two sizes meet at the larger one.
|
|
30
|
+
*/
|
|
31
|
+
async function finishMap(loaded, channels, addressing, signal) {
|
|
32
|
+
const { decodeImage } = await import('@margoengine/decoders/image'), images = new Map(), used = [channels.roughness, channels.metalness].filter((channel) => channel !== undefined);
|
|
33
|
+
for (const { texture } of used) {
|
|
34
|
+
if (images.has(texture))
|
|
35
|
+
continue;
|
|
36
|
+
const source = loaded.textures[texture];
|
|
37
|
+
if (!source)
|
|
38
|
+
throw new LoaderError(F, 'range', `a group names texture ${texture}, outside textures`);
|
|
39
|
+
throwIfAborted(signal, F);
|
|
40
|
+
images.set(texture, await decodeImage(source.data));
|
|
41
|
+
}
|
|
42
|
+
const width = Math.max(...[...images.values()].map((image) => image.width)), height = Math.max(...[...images.values()].map((image) => image.height)), data = new Uint8Array(width * height * 4).fill(255), { tileStyleU, tileStyleV, filter } = addressing, nearest = filter === 'nearest';
|
|
43
|
+
// One axis of a texel position, wrapped as the texture is.
|
|
44
|
+
const wrapped = (i, size, style) => {
|
|
45
|
+
if (wrap(style) === 'repeat')
|
|
46
|
+
return ((i % size) + size) % size;
|
|
47
|
+
if (wrap(style) === 'mirror') {
|
|
48
|
+
const m = ((i % (size * 2)) + size * 2) % (size * 2);
|
|
49
|
+
return m < size ? m : size * 2 - 1 - m;
|
|
50
|
+
}
|
|
51
|
+
return Math.min(size - 1, Math.max(0, i));
|
|
52
|
+
};
|
|
53
|
+
const fill = ({ texture, from, value }, to) => {
|
|
54
|
+
const image = images.get(texture);
|
|
55
|
+
// Rows are stored bottom first: raw texels put row 0 at v = 0, where an image's last row is.
|
|
56
|
+
for (let y = 0; y < height; y++)
|
|
57
|
+
for (let x = 0; x < width; x++) {
|
|
58
|
+
const sx = ((x + 0.5) / width) * image.width - 0.5, sy = ((height - y - 0.5) / height) * image.height - 0.5, x0 = Math.floor(sx), y0 = Math.floor(sy),
|
|
59
|
+
// Between two sizes, blend the four texels around the point, or take the nearest for a nearest texture.
|
|
60
|
+
fx = nearest ? Math.round(sx - x0) : sx - x0, fy = nearest ? Math.round(sy - y0) : sy - y0, texel = (i, j) => image.data[(wrapped(j, image.height, tileStyleV) * image.width + wrapped(i, image.width, tileStyleU)) * 4 + from], sampled = (texel(x0, y0) * (1 - fx) + texel(x0 + 1, y0) * fx) * (1 - fy) +
|
|
61
|
+
(texel(x0, y0 + 1) * (1 - fx) + texel(x0 + 1, y0 + 1) * fx) * fy;
|
|
62
|
+
data[(y * width + x) * 4 + to] = Math.round(value(sampled));
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
if (channels.roughness)
|
|
66
|
+
fill(channels.roughness, 1);
|
|
67
|
+
if (channels.metalness)
|
|
68
|
+
fill(channels.metalness, 2);
|
|
69
|
+
const sampling = nearest ? 'nearest' : 'linear';
|
|
70
|
+
return new Texture({ data, width, height }, {
|
|
71
|
+
colorSpace: 'linear',
|
|
72
|
+
wrapS: wrap(tileStyleU),
|
|
73
|
+
wrapT: wrap(tileStyleV),
|
|
74
|
+
minFilter: sampling,
|
|
75
|
+
magFilter: sampling,
|
|
76
|
+
mipmaps: !nearest,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The maps a group's display properties sample into the glTF layout: metallic ones from red, or roughness from red and
|
|
81
|
+
* metalness from green when both name one resource (section 7.4), and 1 - glossiness from the alpha of the specular
|
|
82
|
+
* map, or the red of its own (section 7.3). A number given in the options leaves its channel out. A metallic factor up
|
|
83
|
+
* to 1 stays the material's number; one above 1 is applied to the texels, which stay at most 1.
|
|
84
|
+
*/
|
|
85
|
+
function channelsOf({ metallic, specular }, options) {
|
|
86
|
+
const scaled = (factor) => (texel) => Math.min(255, texel * factor), out = {};
|
|
87
|
+
if (metallic?.roughnessTexture !== undefined) {
|
|
88
|
+
const { roughnessTexture, metalnessTexture } = metallic;
|
|
89
|
+
if (options.roughness === undefined)
|
|
90
|
+
out.roughness = { texture: roughnessTexture, from: 0, value: scaled(Math.max(1, metallic.roughness)) };
|
|
91
|
+
if (options.metalness === undefined)
|
|
92
|
+
out.metalness = {
|
|
93
|
+
texture: metalnessTexture,
|
|
94
|
+
from: metalnessTexture === roughnessTexture ? 1 : 0,
|
|
95
|
+
value: scaled(Math.max(1, metallic.metalness)),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
if (specular?.glossinessTexture !== undefined && options.roughness === undefined) {
|
|
99
|
+
const { glossinessTexture, specularTexture, glossiness } = specular, gloss = scaled(glossiness);
|
|
100
|
+
out.roughness = {
|
|
101
|
+
texture: glossinessTexture,
|
|
102
|
+
from: glossinessTexture === specularTexture ? 3 : 0,
|
|
103
|
+
value: (texel) => 255 - gloss(texel),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The mean path through each translucent object, in mesh units: 4 V / S over its triangles, the mean chord of a convex
|
|
110
|
+
* solid (Cauchy; Santalo, "Integral Geometry and Geometric Probability", 1976). An open mesh has no volume to speak of.
|
|
111
|
+
*/
|
|
112
|
+
function meanPaths({ positions, indices, groups }) {
|
|
113
|
+
const sums = new Map();
|
|
114
|
+
for (const { objectId, translucent } of groups)
|
|
115
|
+
if (translucent)
|
|
116
|
+
sums.set(objectId, { volume: 0, area: 0, origin: [] });
|
|
117
|
+
for (const group of groups) {
|
|
118
|
+
const sum = sums.get(group.objectId);
|
|
119
|
+
if (!sum)
|
|
120
|
+
continue;
|
|
121
|
+
for (let i = group.start; i < group.start + group.count; i += 3) {
|
|
122
|
+
// About the object's first vertex, so that a part far from the origin keeps its precision.
|
|
123
|
+
if (!sum.origin.length)
|
|
124
|
+
sum.origin = [...positions.subarray(indices[i] * 3, indices[i] * 3 + 3)];
|
|
125
|
+
const [a, b, c] = [0, 1, 2].map((k) => sum.origin.map((o, axis) => positions[indices[i + k] * 3 + axis] - o)), cross = (u, v) => [
|
|
126
|
+
u[1] * v[2] - u[2] * v[1],
|
|
127
|
+
u[2] * v[0] - u[0] * v[2],
|
|
128
|
+
u[0] * v[1] - u[1] * v[0],
|
|
129
|
+
], edge = (to) => to.map((x, axis) => x - a[axis]);
|
|
130
|
+
sum.volume += cross(b, c).reduce((total, x, axis) => total + x * a[axis], 0) / 6;
|
|
131
|
+
sum.area += Math.hypot(...cross(edge(b), edge(c))) / 2;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return new Map([...sums].map(([id, { volume, area }]) => [id, area > 0 ? (4 * Math.abs(volume)) / area : 0]));
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* A translucent group as transmission and volume: Beer-Lambert's `exp(-a t)` is the material's colour to the power of
|
|
138
|
+
* `t / distance`, with the strongest channel setting the distance. The material takes green's refractive index, at
|
|
139
|
+
* least 1, and the spread from red to blue as `KHR_materials_dispersion` defines it.
|
|
140
|
+
*/
|
|
141
|
+
function volumeOf(translucent, metresPerUnit, thickness) {
|
|
142
|
+
const [red, green, blue] = translucent.refractiveIndex, ior = Math.max(1, green), perUnit = translucent.attenuation.map((a) => a * metresPerUnit), most = Math.max(...perUnit), dispersion = ior > 1 ? (20 * (blue - red)) / (ior - 1) : 0;
|
|
143
|
+
return {
|
|
144
|
+
transmission: 1,
|
|
145
|
+
ior,
|
|
146
|
+
// Naming it would add the dispersion lobe to a material that has none.
|
|
147
|
+
...(dispersion > 0 ? { dispersion } : {}),
|
|
148
|
+
thickness,
|
|
149
|
+
attenuationColor: perUnit.map((a) => (most ? Math.exp(-a / most) : 1)),
|
|
150
|
+
attenuationDistance: most ? 1 / most : Infinity,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
/** `basecolorfactor` or `diffusefactor` of a group's display properties, over its colour texture. */
|
|
154
|
+
const colourFactor = ({ metallic, specular }) => metallic?.baseColorFactor ?? specular?.diffuseFactor;
|
|
155
|
+
/**
|
|
156
|
+
* Turns one group's stack into the colour each vertex starts with and the `layered()` layers over it. The colour
|
|
157
|
+
* layers below the first texture layer are blended per corner, in linear light as the spec says, into the vertex
|
|
158
|
+
* colour; the first layer is opaque. Every layer from the first texture up becomes a material layer: a texture mixes by
|
|
159
|
+
* its own alpha (the bottom one covers), a colour layer needs one colour across the group. Texture layers share UV0
|
|
160
|
+
* and UV1 by their coordinates.
|
|
161
|
+
*/
|
|
162
|
+
function stack(loaded, group, layers, vertices, textures, colors, uvs) {
|
|
163
|
+
const data = (layer) => {
|
|
164
|
+
const values = loaded.attributes?.[layer.attribute];
|
|
165
|
+
if (!values)
|
|
166
|
+
throw new LoaderError(F, 'range', `layer attribute ${layer.attribute} is missing from attributes`);
|
|
167
|
+
return values;
|
|
168
|
+
};
|
|
169
|
+
const top = layers.findIndex((layer) => layer.kind === 'texture'), folded = top < 0 ? layers.length : top;
|
|
170
|
+
for (const v of vertices) {
|
|
171
|
+
const out = [1, 1, 1, 1];
|
|
172
|
+
for (let k = 0; k < folded; k++) {
|
|
173
|
+
const c = data(layers[k]).subarray(v * 4, v * 4 + 4), rgb = [0, 1, 2].map((i) => SRGBToLinear(c[i])), a = c[3];
|
|
174
|
+
if (!k)
|
|
175
|
+
out.splice(0, 4, ...rgb, 1);
|
|
176
|
+
else if (layers[k].blend === 'multiply')
|
|
177
|
+
out.splice(0, 4, ...rgb.map((x, i) => x * out[i]), a * out[3]);
|
|
178
|
+
else
|
|
179
|
+
out.splice(0, 4, ...rgb.map((x, i) => x * a + out[i] * (1 - a)), a + out[3] * (1 - a));
|
|
180
|
+
}
|
|
181
|
+
colors.set(out, v * 4);
|
|
182
|
+
}
|
|
183
|
+
const slots = [], same = (a, b) => [...vertices].every((v) => a[v * 2] === b[v * 2] && a[v * 2 + 1] === b[v * 2 + 1]);
|
|
184
|
+
const out = [],
|
|
185
|
+
/** The UV set of each texture layer, by its place in the file's stack. */
|
|
186
|
+
sets = new Map();
|
|
187
|
+
for (let k = folded; k < layers.length; k++) {
|
|
188
|
+
const layer = layers[k], values = data(layer), multiply = layer.blend === 'multiply';
|
|
189
|
+
if (layer.kind === 'color') {
|
|
190
|
+
const c = values.subarray(vertices[0] * 4, vertices[0] * 4 + 4);
|
|
191
|
+
if (![...vertices].every((v) => [0, 1, 2, 3].every((i) => values[v * 4 + i] === c[i])))
|
|
192
|
+
throw new LoaderError(F, 'unsupported', `group ${group.name ?? group.objectId ?? ''}: a colour layer above a texture layer must hold one colour across the group`);
|
|
193
|
+
const color = [0, 1, 2].map((i) => SRGBToLinear(c[i]));
|
|
194
|
+
out.push(multiply ? { color, blend: 'multiply' } : { color, opacity: c[3] });
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
let slot = slots.findIndex((uv) => uv === values || same(uv, values));
|
|
198
|
+
if (slot < 0)
|
|
199
|
+
slot = slots.push(values) - 1;
|
|
200
|
+
if (slot > 1)
|
|
201
|
+
throw new LoaderError(F, 'unsupported', 'a layer stack uses more than two sets of texture coordinates (UV0, UV1)');
|
|
202
|
+
for (const v of vertices)
|
|
203
|
+
uvs[slot].set([values[v * 2], 1 - values[v * 2 + 1]], v * 2);
|
|
204
|
+
const map = textures.get(layer.texture), texCoord = slot,
|
|
205
|
+
// The display properties' colour factor scales the colour of the layer they come from.
|
|
206
|
+
factor = (group.metallic ?? group.specular)?.layer === k ? colourFactor(group) : undefined, tint = factor ? { color: [0, 1, 2].map((i) => SRGBToLinear(factor[i])) } : {};
|
|
207
|
+
sets.set(k, texCoord);
|
|
208
|
+
// The bottom layer starts the stack opaque; a mix layer above covers by its alpha; multiply scales by it.
|
|
209
|
+
out.push({
|
|
210
|
+
...tint,
|
|
211
|
+
...(k === 0
|
|
212
|
+
? { map, texCoord }
|
|
213
|
+
: multiply
|
|
214
|
+
? { map, texCoord, blend: 'multiply' }
|
|
215
|
+
: { map, texCoord, mask: map, maskChannel: 'a' }),
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
return { layers: out, slots: sets };
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Draws a `parse3MFMaterials` result as one materials mesh with a material per group: colour groups, composites and
|
|
222
|
+
* per-corner colours as vertex colours, a texture group's image as the colour map, and a `multiproperties` stack as its
|
|
223
|
+
* layers (`layered()`), blended as the 3MF Materials and Properties Extension 1.2.1 specifies (mix and multiply, in
|
|
224
|
+
* linear light). A group's `metallic` sets its material's metalness and roughness, with their maps. Its `specular` is
|
|
225
|
+
* drawn as an index of refraction of 0 with that specular colour (`KHR_materials_ior`), and roughness 1 - glossiness.
|
|
226
|
+
* Its `translucent` is drawn as transmission through a volume: the thickness is the object's mean chord, 4 V / S, and the
|
|
227
|
+
* attenuation is converted with `metresPerUnit`; draw it with `@margoengine/materials/transmission` to refract the scene
|
|
228
|
+
* behind it, without which the background shows through tinted. `unlit` draws neither. Colour images decode with
|
|
229
|
+
* `createImageBitmap`; roughness, metalness and glossiness maps need the optional `@margoengine/decoders` peer, which
|
|
230
|
+
* reads their texels exactly.
|
|
231
|
+
*
|
|
232
|
+
* @param engine The engine to draw in.
|
|
233
|
+
* @param loaded What `parse3MFMaterials` returned.
|
|
234
|
+
* @param options Normals, surface numbers, draw order and an abort signal.
|
|
235
|
+
* @returns The mesh, its materials and textures, and `dispose()`.
|
|
236
|
+
* @throws LoaderError `unsupported` for a stack needing more than two UV sets or a varying colour above a texture
|
|
237
|
+
* layer, `range` for a group naming a missing texture or layer attribute, `aborted` when the signal fires.
|
|
238
|
+
*
|
|
239
|
+
* @example
|
|
240
|
+
* ```ts
|
|
241
|
+
* import { Engine } from '@margoengine/core';
|
|
242
|
+
* import { parse3MFMaterials } from '@margoengine/loaders/threemf-materials';
|
|
243
|
+
* import { create3MFMesh } from '@margoengine/loaders/threemf-mesh';
|
|
244
|
+
*
|
|
245
|
+
* const engine = await Engine.create(document.querySelector('canvas')!);
|
|
246
|
+
* const bytes = await (await fetch('/prints/multiprop-opaque.3mf')).arrayBuffer();
|
|
247
|
+
* using model = await create3MFMesh(engine, await parse3MFMaterials(bytes));
|
|
248
|
+
* console.log(model.materials.length, model.textures.size);
|
|
249
|
+
* ```
|
|
250
|
+
*/
|
|
251
|
+
export async function create3MFMesh(engine, loaded, options = {}) {
|
|
252
|
+
const { positions, indices, groups = [] } = loaded, { signal } = options;
|
|
253
|
+
if (loaded.kind !== 'mesh' || !indices?.length)
|
|
254
|
+
throw new LoaderError(F, 'unsupported', 'create3MFMesh needs triangles; pass parse3MFMaterials output');
|
|
255
|
+
const mode = options.normals ?? 'smooth';
|
|
256
|
+
if (mode !== 'smooth' && mode !== 'flat')
|
|
257
|
+
throw new LoaderError(F, 'range', 'normals must be smooth or flat');
|
|
258
|
+
const crease = options.creaseAngle ?? 40;
|
|
259
|
+
if (!(crease >= 0 && crease <= 180))
|
|
260
|
+
throw new LoaderError(F, 'range', 'creaseAngle must be 0 to 180 degrees');
|
|
261
|
+
const count = positions.length / 3, used = new Set();
|
|
262
|
+
for (const group of groups) {
|
|
263
|
+
if (group.texture !== undefined)
|
|
264
|
+
used.add(group.texture);
|
|
265
|
+
for (const layer of group.layers ?? [])
|
|
266
|
+
if (layer.texture !== undefined)
|
|
267
|
+
used.add(layer.texture);
|
|
268
|
+
}
|
|
269
|
+
const textures = new Map(),
|
|
270
|
+
/** Repacked metalness and roughness maps, shared by the groups that sample them alike. */
|
|
271
|
+
finishes = new Map(), materials = [],
|
|
272
|
+
/** The materials made so far by what they were made from, and a number for each texture in those keys. */
|
|
273
|
+
made = new Map(), ids = new Map(), keyOf = (parts) => JSON.stringify(parts, (_, value) => {
|
|
274
|
+
if (!(value instanceof Texture))
|
|
275
|
+
return value;
|
|
276
|
+
let id = ids.get(value);
|
|
277
|
+
if (id === undefined)
|
|
278
|
+
ids.set(value, (id = ids.size));
|
|
279
|
+
return `texture ${id}`;
|
|
280
|
+
}), paths = meanPaths(loaded);
|
|
281
|
+
const release = () => {
|
|
282
|
+
for (const material of made.values())
|
|
283
|
+
material.dispose();
|
|
284
|
+
for (const texture of [...textures.values(), ...finishes.values()])
|
|
285
|
+
texture.dispose();
|
|
286
|
+
};
|
|
287
|
+
try {
|
|
288
|
+
for (const k of used) {
|
|
289
|
+
throwIfAborted(signal, F);
|
|
290
|
+
const source = loaded.textures[k];
|
|
291
|
+
if (!source)
|
|
292
|
+
throw new LoaderError(F, 'range', `a group names texture ${k}, outside textures`);
|
|
293
|
+
textures.set(k, await decode(source, signal));
|
|
294
|
+
}
|
|
295
|
+
const colors = new Float32Array(count * 4).fill(1), uvs = [new Float32Array(count * 2), new Float32Array(count * 2)], drawn = [], unique = [];
|
|
296
|
+
for (const group of groups) {
|
|
297
|
+
if (!group.count)
|
|
298
|
+
continue;
|
|
299
|
+
const vertices = indices.subarray(group.start, group.start + group.count), { metallic, specular, translucent } = group, display = metallic ?? specular,
|
|
300
|
+
// A glossiness map holds the whole roughness, as 1 - factor x texel is no factor over a map.
|
|
301
|
+
given = specular
|
|
302
|
+
? specular.glossinessTexture === undefined
|
|
303
|
+
? 1 - specular.glossiness
|
|
304
|
+
: 1
|
|
305
|
+
: (metallic ?? translucent)?.roughness, roughness = options.roughness ?? Math.min(1, given ?? 0.6), metalness = options.metalness ?? (metallic ? Math.min(1, metallic.metalness) : 0), channels = channelsOf(group, options);
|
|
306
|
+
let features = [], slots = new Map(), map, finish, specularMap;
|
|
307
|
+
const specularTexture = options.unlit ? undefined : specular?.specularTexture;
|
|
308
|
+
if (channels.roughness || channels.metalness || specularTexture !== undefined) {
|
|
309
|
+
const colour = group.layers ? group.layers[display.layer]?.texture : group.texture, addressing = loaded.textures[colour];
|
|
310
|
+
if (!addressing)
|
|
311
|
+
throw new LoaderError(F, 'range', 'a group with display property maps needs its colour texture');
|
|
312
|
+
if (channels.roughness || channels.metalness) {
|
|
313
|
+
const key = JSON.stringify([display, colour, !!channels.roughness, !!channels.metalness]);
|
|
314
|
+
finish = finishes.get(key);
|
|
315
|
+
if (!finish)
|
|
316
|
+
finishes.set(key, (finish = await finishMap(loaded, channels, addressing, signal)));
|
|
317
|
+
}
|
|
318
|
+
if (specularTexture !== undefined) {
|
|
319
|
+
const source = loaded.textures[specularTexture];
|
|
320
|
+
if (!source)
|
|
321
|
+
throw new LoaderError(F, 'range', `a group names texture ${specularTexture}, outside textures`);
|
|
322
|
+
const key = JSON.stringify([specularTexture, colour]), { tileStyleU, tileStyleV, filter } = addressing;
|
|
323
|
+
specularMap = finishes.get(key);
|
|
324
|
+
if (!specularMap) {
|
|
325
|
+
specularMap = await decode({ ...source, tileStyleU, tileStyleV, filter }, signal);
|
|
326
|
+
finishes.set(key, specularMap);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
throwIfAborted(signal, F);
|
|
330
|
+
}
|
|
331
|
+
if (group.layers?.length)
|
|
332
|
+
({ layers: features, slots } = stack(loaded, group, group.layers, vertices, textures, colors, uvs));
|
|
333
|
+
else {
|
|
334
|
+
const { colors: rgb, uvs: uv } = loaded, alpha = loaded.attributes?.opacity, factor = colourFactor(group);
|
|
335
|
+
for (const v of vertices) {
|
|
336
|
+
for (let c = 0; c < 3; c++)
|
|
337
|
+
colors[v * 4 + c] =
|
|
338
|
+
SRGBToLinear(rgb?.[v * 3 + c] ?? group.color?.[c] ?? 1) * (factor ? SRGBToLinear(factor[c]) : 1);
|
|
339
|
+
colors[v * 4 + 3] = alpha?.[v] ?? group.color?.[3] ?? 1;
|
|
340
|
+
if (uv)
|
|
341
|
+
uvs[0].set([uv[v * 2], 1 - uv[v * 2 + 1]], v * 2);
|
|
342
|
+
}
|
|
343
|
+
if (group.texture !== undefined)
|
|
344
|
+
map = textures.get(group.texture);
|
|
345
|
+
}
|
|
346
|
+
// A layer sets metalness and roughness where it covers, so each carries the material's own; a map lies over the
|
|
347
|
+
// whole stack as one more layer that leaves the colour as it is.
|
|
348
|
+
if (features.length) {
|
|
349
|
+
if (!finish)
|
|
350
|
+
features = features.map((layer) => ({ ...layer, roughness, metalness }));
|
|
351
|
+
else {
|
|
352
|
+
if (features.length >= 8)
|
|
353
|
+
throw new LoaderError(F, 'unsupported', 'a stack of 8 texture layers has no room for its metallic map');
|
|
354
|
+
const texCoord = slots.get(display.layer) ?? 0;
|
|
355
|
+
features.push({ blend: 'multiply', metalRoughnessMap: finish, texCoord, roughness, metalness });
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
// A translucent surface is see-through by its transmission, not by its colour's alpha.
|
|
359
|
+
if (translucent && !options.unlit)
|
|
360
|
+
for (const v of vertices)
|
|
361
|
+
colors[v * 4 + 3] = 1;
|
|
362
|
+
const transparent = [...vertices].some((v) => colors[v * 4 + 3] < 1), physical = options.unlit
|
|
363
|
+
? {}
|
|
364
|
+
: specular
|
|
365
|
+
? {
|
|
366
|
+
ior: 0,
|
|
367
|
+
specularColor: specular.specularColor.map(SRGBToLinear),
|
|
368
|
+
...(specularMap ? { specularColorMap: specularMap } : {}),
|
|
369
|
+
}
|
|
370
|
+
: translucent
|
|
371
|
+
? volumeOf(translucent, loaded.metresPerUnit ?? 1, paths.get(group.objectId))
|
|
372
|
+
: {};
|
|
373
|
+
const slot = specularMap && slots.get(specular.layer), key = keyOf([physical, map, finish, specularMap, slot, features, roughness, metalness, transparent]);
|
|
374
|
+
let material = made.get(key);
|
|
375
|
+
if (!material) {
|
|
376
|
+
material = new Material({
|
|
377
|
+
...physical,
|
|
378
|
+
...(map ? { map } : {}),
|
|
379
|
+
...(finish && !features.length ? { metalRoughnessMap: finish } : {}),
|
|
380
|
+
...(options.unlit ? { shading: 'basic' } : {}),
|
|
381
|
+
roughness,
|
|
382
|
+
metalness,
|
|
383
|
+
doubleSided: options.doubleSided ?? true,
|
|
384
|
+
transparent,
|
|
385
|
+
features: features.length ? [layered({ layers: features })] : [],
|
|
386
|
+
});
|
|
387
|
+
made.set(key, material);
|
|
388
|
+
if (slot)
|
|
389
|
+
material.setUVTransform({ texCoord: slot }, 'specularColorMap');
|
|
390
|
+
}
|
|
391
|
+
materials.push(material);
|
|
392
|
+
// Opaque ranges that follow each other with one material are one draw; see-through ones stay apart to sort.
|
|
393
|
+
const index = unique.indexOf(material), last = drawn[drawn.length - 1];
|
|
394
|
+
if (last && !transparent && last.materialIndex === index && last.start + last.count === group.start)
|
|
395
|
+
last.count += group.count;
|
|
396
|
+
else {
|
|
397
|
+
if (index < 0)
|
|
398
|
+
unique.push(material);
|
|
399
|
+
drawn.push({ start: group.start, count: group.count, materialIndex: index < 0 ? unique.length - 1 : index });
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
if (!materials.length)
|
|
403
|
+
throw new LoaderError(F, 'unsupported', 'the result has no nonempty groups to draw');
|
|
404
|
+
const normals = mode === 'flat'
|
|
405
|
+
? computeVertexNormals(positions, indices)
|
|
406
|
+
: creasedNormals(positions, { indices, angle: crease, tolerance: 0 });
|
|
407
|
+
// A corner of triangles with no area only gets no direction, and a mesh needs one for every vertex.
|
|
408
|
+
for (let v = 0; v < normals.length; v += 3)
|
|
409
|
+
if (!normals[v] && !normals[v + 1] && !normals[v + 2])
|
|
410
|
+
normals[v + 2] = 1;
|
|
411
|
+
const mesh = createMesh(engine, { positions, normals, indices, uvs: uvs[0], uvs1: uvs[1], colors, groups: drawn }, unique, { renderOrder: options.renderOrder ?? 0 });
|
|
412
|
+
const dispose = () => {
|
|
413
|
+
mesh.destroy();
|
|
414
|
+
release();
|
|
415
|
+
};
|
|
416
|
+
return { mesh, materials, textures, dispose, [Symbol.dispose]: dispose };
|
|
417
|
+
}
|
|
418
|
+
catch (error) {
|
|
419
|
+
release();
|
|
420
|
+
throw error;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type BinaryInput } from './util.js';
|
|
2
|
+
import { type ZipOptions } from './zip.js';
|
|
3
|
+
/** Options of {@link parse3MFKeystore}: the zip limits (`maxEntries` defaults to 65,535 as in parse3MF) and an AbortSignal. */
|
|
4
|
+
export interface ThreeMFKeystoreOptions extends Pick<ZipOptions, 'maxEntries' | 'maxEntryBytes' | 'maxRatio'> {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
}
|
|
7
|
+
/** A content key wrapped for one consumer. */
|
|
8
|
+
export interface ThreeMFKeyAccess {
|
|
9
|
+
/** The consumer's index in `consumers`. */
|
|
10
|
+
consumer: number;
|
|
11
|
+
wrappingAlgorithm: string;
|
|
12
|
+
mgfAlgorithm?: string;
|
|
13
|
+
digestMethod?: string;
|
|
14
|
+
wrappedKey: Uint8Array;
|
|
15
|
+
}
|
|
16
|
+
/** An encrypted part and what decrypting it needs. */
|
|
17
|
+
export interface ThreeMFEncryptedResource {
|
|
18
|
+
/** Its path in the package. */
|
|
19
|
+
path: string;
|
|
20
|
+
algorithm: string;
|
|
21
|
+
compression: 'none' | 'deflate';
|
|
22
|
+
iv?: Uint8Array;
|
|
23
|
+
tag?: Uint8Array;
|
|
24
|
+
aad?: Uint8Array;
|
|
25
|
+
/** The encrypted bytes, after the cipher file's header. */
|
|
26
|
+
content: Uint8Array;
|
|
27
|
+
}
|
|
28
|
+
/** The result of {@link parse3MFKeystore}. */
|
|
29
|
+
export interface ThreeMFKeystore {
|
|
30
|
+
uuid: string;
|
|
31
|
+
consumers: {
|
|
32
|
+
id: string;
|
|
33
|
+
keyId?: string;
|
|
34
|
+
publicKey?: string;
|
|
35
|
+
}[];
|
|
36
|
+
groups: {
|
|
37
|
+
keyUUID: string;
|
|
38
|
+
access: ThreeMFKeyAccess[];
|
|
39
|
+
resources: ThreeMFEncryptedResource[];
|
|
40
|
+
}[];
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Reads a 3MF package's key store, or undefined when it has none. Each encrypted part's bytes come without the cipher
|
|
44
|
+
* file header; unwrapping the keys and decrypting are the caller's.
|
|
45
|
+
*
|
|
46
|
+
* @throws LoaderError for a key store the extension rules out: a bad UUID, an access right with no such consumer, a part
|
|
47
|
+
* listed twice, missing, without an encrypted-file relationship or without a version 0 cipher header, an encrypted root
|
|
48
|
+
* model or relationships part, and ZIP or XML faults.
|
|
49
|
+
*/
|
|
50
|
+
export declare function parse3MFKeystore(input: BinaryInput, options?: ThreeMFKeystoreOptions): Promise<ThreeMFKeystore | undefined>;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Reads the unencrypted structure of the 3MF Consortium's Secure Content Extension
|
|
2
|
+
// (https://github.com/3MFConsortium/spec_securecontent): the key store, the encrypted-file relationships and the cipher
|
|
3
|
+
// file headers. It decrypts nothing and handles no key; the caller does.
|
|
4
|
+
import { LoaderError } from './types.js';
|
|
5
|
+
import { throwIfAborted, toBytes } from './util.js';
|
|
6
|
+
import { readZipDirectory, readZipEntry } from './zip.js';
|
|
7
|
+
import { decodeXML, readXML } from './xml.js';
|
|
8
|
+
const F = '3MF';
|
|
9
|
+
const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
10
|
+
const bad = (message) => {
|
|
11
|
+
throw new LoaderError(F, 'syntax', message);
|
|
12
|
+
};
|
|
13
|
+
const required = (a, key, element) => a[key] ?? bad(`<${element}> without ${key}`);
|
|
14
|
+
const normalize = (path) => path.replace(/\\/g, '/').replace(/^\/+/, '').toLowerCase();
|
|
15
|
+
const bytesOf = (text, what) => {
|
|
16
|
+
try {
|
|
17
|
+
return Uint8Array.from(atob(text.replace(/\s+/g, '')), (c) => c.charCodeAt(0));
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return bad(`${what} is not base64`);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Reads a 3MF package's key store, or undefined when it has none. Each encrypted part's bytes come without the cipher
|
|
25
|
+
* file header; unwrapping the keys and decrypting are the caller's.
|
|
26
|
+
*
|
|
27
|
+
* @throws LoaderError for a key store the extension rules out: a bad UUID, an access right with no such consumer, a part
|
|
28
|
+
* listed twice, missing, without an encrypted-file relationship or without a version 0 cipher header, an encrypted root
|
|
29
|
+
* model or relationships part, and ZIP or XML faults.
|
|
30
|
+
*/
|
|
31
|
+
export async function parse3MFKeystore(input, options = {}) {
|
|
32
|
+
const bytes = toBytes(input, F), byPath = new Map();
|
|
33
|
+
// Default entry limit as parse3MF: a package may hold up to 65,535 model parts, each its own entry.
|
|
34
|
+
for (const entry of readZipDirectory(bytes, { ...options, maxEntries: options.maxEntries ?? 65_535 }))
|
|
35
|
+
byPath.set(normalize(entry.name), entry);
|
|
36
|
+
const read = async (path) => {
|
|
37
|
+
throwIfAborted(options.signal, F);
|
|
38
|
+
const entry = byPath.get(normalize(path));
|
|
39
|
+
if (!entry)
|
|
40
|
+
throw new LoaderError(F, 'syntax', `package part "${path.slice(0, 128)}" is missing`);
|
|
41
|
+
return readZipEntry(bytes, entry, options);
|
|
42
|
+
};
|
|
43
|
+
/** The targets of encrypted-file relationships, from any relationships part. */
|
|
44
|
+
const marked = new Set();
|
|
45
|
+
let location, root;
|
|
46
|
+
for (const path of byPath.keys()) {
|
|
47
|
+
if (!path.endsWith('.rels'))
|
|
48
|
+
continue;
|
|
49
|
+
readXML(decodeXML(await read(path)), {
|
|
50
|
+
open(name, a) {
|
|
51
|
+
if (name !== 'Relationship' || !a.Target)
|
|
52
|
+
return;
|
|
53
|
+
if (a.Type?.endsWith('/encryptedfile'))
|
|
54
|
+
marked.add(normalize(a.Target));
|
|
55
|
+
else if (path === '_rels/.rels' && a.Type?.endsWith('/keystore'))
|
|
56
|
+
location = a.Target;
|
|
57
|
+
else if (path === '_rels/.rels' && a.Type?.endsWith('/3dmodel'))
|
|
58
|
+
root = normalize(a.Target);
|
|
59
|
+
},
|
|
60
|
+
close() { },
|
|
61
|
+
}, F);
|
|
62
|
+
}
|
|
63
|
+
if (location === undefined)
|
|
64
|
+
return undefined;
|
|
65
|
+
const store = { uuid: '', consumers: [], groups: [] }, listed = new Set(), identified = (value) => (UUID.test(value) ? value : bad(`invalid UUID ${value.slice(0, 40)}`));
|
|
66
|
+
let text = '', consumer, group, access, resource;
|
|
67
|
+
readXML(decodeXML(await read(location)), {
|
|
68
|
+
open(name, a) {
|
|
69
|
+
text = '';
|
|
70
|
+
if (name === 'keystore')
|
|
71
|
+
store.uuid = identified(required(a, 'UUID', name));
|
|
72
|
+
else if (name === 'consumer') {
|
|
73
|
+
consumer = { id: required(a, 'consumerid', name), ...(a.keyid === undefined ? {} : { keyId: a.keyid }) };
|
|
74
|
+
if (store.consumers.some((c) => c.id === consumer.id))
|
|
75
|
+
bad(`consumer ${consumer.id.slice(0, 64)} twice`);
|
|
76
|
+
store.consumers.push(consumer);
|
|
77
|
+
}
|
|
78
|
+
else if (name === 'resourcedatagroup') {
|
|
79
|
+
group = { keyUUID: identified(required(a, 'keyuuid', name)), access: [], resources: [] };
|
|
80
|
+
store.groups.push(group);
|
|
81
|
+
}
|
|
82
|
+
else if (name === 'accessright') {
|
|
83
|
+
const at = Number(required(a, 'consumerindex', name));
|
|
84
|
+
if (!group || !store.consumers[at])
|
|
85
|
+
bad('an access right names no consumer of the key store');
|
|
86
|
+
access = { consumer: at, wrappingAlgorithm: '', wrappedKey: new Uint8Array(0) };
|
|
87
|
+
group.access.push(access);
|
|
88
|
+
}
|
|
89
|
+
else if (name === 'kekparams' && access) {
|
|
90
|
+
access.wrappingAlgorithm = required(a, 'wrappingalgorithm', name);
|
|
91
|
+
if (a.mgfalgorithm !== undefined)
|
|
92
|
+
access.mgfAlgorithm = a.mgfalgorithm;
|
|
93
|
+
if (a.digestmethod !== undefined)
|
|
94
|
+
access.digestMethod = a.digestmethod;
|
|
95
|
+
}
|
|
96
|
+
else if (name === 'resourcedata') {
|
|
97
|
+
const path = required(a, 'path', name), key = normalize(path);
|
|
98
|
+
if (!group || listed.has(key))
|
|
99
|
+
bad(`resource ${path.slice(0, 128)} is listed twice or outside a group`);
|
|
100
|
+
if (key === root || key.endsWith('.rels'))
|
|
101
|
+
bad(`the root model and relationships parts must not be encrypted: ${path.slice(0, 128)}`);
|
|
102
|
+
if (!marked.has(key))
|
|
103
|
+
bad(`resource ${path.slice(0, 128)} has no encrypted-file relationship`);
|
|
104
|
+
listed.add(key);
|
|
105
|
+
resource = { path, algorithm: '', compression: 'none', content: new Uint8Array(0) };
|
|
106
|
+
group.resources.push(resource);
|
|
107
|
+
}
|
|
108
|
+
else if (name === 'cekparams' && resource) {
|
|
109
|
+
resource.algorithm = required(a, 'encryptionalgorithm', name);
|
|
110
|
+
const compression = a.compression ?? 'none';
|
|
111
|
+
if (compression !== 'none' && compression !== 'deflate')
|
|
112
|
+
bad('compression must be none or deflate');
|
|
113
|
+
resource.compression = compression;
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
close(name) {
|
|
117
|
+
if (name === 'keyvalue' && consumer)
|
|
118
|
+
consumer.publicKey = text.trim();
|
|
119
|
+
else if (name === 'CipherValue' && access)
|
|
120
|
+
access.wrappedKey = bytesOf(text, name);
|
|
121
|
+
else if ((name === 'iv' || name === 'tag' || name === 'aad') && resource)
|
|
122
|
+
resource[name] = bytesOf(text, name);
|
|
123
|
+
else if (name === 'consumer')
|
|
124
|
+
consumer = undefined;
|
|
125
|
+
else if (name === 'accessright') {
|
|
126
|
+
if (!access?.wrappingAlgorithm || !access.wrappedKey.length)
|
|
127
|
+
bad('an access right needs kekparams and a CipherValue');
|
|
128
|
+
access = undefined;
|
|
129
|
+
}
|
|
130
|
+
else if (name === 'resourcedata') {
|
|
131
|
+
if (!resource?.algorithm)
|
|
132
|
+
bad('a resource needs cekparams');
|
|
133
|
+
resource = undefined;
|
|
134
|
+
}
|
|
135
|
+
else if (name === 'resourcedatagroup')
|
|
136
|
+
group = undefined;
|
|
137
|
+
text = '';
|
|
138
|
+
},
|
|
139
|
+
text(value) {
|
|
140
|
+
text += value;
|
|
141
|
+
},
|
|
142
|
+
}, F);
|
|
143
|
+
if (!store.uuid)
|
|
144
|
+
bad('the key store part holds no keystore element');
|
|
145
|
+
for (const { resources } of store.groups)
|
|
146
|
+
for (const found of resources) {
|
|
147
|
+
const file = await read(found.path), header = file.length >= 12 ? new DataView(file.buffer, file.byteOffset).getUint32(8, true) : 0;
|
|
148
|
+
if ([0x25, 0x33, 0x4d, 0x63, 0x46, 0, 0, 0].some((v, i) => file[i] !== v) || header < 12 || header > file.length)
|
|
149
|
+
bad(`${found.path.slice(0, 128)} is not a version 0 3MF cipher file`);
|
|
150
|
+
found.content = file.subarray(header);
|
|
151
|
+
}
|
|
152
|
+
return store;
|
|
153
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type ThreeMFMesh, type ThreeMFModel, type ThreeMFObject } from './threemf.js';
|
|
2
|
+
/** A decoded height map and how it is read. */
|
|
3
|
+
export interface HeightMap {
|
|
4
|
+
width: number;
|
|
5
|
+
height: number;
|
|
6
|
+
/** RGBA, 16 bits a sample, top row first. */
|
|
7
|
+
data: Uint16Array;
|
|
8
|
+
/** 0 to 3 for R, G, B and A. */
|
|
9
|
+
channel: number;
|
|
10
|
+
tileU: string;
|
|
11
|
+
tileV: string;
|
|
12
|
+
nearest: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** A `disp2dgroup` with its map decoded. */
|
|
15
|
+
export interface HeightGroup {
|
|
16
|
+
height: number;
|
|
17
|
+
offset: number;
|
|
18
|
+
/** `u v f` for each coordinate. */
|
|
19
|
+
coordinates: Float32Array;
|
|
20
|
+
/** A unit vector for each coordinate. */
|
|
21
|
+
vectors: Float32Array;
|
|
22
|
+
map: HeightMap;
|
|
23
|
+
}
|
|
24
|
+
export interface TessellateOptions {
|
|
25
|
+
samplesPerTexel: number;
|
|
26
|
+
maxSegments: number;
|
|
27
|
+
maxTriangles: number;
|
|
28
|
+
}
|
|
29
|
+
/** The displacement at `(u, v)` along a unit vector, in model units (chapter 2). */
|
|
30
|
+
export declare function displacementAt({ map, height, offset }: HeightGroup, u: number, v: number): number;
|
|
31
|
+
/**
|
|
32
|
+
* The displaced surface of one mesh as a new triangle mesh in the same object coordinates: welded where triangles meet
|
|
33
|
+
* in one point, and joined where their displaced edges part (section 5.2: directly when both sides use the same
|
|
34
|
+
* vectors, through the base edge when not). `groups[t]` and `corners[3 t + k]` give triangle `t`'s displacement group
|
|
35
|
+
* (-1 for none) and corner coordinates. Property colors follow their base triangle; a colour gradient is interpolated.
|
|
36
|
+
*/
|
|
37
|
+
export declare function tessellate(model: ThreeMFModel, object: ThreeMFObject, mesh: ThreeMFMesh, groups: readonly (HeightGroup | undefined)[], corners: ArrayLike<number>, { samplesPerTexel, maxSegments, maxTriangles }: TessellateOptions): ThreeMFMesh;
|