fast-mesh-wasm 0.5.0 → 0.5.1
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/README.md +51 -3
- package/dist/{api-BUy7FRx7.js → api-4kz45-Mq.js} +2 -3
- package/dist/{client-CE6RvmvB.js → client-C61Kku4i.js} +62 -18
- package/dist/{client-pv0Fwvl4.d.ts → client-tP6R9foI.d.ts} +13 -8
- package/dist/{colormap-DxGMYVfs.js → colormap-Dr5V3bvs.js} +1 -2
- package/dist/{core-Cke_kZ2e.js → core-4OcWKu3r.js} +2 -2
- package/dist/{core-D2X9GPfK.d.ts → core-CJ9D6U5A.d.ts} +1 -3
- package/dist/{engine-DLQAL9GT.js → engine-X1Awlc5y.js} +13 -8
- package/dist/io.d.ts +294 -0
- package/dist/io.js +1395 -0
- package/dist/{mesh-zj7-wJBw.js → mesh-CWvrjO8S.js} +3 -4
- package/dist/{mesh-RtPVmPQy.d.ts → mesh-D3fv56nF.d.ts} +1 -3
- package/dist/node.d.ts +3 -5
- package/dist/node.js +4 -5
- package/dist/{protocol-z-jeCUGO.d.ts → protocol-BGQAB0op.d.ts} +6 -3
- package/dist/{protocol-DkhGNP0h.js → protocol-Ci9LLiwO.js} +1 -2
- package/dist/r3f.d.ts +22 -6
- package/dist/r3f.js +28 -19
- package/dist/{react-CTADh3NN.js → react-DzrtrzZy.js} +4 -6
- package/dist/react.d.ts +4 -6
- package/dist/react.js +1 -1
- package/dist/{scene-DyYdEQdy.js → scene-BnkCS0sv.js} +592 -16
- package/dist/{scene-like-YcY08oii.d.ts → scene-like-BzkDNHCy.d.ts} +410 -42
- package/dist/{snapshot-Cf6NgDl7.js → snapshot-BkbGPspK.js} +1 -2
- package/dist/{store-C5nzCpxy.d.ts → store-BKFzSykN.d.ts} +3 -9
- package/dist/{store-Z6A2HPih.js → store-CEd2y2KS.js} +7 -9
- package/dist/store.d.ts +2 -4
- package/dist/store.js +4 -5
- package/dist/three.d.ts +2 -6
- package/dist/three.js +4 -6
- package/dist/{views-Dh3aWc2q.js → views-CUBMOK0U.js} +5 -8
- package/dist/wasm/fast_mesh_wasm.d.ts +77 -6
- package/dist/wasm/fast_mesh_wasm.js +167 -6
- package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
- package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +8 -1
- package/dist/wasm-threads/fast_mesh_wasm.d.ts +77 -6
- package/dist/wasm-threads/fast_mesh_wasm.js +167 -6
- package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
- package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +8 -1
- package/dist/web.d.ts +3 -5
- package/dist/web.js +4 -5
- package/dist/worker-engine.d.ts +1 -7
- package/dist/worker-engine.js +1 -1
- package/dist/worker-entry.js +2 -3
- package/dist/worker.d.ts +2 -2
- package/dist/worker.js +1 -1
- package/package.json +16 -4
package/dist/io.js
ADDED
|
@@ -0,0 +1,1395 @@
|
|
|
1
|
+
// src/io/index.ts
|
|
2
|
+
/**
|
|
3
|
+
* Reads the mesh's views, copies them (views borrow wasm memory and die on
|
|
4
|
+
* the next scene call), drops dead slots and optionally applies the
|
|
5
|
+
* placement. Throws when the handle is unknown, like `views` does.
|
|
6
|
+
*/
|
|
7
|
+
function snapshot(scene, mesh, options) {
|
|
8
|
+
const views = scene.views(mesh);
|
|
9
|
+
const positions = views.positions().slice();
|
|
10
|
+
const indices = views.indices().slice();
|
|
11
|
+
const rawNormals = views.normals();
|
|
12
|
+
const rawColors = views.colors();
|
|
13
|
+
const vertexSlots = positions.length / 3;
|
|
14
|
+
const triangleSlots = indices.length / 3;
|
|
15
|
+
const normals = rawNormals !== null && rawNormals !== void 0 && rawNormals.length >= positions.length ? rawNormals.slice() : null;
|
|
16
|
+
const colors = rawColors !== null && rawColors !== void 0 && rawColors.length >= 4 / 3 * positions.length ? rawColors.slice() : null;
|
|
17
|
+
const remap = new Int32Array(vertexSlots).fill(-1);
|
|
18
|
+
const kept = new Uint32Array(indices.length);
|
|
19
|
+
let triangles = 0;
|
|
20
|
+
let vertices = 0;
|
|
21
|
+
for (let t = 0; t < triangleSlots; t++) {
|
|
22
|
+
const a = indices[3 * t];
|
|
23
|
+
const b = indices[3 * t + 1];
|
|
24
|
+
const c = indices[3 * t + 2];
|
|
25
|
+
if (a === 0 && b === 0 && c === 0) continue;
|
|
26
|
+
for (const v of [
|
|
27
|
+
a,
|
|
28
|
+
b,
|
|
29
|
+
c
|
|
30
|
+
]) {
|
|
31
|
+
if (v >= vertexSlots) throw new Error(`fast-mesh-wasm/io: triangle ${t} indexes missing vertex ${v}`);
|
|
32
|
+
if (remap[v] === -1) remap[v] = vertices++;
|
|
33
|
+
}
|
|
34
|
+
kept[3 * triangles] = remap[a];
|
|
35
|
+
kept[3 * triangles + 1] = remap[b];
|
|
36
|
+
kept[3 * triangles + 2] = remap[c];
|
|
37
|
+
triangles++;
|
|
38
|
+
}
|
|
39
|
+
const outPositions = new Float32Array(3 * vertices);
|
|
40
|
+
const outNormals = normals !== null ? new Float32Array(3 * vertices) : null;
|
|
41
|
+
const outColors = colors !== null ? new Uint8Array(4 * vertices) : null;
|
|
42
|
+
for (let v = 0; v < vertexSlots; v++) {
|
|
43
|
+
const to = remap[v];
|
|
44
|
+
if (to === -1) continue;
|
|
45
|
+
outPositions[3 * to] = positions[3 * v];
|
|
46
|
+
outPositions[3 * to + 1] = positions[3 * v + 1];
|
|
47
|
+
outPositions[3 * to + 2] = positions[3 * v + 2];
|
|
48
|
+
if (outNormals !== null && normals !== null) {
|
|
49
|
+
outNormals[3 * to] = normals[3 * v];
|
|
50
|
+
outNormals[3 * to + 1] = normals[3 * v + 1];
|
|
51
|
+
outNormals[3 * to + 2] = normals[3 * v + 2];
|
|
52
|
+
}
|
|
53
|
+
if (outColors !== null && colors !== null) {
|
|
54
|
+
outColors[4 * to] = colors[4 * v];
|
|
55
|
+
outColors[4 * to + 1] = colors[4 * v + 1];
|
|
56
|
+
outColors[4 * to + 2] = colors[4 * v + 2];
|
|
57
|
+
outColors[4 * to + 3] = colors[4 * v + 3];
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (options?.applyPlacement !== false) applyMatrix(scene.matrix4(mesh), outPositions, outNormals);
|
|
61
|
+
return {
|
|
62
|
+
positions: outPositions,
|
|
63
|
+
normals: outNormals,
|
|
64
|
+
colors: outColors,
|
|
65
|
+
indices: kept.subarray(0, 3 * triangles),
|
|
66
|
+
triangles
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Maps positions through the column-major world matrix and normals through
|
|
71
|
+
* its inverse-transpose (renormalized), in place.
|
|
72
|
+
*/
|
|
73
|
+
function applyMatrix(m, positions, normals) {
|
|
74
|
+
const m00 = m[0];
|
|
75
|
+
const m01 = m[1];
|
|
76
|
+
const m02 = m[2];
|
|
77
|
+
const m10 = m[4];
|
|
78
|
+
const m11 = m[5];
|
|
79
|
+
const m12 = m[6];
|
|
80
|
+
const m20 = m[8];
|
|
81
|
+
const m21 = m[9];
|
|
82
|
+
const m22 = m[10];
|
|
83
|
+
const tx = m[12];
|
|
84
|
+
const ty = m[13];
|
|
85
|
+
const tz = m[14];
|
|
86
|
+
for (let i = 0; i < positions.length; i += 3) {
|
|
87
|
+
const x = positions[i];
|
|
88
|
+
const y = positions[i + 1];
|
|
89
|
+
const z = positions[i + 2];
|
|
90
|
+
positions[i] = m00 * x + m10 * y + m20 * z + tx;
|
|
91
|
+
positions[i + 1] = m01 * x + m11 * y + m21 * z + ty;
|
|
92
|
+
positions[i + 2] = m02 * x + m12 * y + m22 * z + tz;
|
|
93
|
+
}
|
|
94
|
+
if (normals === null) return;
|
|
95
|
+
const a00 = m11 * m22 - m12 * m21;
|
|
96
|
+
const a01 = m12 * m20 - m10 * m22;
|
|
97
|
+
const a02 = m10 * m21 - m11 * m20;
|
|
98
|
+
const det = m00 * a00 + m01 * a01 + m02 * a02;
|
|
99
|
+
if (!(Math.abs(det) > 1e-30)) return;
|
|
100
|
+
const s = 1 / det;
|
|
101
|
+
const n00 = a00 * s;
|
|
102
|
+
const n01 = (m02 * m21 - m01 * m22) * s;
|
|
103
|
+
const n02 = (m01 * m12 - m02 * m11) * s;
|
|
104
|
+
const n10 = a01 * s;
|
|
105
|
+
const n11 = (m00 * m22 - m02 * m20) * s;
|
|
106
|
+
const n12 = (m02 * m10 - m00 * m12) * s;
|
|
107
|
+
const n20 = a02 * s;
|
|
108
|
+
const n21 = (m01 * m20 - m00 * m21) * s;
|
|
109
|
+
const n22 = (m00 * m11 - m01 * m10) * s;
|
|
110
|
+
for (let i = 0; i < normals.length; i += 3) {
|
|
111
|
+
const x = normals[i];
|
|
112
|
+
const y = normals[i + 1];
|
|
113
|
+
const z = normals[i + 2];
|
|
114
|
+
const rx = n00 * x + n10 * y + n20 * z;
|
|
115
|
+
const ry = n01 * x + n11 * y + n21 * z;
|
|
116
|
+
const rz = n02 * x + n12 * y + n22 * z;
|
|
117
|
+
const len = Math.hypot(rx, ry, rz);
|
|
118
|
+
if (len > 1e-30) {
|
|
119
|
+
normals[i] = rx / len;
|
|
120
|
+
normals[i + 1] = ry / len;
|
|
121
|
+
normals[i + 2] = rz / len;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** The geometric normal of triangle `t`, or zeros when degenerate. */
|
|
126
|
+
function facetNormal(positions, indices, t, out) {
|
|
127
|
+
const a = 3 * indices[3 * t];
|
|
128
|
+
const b = 3 * indices[3 * t + 1];
|
|
129
|
+
const c = 3 * indices[3 * t + 2];
|
|
130
|
+
const ux = positions[b] - positions[a];
|
|
131
|
+
const uy = positions[b + 1] - positions[a + 1];
|
|
132
|
+
const uz = positions[b + 2] - positions[a + 2];
|
|
133
|
+
const vx = positions[c] - positions[a];
|
|
134
|
+
const vy = positions[c + 1] - positions[a + 1];
|
|
135
|
+
const vz = positions[c + 2] - positions[a + 2];
|
|
136
|
+
const nx = uy * vz - uz * vy;
|
|
137
|
+
const ny = uz * vx - ux * vz;
|
|
138
|
+
const nz = ux * vy - uy * vx;
|
|
139
|
+
const len = Math.hypot(nx, ny, nz);
|
|
140
|
+
out[0] = len > 0 ? nx / len : 0;
|
|
141
|
+
out[1] = len > 0 ? ny / len : 0;
|
|
142
|
+
out[2] = len > 0 ? nz / len : 0;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Binary STL: an 80-byte header, the triangle count, then 50 bytes per
|
|
146
|
+
* triangle (normal, three corners as f32, a zero attribute word).
|
|
147
|
+
*/
|
|
148
|
+
function exportSTL(scene, mesh, options) {
|
|
149
|
+
const snap = snapshot(scene, mesh, options);
|
|
150
|
+
if (options?.binary === false) return new TextEncoder().encode(exportSTLAscii(snap, options?.name ?? "mesh"));
|
|
151
|
+
const bytes = new Uint8Array(84 + 50 * snap.triangles);
|
|
152
|
+
const header = `exported by fast-mesh-wasm${options?.name !== void 0 ? ` (${options.name})` : ""}`;
|
|
153
|
+
bytes.set(new TextEncoder().encode(header).subarray(0, 80), 0);
|
|
154
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
155
|
+
view.setUint32(80, snap.triangles, true);
|
|
156
|
+
const n = /* @__PURE__ */ new Float32Array(3);
|
|
157
|
+
const useNormals = snap.normals !== null;
|
|
158
|
+
for (let t = 0; t < snap.triangles; t++) {
|
|
159
|
+
if (useNormals) {
|
|
160
|
+
const nx = snap.normals[3 * snap.indices[3 * t]] + snap.normals[3 * snap.indices[3 * t + 1]] + snap.normals[3 * snap.indices[3 * t + 2]];
|
|
161
|
+
const ny = snap.normals[3 * snap.indices[3 * t] + 1] + snap.normals[3 * snap.indices[3 * t + 1] + 1] + snap.normals[3 * snap.indices[3 * t + 2] + 1];
|
|
162
|
+
const nz = snap.normals[3 * snap.indices[3 * t] + 2] + snap.normals[3 * snap.indices[3 * t + 1] + 2] + snap.normals[3 * snap.indices[3 * t + 2] + 2];
|
|
163
|
+
const len = Math.hypot(nx, ny, nz);
|
|
164
|
+
n[0] = len > 0 ? nx / len : 0;
|
|
165
|
+
n[1] = len > 0 ? ny / len : 0;
|
|
166
|
+
n[2] = len > 0 ? nz / len : 0;
|
|
167
|
+
} else facetNormal(snap.positions, snap.indices, t, n);
|
|
168
|
+
let at = 84 + 50 * t;
|
|
169
|
+
view.setFloat32(at, n[0], true);
|
|
170
|
+
view.setFloat32(at + 4, n[1], true);
|
|
171
|
+
view.setFloat32(at + 8, n[2], true);
|
|
172
|
+
at += 12;
|
|
173
|
+
for (let k = 0; k < 3; k++) {
|
|
174
|
+
const v = 3 * snap.indices[3 * t + k];
|
|
175
|
+
view.setFloat32(at, snap.positions[v], true);
|
|
176
|
+
view.setFloat32(at + 4, snap.positions[v + 1], true);
|
|
177
|
+
view.setFloat32(at + 8, snap.positions[v + 2], true);
|
|
178
|
+
at += 12;
|
|
179
|
+
}
|
|
180
|
+
view.setUint16(at, 0, true);
|
|
181
|
+
}
|
|
182
|
+
return bytes;
|
|
183
|
+
}
|
|
184
|
+
function exportSTLAscii(snap, name) {
|
|
185
|
+
const parts = [`solid ${name}\n`];
|
|
186
|
+
const n = /* @__PURE__ */ new Float32Array(3);
|
|
187
|
+
for (let t = 0; t < snap.triangles; t++) {
|
|
188
|
+
facetNormal(snap.positions, snap.indices, t, n);
|
|
189
|
+
parts.push(`facet normal ${n[0]} ${n[1]} ${n[2]}\n outer loop\n`);
|
|
190
|
+
for (let k = 0; k < 3; k++) {
|
|
191
|
+
const v = 3 * snap.indices[3 * t + k];
|
|
192
|
+
parts.push(` vertex ${snap.positions[v]} ${snap.positions[v + 1]} ${snap.positions[v + 2]}\n`);
|
|
193
|
+
}
|
|
194
|
+
parts.push(" endloop\nendfacet\n");
|
|
195
|
+
}
|
|
196
|
+
parts.push(`endsolid ${name}\n`);
|
|
197
|
+
return parts.join("");
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Wavefront OBJ: `v` positions (with `r g b` 0..1 suffixes where the mesh
|
|
201
|
+
* is colored, a widely read extension), `vn` normals where present, and
|
|
202
|
+
* `f` faces (`v//vn` with normals, else `v`). 1-based.
|
|
203
|
+
*/
|
|
204
|
+
function exportOBJ(scene, mesh, options) {
|
|
205
|
+
const snap = snapshot(scene, mesh, options);
|
|
206
|
+
const name = options?.name ?? "mesh";
|
|
207
|
+
const vertices = snap.positions.length / 3;
|
|
208
|
+
const parts = [`o ${name}\n`];
|
|
209
|
+
for (let v = 0; v < vertices; v++) if (snap.colors !== null) {
|
|
210
|
+
const r = (snap.colors[4 * v] / 255).toPrecision(8);
|
|
211
|
+
const g = (snap.colors[4 * v + 1] / 255).toPrecision(8);
|
|
212
|
+
const b = (snap.colors[4 * v + 2] / 255).toPrecision(8);
|
|
213
|
+
parts.push(`v ${snap.positions[3 * v]} ${snap.positions[3 * v + 1]} ${snap.positions[3 * v + 2]} ${r} ${g} ${b}\n`);
|
|
214
|
+
} else parts.push(`v ${snap.positions[3 * v]} ${snap.positions[3 * v + 1]} ${snap.positions[3 * v + 2]}\n`);
|
|
215
|
+
const useNormals = snap.normals !== null;
|
|
216
|
+
if (useNormals) for (let v = 0; v < vertices; v++) parts.push(`vn ${snap.normals[3 * v]} ${snap.normals[3 * v + 1]} ${snap.normals[3 * v + 2]}\n`);
|
|
217
|
+
for (let t = 0; t < snap.triangles; t++) {
|
|
218
|
+
const a = snap.indices[3 * t] + 1;
|
|
219
|
+
const b = snap.indices[3 * t + 1] + 1;
|
|
220
|
+
const c = snap.indices[3 * t + 2] + 1;
|
|
221
|
+
parts.push(useNormals ? `f ${a}//${a} ${b}//${b} ${c}//${c}\n` : `f ${a} ${b} ${c}\n`);
|
|
222
|
+
}
|
|
223
|
+
return new TextEncoder().encode(parts.join(""));
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Stanford PLY: `x y z` floats, `nx ny nz` where normals exist, `red green
|
|
227
|
+
* blue alpha` uchar where colors exist, and `vertex_indices` faces.
|
|
228
|
+
*/
|
|
229
|
+
function exportPLY(scene, mesh, options) {
|
|
230
|
+
const snap = snapshot(scene, mesh, options);
|
|
231
|
+
const vertices = snap.positions.length / 3;
|
|
232
|
+
const useNormals = snap.normals !== null;
|
|
233
|
+
const useColors = snap.colors !== null;
|
|
234
|
+
const header = [
|
|
235
|
+
"ply",
|
|
236
|
+
`format ${options?.binary === false ? "ascii 1.0" : "binary_little_endian 1.0"}`,
|
|
237
|
+
`element vertex ${vertices}`,
|
|
238
|
+
"property float x",
|
|
239
|
+
"property float y",
|
|
240
|
+
"property float z",
|
|
241
|
+
...useNormals ? [
|
|
242
|
+
"property float nx",
|
|
243
|
+
"property float ny",
|
|
244
|
+
"property float nz"
|
|
245
|
+
] : [],
|
|
246
|
+
...useColors ? [
|
|
247
|
+
"property uchar red",
|
|
248
|
+
"property uchar green",
|
|
249
|
+
"property uchar blue",
|
|
250
|
+
"property uchar alpha"
|
|
251
|
+
] : [],
|
|
252
|
+
`element face ${snap.triangles}`,
|
|
253
|
+
"property list uchar uint vertex_indices",
|
|
254
|
+
"end_header",
|
|
255
|
+
""
|
|
256
|
+
].join("\n");
|
|
257
|
+
if (options?.binary === false) {
|
|
258
|
+
const parts = [header];
|
|
259
|
+
for (let v = 0; v < vertices; v++) {
|
|
260
|
+
let line = `${snap.positions[3 * v]} ${snap.positions[3 * v + 1]} ${snap.positions[3 * v + 2]}`;
|
|
261
|
+
if (useNormals) line += ` ${snap.normals[3 * v]} ${snap.normals[3 * v + 1]} ${snap.normals[3 * v + 2]}`;
|
|
262
|
+
if (useColors) line += ` ${snap.colors?.[4 * v]} ${snap.colors?.[4 * v + 1]} ${snap.colors?.[4 * v + 2]} ${snap.colors?.[4 * v + 3]}`;
|
|
263
|
+
parts.push(`${line}\n`);
|
|
264
|
+
}
|
|
265
|
+
for (let t = 0; t < snap.triangles; t++) parts.push(`3 ${snap.indices[3 * t]} ${snap.indices[3 * t + 1]} ${snap.indices[3 * t + 2]}\n`);
|
|
266
|
+
return new TextEncoder().encode(parts.join(""));
|
|
267
|
+
}
|
|
268
|
+
const head = new TextEncoder().encode(header);
|
|
269
|
+
const body = new Uint8Array(vertices * (4 * (3 + (useNormals ? 3 : 0)) + (useColors ? 4 : 0)) + snap.triangles * 13);
|
|
270
|
+
const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
|
|
271
|
+
let at = 0;
|
|
272
|
+
for (let v = 0; v < vertices; v++) {
|
|
273
|
+
view.setFloat32(at, snap.positions[3 * v], true);
|
|
274
|
+
view.setFloat32(at + 4, snap.positions[3 * v + 1], true);
|
|
275
|
+
view.setFloat32(at + 8, snap.positions[3 * v + 2], true);
|
|
276
|
+
at += 12;
|
|
277
|
+
if (useNormals) {
|
|
278
|
+
view.setFloat32(at, snap.normals[3 * v], true);
|
|
279
|
+
view.setFloat32(at + 4, snap.normals[3 * v + 1], true);
|
|
280
|
+
view.setFloat32(at + 8, snap.normals[3 * v + 2], true);
|
|
281
|
+
at += 12;
|
|
282
|
+
}
|
|
283
|
+
if (useColors) {
|
|
284
|
+
body[at] = snap.colors?.[4 * v] ?? 0;
|
|
285
|
+
body[at + 1] = snap.colors?.[4 * v + 1] ?? 0;
|
|
286
|
+
body[at + 2] = snap.colors?.[4 * v + 2] ?? 0;
|
|
287
|
+
body[at + 3] = snap.colors?.[4 * v + 3] ?? 0;
|
|
288
|
+
at += 4;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
for (let t = 0; t < snap.triangles; t++) {
|
|
292
|
+
view.setUint8(at, 3);
|
|
293
|
+
view.setUint32(at + 1, snap.indices[3 * t], true);
|
|
294
|
+
view.setUint32(at + 5, snap.indices[3 * t + 1], true);
|
|
295
|
+
view.setUint32(at + 9, snap.indices[3 * t + 2], true);
|
|
296
|
+
at += 13;
|
|
297
|
+
}
|
|
298
|
+
const out = new Uint8Array(head.length + body.length);
|
|
299
|
+
out.set(head, 0);
|
|
300
|
+
out.set(body, head.length);
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
303
|
+
function exportGLTF(scene, mesh, options) {
|
|
304
|
+
if (options?.draco === true) return exportGLTFDraco(scene, mesh, options);
|
|
305
|
+
const snap = snapshot(scene, mesh, options);
|
|
306
|
+
const name = options?.name ?? "mesh";
|
|
307
|
+
const vertices = snap.positions.length / 3;
|
|
308
|
+
const useNormals = snap.normals !== null;
|
|
309
|
+
const useColors = snap.colors !== null;
|
|
310
|
+
const positionBytes = new Uint8Array(snap.positions.buffer, snap.positions.byteOffset, snap.positions.byteLength);
|
|
311
|
+
const normalBytes = snap.normals !== null ? new Uint8Array(snap.normals.buffer, snap.normals.byteOffset, snap.normals.byteLength) : null;
|
|
312
|
+
const chunks = [positionBytes];
|
|
313
|
+
if (normalBytes !== null) chunks.push(normalBytes);
|
|
314
|
+
let colorBytes = null;
|
|
315
|
+
if (snap.colors !== null) {
|
|
316
|
+
colorBytes = new Uint8Array(snap.colors.buffer, snap.colors.byteOffset, snap.colors.byteLength);
|
|
317
|
+
chunks.push(colorBytes);
|
|
318
|
+
}
|
|
319
|
+
const indicesCopy = new Uint32Array(snap.indices);
|
|
320
|
+
const indicesChunk = new Uint8Array(indicesCopy.buffer, indicesCopy.byteOffset, indicesCopy.byteLength);
|
|
321
|
+
chunks.push(indicesChunk);
|
|
322
|
+
let offset = 0;
|
|
323
|
+
const bufferViews = [];
|
|
324
|
+
for (const chunk of chunks) {
|
|
325
|
+
bufferViews.push({
|
|
326
|
+
byteOffset: offset,
|
|
327
|
+
byteLength: chunk.length,
|
|
328
|
+
target: 34962
|
|
329
|
+
});
|
|
330
|
+
offset += chunk.length;
|
|
331
|
+
}
|
|
332
|
+
bufferViews[bufferViews.length - 1].target = 34963;
|
|
333
|
+
const binLength = offset;
|
|
334
|
+
const { min, max } = positionBounds(snap.positions);
|
|
335
|
+
let nextView = 1;
|
|
336
|
+
const positionView = 0;
|
|
337
|
+
const normalView = useNormals ? nextView++ : -1;
|
|
338
|
+
const colorView = useColors ? nextView++ : -1;
|
|
339
|
+
const attributes = { POSITION: 0 };
|
|
340
|
+
let accessorIndex = 1;
|
|
341
|
+
if (useNormals) attributes["NORMAL"] = accessorIndex++;
|
|
342
|
+
if (useColors) attributes["COLOR_0"] = accessorIndex++;
|
|
343
|
+
const accessors = [{
|
|
344
|
+
bufferView: positionView,
|
|
345
|
+
componentType: 5126,
|
|
346
|
+
count: vertices,
|
|
347
|
+
type: "VEC3",
|
|
348
|
+
min,
|
|
349
|
+
max
|
|
350
|
+
}];
|
|
351
|
+
if (useNormals) accessors.push({
|
|
352
|
+
bufferView: normalView,
|
|
353
|
+
componentType: 5126,
|
|
354
|
+
count: vertices,
|
|
355
|
+
type: "VEC3"
|
|
356
|
+
});
|
|
357
|
+
if (useColors) accessors.push({
|
|
358
|
+
bufferView: colorView,
|
|
359
|
+
componentType: 5121,
|
|
360
|
+
count: vertices,
|
|
361
|
+
type: "VEC4",
|
|
362
|
+
normalized: true
|
|
363
|
+
});
|
|
364
|
+
accessors.push({
|
|
365
|
+
bufferView: bufferViews.length - 1,
|
|
366
|
+
componentType: 5125,
|
|
367
|
+
count: snap.indices.length,
|
|
368
|
+
type: "SCALAR"
|
|
369
|
+
});
|
|
370
|
+
return packGLTF({
|
|
371
|
+
asset: {
|
|
372
|
+
version: "2.0",
|
|
373
|
+
generator: options?.generator ?? "fast-mesh-wasm"
|
|
374
|
+
},
|
|
375
|
+
scenes: [{ nodes: [0] }],
|
|
376
|
+
nodes: [{
|
|
377
|
+
mesh: 0,
|
|
378
|
+
name
|
|
379
|
+
}],
|
|
380
|
+
meshes: [{
|
|
381
|
+
name,
|
|
382
|
+
primitives: [{
|
|
383
|
+
attributes,
|
|
384
|
+
indices: accessors.length - 1,
|
|
385
|
+
mode: 4
|
|
386
|
+
}]
|
|
387
|
+
}],
|
|
388
|
+
accessors,
|
|
389
|
+
bufferViews: bufferViews.map((b) => ({
|
|
390
|
+
buffer: 0,
|
|
391
|
+
...b
|
|
392
|
+
})),
|
|
393
|
+
buffers: [{ byteLength: binLength }]
|
|
394
|
+
}, chunks, options?.binary !== false);
|
|
395
|
+
}
|
|
396
|
+
/** The POSITION min/max over compacted vertices (zeros without vertices). */
|
|
397
|
+
function positionBounds(positions) {
|
|
398
|
+
const min = [
|
|
399
|
+
0,
|
|
400
|
+
0,
|
|
401
|
+
0
|
|
402
|
+
];
|
|
403
|
+
const max = [
|
|
404
|
+
0,
|
|
405
|
+
0,
|
|
406
|
+
0
|
|
407
|
+
];
|
|
408
|
+
const vertices = positions.length / 3;
|
|
409
|
+
if (vertices > 0) {
|
|
410
|
+
min[0] = positions[0];
|
|
411
|
+
min[1] = positions[1];
|
|
412
|
+
min[2] = positions[2];
|
|
413
|
+
max[0] = min[0];
|
|
414
|
+
max[1] = min[1];
|
|
415
|
+
max[2] = min[2];
|
|
416
|
+
for (let v = 1; v < vertices; v++) for (let c = 0; c < 3; c++) {
|
|
417
|
+
const x = positions[3 * v + c];
|
|
418
|
+
if (x < min[c]) min[c] = x;
|
|
419
|
+
if (x > max[c]) max[c] = x;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return {
|
|
423
|
+
min,
|
|
424
|
+
max
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Packs the asset JSON plus its buffer chunks into one value: a binary
|
|
429
|
+
* `.glb`, or `.gltf` JSON with the buffer embedded as a base64 data URI.
|
|
430
|
+
*/
|
|
431
|
+
function packGLTF(json, chunks, binary) {
|
|
432
|
+
const binLength = json.buffers[0].byteLength;
|
|
433
|
+
if (!binary) {
|
|
434
|
+
const bin = concat(chunks, binLength);
|
|
435
|
+
json.buffers[0].uri = `data:application/octet-stream;base64,${toBase64(bin)}`;
|
|
436
|
+
return new TextEncoder().encode(JSON.stringify(json));
|
|
437
|
+
}
|
|
438
|
+
const jsonBytes = new TextEncoder().encode(JSON.stringify(json));
|
|
439
|
+
const jsonPadded = padLength(jsonBytes.length);
|
|
440
|
+
const binPadded = binLength + 3 & -4;
|
|
441
|
+
const total = 20 + jsonPadded + 8 + binPadded;
|
|
442
|
+
const out = new Uint8Array(total);
|
|
443
|
+
const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
|
|
444
|
+
view.setUint32(0, 1179937895, true);
|
|
445
|
+
view.setUint32(4, 2, true);
|
|
446
|
+
view.setUint32(8, total, true);
|
|
447
|
+
view.setUint32(12, jsonPadded, true);
|
|
448
|
+
view.setUint32(16, 1313821514, true);
|
|
449
|
+
out.set(jsonBytes, 20);
|
|
450
|
+
out.fill(32, 20 + jsonBytes.length, 20 + jsonPadded);
|
|
451
|
+
const binAt = 20 + jsonPadded;
|
|
452
|
+
view.setUint32(binAt, binPadded, true);
|
|
453
|
+
view.setUint32(binAt + 4, 5130562, true);
|
|
454
|
+
let at = binAt + 8;
|
|
455
|
+
for (const chunk of chunks) {
|
|
456
|
+
out.set(chunk, at);
|
|
457
|
+
at += chunk.length;
|
|
458
|
+
}
|
|
459
|
+
return out;
|
|
460
|
+
}
|
|
461
|
+
function concat(chunks, total) {
|
|
462
|
+
const out = new Uint8Array(total);
|
|
463
|
+
let at = 0;
|
|
464
|
+
for (const chunk of chunks) {
|
|
465
|
+
out.set(chunk, at);
|
|
466
|
+
at += chunk.length;
|
|
467
|
+
}
|
|
468
|
+
return out;
|
|
469
|
+
}
|
|
470
|
+
function padLength(length) {
|
|
471
|
+
return length + 3 & -4;
|
|
472
|
+
}
|
|
473
|
+
function toBase64(bytes) {
|
|
474
|
+
const g = globalThis;
|
|
475
|
+
if (g.Buffer !== void 0) return g.Buffer.from(bytes).toString("base64");
|
|
476
|
+
let text = "";
|
|
477
|
+
for (let i = 0; i < bytes.length; i += 32768) text += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
478
|
+
return btoa(text);
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Encodes a triangle mesh into standalone Draco bytes (a `.drc` file):
|
|
482
|
+
* positions always, plus the `normals`/`colors` options when given.
|
|
483
|
+
* Positions encode as 32-bit floats (wider inputs narrow).
|
|
484
|
+
*
|
|
485
|
+
* The draco3d encoder (WASM) initializes on first use; its module is shared
|
|
486
|
+
* across calls. Needs the `draco3d` package installed unless `options`
|
|
487
|
+
* supplies the module or its `.wasm`.
|
|
488
|
+
*
|
|
489
|
+
* Decodes through {@link decodeDraco} (positions and faces only: it maps
|
|
490
|
+
* POSITION alone, so normals and colors need draco3d's own decoder).
|
|
491
|
+
*/
|
|
492
|
+
async function encodeDraco(positions, indices, options) {
|
|
493
|
+
const checkedPositions = checkedEncodePositions(positions);
|
|
494
|
+
const checkedIndices = checkedEncodeIndices(indices, checkedPositions.length / 3);
|
|
495
|
+
const checkedNormals = checkedEncodeNormals(options?.normals, checkedPositions.length);
|
|
496
|
+
const checkedColors = checkedEncodeColors(options?.colors, checkedPositions.length / 3);
|
|
497
|
+
const settings = encodeSettings(options);
|
|
498
|
+
return encodeMeshDraco(await encoderOf(options), checkedPositions, checkedIndices, checkedNormals, checkedColors, settings).bytes;
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* glTF 2.0 with `draco: true`: one node, one mesh, one `TRIANGLES`
|
|
502
|
+
* primitive whose attributes ride a Draco bitstream in a single buffer view.
|
|
503
|
+
* The primitive's accessors describe the decoded shape (POSITION keeps its
|
|
504
|
+
* min/max); the `KHR_draco_mesh_compression` extension maps them to the
|
|
505
|
+
* bitstream's attribute ids.
|
|
506
|
+
*/
|
|
507
|
+
async function exportGLTFDraco(scene, mesh, options) {
|
|
508
|
+
const snap = snapshot(scene, mesh, options);
|
|
509
|
+
const name = options?.name ?? "mesh";
|
|
510
|
+
const vertices = snap.positions.length / 3;
|
|
511
|
+
const settings = encodeSettings(options?.dracoOptions);
|
|
512
|
+
const positions = checkedEncodePositions(snap.positions);
|
|
513
|
+
const indices = checkedEncodeIndices(snap.indices, vertices);
|
|
514
|
+
const normals = checkedEncodeNormals(snap.normals, positions.length);
|
|
515
|
+
const colors = checkedEncodeColors(snap.colors, vertices);
|
|
516
|
+
const { bytes, positionId, normalId, colorId } = encodeMeshDraco(await encoderOf(options?.dracoOptions), positions, indices, normals, colors, settings);
|
|
517
|
+
const { min, max } = positionBounds(snap.positions);
|
|
518
|
+
const attributes = { POSITION: 0 };
|
|
519
|
+
const accessors = [{
|
|
520
|
+
componentType: 5126,
|
|
521
|
+
count: vertices,
|
|
522
|
+
type: "VEC3",
|
|
523
|
+
min,
|
|
524
|
+
max
|
|
525
|
+
}];
|
|
526
|
+
const dracoAttributes = { POSITION: positionId };
|
|
527
|
+
let accessorIndex = 1;
|
|
528
|
+
if (normals !== null) {
|
|
529
|
+
attributes["NORMAL"] = accessorIndex++;
|
|
530
|
+
accessors.push({
|
|
531
|
+
componentType: 5126,
|
|
532
|
+
count: vertices,
|
|
533
|
+
type: "VEC3"
|
|
534
|
+
});
|
|
535
|
+
dracoAttributes["NORMAL"] = normalId;
|
|
536
|
+
}
|
|
537
|
+
if (colors !== null) {
|
|
538
|
+
attributes["COLOR_0"] = accessorIndex++;
|
|
539
|
+
accessors.push({
|
|
540
|
+
componentType: 5121,
|
|
541
|
+
count: vertices,
|
|
542
|
+
type: "VEC4",
|
|
543
|
+
normalized: true
|
|
544
|
+
});
|
|
545
|
+
dracoAttributes["COLOR_0"] = colorId;
|
|
546
|
+
}
|
|
547
|
+
accessors.push({
|
|
548
|
+
componentType: 5125,
|
|
549
|
+
count: indices.length,
|
|
550
|
+
type: "SCALAR"
|
|
551
|
+
});
|
|
552
|
+
return packGLTF({
|
|
553
|
+
asset: {
|
|
554
|
+
version: "2.0",
|
|
555
|
+
generator: options?.generator ?? "fast-mesh-wasm"
|
|
556
|
+
},
|
|
557
|
+
scenes: [{ nodes: [0] }],
|
|
558
|
+
nodes: [{
|
|
559
|
+
mesh: 0,
|
|
560
|
+
name
|
|
561
|
+
}],
|
|
562
|
+
meshes: [{
|
|
563
|
+
name,
|
|
564
|
+
primitives: [{
|
|
565
|
+
attributes,
|
|
566
|
+
indices: accessors.length - 1,
|
|
567
|
+
mode: 4,
|
|
568
|
+
extensions: { KHR_draco_mesh_compression: {
|
|
569
|
+
bufferView: 0,
|
|
570
|
+
attributes: dracoAttributes
|
|
571
|
+
} }
|
|
572
|
+
}]
|
|
573
|
+
}],
|
|
574
|
+
accessors,
|
|
575
|
+
bufferViews: [{
|
|
576
|
+
buffer: 0,
|
|
577
|
+
byteOffset: 0,
|
|
578
|
+
byteLength: bytes.length
|
|
579
|
+
}],
|
|
580
|
+
buffers: [{ byteLength: bytes.length }],
|
|
581
|
+
extensionsUsed: ["KHR_draco_mesh_compression"],
|
|
582
|
+
extensionsRequired: ["KHR_draco_mesh_compression"]
|
|
583
|
+
}, [bytes], options?.binary !== false);
|
|
584
|
+
}
|
|
585
|
+
/** Validates the quantization/level/order options before the module loads. */
|
|
586
|
+
function encodeSettings(options) {
|
|
587
|
+
const bits = options?.quantizationBits;
|
|
588
|
+
checkedQuantizationBits(bits?.texCoord, "texCoord", 12);
|
|
589
|
+
const level = options?.compressionLevel ?? 5;
|
|
590
|
+
if (!Number.isInteger(level) || level < 0 || level > 10) throw new Error(`Draco: the compression level must be an integer from 0 to 10 (got ${options?.compressionLevel})`);
|
|
591
|
+
return {
|
|
592
|
+
positionBits: checkedQuantizationBits(bits?.position, "position", 14),
|
|
593
|
+
normalBits: checkedQuantizationBits(bits?.normal, "normal", 10),
|
|
594
|
+
colorBits: checkedQuantizationBits(bits?.color, "color", 8),
|
|
595
|
+
level,
|
|
596
|
+
preserveFaceOrder: options?.preserveFaceOrder === true
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* One attribute's quantization bits: the default without an override, else
|
|
601
|
+
* an integer 1..30. Checked here because the encoder accepts any int.
|
|
602
|
+
*/
|
|
603
|
+
function checkedQuantizationBits(value, name, fallback) {
|
|
604
|
+
if (value === void 0) return fallback;
|
|
605
|
+
if (!Number.isInteger(value) || value < 1 || value > 30) throw new Error(`Draco: ${name} quantization bits must be an integer from 1 to 30 (got ${value})`);
|
|
606
|
+
return value;
|
|
607
|
+
}
|
|
608
|
+
/** Copies positions to f32, checking length (3 per vertex) and finiteness. */
|
|
609
|
+
function checkedEncodePositions(positions) {
|
|
610
|
+
if (positions.length === 0) throw new Error("Draco: cannot encode a mesh with no vertices");
|
|
611
|
+
if (positions.length % 3 !== 0) throw new Error(`Draco: positions need 3 numbers per vertex (got length ${positions.length})`);
|
|
612
|
+
const out = Float32Array.from(positions);
|
|
613
|
+
for (let i = 0; i < out.length; i++) if (!Number.isFinite(out[i])) throw new Error(`Draco: position ${Math.floor(i / 3)} is not finite`);
|
|
614
|
+
return out;
|
|
615
|
+
}
|
|
616
|
+
/** Copies indices to u32, checking length (3 per triangle) and range. */
|
|
617
|
+
function checkedEncodeIndices(indices, vertices) {
|
|
618
|
+
if (indices.length === 0) throw new Error("Draco: cannot encode a mesh with no triangles");
|
|
619
|
+
if (indices.length % 3 !== 0) throw new Error(`Draco: indices need 3 corners per triangle (got length ${indices.length})`);
|
|
620
|
+
const out = new Uint32Array(indices.length);
|
|
621
|
+
for (let t = 0; t < indices.length / 3; t++) for (let k = 0; k < 3; k++) {
|
|
622
|
+
const c = indices[3 * t + k];
|
|
623
|
+
if (!Number.isInteger(c) || c < 0 || c >= vertices) throw new Error(`Draco: triangle ${t} indexes missing vertex ${c}`);
|
|
624
|
+
out[3 * t + k] = c;
|
|
625
|
+
}
|
|
626
|
+
return out;
|
|
627
|
+
}
|
|
628
|
+
/** Copies normals to f32 (`null` without), checking length and finiteness. */
|
|
629
|
+
function checkedEncodeNormals(normals, positionsLength) {
|
|
630
|
+
if (normals === null || normals === void 0) return null;
|
|
631
|
+
if (normals.length !== positionsLength) throw new Error(`Draco: normals need 3 numbers per vertex (got length ${normals.length} for ${positionsLength / 3} vertices)`);
|
|
632
|
+
const out = Float32Array.from(normals);
|
|
633
|
+
for (let i = 0; i < out.length; i++) if (!Number.isFinite(out[i])) throw new Error(`Draco: normal ${Math.floor(i / 3)} is not finite`);
|
|
634
|
+
return out;
|
|
635
|
+
}
|
|
636
|
+
/** Copies colors to RGBA bytes (`null` without), checking length and byte range. */
|
|
637
|
+
function checkedEncodeColors(colors, vertices) {
|
|
638
|
+
if (colors === null || colors === void 0) return null;
|
|
639
|
+
if (colors.length !== 4 * vertices) throw new Error(`Draco: colors need 4 bytes per vertex (got length ${colors.length} for ${vertices} vertices)`);
|
|
640
|
+
const out = new Uint8Array(4 * vertices);
|
|
641
|
+
for (let i = 0; i < out.length; i++) {
|
|
642
|
+
const c = colors[i];
|
|
643
|
+
if (!Number.isInteger(c) || c < 0 || c > 255) throw new Error(`Draco: colors[${i}] is not a byte 0..255 (got ${c})`);
|
|
644
|
+
out[i] = c;
|
|
645
|
+
}
|
|
646
|
+
return out;
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Builds the mesh (faces, POSITION, NORMAL/COLOR when present) and encodes
|
|
650
|
+
* it with the resolved settings. Colors ride a normalized uint8 attribute,
|
|
651
|
+
* like glTF's `COLOR_0`. Throws when the encoder reports failure.
|
|
652
|
+
*/
|
|
653
|
+
function encodeMeshDraco(module, positions, indices, normals, colors, settings) {
|
|
654
|
+
const mesh = new module.Mesh();
|
|
655
|
+
const builder = new module.MeshBuilder();
|
|
656
|
+
try {
|
|
657
|
+
builder.AddFacesToMesh(mesh, indices.length / 3, indices);
|
|
658
|
+
const positionId = builder.AddFloatAttributeToMesh(mesh, module.POSITION, positions.length / 3, 3, positions);
|
|
659
|
+
let normalId = null;
|
|
660
|
+
let colorId = null;
|
|
661
|
+
if (normals !== null) normalId = builder.AddFloatAttributeToMesh(mesh, module.NORMAL, normals.length / 3, 3, normals);
|
|
662
|
+
if (colors !== null) {
|
|
663
|
+
colorId = builder.AddUInt8Attribute(mesh, module.COLOR, colors.length / 4, 4, colors);
|
|
664
|
+
builder.SetNormalizedFlagForAttribute(mesh, colorId, true);
|
|
665
|
+
}
|
|
666
|
+
const encoder = new module.Encoder();
|
|
667
|
+
try {
|
|
668
|
+
encoder.SetSpeedOptions(10 - settings.level, 10 - settings.level);
|
|
669
|
+
encoder.SetAttributeQuantization(module.POSITION, settings.positionBits);
|
|
670
|
+
if (normals !== null) encoder.SetAttributeQuantization(module.NORMAL, settings.normalBits);
|
|
671
|
+
if (colors !== null) encoder.SetAttributeQuantization(module.COLOR, settings.colorBits);
|
|
672
|
+
encoder.SetEncodingMethod(settings.preserveFaceOrder ? module.MESH_SEQUENTIAL_ENCODING : module.MESH_EDGEBREAKER_ENCODING);
|
|
673
|
+
const out = new module.DracoInt8Array();
|
|
674
|
+
try {
|
|
675
|
+
const length = encoder.EncodeMeshToDracoBuffer(mesh, out);
|
|
676
|
+
if (!(length > 0)) throw new Error("Draco: encoding failed (the encoder returned no bytes)");
|
|
677
|
+
const bytes = new Uint8Array(length);
|
|
678
|
+
for (let i = 0; i < length; i++) bytes[i] = out.GetValue(i);
|
|
679
|
+
return {
|
|
680
|
+
bytes,
|
|
681
|
+
positionId,
|
|
682
|
+
normalId,
|
|
683
|
+
colorId
|
|
684
|
+
};
|
|
685
|
+
} finally {
|
|
686
|
+
module.destroy(out);
|
|
687
|
+
}
|
|
688
|
+
} finally {
|
|
689
|
+
module.destroy(encoder);
|
|
690
|
+
}
|
|
691
|
+
} finally {
|
|
692
|
+
module.destroy(builder);
|
|
693
|
+
module.destroy(mesh);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
/** The shared draco3d encoder module: `options`'s, or a lazily created one. */
|
|
697
|
+
async function encoderOf(options) {
|
|
698
|
+
if (options?.encoderModule !== void 0) {
|
|
699
|
+
const module = options.encoderModule;
|
|
700
|
+
if (typeof module?.Encoder !== "function" || typeof module?.MeshBuilder !== "function") throw new Error("Draco: the encoder module is not a draco3d encoder module (from createEncoderModule)");
|
|
701
|
+
return module;
|
|
702
|
+
}
|
|
703
|
+
if (options?.wasmBinary === void 0 && sharedEncoderModule !== null) return sharedEncoderModule;
|
|
704
|
+
const created = await createEncoderModule(options?.wasmBinary);
|
|
705
|
+
if (options?.wasmBinary === void 0) sharedEncoderModule = created;
|
|
706
|
+
return created;
|
|
707
|
+
}
|
|
708
|
+
/** The process-wide encoder module, created on the first default encode. */
|
|
709
|
+
let sharedEncoderModule = null;
|
|
710
|
+
/**
|
|
711
|
+
* Creates a draco3d encoder module, optionally seeded with the `.wasm` bytes.
|
|
712
|
+
* Imported lazily so bundles that never touch Draco never load the encoder.
|
|
713
|
+
*/
|
|
714
|
+
async function createEncoderModule(wasmBinary) {
|
|
715
|
+
let create;
|
|
716
|
+
try {
|
|
717
|
+
({createEncoderModule: create} = await import("draco3d"));
|
|
718
|
+
} catch {
|
|
719
|
+
throw new Error("Draco: encoding needs the draco3d package (npm install draco3d), or pass an encoder module");
|
|
720
|
+
}
|
|
721
|
+
const init = {};
|
|
722
|
+
if (wasmBinary !== void 0) init["wasmBinary"] = wasmBinary;
|
|
723
|
+
return create(init);
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Reads a glTF 2.0 asset: a binary `.glb`, or a `.gltf` JSON whose buffers
|
|
727
|
+
* are embedded base64 data URIs. Every triangle primitive of every mesh
|
|
728
|
+
* instanced by the default scene becomes one mesh (node transforms composed
|
|
729
|
+
* down the hierarchy, so placements are preserved); other primitive modes
|
|
730
|
+
* throw, except `TRIANGLE_STRIP` and `TRIANGLE_FAN`, which are expanded.
|
|
731
|
+
*
|
|
732
|
+
* @throws When the container is malformed, a buffer is external (load it
|
|
733
|
+
* with {@link importGLTFAsync} and a `resolveBuffer` callback), a primitive
|
|
734
|
+
* is Draco-compressed (decode it with {@link importGLTFAsync}) or not a
|
|
735
|
+
* triangle mesh, or the file holds no triangle meshes.
|
|
736
|
+
*/
|
|
737
|
+
function importGLTF(bytes) {
|
|
738
|
+
const { json, bin } = splitContainer(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
|
|
739
|
+
const doc = checkedDocument(json);
|
|
740
|
+
const buffers = resolveBuffers(doc, bin);
|
|
741
|
+
const usedNames = /* @__PURE__ */ new Map();
|
|
742
|
+
const kept = collectPrimitiveSpecs(doc).map((spec) => readPrimitive(doc, buffers, spec.node, spec.mesh, spec.primitive, spec.world, usedNames)).filter((p) => p.indices.length > 0);
|
|
743
|
+
if (kept.length === 0) throw new Error("glTF: the file has no triangle meshes");
|
|
744
|
+
return kept;
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Walks the default scene's node hierarchy once, resolving every instanced
|
|
748
|
+
* primitive with the world matrix its node placements compose. Shared by the
|
|
749
|
+
* sync and async importers, so both see the same nodes in the same order and
|
|
750
|
+
* fail on the same malformed hierarchies.
|
|
751
|
+
*/
|
|
752
|
+
function collectPrimitiveSpecs(doc) {
|
|
753
|
+
const roots = rootNodes(doc);
|
|
754
|
+
const specs = [];
|
|
755
|
+
const identity = Float64Array.from([
|
|
756
|
+
1,
|
|
757
|
+
0,
|
|
758
|
+
0,
|
|
759
|
+
0,
|
|
760
|
+
0,
|
|
761
|
+
1,
|
|
762
|
+
0,
|
|
763
|
+
0,
|
|
764
|
+
0,
|
|
765
|
+
0,
|
|
766
|
+
1,
|
|
767
|
+
0,
|
|
768
|
+
0,
|
|
769
|
+
0,
|
|
770
|
+
0,
|
|
771
|
+
1
|
|
772
|
+
]);
|
|
773
|
+
const trail = /* @__PURE__ */ new Set();
|
|
774
|
+
const visit = (nodeIndex, parent) => {
|
|
775
|
+
const nodes = doc.nodes ?? [];
|
|
776
|
+
const node = nodes[nodeIndex];
|
|
777
|
+
if (node === void 0) throw new Error(`glTF: node ${nodeIndex} is missing`);
|
|
778
|
+
if (trail.has(nodeIndex)) throw new Error(`glTF: the node hierarchy cycles through node ${nodeIndex}`);
|
|
779
|
+
trail.add(nodeIndex);
|
|
780
|
+
try {
|
|
781
|
+
const world = multiplyAffine(parent, localMatrix(node, nodeIndex));
|
|
782
|
+
if (node.mesh !== void 0) {
|
|
783
|
+
const mesh = doc.meshes?.[node.mesh];
|
|
784
|
+
if (mesh === void 0) throw new Error(`glTF: node ${nodeIndex} points at missing mesh ${node.mesh}`);
|
|
785
|
+
for (const primitive of mesh.primitives) specs.push({
|
|
786
|
+
node,
|
|
787
|
+
mesh,
|
|
788
|
+
primitive,
|
|
789
|
+
world
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
for (const child of node.children ?? []) {
|
|
793
|
+
if (!Number.isInteger(child) || child < 0 || child >= nodes.length) throw new Error(`glTF: node ${nodeIndex} has child ${child} past its ${nodes.length} nodes`);
|
|
794
|
+
visit(child, world);
|
|
795
|
+
}
|
|
796
|
+
} finally {
|
|
797
|
+
trail.delete(nodeIndex);
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
for (const root of roots) visit(root, identity);
|
|
801
|
+
return specs;
|
|
802
|
+
}
|
|
803
|
+
/**
|
|
804
|
+
* Decodes a standalone Draco file (`.drc`): a compressed triangle mesh. Only
|
|
805
|
+
* triangle meshes decode; point clouds throw.
|
|
806
|
+
*
|
|
807
|
+
* The draco3d decoder (WASM) initializes on first use; its module is shared
|
|
808
|
+
* across calls. Needs the `draco3d` package installed unless `options`
|
|
809
|
+
* supplies the module or its `.wasm`.
|
|
810
|
+
*
|
|
811
|
+
* @throws When the bytes are not a Draco triangle mesh.
|
|
812
|
+
*/
|
|
813
|
+
async function decodeDraco(bytes, options) {
|
|
814
|
+
const raw = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
815
|
+
return decodeDracoMesh(await decoderOf(options), raw, "Draco");
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Reads a glTF 2.0 asset like {@link importGLTF}: `KHR_draco_mesh_compression`
|
|
819
|
+
* primitives decode through the draco3d decoder (WASM), and external
|
|
820
|
+
* (non-embedded) `.bin` buffers load through `options.resolveBuffer`. A Draco
|
|
821
|
+
* primitive's positions and faces come from its compressed buffer view
|
|
822
|
+
* (attribute ids from the extension); its node placement still bakes into
|
|
823
|
+
* world positions, while colors read as `null` (compressed attributes beyond
|
|
824
|
+
* POSITION are not mapped).
|
|
825
|
+
*
|
|
826
|
+
* Primitives without the extension decode synchronously in place, so assets
|
|
827
|
+
* without Draco never initialize the decoder.
|
|
828
|
+
*
|
|
829
|
+
* @throws When the container is malformed, a buffer is external without a
|
|
830
|
+
* `resolveBuffer` (or its bytes cannot be resolved), a Draco primitive fails
|
|
831
|
+
* to decode, a primitive is not a triangle mesh, or the file holds no
|
|
832
|
+
* triangle meshes.
|
|
833
|
+
*/
|
|
834
|
+
async function importGLTFAsync(bytes, options) {
|
|
835
|
+
const { json, bin } = splitContainer(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
|
|
836
|
+
const doc = checkedDocument(json);
|
|
837
|
+
const buffers = await resolveBuffersAsync(doc, bin, options?.resolveBuffer);
|
|
838
|
+
const specs = collectPrimitiveSpecs(doc);
|
|
839
|
+
const usedNames = /* @__PURE__ */ new Map();
|
|
840
|
+
let shared = null;
|
|
841
|
+
const decoderOfOptions = async () => {
|
|
842
|
+
if (shared === null) shared = await decoderOf(options);
|
|
843
|
+
return shared;
|
|
844
|
+
};
|
|
845
|
+
const parts = [];
|
|
846
|
+
for (const spec of specs) if (spec.primitive.extensions?.["KHR_draco_mesh_compression"] === void 0) parts.push(readPrimitive(doc, buffers, spec.node, spec.mesh, spec.primitive, spec.world, usedNames));
|
|
847
|
+
else parts.push(await readPrimitiveDraco(doc, buffers, spec, usedNames, decoderOfOptions));
|
|
848
|
+
const kept = parts.filter((p) => p.indices.length > 0);
|
|
849
|
+
if (kept.length === 0) throw new Error("glTF: the file has no triangle meshes");
|
|
850
|
+
return kept;
|
|
851
|
+
}
|
|
852
|
+
/** The shared draco3d decoder module: `options`'s, or a lazily created one. */
|
|
853
|
+
async function decoderOf(options) {
|
|
854
|
+
if (options?.decoderModule !== void 0) {
|
|
855
|
+
const module = options.decoderModule;
|
|
856
|
+
if (typeof module?.Decoder !== "function" || typeof module?.DecoderBuffer !== "function") throw new Error("Draco: the decoder module is not a draco3d decoder module (from createDecoderModule)");
|
|
857
|
+
return module;
|
|
858
|
+
}
|
|
859
|
+
if (options?.wasmBinary === void 0 && sharedDecoderModule !== null) return sharedDecoderModule;
|
|
860
|
+
const created = await createDecoderModule(options?.wasmBinary);
|
|
861
|
+
if (options?.wasmBinary === void 0) sharedDecoderModule = created;
|
|
862
|
+
return created;
|
|
863
|
+
}
|
|
864
|
+
/** The process-wide decoder module, created on the first default decode. */
|
|
865
|
+
let sharedDecoderModule = null;
|
|
866
|
+
/**
|
|
867
|
+
* Creates a draco3d decoder module, optionally seeded with the `.wasm` bytes.
|
|
868
|
+
* Imported lazily so bundles that never touch Draco never load the decoder.
|
|
869
|
+
*/
|
|
870
|
+
async function createDecoderModule(wasmBinary) {
|
|
871
|
+
let create;
|
|
872
|
+
try {
|
|
873
|
+
({createDecoderModule: create} = await import("draco3d"));
|
|
874
|
+
} catch {
|
|
875
|
+
throw new Error("Draco: decoding needs the draco3d package (npm install draco3d), or pass a decoder module");
|
|
876
|
+
}
|
|
877
|
+
const init = {};
|
|
878
|
+
if (wasmBinary !== void 0) init["wasmBinary"] = wasmBinary;
|
|
879
|
+
return create(init);
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* Decodes Draco-compressed bytes into positions and faces. `what` prefixes
|
|
883
|
+
* every error (`"Draco"` for files, `glTF: "name"` for primitives). Reads
|
|
884
|
+
* POSITION by type, or the extension's attribute id when one is given (the
|
|
885
|
+
* ids the encoder wrote need not match the decoder's lookup).
|
|
886
|
+
*/
|
|
887
|
+
function decodeDracoMesh(module, bytes, what, positionId) {
|
|
888
|
+
const decoder = new module.Decoder();
|
|
889
|
+
const buffer = new module.DecoderBuffer();
|
|
890
|
+
const view = new Int8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
891
|
+
try {
|
|
892
|
+
let geometryType;
|
|
893
|
+
try {
|
|
894
|
+
buffer.Init(view, view.length);
|
|
895
|
+
geometryType = decoder.GetEncodedGeometryType(buffer);
|
|
896
|
+
} catch {
|
|
897
|
+
throw new Error(`${what}: the bytes are not Draco-compressed geometry`);
|
|
898
|
+
}
|
|
899
|
+
if (geometryType !== module.TRIANGULAR_MESH) throw new Error(`${what}: only Draco triangle meshes decode (not point clouds)`);
|
|
900
|
+
const mesh = new module.Mesh();
|
|
901
|
+
try {
|
|
902
|
+
const status = decoder.DecodeBufferToMesh(buffer, mesh);
|
|
903
|
+
if (!status.ok()) throw new Error(`${what}: Draco decode failed (${status.error_msg()})`);
|
|
904
|
+
const vertices = mesh.num_points();
|
|
905
|
+
const attribute = positionId === void 0 ? decoder.GetAttribute(mesh, checkedPositionId(decoder, mesh, module, what)) : checkedUniqueAttribute(decoder, mesh, positionId, what);
|
|
906
|
+
const positions = new Float64Array(3 * vertices);
|
|
907
|
+
const floats = new module.DracoFloat32Array();
|
|
908
|
+
try {
|
|
909
|
+
decoder.GetAttributeFloatForAllPoints(mesh, attribute, floats);
|
|
910
|
+
for (let v = 0; v < vertices; v++) {
|
|
911
|
+
positions[3 * v] = floats.GetValue(3 * v);
|
|
912
|
+
positions[3 * v + 1] = floats.GetValue(3 * v + 1);
|
|
913
|
+
positions[3 * v + 2] = floats.GetValue(3 * v + 2);
|
|
914
|
+
}
|
|
915
|
+
} finally {
|
|
916
|
+
module.destroy(floats);
|
|
917
|
+
}
|
|
918
|
+
const faces = mesh.num_faces();
|
|
919
|
+
const indices = new Uint32Array(3 * faces);
|
|
920
|
+
const face = new module.DracoInt32Array();
|
|
921
|
+
try {
|
|
922
|
+
for (let f = 0; f < faces; f++) {
|
|
923
|
+
decoder.GetFaceFromMesh(mesh, f, face);
|
|
924
|
+
indices[3 * f] = face.GetValue(0);
|
|
925
|
+
indices[3 * f + 1] = face.GetValue(1);
|
|
926
|
+
indices[3 * f + 2] = face.GetValue(2);
|
|
927
|
+
}
|
|
928
|
+
} finally {
|
|
929
|
+
module.destroy(face);
|
|
930
|
+
}
|
|
931
|
+
return {
|
|
932
|
+
positions,
|
|
933
|
+
indices
|
|
934
|
+
};
|
|
935
|
+
} finally {
|
|
936
|
+
module.destroy(mesh);
|
|
937
|
+
}
|
|
938
|
+
} finally {
|
|
939
|
+
module.destroy(buffer);
|
|
940
|
+
module.destroy(decoder);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
/** POSITION by decoder lookup (standalone `.drc`): throws without one. */
|
|
944
|
+
function checkedPositionId(decoder, mesh, module, what) {
|
|
945
|
+
const id = decoder.GetAttributeId(mesh, module.POSITION);
|
|
946
|
+
if (id < 0) throw new Error(`${what}: the Draco mesh has no POSITION attribute`);
|
|
947
|
+
return id;
|
|
948
|
+
}
|
|
949
|
+
/** POSITION by the KHR extension's attribute id: throws on a dangling one. */
|
|
950
|
+
function checkedUniqueAttribute(decoder, mesh, positionId, what) {
|
|
951
|
+
const attribute = decoder.GetAttributeByUniqueId(mesh, positionId);
|
|
952
|
+
if (attribute === void 0 || attribute === null) throw new Error(`${what} points at missing Draco POSITION attribute ${positionId}`);
|
|
953
|
+
return attribute;
|
|
954
|
+
}
|
|
955
|
+
/** Reads one Draco-compressed primitive: the extension's buffer view decoded, placement baked. */
|
|
956
|
+
async function readPrimitiveDraco(doc, buffers, spec, usedNames, decoderOfOptions) {
|
|
957
|
+
const name = dedupName(spec.node, spec.mesh, usedNames);
|
|
958
|
+
const what = `glTF: "${name}"`;
|
|
959
|
+
const extension = spec.primitive.extensions?.["KHR_draco_mesh_compression"];
|
|
960
|
+
const viewIndex = extension?.bufferView;
|
|
961
|
+
const attributes = extension?.attributes;
|
|
962
|
+
if (typeof extension !== "object" || extension === null || !Number.isInteger(viewIndex) || typeof attributes !== "object" || attributes === null) throw new Error(`${what} has a bad KHR_draco_mesh_compression extension (a buffer view and attributes)`);
|
|
963
|
+
if ((spec.primitive.mode ?? 4) !== 4) throw new Error(`${what} has primitive mode ${spec.primitive.mode} (only TRIANGLES Draco primitives are supported)`);
|
|
964
|
+
const bufferView = doc.bufferViews?.[viewIndex];
|
|
965
|
+
if (bufferView === void 0) throw new Error(`${what} points at missing buffer view ${viewIndex}`);
|
|
966
|
+
const buffer = buffers[bufferView.buffer ?? 0];
|
|
967
|
+
if (buffer === void 0) throw new Error(`${what} points at missing buffer ${bufferView.buffer ?? 0}`);
|
|
968
|
+
const base = bufferView.byteOffset ?? 0;
|
|
969
|
+
const end = base + (bufferView.byteLength ?? buffer.length - base);
|
|
970
|
+
if (!(base >= 0) || end > buffer.length) throw new Error(`${what} Draco buffer view runs past the end of its buffer`);
|
|
971
|
+
const module = await decoderOfOptions();
|
|
972
|
+
const positionAttr = attributes["POSITION"];
|
|
973
|
+
let positionId;
|
|
974
|
+
if (positionAttr !== void 0) {
|
|
975
|
+
if (!Number.isInteger(positionAttr) || positionAttr < 0) throw new Error(`${what} has a bad KHR_draco_mesh_compression POSITION attribute id`);
|
|
976
|
+
positionId = positionAttr;
|
|
977
|
+
}
|
|
978
|
+
const { positions, indices } = decodeDracoMesh(module, buffer.subarray(base, end), what, positionId);
|
|
979
|
+
const world = spec.world;
|
|
980
|
+
for (let i = 0; i < positions.length; i += 3) {
|
|
981
|
+
const x = positions[i];
|
|
982
|
+
const y = positions[i + 1];
|
|
983
|
+
const z = positions[i + 2];
|
|
984
|
+
positions[i] = world[0] * x + world[4] * y + world[8] * z + world[12];
|
|
985
|
+
positions[i + 1] = world[1] * x + world[5] * y + world[9] * z + world[13];
|
|
986
|
+
positions[i + 2] = world[2] * x + world[6] * y + world[10] * z + world[14];
|
|
987
|
+
}
|
|
988
|
+
return {
|
|
989
|
+
name,
|
|
990
|
+
positions,
|
|
991
|
+
indices,
|
|
992
|
+
placement: world.slice(),
|
|
993
|
+
colors: null
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
/** The asset JSON, checked to be an object before the importers read it. */
|
|
997
|
+
function checkedDocument(json) {
|
|
998
|
+
const doc = json;
|
|
999
|
+
if (typeof doc !== "object" || doc === null || Array.isArray(doc)) throw new Error("glTF: the asset is not a JSON object");
|
|
1000
|
+
return doc;
|
|
1001
|
+
}
|
|
1002
|
+
/** Splits the input into the asset JSON and the GLB body chunk (if any). */
|
|
1003
|
+
function splitContainer(raw) {
|
|
1004
|
+
const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
|
|
1005
|
+
if (raw.length >= 12 && view.getUint32(0, true) === 1179937895) {
|
|
1006
|
+
const version = view.getUint32(4, true);
|
|
1007
|
+
if (version !== 2) throw new Error(`glTF: unsupported GLB version ${version} (only 2.0)`);
|
|
1008
|
+
const length = view.getUint32(8, true);
|
|
1009
|
+
if (length > raw.length) throw new Error("glTF: the GLB length runs past the end of the file");
|
|
1010
|
+
let json = null;
|
|
1011
|
+
let bin = null;
|
|
1012
|
+
let at = 12;
|
|
1013
|
+
while (at + 8 <= length) {
|
|
1014
|
+
const chunkLength = view.getUint32(at, true);
|
|
1015
|
+
const chunkType = view.getUint32(at + 4, true);
|
|
1016
|
+
const start = at + 8;
|
|
1017
|
+
const end = start + chunkLength;
|
|
1018
|
+
if (end > raw.length) throw new Error("glTF: a GLB chunk runs past the end of the file");
|
|
1019
|
+
if (chunkType === 1313821514) json = raw.subarray(start, end);
|
|
1020
|
+
else if (chunkType === 5130562) bin = raw.subarray(start, end);
|
|
1021
|
+
at = end;
|
|
1022
|
+
}
|
|
1023
|
+
if (json === null) throw new Error("glTF: the GLB has no JSON chunk");
|
|
1024
|
+
return {
|
|
1025
|
+
json: parseAssetJson(json),
|
|
1026
|
+
bin
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
return {
|
|
1030
|
+
json: parseAssetJson(raw),
|
|
1031
|
+
bin: null
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
function parseAssetJson(bytes) {
|
|
1035
|
+
try {
|
|
1036
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
throw new Error(`glTF: the asset JSON does not parse (${error instanceof Error ? error.message : String(error)})`);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
/** Resolves every declared buffer to bytes: the GLB body chunk or embedded base64 data URIs. */
|
|
1042
|
+
function resolveBuffers(doc, bin) {
|
|
1043
|
+
const declared = doc.buffers ?? [];
|
|
1044
|
+
if (bin !== null) {
|
|
1045
|
+
if (declared.length === 0) return [bin];
|
|
1046
|
+
return declared.map((b, i) => {
|
|
1047
|
+
if (i === 0 && b.uri === void 0) return bin.subarray(0, Math.min(b.byteLength, bin.length));
|
|
1048
|
+
if (b.uri === void 0) throw new Error(`glTF: buffer ${i} has no URI and is not the GLB body (only the first GLB buffer may omit its URI)`);
|
|
1049
|
+
return decodeDataUri(b.uri, i);
|
|
1050
|
+
});
|
|
1051
|
+
}
|
|
1052
|
+
if (declared.length === 0) return [];
|
|
1053
|
+
return declared.map((b, i) => {
|
|
1054
|
+
if (b.uri === void 0) throw new Error(`glTF: buffer ${i} is external (only embedded base64 buffers are supported; load it with importGLTFAsync and a resolveBuffer callback)`);
|
|
1055
|
+
return decodeDataUri(b.uri, i);
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Resolves every declared buffer to bytes like {@link resolveBuffers}, and
|
|
1060
|
+
* additionally loads external (non-embedded) `.bin` buffers through
|
|
1061
|
+
* `resolveBuffer`. Embedded data URIs and the GLB body chunk decode inline,
|
|
1062
|
+
* exactly as the sync path does; the importer itself never fetches.
|
|
1063
|
+
*/
|
|
1064
|
+
async function resolveBuffersAsync(doc, bin, resolveBuffer) {
|
|
1065
|
+
const declared = doc.buffers ?? [];
|
|
1066
|
+
if (bin !== null && declared.length === 0) return [bin];
|
|
1067
|
+
if (bin === null && declared.length === 0) return [];
|
|
1068
|
+
const out = [];
|
|
1069
|
+
for (const [i, b] of declared.entries()) if (bin !== null && i === 0 && b.uri === void 0) out.push(bin.subarray(0, Math.min(b.byteLength, bin.length)));
|
|
1070
|
+
else if (b.uri === void 0) throw new Error(`glTF: buffer ${i} has no URI and is not the GLB body (only the first GLB buffer may omit its URI)`);
|
|
1071
|
+
else if (b.uri.startsWith("data:")) out.push(decodeDataUri(b.uri, i));
|
|
1072
|
+
else out.push(await resolveExternal(b.uri, i, resolveBuffer));
|
|
1073
|
+
return out;
|
|
1074
|
+
}
|
|
1075
|
+
/**
|
|
1076
|
+
* Loads one external buffer through the caller's resolver. Throws without a
|
|
1077
|
+
* resolver, wraps a resolver failure with the buffer's index and URI, and
|
|
1078
|
+
* rejects anything but bytes.
|
|
1079
|
+
*/
|
|
1080
|
+
async function resolveExternal(uri, index, resolveBuffer) {
|
|
1081
|
+
const what = `glTF: buffer ${index} ("${shortUri(uri)}")`;
|
|
1082
|
+
if (resolveBuffer === void 0) throw new Error(`${what} is external; pass a resolveBuffer callback to load it`);
|
|
1083
|
+
let bytes;
|
|
1084
|
+
try {
|
|
1085
|
+
bytes = await resolveBuffer(uri);
|
|
1086
|
+
} catch (error) {
|
|
1087
|
+
throw new Error(`${what} could not be resolved (${error instanceof Error ? error.message : String(error)})`);
|
|
1088
|
+
}
|
|
1089
|
+
if (bytes instanceof Uint8Array) return bytes;
|
|
1090
|
+
if (bytes instanceof ArrayBuffer) return new Uint8Array(bytes);
|
|
1091
|
+
throw new Error(`${what} resolved to no bytes (the resolveBuffer callback must return a Uint8Array or ArrayBuffer)`);
|
|
1092
|
+
}
|
|
1093
|
+
/** A URI shortened for error messages: hostile files can declare megabytes of URI. */
|
|
1094
|
+
function shortUri(uri) {
|
|
1095
|
+
return uri.length > 120 ? `${uri.slice(0, 117)}...` : uri;
|
|
1096
|
+
}
|
|
1097
|
+
function decodeDataUri(uri, buffer) {
|
|
1098
|
+
const at = uri.indexOf(";base64,");
|
|
1099
|
+
if (!uri.startsWith("data:") || at === -1) throw new Error(`glTF: buffer ${buffer} is external (only embedded base64 buffers are supported; load it with importGLTFAsync and a resolveBuffer callback)`);
|
|
1100
|
+
return decodeBase64(uri.slice(at + 8), buffer);
|
|
1101
|
+
}
|
|
1102
|
+
const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
1103
|
+
function decodeBase64(text, buffer) {
|
|
1104
|
+
const fail = () => /* @__PURE__ */ new Error(`glTF: buffer ${buffer} is not valid base64`);
|
|
1105
|
+
const clean = text.replace(/\s/g, "");
|
|
1106
|
+
if (clean.length % 4 !== 0) throw fail();
|
|
1107
|
+
let padding = 0;
|
|
1108
|
+
if (clean.endsWith("==")) padding = 2;
|
|
1109
|
+
else if (clean.endsWith("=")) padding = 1;
|
|
1110
|
+
const out = new Uint8Array(clean.length / 4 * 3 - padding);
|
|
1111
|
+
let at = 0;
|
|
1112
|
+
for (let i = 0; i < clean.length; i += 4) {
|
|
1113
|
+
let n = 0;
|
|
1114
|
+
let pad = 0;
|
|
1115
|
+
for (let k = 0; k < 4; k++) {
|
|
1116
|
+
const c = clean[i + k];
|
|
1117
|
+
if (c === "=") {
|
|
1118
|
+
if (i + 4 !== clean.length || k < 2) throw fail();
|
|
1119
|
+
pad++;
|
|
1120
|
+
n <<= 6;
|
|
1121
|
+
} else {
|
|
1122
|
+
const v = BASE64.indexOf(c);
|
|
1123
|
+
if (v === -1 || pad > 0) throw fail();
|
|
1124
|
+
n = n << 6 | v;
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
out[at++] = n >>> 16 & 255;
|
|
1128
|
+
if (pad < 2) out[at++] = n >>> 8 & 255;
|
|
1129
|
+
if (pad < 1) out[at++] = n & 255;
|
|
1130
|
+
}
|
|
1131
|
+
return out;
|
|
1132
|
+
}
|
|
1133
|
+
/** The root node indices: the default scene's, or every unparented node without scenes. */
|
|
1134
|
+
function rootNodes(doc) {
|
|
1135
|
+
const nodes = doc.nodes ?? [];
|
|
1136
|
+
const scenes = doc.scenes ?? [];
|
|
1137
|
+
if (scenes.length > 0) {
|
|
1138
|
+
const index = doc.scene ?? 0;
|
|
1139
|
+
const scene = scenes[index];
|
|
1140
|
+
if (scene === void 0) throw new Error(`glTF: scene ${index} is missing (the file has ${scenes.length})`);
|
|
1141
|
+
const roots = scene.nodes ?? [];
|
|
1142
|
+
for (const root of roots) if (!Number.isInteger(root) || root < 0 || root >= nodes.length) throw new Error(`glTF: scene ${index} points at missing node ${root}`);
|
|
1143
|
+
return roots;
|
|
1144
|
+
}
|
|
1145
|
+
const parented = /* @__PURE__ */ new Set();
|
|
1146
|
+
for (const node of nodes) for (const child of node.children ?? []) parented.add(child);
|
|
1147
|
+
return nodes.map((_, i) => i).filter((i) => !parented.has(i));
|
|
1148
|
+
}
|
|
1149
|
+
/** The node's local matrix (column-major): `matrix`, else TRS composed. */
|
|
1150
|
+
function localMatrix(node, nodeIndex) {
|
|
1151
|
+
const what = `node ${nodeIndex}${node.name !== void 0 ? ` "${node.name}"` : ""}`;
|
|
1152
|
+
if (node.matrix !== void 0) {
|
|
1153
|
+
if (node.matrix.length !== 16 || node.matrix.some((x) => !Number.isFinite(x))) throw new Error(`glTF: ${what} has a bad matrix (16 finite numbers)`);
|
|
1154
|
+
return Float64Array.from(node.matrix);
|
|
1155
|
+
}
|
|
1156
|
+
const t = node.translation ?? [
|
|
1157
|
+
0,
|
|
1158
|
+
0,
|
|
1159
|
+
0
|
|
1160
|
+
];
|
|
1161
|
+
const r = node.rotation ?? [
|
|
1162
|
+
0,
|
|
1163
|
+
0,
|
|
1164
|
+
0,
|
|
1165
|
+
1
|
|
1166
|
+
];
|
|
1167
|
+
const s = node.scale ?? [
|
|
1168
|
+
1,
|
|
1169
|
+
1,
|
|
1170
|
+
1
|
|
1171
|
+
];
|
|
1172
|
+
if (t.length !== 3 || r.length !== 4 || s.length !== 3 || [
|
|
1173
|
+
...t,
|
|
1174
|
+
...r,
|
|
1175
|
+
...s
|
|
1176
|
+
].some((x) => !Number.isFinite(x))) throw new Error(`glTF: ${what} has a bad TRS transform`);
|
|
1177
|
+
const len = Math.hypot(r[0], r[1], r[2], r[3]);
|
|
1178
|
+
if (!(len > 1e-30)) throw new Error(`glTF: ${what} has a zero rotation quaternion`);
|
|
1179
|
+
const x = r[0] / len;
|
|
1180
|
+
const y = r[1] / len;
|
|
1181
|
+
const z = r[2] / len;
|
|
1182
|
+
const w = r[3] / len;
|
|
1183
|
+
const r00 = 1 - 2 * (y * y + z * z);
|
|
1184
|
+
const r01 = 2 * (x * y - z * w);
|
|
1185
|
+
const r02 = 2 * (x * z + y * w);
|
|
1186
|
+
const r10 = 2 * (x * y + z * w);
|
|
1187
|
+
const r11 = 1 - 2 * (x * x + z * z);
|
|
1188
|
+
const r12 = 2 * (y * z - x * w);
|
|
1189
|
+
const r20 = 2 * (x * z - y * w);
|
|
1190
|
+
const r21 = 2 * (y * z + x * w);
|
|
1191
|
+
const r22 = 1 - 2 * (x * x + y * y);
|
|
1192
|
+
return Float64Array.from([
|
|
1193
|
+
r00 * s[0],
|
|
1194
|
+
r10 * s[0],
|
|
1195
|
+
r20 * s[0],
|
|
1196
|
+
0,
|
|
1197
|
+
r01 * s[1],
|
|
1198
|
+
r11 * s[1],
|
|
1199
|
+
r21 * s[1],
|
|
1200
|
+
0,
|
|
1201
|
+
r02 * s[2],
|
|
1202
|
+
r12 * s[2],
|
|
1203
|
+
r22 * s[2],
|
|
1204
|
+
0,
|
|
1205
|
+
t[0],
|
|
1206
|
+
t[1],
|
|
1207
|
+
t[2],
|
|
1208
|
+
1
|
|
1209
|
+
]);
|
|
1210
|
+
}
|
|
1211
|
+
/** Column-major product of two affine matrices. */
|
|
1212
|
+
function multiplyAffine(a, b) {
|
|
1213
|
+
const out = /* @__PURE__ */ new Float64Array(16);
|
|
1214
|
+
for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) out[c * 4 + r] = a[r] * b[c * 4] + a[4 + r] * b[c * 4 + 1] + a[8 + r] * b[c * 4 + 2] + a[12 + r] * b[c * 4 + 3];
|
|
1215
|
+
return out;
|
|
1216
|
+
}
|
|
1217
|
+
const COMPONENT_SIZE = {
|
|
1218
|
+
5120: 1,
|
|
1219
|
+
5121: 1,
|
|
1220
|
+
5122: 2,
|
|
1221
|
+
5123: 2,
|
|
1222
|
+
5125: 4,
|
|
1223
|
+
5126: 4
|
|
1224
|
+
};
|
|
1225
|
+
const TYPE_COMPONENTS = {
|
|
1226
|
+
SCALAR: 1,
|
|
1227
|
+
VEC2: 2,
|
|
1228
|
+
VEC3: 3,
|
|
1229
|
+
VEC4: 4
|
|
1230
|
+
};
|
|
1231
|
+
/** Resolves an accessor to its buffer bytes, honoring view/element offsets and interleaved strides. */
|
|
1232
|
+
function accessorData(doc, buffers, index, what) {
|
|
1233
|
+
const accessor = doc.accessors?.[index];
|
|
1234
|
+
if (accessor === void 0) throw new Error(`glTF: the ${what} accessor ${index} is missing`);
|
|
1235
|
+
const size = COMPONENT_SIZE[accessor.componentType];
|
|
1236
|
+
if (size === void 0) throw new Error(`glTF: the ${what} accessor has component type ${accessor.componentType}`);
|
|
1237
|
+
const components = TYPE_COMPONENTS[accessor.type];
|
|
1238
|
+
if (components === void 0) throw new Error(`glTF: the ${what} accessor has type "${accessor.type}"`);
|
|
1239
|
+
if (!Number.isInteger(accessor.count) || accessor.count < 0) throw new Error(`glTF: the ${what} accessor has count ${accessor.count}`);
|
|
1240
|
+
if (accessor.sparse !== void 0) throw new Error(`glTF: sparse accessors are not supported (${what})`);
|
|
1241
|
+
if (accessor.bufferView === void 0) return {
|
|
1242
|
+
buffer: /* @__PURE__ */ new Uint8Array(0),
|
|
1243
|
+
view: /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(0)),
|
|
1244
|
+
base: 0,
|
|
1245
|
+
count: accessor.count,
|
|
1246
|
+
componentType: accessor.componentType,
|
|
1247
|
+
components,
|
|
1248
|
+
size,
|
|
1249
|
+
stride: components * size
|
|
1250
|
+
};
|
|
1251
|
+
const bufferView = doc.bufferViews?.[accessor.bufferView];
|
|
1252
|
+
if (bufferView === void 0) throw new Error(`glTF: the ${what} buffer view ${accessor.bufferView} is missing`);
|
|
1253
|
+
const buffer = buffers[bufferView.buffer ?? 0];
|
|
1254
|
+
if (buffer === void 0) throw new Error(`glTF: the ${what} buffer ${bufferView.buffer ?? 0} is missing`);
|
|
1255
|
+
const base = (bufferView.byteOffset ?? 0) + (accessor.byteOffset ?? 0);
|
|
1256
|
+
const stride = bufferView.byteStride ?? components * size;
|
|
1257
|
+
if (!(stride >= components * size)) throw new Error(`glTF: the ${what} stride ${stride} is narrower than its elements`);
|
|
1258
|
+
if (accessor.count > 0) {
|
|
1259
|
+
const end = base + (accessor.count - 1) * stride + components * size;
|
|
1260
|
+
if (!(base >= 0) || end > buffer.length) throw new Error(`glTF: the ${what} accessor runs past the end of its buffer`);
|
|
1261
|
+
}
|
|
1262
|
+
return {
|
|
1263
|
+
buffer,
|
|
1264
|
+
view: new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength),
|
|
1265
|
+
base,
|
|
1266
|
+
count: accessor.count,
|
|
1267
|
+
componentType: accessor.componentType,
|
|
1268
|
+
components,
|
|
1269
|
+
size,
|
|
1270
|
+
stride
|
|
1271
|
+
};
|
|
1272
|
+
}
|
|
1273
|
+
function readFloat(data, element, component) {
|
|
1274
|
+
return data.view.getFloat32(data.base + element * data.stride + component * data.size, true);
|
|
1275
|
+
}
|
|
1276
|
+
function readPrimitive(doc, buffers, node, mesh, primitive, world, usedNames) {
|
|
1277
|
+
const name = dedupName(node, mesh, usedNames);
|
|
1278
|
+
if (primitive.extensions?.["KHR_draco_mesh_compression"] !== void 0) throw new Error(`glTF: "${name}" uses KHR_draco_mesh_compression (decode it with importGLTFAsync)`);
|
|
1279
|
+
if (typeof primitive.attributes["POSITION"] !== "number") throw new Error(`glTF: "${name}" has a primitive without POSITION`);
|
|
1280
|
+
const positions = readPositions(doc, buffers, primitive.attributes["POSITION"], name);
|
|
1281
|
+
const indices = readPrimitiveIndices(doc, buffers, primitive, positions.length / 3, name);
|
|
1282
|
+
for (let i = 0; i < positions.length; i += 3) {
|
|
1283
|
+
const x = positions[i];
|
|
1284
|
+
const y = positions[i + 1];
|
|
1285
|
+
const z = positions[i + 2];
|
|
1286
|
+
positions[i] = world[0] * x + world[4] * y + world[8] * z + world[12];
|
|
1287
|
+
positions[i + 1] = world[1] * x + world[5] * y + world[9] * z + world[13];
|
|
1288
|
+
positions[i + 2] = world[2] * x + world[6] * y + world[10] * z + world[14];
|
|
1289
|
+
}
|
|
1290
|
+
const colors = typeof primitive.attributes["COLOR_0"] === "number" ? readColors(doc, buffers, primitive.attributes["COLOR_0"], positions.length / 3, name) : null;
|
|
1291
|
+
return {
|
|
1292
|
+
name,
|
|
1293
|
+
positions,
|
|
1294
|
+
indices,
|
|
1295
|
+
placement: world.slice(),
|
|
1296
|
+
colors
|
|
1297
|
+
};
|
|
1298
|
+
}
|
|
1299
|
+
/** The deduplicated mesh name: the node name, else the mesh name, else `"mesh"`. */
|
|
1300
|
+
function dedupName(node, mesh, usedNames) {
|
|
1301
|
+
const base = node.name ?? mesh.name ?? "mesh";
|
|
1302
|
+
const seen = usedNames.get(base) ?? 0;
|
|
1303
|
+
usedNames.set(base, seen + 1);
|
|
1304
|
+
return seen === 0 ? base : `${base} (${seen + 1})`;
|
|
1305
|
+
}
|
|
1306
|
+
function readPositions(doc, buffers, index, name) {
|
|
1307
|
+
const data = accessorData(doc, buffers, index, "POSITION");
|
|
1308
|
+
if (data.components !== 3 || data.componentType !== 5126) throw new Error(`glTF: "${name}" has POSITION with ${data.components} ${data.size}-byte components (VEC3 float)`);
|
|
1309
|
+
const out = new Float64Array(3 * data.count);
|
|
1310
|
+
for (let i = 0; i < data.count; i++) {
|
|
1311
|
+
out[3 * i] = readFloat(data, i, 0);
|
|
1312
|
+
out[3 * i + 1] = readFloat(data, i, 1);
|
|
1313
|
+
out[3 * i + 2] = readFloat(data, i, 2);
|
|
1314
|
+
if (!Number.isFinite(out[3 * i]) || !Number.isFinite(out[3 * i + 1]) || !Number.isFinite(out[3 * i + 2])) throw new Error(`glTF: "${name}" has a non-finite position`);
|
|
1315
|
+
}
|
|
1316
|
+
return out;
|
|
1317
|
+
}
|
|
1318
|
+
function readPrimitiveIndices(doc, buffers, primitive, vertices, name) {
|
|
1319
|
+
const mode = primitive.mode ?? 4;
|
|
1320
|
+
let corners;
|
|
1321
|
+
if (primitive.indices === void 0) corners = Uint32Array.from({ length: accessorCount(doc, primitive, name) }, (_, i) => i);
|
|
1322
|
+
else {
|
|
1323
|
+
const data = accessorData(doc, buffers, primitive.indices, "index");
|
|
1324
|
+
if (data.components !== 1 || data.componentType !== 5121 && data.componentType !== 5123 && data.componentType !== 5125) throw new Error(`glTF: "${name}" has non-scalar 8/16/32-bit unsigned indices`);
|
|
1325
|
+
corners = new Uint32Array(data.count);
|
|
1326
|
+
for (let i = 0; i < data.count; i++) {
|
|
1327
|
+
const at = data.base + i * data.stride;
|
|
1328
|
+
corners[i] = data.componentType === 5121 ? data.view.getUint8(at) : data.componentType === 5123 ? data.view.getUint16(at, true) : data.view.getUint32(at, true);
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
for (const c of corners) if (c >= vertices) throw new Error(`glTF: "${name}" indexes vertex ${c} past its ${vertices} vertices`);
|
|
1332
|
+
if (mode === 4) {
|
|
1333
|
+
if (corners.length % 3 !== 0) throw new Error(`glTF: "${name}" has ${corners.length} TRIANGLES corners (a multiple of 3)`);
|
|
1334
|
+
return corners;
|
|
1335
|
+
}
|
|
1336
|
+
if (mode !== 5 && mode !== 6) throw new Error(`glTF: "${name}" has primitive mode ${mode} (only TRIANGLES, TRIANGLE_STRIP and TRIANGLE_FAN are supported)`);
|
|
1337
|
+
if (corners.length < 3) return /* @__PURE__ */ new Uint32Array(0);
|
|
1338
|
+
if (mode === 5) {
|
|
1339
|
+
const out = new Uint32Array((corners.length - 2) * 3);
|
|
1340
|
+
for (let i = 0; i + 2 < corners.length; i++) if (i % 2 === 0) out.set([
|
|
1341
|
+
corners[i],
|
|
1342
|
+
corners[i + 1],
|
|
1343
|
+
corners[i + 2]
|
|
1344
|
+
], 3 * i);
|
|
1345
|
+
else out.set([
|
|
1346
|
+
corners[i],
|
|
1347
|
+
corners[i + 2],
|
|
1348
|
+
corners[i + 1]
|
|
1349
|
+
], 3 * i);
|
|
1350
|
+
return out;
|
|
1351
|
+
}
|
|
1352
|
+
if (mode === 6) {
|
|
1353
|
+
const out = new Uint32Array((corners.length - 2) * 3);
|
|
1354
|
+
for (let i = 0; i + 2 < corners.length; i++) out.set([
|
|
1355
|
+
corners[0],
|
|
1356
|
+
corners[i + 1],
|
|
1357
|
+
corners[i + 2]
|
|
1358
|
+
], 3 * i);
|
|
1359
|
+
return out;
|
|
1360
|
+
}
|
|
1361
|
+
throw new Error(`glTF: unreachable primitive mode ${mode}`);
|
|
1362
|
+
}
|
|
1363
|
+
/** The corner count of a non-indexed primitive: its POSITION count. */
|
|
1364
|
+
function accessorCount(doc, primitive, name) {
|
|
1365
|
+
const accessor = doc.accessors?.[primitive.attributes["POSITION"]];
|
|
1366
|
+
if (accessor === void 0) throw new Error(`glTF: "${name}" has a primitive without POSITION`);
|
|
1367
|
+
return accessor.count;
|
|
1368
|
+
}
|
|
1369
|
+
function readColors(doc, buffers, index, vertices, name) {
|
|
1370
|
+
const data = accessorData(doc, buffers, index, "COLOR_0");
|
|
1371
|
+
if (data.components !== 3 && data.components !== 4 || data.componentType !== 5121 && data.componentType !== 5126) throw new Error(`glTF: "${name}" has COLOR_0 with ${data.components} ${data.size}-byte components (u8 or float VEC3/VEC4)`);
|
|
1372
|
+
if (data.count !== vertices) throw new Error(`glTF: "${name}" has ${data.count} colors for ${vertices} vertices`);
|
|
1373
|
+
if (data.size === 1 && data.components === 4) {
|
|
1374
|
+
const out = new Uint8Array(4 * vertices);
|
|
1375
|
+
for (let i = 0; i < vertices; i++) {
|
|
1376
|
+
const at = data.base + i * data.stride;
|
|
1377
|
+
out[4 * i] = data.view.getUint8(at);
|
|
1378
|
+
out[4 * i + 1] = data.view.getUint8(at + 1);
|
|
1379
|
+
out[4 * i + 2] = data.view.getUint8(at + 2);
|
|
1380
|
+
out[4 * i + 3] = data.view.getUint8(at + 3);
|
|
1381
|
+
}
|
|
1382
|
+
return out;
|
|
1383
|
+
}
|
|
1384
|
+
const out = new Uint8Array(4 * vertices);
|
|
1385
|
+
for (let i = 0; i < vertices; i++) for (let c = 0; c < 4; c++) {
|
|
1386
|
+
let v;
|
|
1387
|
+
if (c < data.components) {
|
|
1388
|
+
const at = data.base + i * data.stride + c * data.size;
|
|
1389
|
+
v = data.size === 1 ? data.view.getUint8(at) / 255 : data.view.getFloat32(at, true);
|
|
1390
|
+
} else v = 1;
|
|
1391
|
+
out[4 * i + c] = Math.round(Math.min(1, Math.max(0, v)) * 255);
|
|
1392
|
+
}
|
|
1393
|
+
return out;
|
|
1394
|
+
}
|
|
1395
|
+
export { decodeDraco, encodeDraco, exportGLTF, exportOBJ, exportPLY, exportSTL, importGLTF, importGLTFAsync };
|