@margoengine/loaders 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1198 -3
- package/dist/3dm.d.ts +161 -0
- package/dist/3dm.js +289 -0
- package/dist/3ds.d.ts +124 -0
- package/dist/3ds.js +392 -0
- package/dist/acclaim.d.ts +90 -0
- package/dist/acclaim.js +312 -0
- package/dist/amf.d.ts +45 -0
- package/dist/amf.js +256 -0
- package/dist/babylon.d.ts +197 -0
- package/dist/babylon.js +701 -0
- package/dist/common.d.ts +7 -0
- package/dist/common.js +6 -0
- package/dist/dae-animation.d.ts +66 -0
- package/dist/dae-animation.js +266 -0
- package/dist/dae-common.d.ts +95 -0
- package/dist/dae-common.js +226 -0
- package/dist/dae-controllers.d.ts +57 -0
- package/dist/dae-controllers.js +164 -0
- package/dist/dae-pose.d.ts +131 -0
- package/dist/dae-pose.js +381 -0
- package/dist/dae-scene.d.ts +203 -0
- package/dist/dae-scene.js +279 -0
- package/dist/dae.d.ts +161 -0
- package/dist/dae.js +633 -0
- package/dist/detect.d.ts +20 -0
- package/dist/detect.js +72 -0
- package/dist/dxf.d.ts +81 -0
- package/dist/dxf.js +774 -0
- package/dist/engine.d.ts +36 -0
- package/dist/engine.js +117 -0
- package/dist/font-opentype.d.ts +14 -0
- package/dist/font-opentype.js +33 -0
- package/dist/font-woff.d.ts +23 -0
- package/dist/font-woff.js +293 -0
- package/dist/font.d.ts +41 -0
- package/dist/font.js +26 -0
- package/dist/gcode.d.ts +55 -0
- package/dist/gcode.js +278 -0
- package/dist/geo-model.d.ts +84 -0
- package/dist/geo-model.js +220 -0
- package/dist/geo-mvt.d.ts +15 -0
- package/dist/geo-mvt.js +302 -0
- package/dist/geo-shp.d.ts +15 -0
- package/dist/geo-shp.js +234 -0
- package/dist/geo-xml.d.ts +6 -0
- package/dist/geo-xml.js +165 -0
- package/dist/geo.d.ts +8 -0
- package/dist/geo.js +59 -0
- package/dist/geometry.d.ts +60 -0
- package/dist/geometry.js +273 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.js +28 -0
- package/dist/kmz.d.ts +78 -0
- package/dist/kmz.js +173 -0
- package/dist/las.d.ts +92 -0
- package/dist/las.js +110 -0
- package/dist/ldraw.d.ts +118 -0
- package/dist/ldraw.js +474 -0
- package/dist/load.d.ts +72 -0
- package/dist/load.js +205 -0
- package/dist/lottie.d.ts +154 -0
- package/dist/lottie.js +893 -0
- package/dist/lwo.d.ts +81 -0
- package/dist/lwo.js +454 -0
- package/dist/lzf.d.ts +13 -0
- package/dist/lzf.js +56 -0
- package/dist/materialx.d.ts +120 -0
- package/dist/materialx.js +563 -0
- package/dist/md2.d.ts +52 -0
- package/dist/md2.js +112 -0
- package/dist/mmcif.d.ts +14 -0
- package/dist/mmcif.js +246 -0
- package/dist/mmd.d.ts +244 -0
- package/dist/mmd.js +958 -0
- package/dist/mocap.d.ts +71 -0
- package/dist/mocap.js +178 -0
- package/dist/molecule-common.d.ts +4 -0
- package/dist/molecule-common.js +54 -0
- package/dist/mtl.d.ts +120 -0
- package/dist/mtl.js +469 -0
- package/dist/normals.d.ts +7 -0
- package/dist/normals.js +31 -0
- package/dist/nrrd.d.ts +63 -0
- package/dist/nrrd.js +743 -0
- package/dist/nurbs.d.ts +118 -0
- package/dist/nurbs.js +265 -0
- package/dist/obj.d.ts +143 -0
- package/dist/obj.js +456 -0
- package/dist/off.d.ts +10 -0
- package/dist/off.js +155 -0
- package/dist/outline-font.d.ts +87 -0
- package/dist/outline-font.js +110 -0
- package/dist/outline.d.ts +20 -0
- package/dist/outline.js +215 -0
- package/dist/pcd.d.ts +34 -0
- package/dist/pcd.js +258 -0
- package/dist/pdb.d.ts +67 -0
- package/dist/pdb.js +126 -0
- package/dist/ply.d.ts +35 -0
- package/dist/ply.js +392 -0
- package/dist/polygon.d.ts +9 -0
- package/dist/polygon.js +49 -0
- package/dist/prwm.d.ts +24 -0
- package/dist/prwm.js +114 -0
- package/dist/render.d.ts +27 -0
- package/dist/render.js +153 -0
- package/dist/sfnt-cff.d.ts +37 -0
- package/dist/sfnt-cff.js +749 -0
- package/dist/sfnt-layout.d.ts +24 -0
- package/dist/sfnt-layout.js +266 -0
- package/dist/sfnt-reader.d.ts +28 -0
- package/dist/sfnt-reader.js +87 -0
- package/dist/sfnt-variation.d.ts +40 -0
- package/dist/sfnt-variation.js +318 -0
- package/dist/shared/asset-url.js +82 -0
- package/dist/shared/crc32.d.ts +2 -0
- package/dist/shared/crc32.js +47 -0
- package/dist/shared/errors.js +36 -0
- package/dist/shared/inflate.js +284 -0
- package/dist/shared/normals.js +26 -0
- package/dist/shared/scene-scope.js +56 -0
- package/dist/shared/trailing-data.js +42 -0
- package/dist/stl.d.ts +64 -0
- package/dist/stl.js +309 -0
- package/dist/svg.d.ts +90 -0
- package/dist/svg.js +1007 -0
- package/dist/tds.d.ts +2 -0
- package/dist/tds.js +2 -0
- package/dist/textures.d.ts +42 -0
- package/dist/textures.js +53 -0
- package/dist/threemf-lattice.d.ts +139 -0
- package/dist/threemf-lattice.js +514 -0
- package/dist/threemf-materials.d.ts +75 -0
- package/dist/threemf-materials.js +314 -0
- package/dist/threemf-mesh.d.ts +60 -0
- package/dist/threemf-mesh.js +201 -0
- package/dist/threemf.d.ts +101 -0
- package/dist/threemf.js +415 -0
- package/dist/tilt.d.ts +62 -0
- package/dist/tilt.js +186 -0
- package/dist/tmx.d.ts +151 -0
- package/dist/tmx.js +394 -0
- package/dist/ttf.d.ts +78 -0
- package/dist/ttf.js +568 -0
- package/dist/types.d.ts +90 -0
- package/dist/types.js +35 -0
- package/dist/usd.d.ts +2 -0
- package/dist/usd.js +2 -0
- package/dist/usd.worker.d.ts +1 -0
- package/dist/usdz.d.ts +50 -0
- package/dist/usdz.js +646 -0
- package/dist/util.d.ts +75 -0
- package/dist/util.js +241 -0
- package/dist/vdb.d.ts +111 -0
- package/dist/vdb.js +663 -0
- package/dist/vrml.d.ts +53 -0
- package/dist/vrml.js +532 -0
- package/dist/vtk-cells.d.ts +29 -0
- package/dist/vtk-cells.js +211 -0
- package/dist/vtk-legacy.d.ts +57 -0
- package/dist/vtk-legacy.js +439 -0
- package/dist/vtk-reader.d.ts +19 -0
- package/dist/vtk-reader.js +134 -0
- package/dist/vtk-xml.d.ts +96 -0
- package/dist/vtk-xml.js +578 -0
- package/dist/vtk.d.ts +13 -0
- package/dist/vtk.js +234 -0
- package/dist/woff-glyf.d.ts +17 -0
- package/dist/woff-glyf.js +215 -0
- package/dist/worker.d.ts +10 -0
- package/dist/worker.js +93 -0
- package/dist/workers/usd.js +3 -0
- package/dist/xfile.d.ts +99 -0
- package/dist/xfile.js +706 -0
- package/dist/xml.d.ts +107 -0
- package/dist/xml.js +843 -0
- package/dist/xyz.d.ts +16 -0
- package/dist/xyz.js +110 -0
- package/dist/zip.d.ts +38 -0
- package/dist/zip.js +150 -0
- package/package.json +246 -6
package/dist/babylon.js
ADDED
|
@@ -0,0 +1,701 @@
|
|
|
1
|
+
// Babylon.js `.babylon` scenes: a JSON file of meshes, geometries, materials, cameras, lights, skeletons and animations.
|
|
2
|
+
// Read from the public description of the file (doc.babylonjs.com, "Babylon file format" and the serialization
|
|
3
|
+
// reference). Babylon is left-handed with Y up; `rightHanded` (default true) mirrors Z into the engine's space.
|
|
4
|
+
import { LoaderError } from './types.js';
|
|
5
|
+
import { DEFAULT_MAX_VERTICES, DEFAULT_MAX_TRIANGLES, toBytes } from './util.js';
|
|
6
|
+
const F = 'BABYLON';
|
|
7
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
8
|
+
const syntax = (m) => {
|
|
9
|
+
throw new LoaderError(F, 'syntax', m);
|
|
10
|
+
};
|
|
11
|
+
const list = (v, what) => {
|
|
12
|
+
if (v === undefined)
|
|
13
|
+
return [];
|
|
14
|
+
if (!Array.isArray(v))
|
|
15
|
+
return syntax(`${what} is not an array`);
|
|
16
|
+
for (const item of v)
|
|
17
|
+
if (!isObject(item))
|
|
18
|
+
syntax(`${what} holds a value that is not an object`);
|
|
19
|
+
return v;
|
|
20
|
+
};
|
|
21
|
+
const str = (v, fallback) => typeof v === 'string' ? v : typeof v === 'number' ? String(v) : fallback;
|
|
22
|
+
const num = (v, fallback) => (typeof v === 'number' && Number.isFinite(v) ? v : fallback);
|
|
23
|
+
const flag = (v, fallback) => typeof v === 'boolean' ? v : typeof v === 'number' ? v !== 0 : fallback;
|
|
24
|
+
function vec(v, n, fallback, what) {
|
|
25
|
+
if (v === undefined || v === null)
|
|
26
|
+
return fallback;
|
|
27
|
+
if (!Array.isArray(v) || v.length < n || v.slice(0, n).some((x) => typeof x !== 'number' || !Number.isFinite(x)))
|
|
28
|
+
return syntax(`${what} must be ${n} numbers`);
|
|
29
|
+
return v.slice(0, n);
|
|
30
|
+
}
|
|
31
|
+
function numbers(v, what, multiple, max) {
|
|
32
|
+
if (v === undefined || v === null)
|
|
33
|
+
return undefined;
|
|
34
|
+
if (!Array.isArray(v))
|
|
35
|
+
return syntax(`${what} is not an array`);
|
|
36
|
+
if (v.length > max)
|
|
37
|
+
throw new LoaderError(F, 'limit', `${what} has ${v.length} values, past the limit of ${max}`);
|
|
38
|
+
if (v.length % multiple)
|
|
39
|
+
syntax(`${what} length ${v.length} is not a multiple of ${multiple}`);
|
|
40
|
+
for (let i = 0; i < v.length; i++)
|
|
41
|
+
if (typeof v[i] !== 'number' || !Number.isFinite(v[i]))
|
|
42
|
+
syntax(`${what}[${i}] is not a number`);
|
|
43
|
+
return v;
|
|
44
|
+
}
|
|
45
|
+
const srgbToLinear = (c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
|
|
46
|
+
const linearToSrgb = (c) => (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055);
|
|
47
|
+
function eulerToQuaternion(x, y, z) {
|
|
48
|
+
// Babylon's YXZ order: roll about Z first, then pitch about X, then yaw about Y; q = qy * qx * qz.
|
|
49
|
+
const [sx, cx, sy, cy, sz, cz] = [
|
|
50
|
+
Math.sin(x / 2),
|
|
51
|
+
Math.cos(x / 2),
|
|
52
|
+
Math.sin(y / 2),
|
|
53
|
+
Math.cos(y / 2),
|
|
54
|
+
Math.sin(z / 2),
|
|
55
|
+
Math.cos(z / 2),
|
|
56
|
+
];
|
|
57
|
+
// qy * qx
|
|
58
|
+
const ax = cy * sx, ay = sy * cx, az = -sy * sx, aw = cy * cx;
|
|
59
|
+
// (qy * qx) * qz, qz = (0, 0, sz, cz)
|
|
60
|
+
return [ax * cz + ay * sz, ay * cz - ax * sz, az * cz + aw * sz, aw * cz - az * sz];
|
|
61
|
+
}
|
|
62
|
+
function decodeBase64(text, what) {
|
|
63
|
+
try {
|
|
64
|
+
const bin = atob(text);
|
|
65
|
+
const out = new Uint8Array(bin.length);
|
|
66
|
+
for (let i = 0; i < bin.length; i++)
|
|
67
|
+
out[i] = bin.charCodeAt(i);
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return syntax(`${what} is not valid base64`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Parses a Babylon.js `.babylon` scene. `input` is the file's bytes, its JSON text or the parsed object. Meshes keep the
|
|
76
|
+
* file's own vertices (`positions`, `normals`, `uvs`, `uvs2`, `colors`, `indices`) or the shared `geometries` they name;
|
|
77
|
+
* `instances` become meshes that share the geometry object. Skeletons, per-vertex bone weights and node animations are
|
|
78
|
+
* read; particle systems, sprites, sounds, post processes, LODs and delay-loaded binary mesh data are skipped with a
|
|
79
|
+
* warning. Bad shapes, out-of-range indices and counts past the limits throw a `LoaderError`.
|
|
80
|
+
*/
|
|
81
|
+
export function parseBabylon(input, options = {}) {
|
|
82
|
+
const maxBytes = options.maxBytes ?? 256 * 1024 * 1024, maxVertices = options.maxVertices ?? DEFAULT_MAX_VERTICES, maxTriangles = options.maxTriangles ?? DEFAULT_MAX_TRIANGLES, maxNodes = options.maxNodes ?? 100_000, maxTextureBytes = options.maxTextureBytes ?? 64 * 1024 * 1024, rh = options.rightHanded ?? true;
|
|
83
|
+
for (const [k, v] of Object.entries({ maxBytes, maxVertices, maxTriangles, maxNodes, maxTextureBytes }))
|
|
84
|
+
if (!Number.isSafeInteger(v) || v < 0)
|
|
85
|
+
throw new LoaderError(F, 'range', `${k} must be a non-negative integer`);
|
|
86
|
+
let doc;
|
|
87
|
+
if (typeof input === 'string' || ArrayBuffer.isView(input) || input instanceof ArrayBuffer) {
|
|
88
|
+
let text;
|
|
89
|
+
if (typeof input === 'string') {
|
|
90
|
+
if (input.length > maxBytes)
|
|
91
|
+
throw new LoaderError(F, 'limit', `file is past the limit of ${maxBytes} bytes`);
|
|
92
|
+
text = input;
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
const bytes = toBytes(input, F);
|
|
96
|
+
if (bytes.length > maxBytes)
|
|
97
|
+
throw new LoaderError(F, 'limit', `file is past the limit of ${maxBytes} bytes`);
|
|
98
|
+
text = new TextDecoder('utf-8', { fatal: false }).decode(bytes);
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
doc = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
|
|
102
|
+
}
|
|
103
|
+
catch (e) {
|
|
104
|
+
throw new LoaderError(F, 'syntax', `not valid JSON (${e.message.slice(0, 80)})`, { cause: e });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
else if (isObject(input))
|
|
108
|
+
doc = input;
|
|
109
|
+
else
|
|
110
|
+
throw new LoaderError(F, 'range', 'expected bytes, JSON text or a parsed object');
|
|
111
|
+
if (!isObject(doc))
|
|
112
|
+
return syntax('the file is not a JSON object');
|
|
113
|
+
if (doc.meshes === undefined &&
|
|
114
|
+
doc.cameras === undefined &&
|
|
115
|
+
doc.lights === undefined &&
|
|
116
|
+
doc.materials === undefined &&
|
|
117
|
+
doc.geometries === undefined &&
|
|
118
|
+
doc.transformNodes === undefined)
|
|
119
|
+
throw new LoaderError(F, 'header', 'no meshes, cameras, lights, materials or geometries: not a .babylon scene');
|
|
120
|
+
const warnings = [];
|
|
121
|
+
const warn = (m) => {
|
|
122
|
+
if (warnings.length < 200)
|
|
123
|
+
warnings.push(m);
|
|
124
|
+
};
|
|
125
|
+
let nodeCount = 0;
|
|
126
|
+
const countNode = () => {
|
|
127
|
+
if (++nodeCount > maxNodes)
|
|
128
|
+
throw new LoaderError(F, 'limit', `more than ${maxNodes} nodes`);
|
|
129
|
+
};
|
|
130
|
+
// Mirror helpers.
|
|
131
|
+
const P = (v) => [v[0], v[1], rh ? 0 - v[2] : v[2]];
|
|
132
|
+
const Q = (q) => rh ? [0 - q[0], 0 - q[1], q[2], q[3]] : [q[0], q[1], q[2], q[3]];
|
|
133
|
+
// ---- textures and materials
|
|
134
|
+
let textureBytes = 0;
|
|
135
|
+
const texture = (v, what) => {
|
|
136
|
+
if (!isObject(v))
|
|
137
|
+
return undefined;
|
|
138
|
+
const t = {
|
|
139
|
+
name: str(v.name, ''),
|
|
140
|
+
level: num(v.level, 1),
|
|
141
|
+
offset: [num(v.uOffset, 0), num(v.vOffset, 0)],
|
|
142
|
+
scale: [num(v.uScale, 1), num(v.vScale, 1)],
|
|
143
|
+
angle: num(v.wAng, 0),
|
|
144
|
+
hasAlpha: flag(v.hasAlpha, false),
|
|
145
|
+
invertY: flag(v.invertY, true),
|
|
146
|
+
uvSet: num(v.coordinatesIndex, 0),
|
|
147
|
+
wrap: [num(v.wrapU, 1), num(v.wrapV, 1)],
|
|
148
|
+
};
|
|
149
|
+
if (typeof v.base64String === 'string') {
|
|
150
|
+
const m = /^data:([^;,]+)?(?:;[^,]*)?,/.exec(v.base64String);
|
|
151
|
+
const body = m ? v.base64String.slice(m[0].length) : v.base64String;
|
|
152
|
+
if (body.length * 0.75 + textureBytes > maxTextureBytes)
|
|
153
|
+
throw new LoaderError(F, 'limit', `embedded textures pass the limit of ${maxTextureBytes} bytes`);
|
|
154
|
+
t.data = decodeBase64(body, `${what} base64String`);
|
|
155
|
+
textureBytes += t.data.length;
|
|
156
|
+
if (m?.[1])
|
|
157
|
+
t.mimeType = m[1];
|
|
158
|
+
}
|
|
159
|
+
return t;
|
|
160
|
+
};
|
|
161
|
+
const rgb = (v, fallback, what, linearize) => {
|
|
162
|
+
const c = vec(v, 3, fallback, what);
|
|
163
|
+
return (linearize ? c.map((x) => srgbToLinear(Math.min(1, Math.max(0, x)))) : c);
|
|
164
|
+
};
|
|
165
|
+
const materials = [];
|
|
166
|
+
for (const m of list(doc.materials, 'materials')) {
|
|
167
|
+
const className = str(m.customType, 'BABYLON.StandardMaterial');
|
|
168
|
+
const pbr = /PBR/i.test(className);
|
|
169
|
+
const alpha = num(m.alpha, 1);
|
|
170
|
+
const textures = {};
|
|
171
|
+
const put = (slot, v) => {
|
|
172
|
+
const t = texture(v, `material ${str(m.id, '?')} ${slot}`);
|
|
173
|
+
if (t)
|
|
174
|
+
textures[slot] = t;
|
|
175
|
+
};
|
|
176
|
+
if (pbr) {
|
|
177
|
+
put('color', m.baseTexture ?? m.albedoTexture);
|
|
178
|
+
put('metallicRoughness', m.metallicRoughnessTexture ?? m.metallicTexture);
|
|
179
|
+
put('occlusion', m.ambientTexture);
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
put('color', m.diffuseTexture);
|
|
183
|
+
put('specular', m.specularTexture);
|
|
184
|
+
put('occlusion', m.ambientTexture);
|
|
185
|
+
}
|
|
186
|
+
put('normal', m.normalTexture ?? m.bumpTexture);
|
|
187
|
+
put('emissive', m.emissiveTexture);
|
|
188
|
+
put('opacity', m.opacityTexture);
|
|
189
|
+
const base = pbr ? (m.baseColor ?? m.albedo ?? m.albedoColor) : m.diffuse;
|
|
190
|
+
const c = rgb(base, [1, 1, 1], `material ${str(m.id, '?')} color`, !pbr);
|
|
191
|
+
const metallic = pbr ? num(m.metallic, 1) : undefined, roughness = pbr ? num(m.roughness, 1) : undefined;
|
|
192
|
+
materials.push({
|
|
193
|
+
id: str(m.id, str(m.name, `material_${materials.length}`)),
|
|
194
|
+
name: str(m.name, str(m.id, `material_${materials.length}`)),
|
|
195
|
+
kind: pbr ? 'pbr' : 'standard',
|
|
196
|
+
className,
|
|
197
|
+
color: [c[0], c[1], c[2], alpha],
|
|
198
|
+
emissive: rgb(m.emissive, [0, 0, 0], 'emissive', !pbr),
|
|
199
|
+
specular: rgb(m.specular, [1, 1, 1], 'specular', !pbr),
|
|
200
|
+
specularPower: num(m.specularPower, 64),
|
|
201
|
+
...(metallic !== undefined ? { metallic } : {}),
|
|
202
|
+
...(roughness !== undefined ? { roughness } : {}),
|
|
203
|
+
alpha,
|
|
204
|
+
doubleSided: m.backFaceCulling === false || m.doubleSided === true || m.twoSidedLighting === true,
|
|
205
|
+
unlit: flag(m.disableLighting, false) || flag(m.unlit, false),
|
|
206
|
+
textures,
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
const multiMaterials = list(doc.multiMaterials, 'multiMaterials').map((m, i) => ({
|
|
210
|
+
id: str(m.id, str(m.name, `multi_${i}`)),
|
|
211
|
+
name: str(m.name, str(m.id, `multi_${i}`)),
|
|
212
|
+
materials: Array.isArray(m.materials) ? m.materials.map((x) => str(x, '')) : [],
|
|
213
|
+
}));
|
|
214
|
+
// ---- shared geometries
|
|
215
|
+
let vertexTotal = 0, triangleTotal = 0;
|
|
216
|
+
const geometries = new Map();
|
|
217
|
+
const vd = isObject(doc.geometries) ? doc.geometries : {};
|
|
218
|
+
for (const g of [...list(vd.vertexData, 'geometries.vertexData'), ...list(vd.boxes, 'geometries.boxes')])
|
|
219
|
+
if (typeof g.id === 'string')
|
|
220
|
+
geometries.set(g.id, g);
|
|
221
|
+
const buildGeometry = (src, what) => {
|
|
222
|
+
const pos = numbers(src.positions, `${what} positions`, 3, maxVertices * 3);
|
|
223
|
+
if (!pos || pos.length === 0)
|
|
224
|
+
return null;
|
|
225
|
+
const count = pos.length / 3;
|
|
226
|
+
vertexTotal += count;
|
|
227
|
+
if (vertexTotal > maxVertices)
|
|
228
|
+
throw new LoaderError(F, 'limit', `vertex count ${vertexTotal} exceeds the limit of ${maxVertices}`);
|
|
229
|
+
const per = (key, width, label) => {
|
|
230
|
+
const a = numbers(src[key], `${what} ${label}`, width, count * width);
|
|
231
|
+
if (a && a.length !== count * width)
|
|
232
|
+
syntax(`${what} ${label} has ${a.length / width} entries for ${count} vertices`);
|
|
233
|
+
return a;
|
|
234
|
+
};
|
|
235
|
+
const normals = per('normals', 3, 'normals'), uvs = per('uvs', 2, 'uvs'), uvs2 = per('uvs2', 2, 'uvs2'), colors = per('colors', 4, 'colors');
|
|
236
|
+
let indexList = numbers(src.indices, `${what} indices`, 3, maxTriangles * 3);
|
|
237
|
+
if (!indexList) {
|
|
238
|
+
if (count % 3)
|
|
239
|
+
syntax(`${what} has no indices and ${count} vertices, not a multiple of 3`);
|
|
240
|
+
indexList = Array.from({ length: count }, (_, i) => i);
|
|
241
|
+
}
|
|
242
|
+
triangleTotal += indexList.length / 3;
|
|
243
|
+
if (triangleTotal > maxTriangles)
|
|
244
|
+
throw new LoaderError(F, 'limit', `triangle count ${triangleTotal} exceeds the limit of ${maxTriangles}`);
|
|
245
|
+
const indices = new Uint32Array(indexList.length);
|
|
246
|
+
for (let i = 0; i < indexList.length; i += 3) {
|
|
247
|
+
const a = indexList[i], b = indexList[i + 1], c = indexList[i + 2];
|
|
248
|
+
for (const v of [a, b, c])
|
|
249
|
+
if (!Number.isInteger(v) || v < 0 || v >= count)
|
|
250
|
+
throw new LoaderError(F, 'range', `${what}: index ${v} is outside the ${count} vertices`);
|
|
251
|
+
indices[i] = a;
|
|
252
|
+
indices[i + 1] = rh ? c : b;
|
|
253
|
+
indices[i + 2] = rh ? b : c;
|
|
254
|
+
}
|
|
255
|
+
const positions = new Float32Array(pos);
|
|
256
|
+
const nrm = normals ? new Float32Array(normals) : undefined;
|
|
257
|
+
if (rh) {
|
|
258
|
+
for (let i = 2; i < positions.length; i += 3)
|
|
259
|
+
positions[i] = 0 - positions[i];
|
|
260
|
+
if (nrm)
|
|
261
|
+
for (let i = 2; i < nrm.length; i += 3)
|
|
262
|
+
nrm[i] = 0 - nrm[i];
|
|
263
|
+
}
|
|
264
|
+
const geometry = { kind: 'mesh', positions, indices };
|
|
265
|
+
if (nrm)
|
|
266
|
+
geometry.normals = nrm;
|
|
267
|
+
if (uvs)
|
|
268
|
+
geometry.uvs = new Float32Array(uvs);
|
|
269
|
+
if (uvs2)
|
|
270
|
+
geometry.attributes = { uv1: new Float32Array(uvs2) };
|
|
271
|
+
if (colors) {
|
|
272
|
+
const c3 = new Float32Array(count * 3);
|
|
273
|
+
for (let i = 0; i < count; i++)
|
|
274
|
+
for (let k = 0; k < 3; k++)
|
|
275
|
+
c3[i * 3 + k] = colors[i * 4 + k];
|
|
276
|
+
geometry.colors = c3;
|
|
277
|
+
}
|
|
278
|
+
const subs = list(src.subMeshes, `${what} subMeshes`);
|
|
279
|
+
if (subs.length) {
|
|
280
|
+
const groups = [];
|
|
281
|
+
for (const s of subs) {
|
|
282
|
+
const start = num(s.indexStart, 0), n = num(s.indexCount, 0);
|
|
283
|
+
if (!Number.isInteger(start) ||
|
|
284
|
+
!Number.isInteger(n) ||
|
|
285
|
+
start < 0 ||
|
|
286
|
+
n < 0 ||
|
|
287
|
+
start + n > indices.length ||
|
|
288
|
+
start % 3 ||
|
|
289
|
+
n % 3)
|
|
290
|
+
throw new LoaderError(F, 'range', `${what}: a subMesh covers indices ${start} to ${start + n} of ${indices.length}`);
|
|
291
|
+
groups.push({ start, count: n, properties: { materialIndex: num(s.materialIndex, 0) } });
|
|
292
|
+
}
|
|
293
|
+
geometry.groups = groups;
|
|
294
|
+
}
|
|
295
|
+
const out = { geometry };
|
|
296
|
+
// Bone data: four 8-bit indices packed in one number per vertex, and four weights.
|
|
297
|
+
const skin = (indexKey, weightKey) => {
|
|
298
|
+
const bi = per(indexKey, 1, indexKey), bw = per(weightKey, 4, weightKey);
|
|
299
|
+
if (!bi || !bw)
|
|
300
|
+
return undefined;
|
|
301
|
+
const j = new Uint16Array(count * 4);
|
|
302
|
+
for (let i = 0; i < count; i++) {
|
|
303
|
+
const packed = bi[i] >>> 0;
|
|
304
|
+
for (let k = 0; k < 4; k++)
|
|
305
|
+
j[i * 4 + k] = (packed >>> (8 * k)) & 255;
|
|
306
|
+
}
|
|
307
|
+
return [j, new Float32Array(bw)];
|
|
308
|
+
};
|
|
309
|
+
const first = skin('matricesIndices', 'matricesWeights');
|
|
310
|
+
if (first)
|
|
311
|
+
[out.joints, out.weights] = first;
|
|
312
|
+
const extra = first && skin('matricesIndicesExtra', 'matricesWeightsExtra');
|
|
313
|
+
if (extra)
|
|
314
|
+
[out.joints1, out.weights1] = extra;
|
|
315
|
+
return out;
|
|
316
|
+
};
|
|
317
|
+
// ---- animations
|
|
318
|
+
const animationsOf = (v, what) => {
|
|
319
|
+
const out = [];
|
|
320
|
+
for (const a of list(v, `${what} animations`)) {
|
|
321
|
+
const property = str(a.property, '');
|
|
322
|
+
if (!['position', 'rotation', 'rotationQuaternion', 'scaling'].includes(property))
|
|
323
|
+
continue;
|
|
324
|
+
const keys = list(a.keys, `${what} animation keys`);
|
|
325
|
+
if (keys.length > 1_000_000)
|
|
326
|
+
throw new LoaderError(F, 'limit', 'an animation has more than 1,000,000 keys');
|
|
327
|
+
const width = property === 'rotationQuaternion' ? 4 : 3;
|
|
328
|
+
out.push({
|
|
329
|
+
name: str(a.name, property),
|
|
330
|
+
property: property === 'rotation' ? 'rotationQuaternion' : property,
|
|
331
|
+
fps: num(a.framePerSecond, 60),
|
|
332
|
+
loop: num(a.loopBehavior, 1) !== 2,
|
|
333
|
+
keys: keys.map((k) => {
|
|
334
|
+
const raw = vec(k.values, width, [], `${what} animation key`), frame = num(k.frame, 0);
|
|
335
|
+
if (property === 'position')
|
|
336
|
+
return { frame, values: P(raw) };
|
|
337
|
+
if (property === 'rotation')
|
|
338
|
+
return { frame, values: Q(eulerToQuaternion(raw[0], raw[1], raw[2])) };
|
|
339
|
+
if (property === 'rotationQuaternion')
|
|
340
|
+
return { frame, values: Q(raw) };
|
|
341
|
+
return { frame, values: raw };
|
|
342
|
+
}),
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
return out;
|
|
346
|
+
};
|
|
347
|
+
// ---- nodes
|
|
348
|
+
const nodeFields = (n, what) => {
|
|
349
|
+
if (n.pivotMatrix !== undefined &&
|
|
350
|
+
Array.isArray(n.pivotMatrix) &&
|
|
351
|
+
n.pivotMatrix.some((x, i) => x !== (i % 5 === 0 ? 1 : 0)))
|
|
352
|
+
warn(`${what}: pivotMatrix is not applied`);
|
|
353
|
+
const t = vec(n.position, 3, [0, 0, 0], `${what} position`);
|
|
354
|
+
const q = Array.isArray(n.rotationQuaternion)
|
|
355
|
+
? vec(n.rotationQuaternion, 4, [0, 0, 0, 1], `${what} rotationQuaternion`)
|
|
356
|
+
: (() => {
|
|
357
|
+
const e = vec(n.rotation, 3, [0, 0, 0], `${what} rotation`);
|
|
358
|
+
return eulerToQuaternion(e[0], e[1], e[2]);
|
|
359
|
+
})();
|
|
360
|
+
const parentId = n.parentId ?? n.parentID;
|
|
361
|
+
return {
|
|
362
|
+
id: str(n.id, str(n.name, `node_${nodeCount}`)),
|
|
363
|
+
name: str(n.name, str(n.id, `node_${nodeCount}`)),
|
|
364
|
+
...(parentId !== undefined && parentId !== null ? { parentId: str(parentId, '') } : {}),
|
|
365
|
+
translation: P(t),
|
|
366
|
+
rotation: Q(q),
|
|
367
|
+
scale: vec(n.scaling, 3, [1, 1, 1], `${what} scaling`),
|
|
368
|
+
visible: flag(n.isVisible, true) && flag(n.isEnabled, true),
|
|
369
|
+
animations: animationsOf(n.animations, what),
|
|
370
|
+
};
|
|
371
|
+
};
|
|
372
|
+
const transformNodes = [];
|
|
373
|
+
for (const n of list(doc.transformNodes, 'transformNodes')) {
|
|
374
|
+
countNode();
|
|
375
|
+
transformNodes.push(nodeFields(n, `transformNode ${str(n.id, '?')}`));
|
|
376
|
+
}
|
|
377
|
+
const meshes = [];
|
|
378
|
+
const cache = new Map();
|
|
379
|
+
for (const m of list(doc.meshes, 'meshes')) {
|
|
380
|
+
countNode();
|
|
381
|
+
const what = `mesh ${str(m.id, str(m.name, '?'))}`;
|
|
382
|
+
const node = nodeFields(m, what);
|
|
383
|
+
if (typeof m.delayLoadingFile === 'string' && m.positions === undefined && m.geometryId === undefined) {
|
|
384
|
+
warn(`${what}: delay-loaded binary data (${m.delayLoadingFile}) is not read`);
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
const geometryId = typeof m.geometryId === 'string' ? m.geometryId : undefined;
|
|
388
|
+
let built;
|
|
389
|
+
if (geometryId !== undefined) {
|
|
390
|
+
const src = geometries.get(geometryId);
|
|
391
|
+
if (!src)
|
|
392
|
+
throw new LoaderError(F, 'range', `${what} names geometry "${geometryId}" which the file does not hold`);
|
|
393
|
+
if (!cache.has(geometryId))
|
|
394
|
+
cache.set(geometryId, buildGeometry(src, `geometry ${geometryId}`));
|
|
395
|
+
built = cache.get(geometryId);
|
|
396
|
+
// Submeshes belong to the mesh, not the shared vertex data.
|
|
397
|
+
if (built && Array.isArray(m.subMeshes) && m.subMeshes.length) {
|
|
398
|
+
const copy = { ...built, geometry: { ...built.geometry } };
|
|
399
|
+
const subs = list(m.subMeshes, `${what} subMeshes`);
|
|
400
|
+
copy.geometry.groups = subs.map((s) => ({
|
|
401
|
+
start: num(s.indexStart, 0),
|
|
402
|
+
count: num(s.indexCount, 0),
|
|
403
|
+
properties: { materialIndex: num(s.materialIndex, 0) },
|
|
404
|
+
}));
|
|
405
|
+
for (const g of copy.geometry.groups)
|
|
406
|
+
if (g.start < 0 || g.count < 0 || g.start + g.count > copy.geometry.indices.length)
|
|
407
|
+
throw new LoaderError(F, 'range', `${what}: a subMesh covers indices past the geometry`);
|
|
408
|
+
built = copy;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
else
|
|
412
|
+
built = buildGeometry(m, what);
|
|
413
|
+
if (!built) {
|
|
414
|
+
// A mesh with no vertices is a plain parent.
|
|
415
|
+
transformNodes.push(node);
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
const mesh = { ...node, geometry: built.geometry };
|
|
419
|
+
if (typeof m.materialId === 'string')
|
|
420
|
+
mesh.materialId = m.materialId;
|
|
421
|
+
if (m.skeletonId !== undefined && m.skeletonId !== null && m.skeletonId !== -1)
|
|
422
|
+
mesh.skeletonId = str(m.skeletonId, '');
|
|
423
|
+
if (built.joints) {
|
|
424
|
+
mesh.joints = built.joints;
|
|
425
|
+
mesh.weights = built.weights;
|
|
426
|
+
}
|
|
427
|
+
if (built.joints1) {
|
|
428
|
+
mesh.joints1 = built.joints1;
|
|
429
|
+
mesh.weights1 = built.weights1;
|
|
430
|
+
}
|
|
431
|
+
meshes.push(mesh);
|
|
432
|
+
for (const inst of list(m.instances, `${what} instances`)) {
|
|
433
|
+
countNode();
|
|
434
|
+
const n2 = nodeFields({ ...inst, parentId: m.parentId ?? m.parentID }, `${what} instance`);
|
|
435
|
+
meshes.push({ ...mesh, ...n2, parentId: n2.parentId, instanceOf: mesh.id });
|
|
436
|
+
if (n2.parentId === undefined)
|
|
437
|
+
delete meshes[meshes.length - 1].parentId;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
// ---- cameras and lights
|
|
441
|
+
const cameras = [];
|
|
442
|
+
for (const c of list(doc.cameras, 'cameras')) {
|
|
443
|
+
countNode();
|
|
444
|
+
const what = `camera ${str(c.id, '?')}`;
|
|
445
|
+
const className = str(c.type, 'FreeCamera');
|
|
446
|
+
const position = vec(c.position, 3, [0, 0, 0], `${what} position`);
|
|
447
|
+
let target;
|
|
448
|
+
if (/ArcRotate/i.test(className)) {
|
|
449
|
+
const t = vec(c.target, 3, [0, 0, 0], `${what} target`), alpha = num(c.alpha, -Math.PI / 2), beta = num(c.beta, Math.PI / 2), radius = num(c.radius, 10);
|
|
450
|
+
target = t;
|
|
451
|
+
position[0] = t[0] + radius * Math.cos(alpha) * Math.sin(beta);
|
|
452
|
+
position[1] = t[1] + radius * Math.cos(beta);
|
|
453
|
+
position[2] = t[2] + radius * Math.sin(alpha) * Math.sin(beta);
|
|
454
|
+
}
|
|
455
|
+
else if (Array.isArray(c.target))
|
|
456
|
+
target = vec(c.target, 3, [0, 0, 1], `${what} target`);
|
|
457
|
+
else {
|
|
458
|
+
const q = Array.isArray(c.rotationQuaternion)
|
|
459
|
+
? vec(c.rotationQuaternion, 4, [0, 0, 0, 1], `${what} rotationQuaternion`)
|
|
460
|
+
: eulerToQuaternion(...vec(c.rotation, 3, [0, 0, 0], `${what} rotation`));
|
|
461
|
+
// Rotate +Z (Babylon looks along +Z) by q.
|
|
462
|
+
const [x, y, z, w] = q;
|
|
463
|
+
target = [
|
|
464
|
+
position[0] + 2 * (x * z + w * y),
|
|
465
|
+
position[1] + 2 * (y * z - w * x),
|
|
466
|
+
position[2] + 1 - 2 * (x * x + y * y),
|
|
467
|
+
];
|
|
468
|
+
}
|
|
469
|
+
const cam = {
|
|
470
|
+
id: str(c.id, str(c.name, `camera_${cameras.length}`)),
|
|
471
|
+
name: str(c.name, str(c.id, `camera_${cameras.length}`)),
|
|
472
|
+
className,
|
|
473
|
+
position: P(position),
|
|
474
|
+
target: P(target),
|
|
475
|
+
fov: num(c.fov, 0.8),
|
|
476
|
+
near: num(c.minZ, 1),
|
|
477
|
+
far: num(c.maxZ, 10000),
|
|
478
|
+
};
|
|
479
|
+
if (c.parentId !== undefined && c.parentId !== null)
|
|
480
|
+
cam.parentId = str(c.parentId, '');
|
|
481
|
+
if (num(c.mode, 0) === 1)
|
|
482
|
+
cam.orthographic = {
|
|
483
|
+
left: num(c.orthoLeft, -1),
|
|
484
|
+
right: num(c.orthoRight, 1),
|
|
485
|
+
top: num(c.orthoTop, 1),
|
|
486
|
+
bottom: num(c.orthoBottom, -1),
|
|
487
|
+
};
|
|
488
|
+
cameras.push(cam);
|
|
489
|
+
}
|
|
490
|
+
const lights = [];
|
|
491
|
+
const KINDS = ['point', 'directional', 'spot', 'hemispheric'];
|
|
492
|
+
for (const l of list(doc.lights, 'lights')) {
|
|
493
|
+
countNode();
|
|
494
|
+
const what = `light ${str(l.id, '?')}`;
|
|
495
|
+
const type = num(l.type, 0);
|
|
496
|
+
if (!Number.isInteger(type) || type < 0 || type > 3) {
|
|
497
|
+
warn(`${what}: light type ${type} is not read`);
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
500
|
+
const light = {
|
|
501
|
+
id: str(l.id, str(l.name, `light_${lights.length}`)),
|
|
502
|
+
name: str(l.name, str(l.id, `light_${lights.length}`)),
|
|
503
|
+
kind: KINDS[type],
|
|
504
|
+
color: rgb(l.diffuse, [1, 1, 1], `${what} diffuse`, false),
|
|
505
|
+
intensity: num(l.intensity, 1),
|
|
506
|
+
};
|
|
507
|
+
if (l.parentId !== undefined && l.parentId !== null)
|
|
508
|
+
light.parentId = str(l.parentId, '');
|
|
509
|
+
if (type !== 3 && l.position !== undefined)
|
|
510
|
+
light.position = P(vec(l.position, 3, [0, 0, 0], `${what} position`));
|
|
511
|
+
if (type !== 0 && l.direction !== undefined)
|
|
512
|
+
light.direction = P(vec(l.direction, 3, [0, -1, 0], `${what} direction`));
|
|
513
|
+
if (l.range !== undefined && num(l.range, Infinity) < 1e30)
|
|
514
|
+
light.range = num(l.range, Infinity);
|
|
515
|
+
if (type === 2) {
|
|
516
|
+
light.angle = num(l.angle, Math.PI / 2);
|
|
517
|
+
if (l.innerAngle !== undefined)
|
|
518
|
+
light.innerAngle = num(l.innerAngle, 0);
|
|
519
|
+
}
|
|
520
|
+
if (type === 3 && l.groundColor !== undefined)
|
|
521
|
+
light.groundColor = rgb(l.groundColor, [0, 0, 0], `${what} groundColor`, false);
|
|
522
|
+
lights.push(light);
|
|
523
|
+
}
|
|
524
|
+
// ---- skeletons
|
|
525
|
+
const skeletons = list(doc.skeletons, 'skeletons').map((s, i) => {
|
|
526
|
+
const bones = list(s.bones, `skeleton ${i} bones`);
|
|
527
|
+
if (bones.length > 4096)
|
|
528
|
+
throw new LoaderError(F, 'limit', `skeleton ${i} has ${bones.length} bones, past 4096`);
|
|
529
|
+
return {
|
|
530
|
+
id: str(s.id, String(i)),
|
|
531
|
+
name: str(s.name, `skeleton_${i}`),
|
|
532
|
+
bones: bones.map((b, k) => {
|
|
533
|
+
const m = vec(b.matrix, 16, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], `skeleton ${i} bone ${k} matrix`);
|
|
534
|
+
// Babylon writes row-major with row vectors: the same 16 numbers are the column-vector matrix, column-major.
|
|
535
|
+
if (rh)
|
|
536
|
+
for (let r = 0; r < 16; r++) {
|
|
537
|
+
const row = r & 3, col = r >> 2;
|
|
538
|
+
if ((row === 2) !== (col === 2))
|
|
539
|
+
m[r] = 0 - m[r]; // S M S, S = diag(1, 1, -1, 1)
|
|
540
|
+
}
|
|
541
|
+
return {
|
|
542
|
+
name: str(b.name, `bone_${k}`),
|
|
543
|
+
index: num(b.index, k),
|
|
544
|
+
parentBoneIndex: num(b.parentBoneIndex, -1),
|
|
545
|
+
matrix: m,
|
|
546
|
+
};
|
|
547
|
+
}),
|
|
548
|
+
};
|
|
549
|
+
});
|
|
550
|
+
// Parent chains must end: a cycle would hang every walk over the nodes.
|
|
551
|
+
const parents = new Map();
|
|
552
|
+
for (const n of [...meshes, ...transformNodes])
|
|
553
|
+
if (!parents.has(n.id))
|
|
554
|
+
parents.set(n.id, n.parentId);
|
|
555
|
+
for (const start of parents.keys()) {
|
|
556
|
+
let at = start;
|
|
557
|
+
for (let d = 0; at !== undefined && parents.has(at); d++, at = parents.get(at))
|
|
558
|
+
if (d > parents.size)
|
|
559
|
+
throw new LoaderError(F, 'syntax', `node "${start}" is its own ancestor`);
|
|
560
|
+
}
|
|
561
|
+
const out = {
|
|
562
|
+
meshes,
|
|
563
|
+
transformNodes,
|
|
564
|
+
materials,
|
|
565
|
+
multiMaterials,
|
|
566
|
+
cameras,
|
|
567
|
+
lights,
|
|
568
|
+
skeletons,
|
|
569
|
+
warnings,
|
|
570
|
+
};
|
|
571
|
+
if (Array.isArray(doc.clearColor))
|
|
572
|
+
out.clearColor = vec(doc.clearColor, 3, [0, 0, 0], 'clearColor');
|
|
573
|
+
if (Array.isArray(doc.ambientColor))
|
|
574
|
+
out.ambientColor = vec(doc.ambientColor, 3, [0, 0, 0], 'ambientColor');
|
|
575
|
+
if (typeof doc.activeCameraID === 'string')
|
|
576
|
+
out.activeCameraId = doc.activeCameraID;
|
|
577
|
+
if (isObject(doc.producer))
|
|
578
|
+
out.producer = { name: str(doc.producer.name, ''), version: str(doc.producer.version, '') };
|
|
579
|
+
return out;
|
|
580
|
+
}
|
|
581
|
+
function composeTRS(t, q, s) {
|
|
582
|
+
const [x, y, z, w] = q;
|
|
583
|
+
const m = new Float64Array(16);
|
|
584
|
+
m[0] = (1 - 2 * (y * y + z * z)) * s[0];
|
|
585
|
+
m[1] = 2 * (x * y + z * w) * s[0];
|
|
586
|
+
m[2] = 2 * (x * z - y * w) * s[0];
|
|
587
|
+
m[4] = 2 * (x * y - z * w) * s[1];
|
|
588
|
+
m[5] = (1 - 2 * (x * x + z * z)) * s[1];
|
|
589
|
+
m[6] = 2 * (y * z + x * w) * s[1];
|
|
590
|
+
m[8] = 2 * (x * z + y * w) * s[2];
|
|
591
|
+
m[9] = 2 * (y * z - x * w) * s[2];
|
|
592
|
+
m[10] = (1 - 2 * (x * x + y * y)) * s[2];
|
|
593
|
+
m[12] = t[0];
|
|
594
|
+
m[13] = t[1];
|
|
595
|
+
m[14] = t[2];
|
|
596
|
+
m[15] = 1;
|
|
597
|
+
return m;
|
|
598
|
+
}
|
|
599
|
+
function mul(a, b) {
|
|
600
|
+
const o = new Float64Array(16);
|
|
601
|
+
for (let c = 0; c < 4; c++)
|
|
602
|
+
for (let r = 0; r < 4; r++)
|
|
603
|
+
for (let k = 0; k < 4; k++)
|
|
604
|
+
o[c * 4 + r] += a[k * 4 + r] * b[c * 4 + k];
|
|
605
|
+
return o;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Bakes every mesh's world transform into one geometry: parents, then the mesh's own placement. Each mesh becomes a
|
|
609
|
+
* group (`name`, its material's colour when the material is a plain one). A mirroring transform (a negative scale)
|
|
610
|
+
* flips the winding so faces keep facing out.
|
|
611
|
+
*/
|
|
612
|
+
export function flattenBabylon(scene, options = {}) {
|
|
613
|
+
const onlyVisible = options.onlyVisible ?? true;
|
|
614
|
+
const byId = new Map();
|
|
615
|
+
for (const n of [...scene.transformNodes, ...scene.meshes])
|
|
616
|
+
if (!byId.has(n.id))
|
|
617
|
+
byId.set(n.id, n);
|
|
618
|
+
const materials = new Map(scene.materials.map((m) => [m.id, m]));
|
|
619
|
+
const world = (n) => {
|
|
620
|
+
let m = composeTRS(n.translation, n.rotation, n.scale);
|
|
621
|
+
let at = n, hops = 0;
|
|
622
|
+
if (onlyVisible && !n.visible)
|
|
623
|
+
return null;
|
|
624
|
+
while (at.parentId !== undefined && hops++ < byId.size + 1) {
|
|
625
|
+
const p = byId.get(at.parentId);
|
|
626
|
+
if (!p)
|
|
627
|
+
break;
|
|
628
|
+
if (onlyVisible && !p.visible)
|
|
629
|
+
return null;
|
|
630
|
+
m = mul(composeTRS(p.translation, p.rotation, p.scale), m);
|
|
631
|
+
at = p;
|
|
632
|
+
}
|
|
633
|
+
return m;
|
|
634
|
+
};
|
|
635
|
+
const positions = [], normals = [], uvs = [], indices = [], groups = [];
|
|
636
|
+
let withNormals = true, withUvs = true;
|
|
637
|
+
const placed = [];
|
|
638
|
+
for (const mesh of scene.meshes) {
|
|
639
|
+
const m = world(mesh);
|
|
640
|
+
if (m)
|
|
641
|
+
placed.push({ mesh, m });
|
|
642
|
+
if (m && !mesh.geometry.normals)
|
|
643
|
+
withNormals = false;
|
|
644
|
+
if (m && !mesh.geometry.uvs)
|
|
645
|
+
withUvs = false;
|
|
646
|
+
}
|
|
647
|
+
for (const { mesh, m } of placed) {
|
|
648
|
+
const g = mesh.geometry, base = positions.length / 3;
|
|
649
|
+
const det = m[0] * (m[5] * m[10] - m[6] * m[9]) - m[4] * (m[1] * m[10] - m[2] * m[9]) + m[8] * (m[1] * m[6] - m[2] * m[5]);
|
|
650
|
+
for (let i = 0; i < g.positions.length; i += 3) {
|
|
651
|
+
const x = g.positions[i], y = g.positions[i + 1], z = g.positions[i + 2];
|
|
652
|
+
positions.push(m[0] * x + m[4] * y + m[8] * z + m[12], m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14]);
|
|
653
|
+
if (withNormals) {
|
|
654
|
+
// Normals follow the inverse transpose; for TRS that is the rotation with the scale divided out twice.
|
|
655
|
+
const nx = g.normals[i], ny = g.normals[i + 1], nz = g.normals[i + 2];
|
|
656
|
+
const sx = m[0] ** 2 + m[1] ** 2 + m[2] ** 2 || 1, sy = m[4] ** 2 + m[5] ** 2 + m[6] ** 2 || 1, sz = m[8] ** 2 + m[9] ** 2 + m[10] ** 2 || 1;
|
|
657
|
+
const vx = (m[0] * nx) / sx + (m[4] * ny) / sy + (m[8] * nz) / sz, vy = (m[1] * nx) / sx + (m[5] * ny) / sy + (m[9] * nz) / sz, vz = (m[2] * nx) / sx + (m[6] * ny) / sy + (m[10] * nz) / sz;
|
|
658
|
+
const len = Math.hypot(vx, vy, vz) || 1;
|
|
659
|
+
normals.push(vx / len, vy / len, vz / len);
|
|
660
|
+
}
|
|
661
|
+
if (withUvs)
|
|
662
|
+
uvs.push(g.uvs[(i / 3) * 2], g.uvs[(i / 3) * 2 + 1]);
|
|
663
|
+
}
|
|
664
|
+
const start = indices.length;
|
|
665
|
+
for (let i = 0; i < g.indices.length; i += 3) {
|
|
666
|
+
const a = g.indices[i] + base, b = g.indices[i + 1] + base, c = g.indices[i + 2] + base;
|
|
667
|
+
if (det < 0)
|
|
668
|
+
indices.push(a, c, b);
|
|
669
|
+
else
|
|
670
|
+
indices.push(a, b, c);
|
|
671
|
+
}
|
|
672
|
+
const material = mesh.materialId ? materials.get(mesh.materialId) : undefined;
|
|
673
|
+
groups.push({
|
|
674
|
+
start,
|
|
675
|
+
count: indices.length - start,
|
|
676
|
+
name: mesh.name,
|
|
677
|
+
// LoadedGroup.color is sRGB; the material's colour is linear, so convert it back (alpha stays as it is).
|
|
678
|
+
...(material
|
|
679
|
+
? {
|
|
680
|
+
color: [
|
|
681
|
+
linearToSrgb(material.color[0]),
|
|
682
|
+
linearToSrgb(material.color[1]),
|
|
683
|
+
linearToSrgb(material.color[2]),
|
|
684
|
+
material.color[3],
|
|
685
|
+
],
|
|
686
|
+
}
|
|
687
|
+
: {}),
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
const out = {
|
|
691
|
+
kind: 'mesh',
|
|
692
|
+
positions: new Float32Array(positions),
|
|
693
|
+
indices: new Uint32Array(indices),
|
|
694
|
+
groups,
|
|
695
|
+
};
|
|
696
|
+
if (withNormals && normals.length)
|
|
697
|
+
out.normals = new Float32Array(normals);
|
|
698
|
+
if (withUvs && uvs.length)
|
|
699
|
+
out.uvs = new Float32Array(uvs);
|
|
700
|
+
return out;
|
|
701
|
+
}
|