@margoengine/loaders 0.1.0 → 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 -201
- package/NOTICE +4 -4
- package/README.md +1666 -1198
- package/dist/crease.d.ts +7 -0
- package/dist/crease.js +67 -0
- package/dist/dae-common.js +1 -1
- package/dist/dae-kinematics.d.ts +65 -0
- package/dist/dae-kinematics.js +461 -0
- package/dist/dae.d.ts +9 -4
- package/dist/dae.js +16 -5
- 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 +42 -1
- package/dist/dxf.js +226 -15
- package/dist/engine.d.ts +5 -0
- package/dist/engine.js +3 -0
- package/dist/gcode.d.ts +37 -0
- package/dist/gcode.js +91 -0
- package/dist/geometry.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/mtl.d.ts +8 -3
- package/dist/mtl.js +91 -10
- package/dist/nrrd.d.ts +12 -5
- package/dist/nrrd.js +68 -26
- package/dist/obj.d.ts +3 -1
- package/dist/obj.js +7 -1
- package/dist/render.d.ts +9 -4
- package/dist/render.js +31 -3
- package/dist/shared/asset-url.js +82 -82
- package/dist/shared/crc32.d.ts +2 -2
- package/dist/shared/crc32.js +47 -47
- package/dist/shared/errors.js +36 -36
- package/dist/shared/inflate.js +284 -284
- package/dist/shared/normals.js +26 -26
- package/dist/shared/scene-scope.js +54 -54
- package/dist/shared/trailing-data.js +45 -42
- 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.js +10 -145
- package/dist/threemf-levelset.d.ts +23 -0
- package/dist/threemf-levelset.js +105 -0
- package/dist/threemf-materials.d.ts +89 -2
- package/dist/threemf-materials.js +194 -11
- package/dist/threemf-mesh.d.ts +21 -6
- package/dist/threemf-mesh.js +266 -45
- 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 +73 -4
- package/dist/threemf.js +235 -41
- package/dist/types.d.ts +18 -0
- package/dist/workers/usd.js +1 -1
- package/package.json +291 -246
package/dist/threemf-mesh.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { Material, Texture, createMesh } from '@margoengine/materials';
|
|
1
|
+
import { Material, Texture, createMesh, } from '@margoengine/materials';
|
|
2
2
|
import { layered } from '@margoengine/materials/layered';
|
|
3
|
+
import { creasedNormals } from '@margoengine/geometry/utils';
|
|
3
4
|
import { SRGBToLinear } from '@margoengine/math/color';
|
|
4
5
|
import { computeVertexNormals } from './normals.js';
|
|
5
6
|
import { LoaderError } from './types.js';
|
|
@@ -22,17 +23,135 @@ async function decode(texture, signal) {
|
|
|
22
23
|
mipmaps: !nearest,
|
|
23
24
|
});
|
|
24
25
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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
|
+
};
|
|
33
105
|
}
|
|
34
106
|
return out;
|
|
35
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;
|
|
36
155
|
/**
|
|
37
156
|
* Turns one group's stack into the colour each vertex starts with and the `layered()` layers over it. The colour
|
|
38
157
|
* layers below the first texture layer are blended per corner, in linear light as the spec says, into the vertex
|
|
@@ -62,7 +181,9 @@ function stack(loaded, group, layers, vertices, textures, colors, uvs) {
|
|
|
62
181
|
colors.set(out, v * 4);
|
|
63
182
|
}
|
|
64
183
|
const slots = [], same = (a, b) => [...vertices].every((v) => a[v * 2] === b[v * 2] && a[v * 2 + 1] === b[v * 2 + 1]);
|
|
65
|
-
const out = []
|
|
184
|
+
const out = [],
|
|
185
|
+
/** The UV set of each texture layer, by its place in the file's stack. */
|
|
186
|
+
sets = new Map();
|
|
66
187
|
for (let k = folded; k < layers.length; k++) {
|
|
67
188
|
const layer = layers[k], values = data(layer), multiply = layer.blend === 'multiply';
|
|
68
189
|
if (layer.kind === 'color') {
|
|
@@ -80,21 +201,33 @@ function stack(loaded, group, layers, vertices, textures, colors, uvs) {
|
|
|
80
201
|
throw new LoaderError(F, 'unsupported', 'a layer stack uses more than two sets of texture coordinates (UV0, UV1)');
|
|
81
202
|
for (const v of vertices)
|
|
82
203
|
uvs[slot].set([values[v * 2], 1 - values[v * 2 + 1]], v * 2);
|
|
83
|
-
const map = textures.get(layer.texture), texCoord = slot
|
|
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);
|
|
84
208
|
// The bottom layer starts the stack opaque; a mix layer above covers by its alpha; multiply scales by it.
|
|
85
|
-
out.push(
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
? { map, texCoord
|
|
89
|
-
:
|
|
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
|
+
});
|
|
90
217
|
}
|
|
91
|
-
return out;
|
|
218
|
+
return { layers: out, slots: sets };
|
|
92
219
|
}
|
|
93
220
|
/**
|
|
94
221
|
* Draws a `parse3MFMaterials` result as one materials mesh with a material per group: colour groups, composites and
|
|
95
222
|
* per-corner colours as vertex colours, a texture group's image as the colour map, and a `multiproperties` stack as its
|
|
96
223
|
* layers (`layered()`), blended as the 3MF Materials and Properties Extension 1.2.1 specifies (mix and multiply, in
|
|
97
|
-
* linear light).
|
|
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.
|
|
98
231
|
*
|
|
99
232
|
* @param engine The engine to draw in.
|
|
100
233
|
* @param loaded What `parse3MFMaterials` returned.
|
|
@@ -122,6 +255,9 @@ export async function create3MFMesh(engine, loaded, options = {}) {
|
|
|
122
255
|
const mode = options.normals ?? 'smooth';
|
|
123
256
|
if (mode !== 'smooth' && mode !== 'flat')
|
|
124
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');
|
|
125
261
|
const count = positions.length / 3, used = new Set();
|
|
126
262
|
for (const group of groups) {
|
|
127
263
|
if (group.texture !== undefined)
|
|
@@ -130,11 +266,22 @@ export async function create3MFMesh(engine, loaded, options = {}) {
|
|
|
130
266
|
if (layer.texture !== undefined)
|
|
131
267
|
used.add(layer.texture);
|
|
132
268
|
}
|
|
133
|
-
const textures = new Map(),
|
|
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);
|
|
134
281
|
const release = () => {
|
|
135
|
-
for (const material of
|
|
282
|
+
for (const material of made.values())
|
|
136
283
|
material.dispose();
|
|
137
|
-
for (const texture of textures.values())
|
|
284
|
+
for (const texture of [...textures.values(), ...finishes.values()])
|
|
138
285
|
texture.dispose();
|
|
139
286
|
};
|
|
140
287
|
try {
|
|
@@ -145,19 +292,50 @@ export async function create3MFMesh(engine, loaded, options = {}) {
|
|
|
145
292
|
throw new LoaderError(F, 'range', `a group names texture ${k}, outside textures`);
|
|
146
293
|
textures.set(k, await decode(source, signal));
|
|
147
294
|
}
|
|
148
|
-
const colors = new Float32Array(count * 4).fill(1), uvs = [new Float32Array(count * 2), new Float32Array(count * 2)],
|
|
295
|
+
const colors = new Float32Array(count * 4).fill(1), uvs = [new Float32Array(count * 2), new Float32Array(count * 2)], drawn = [], unique = [];
|
|
149
296
|
for (const group of groups) {
|
|
150
297
|
if (!group.count)
|
|
151
298
|
continue;
|
|
152
|
-
const vertices = indices.subarray(group.start, group.start + group.count)
|
|
153
|
-
|
|
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
|
+
}
|
|
154
331
|
if (group.layers?.length)
|
|
155
|
-
features = stack(loaded, group, group.layers, vertices, textures, colors, uvs);
|
|
332
|
+
({ layers: features, slots } = stack(loaded, group, group.layers, vertices, textures, colors, uvs));
|
|
156
333
|
else {
|
|
157
|
-
const { colors: rgb, uvs: uv } = loaded, alpha = loaded.attributes?.opacity;
|
|
334
|
+
const { colors: rgb, uvs: uv } = loaded, alpha = loaded.attributes?.opacity, factor = colourFactor(group);
|
|
158
335
|
for (const v of vertices) {
|
|
159
336
|
for (let c = 0; c < 3; c++)
|
|
160
|
-
colors[v * 4 + c] =
|
|
337
|
+
colors[v * 4 + c] =
|
|
338
|
+
SRGBToLinear(rgb?.[v * 3 + c] ?? group.color?.[c] ?? 1) * (factor ? SRGBToLinear(factor[c]) : 1);
|
|
161
339
|
colors[v * 4 + 3] = alpha?.[v] ?? group.color?.[3] ?? 1;
|
|
162
340
|
if (uv)
|
|
163
341
|
uvs[0].set([uv[v * 2], 1 - uv[v * 2 + 1]], v * 2);
|
|
@@ -165,29 +343,72 @@ export async function create3MFMesh(engine, loaded, options = {}) {
|
|
|
165
343
|
if (group.texture !== undefined)
|
|
166
344
|
map = textures.get(group.texture);
|
|
167
345
|
}
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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
|
+
}
|
|
179
401
|
}
|
|
180
402
|
if (!materials.length)
|
|
181
403
|
throw new LoaderError(F, 'unsupported', 'the result has no nonempty groups to draw');
|
|
182
404
|
const normals = mode === 'flat'
|
|
183
405
|
? computeVertexNormals(positions, indices)
|
|
184
|
-
: (
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
const mesh = createMesh(engine, { positions, normals, indices, uvs: uvs[0], uvs1: uvs[1], colors, groups: geometryGroups }, materials, { renderOrder: options.renderOrder ?? 0 });
|
|
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 });
|
|
191
412
|
const dispose = () => {
|
|
192
413
|
mesh.destroy();
|
|
193
414
|
release();
|
|
@@ -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;
|