A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(assets): a .fbx is a model source like a .gltf is
esengine099c020a79b8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 24d2e7fce..75ebd29be 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,27 @@ published separately; it ships inside the editor.### Added+- **FBX import.** A `.fbx` is a model source like a `.gltf` is: drop one in and it+ writes the same products — `.esmesh` per material run, the images it embeds, an+ `.esmaterial`, an `.estimeline` per take, and the `.esprefab` that assembles+ them. Parsing is [ufbx](https://github.com/ufbx/ufbx), vendored and built to+ wasm, so nothing needs the Autodesk FBX SDK; binary and ASCII, every version+ from the 5000-series up.++ What FBX needs that glTF does not is settled before the products are written:+ axes and units converted to the engine's, polygons triangulated, geometry+ transforms turned into real entities, and Euler curves — with their pivots and+ pre-rotations — baked into the TRS keyframes a track can hold. Rigged models+ arrive rigged, bind pose and all.++ Two things it reports rather than carries: separate metalness/roughness maps+ (the engine samples one image packed as glTF packs it) and opacity maps.++ The import's two doors are now one reader — the editor and+ `estella import-model` (was `import-gltf`, still accepted) share it, along with+ everything downstream of a format, which is what keeps a second source format+ from being a second set of rules for what a model is.+- **A 3D scene the release argument can point at.** `examples/lighting-3d`: askinned model held at a bend, a sun that casts it onto the panel behind it, anda baked environment its metal reflects — the sky on top, the ground on its face.diff --git a/desktop/electron-builder.yml b/desktop/electron-builder.ymlindex 592e55f02..92181cce1 100644--- a/desktop/electron-builder.yml+++ b/desktop/electron-builder.yml@@ -51,6 +51,11 @@ asarUnpack:extraResources:- from: ../build-tools/basisto: build-tools/basis+ # The FBX reader, shipped for the same reason and by the same rule: the model+ # import loads build-tools/ufbx/reader.mjs, which finds its own .wasm beside+ # itself — inside the asar it would find nothing.+ - from: ../build-tools/ufbx+ to: build-tools/ufbx# The SDK's TypeScript declarations, shipped as a real resource so a project's# `.esengine/sdk` types mirror can be staged on open (see electron/main.ts →# syncSdkTypes). electron-builder strips *.d.ts from node_modules by defaultdiff --git a/desktop/electron/importModel.ts b/desktop/electron/importModel.tsindex 08c8c2ff2..61c86ef73 100644--- a/desktop/electron/importModel.ts+++ b/desktop/electron/importModel.ts@@ -1,8 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file Model import: a `.gltf`/`.glb` in the project produces the assets a- * scene can actually reference.+ * @file Model import: a `.gltf`/`.glb`/`.fbx` in the project produces the assets+ * a scene can actually reference.** The engine loads none of the source formats — a Mesh2D reads `.esmesh` — so a* model that is only copied in leaves the user with a file nothing can draw.@@ -16,8 +16,9 @@ import { resolveInRoot, META_EXT } from './projectFs';import { capture } from './fileJournal';import { adoptOrphan } from '../../pipeline/src/assets/assetMeta';import {- importGltfMeshes, encodeImportedMesh, assembleGltfPrefab, materialProducts,-} from '../../pipeline/src/assets/gltfImport';+ encodeImportedMesh, assembleModelPrefab, materialProducts,+} from '../../pipeline/src/assets/modelImport';+import { modelStem, readModelSource } from '../../pipeline/src/assets/readModelSource';export interface ModelImportResult {/** Project-relative paths of everything written, in the order it was produced. */@@ -26,11 +27,7 @@ export interface ModelImportResult {warnings: string[];}-export const MODEL_EXTENSIONS = ['.gltf', '.glb'];--export function isModelSource(file: string): boolean {- return MODEL_EXTENSIONS.includes(path.extname(file).toLowerCase());-}+export { MODEL_EXTENSIONS, isModelSource } from '../../pipeline/src/assets/readModelSource';/*** Import `absSource` (already inside the project) into `destDir`, writing the@@ -45,15 +42,18 @@ export async function importModel(root: string, destDir: string, absSource: striconst absDir = resolveInRoot(root, destDir);await mkdir(absDir, { recursive: true });const sourceDir = originDir ?? path.dirname(absSource);- const stem = path.basename(absSource).replace(/\.(gltf|glb)$/i, '');+ const stem = modelStem(absSource);const projectRef = (abs: string): string =>path.relative(path.resolve(root), abs).split(path.sep).join('/');- const { meshes, textures, nodes, animations, externalFiles, warnings } = await importGltfMeshes(+ const { meshes, textures, nodes, animations, externalFiles, warnings } = await readModelSource(new Uint8Array(readFileSync(absSource)), stem,- (uri) => {- const abs = path.join(sourceDir, decodeURIComponent(uri));- return existsSync(abs) ? new Uint8Array(readFileSync(abs)) : null;+ {+ filename: absSource,+ externalBuffers: (uri) => {+ const abs = path.join(sourceDir, decodeURIComponent(uri));+ return existsSync(abs) ? new Uint8Array(readFileSync(abs)) : null;+ },},);@@ -125,11 +125,11 @@ export async function importModel(root: string, destDir: string, absSource: strifirstClip ??= rel;}if (meshes.length > 0) {- const prefab = assembleGltfPrefab(stem, meshes, { refs, nodes, scale, timeline: firstClip });+ const prefab = assembleModelPrefab(stem, meshes, { refs, nodes, scale, timeline: firstClip });await write(`${stem}.esprefab`, `${JSON.stringify(prefab, null, 2)}\n`);- // A glTF is in metres and a world unit is a design pixel, so a real-world- // model arrives a few pixels across. Said, not guessed at: the scale is the- // user's, and this is where they find out they have one.+ // Models are authored in metres and a world unit is a design pixel, so a+ // real-world model arrives a few pixels across. Said, not guessed at: the+ // scale is the user's, and this is where they find out they have one.const extent = Math.max(...meshes.flatMap((m) => m.data.aabbMax.map((v, i) => v - (m.data.aabbMin[i] ?? 0))));if (scale === 1 && extent < 8) {diff --git a/desktop/scripts/editor-checks/model-reimport.mjs b/desktop/scripts/editor-checks/model-reimport.mjsindex ba96d3296..e02f78cff 100644--- a/desktop/scripts/editor-checks/model-reimport.mjs+++ b/desktop/scripts/editor-checks/model-reimport.mjs@@ -10,12 +10,17 @@* ordinary importer is what connects the watcher, the Reimport row and the* settings to it — none of which a unit test can exercise, because every one of* them lives on the other side of the editor's own file plumbing.+ *+ * The `.fbx` half is here for one more reason: its reader is a wasm module+ * loaded from disk beside the app, which only the real, bundled editor can+ * prove it can still find.*/import { mkdir, readFile, writeFile } from 'node:fs/promises';import { existsSync } from 'node:fs';import { cp } from 'node:fs/promises';import path from 'node:path';import { makeProject, checker, DESKTOP } from '../lib/editorDriver.mjs';+import { skinnedBar } from '../lib/fbxFixtures.mjs';const EXAMPLE = path.resolve(DESKTOP, '..', 'examples', 'sprite-rendering');@@ -95,6 +100,20 @@ export async function run(ed) {return check.failures;}+ // An FBX arrives the same way and through the same importer; what it proves+ // that the glTF cannot is that the bundled editor still reaches its reader.+ const fbx = path.join(root, 'assets/models/rig.fbx');+ await writeFile(fbx, skinnedBar());+ const rig = path.join(root, 'assets/models/rig.esprefab');+ if (check(await until(ed, rig, (p) => p.entities?.length > 0),+ 'an .fbx written into the project produced no prefab — its reader never ran')) {+ check(existsSync(path.join(root, 'assets/models/rig.esmesh')),+ 'the .fbx prefab exists but the mesh it references does not');+ const clip = path.join(root, 'assets/models/rig_Take_001.estimeline');+ check(await until(ed, clip, (c) => c.tracks?.length > 0),+ 'the .fbx animation produced no clip — its curves were never baked');+ }+// Set the way the inspector sets it — the setting decides a product, so// writing it has to remake that product with no further prompting.await ed.call('set_import_settings',diff --git a/desktop/scripts/lib/fbxFixtures.d.mts b/desktop/scripts/lib/fbxFixtures.d.mtsnew file mode 100644index 000000000..5c517c718--- /dev/null+++ b/desktop/scripts/lib/fbxFixtures.d.mts@@ -0,0 +1,9 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** @see fbxFixtures.mjs */++/** A red-tinted triangle under a moved node, sampling an image beside the file. */+export declare function texturedTriangle(): Uint8Array;++/** Two bones and a quad bound to them, the upper bone turning 90° about Z. */+export declare function skinnedBar(): Uint8Array;diff --git a/desktop/scripts/lib/fbxFixtures.mjs b/desktop/scripts/lib/fbxFixtures.mjsnew file mode 100644index 000000000..932ac4f73--- /dev/null+++ b/desktop/scripts/lib/fbxFixtures.mjs@@ -0,0 +1,276 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file FBX sources written by hand, in the format's own ASCII dialect.+ *+ * An FBX fixture is normally a binary blob nobody can read or edit, which makes+ * a failing test a mystery. These are text: the vertices, the bind matrices and+ * the keyframes a test asserts on are visible in the file that produced them.+ * ufbx reads ASCII and binary through the same parser, so what they exercise is+ * this project's reading of a scene, not one particular container.+ *+ * Shared because the same models are the claim in two places: a unit test on the+ * importer, and a check that the real editor's import door reads them too.+ */++/** FBX stores time in ticks; this many are one second. */+const TICKS_PER_SECOND = 46186158000;++/** Keyframe interpolation flags (ufbxi_key_flags): linear, no tangents. */+const KEY_LINEAR = 4;++const header = (creator) => `; FBX 7.4.0 project file+FBXHeaderExtension: {+\tFBXHeaderVersion: 1003+\tFBXVersion: 7400+\tCreator: "${creator}"+}+GlobalSettings: {+\tVersion: 1000+\tProperties70: {+\t\tP: "UpAxis", "int", "Integer", "",1+\t\tP: "UpAxisSign", "int", "Integer", "",1+\t\tP: "FrontAxis", "int", "Integer", "",2+\t\tP: "FrontAxisSign", "int", "Integer", "",1+\t\tP: "CoordAxis", "int", "Integer", "",0+\t\tP: "CoordAxisSign", "int", "Integer", "",1+\t\tP: "UnitScaleFactor", "double", "Number", "",100+\t}+}+`;++/** An FBX array literal: `*<count> { a: ... }`, indented to sit inside a node. */+function array(name, values, indent) {+ const pad = '\t'.repeat(indent);+ return `${pad}${name}: *${values.length} {\n${pad}\ta: ${values.join(',')}\n${pad}}\n`;+}++/**+ * A polygon's vertex indices as FBX spells them: the last index of each face is+ * bit-flipped, which is how a reader finds the face boundary in a flat array.+ */+function polygons(faces) {+ return faces.flatMap((face) => face.map((ix, i) => (i === face.length - 1 ? ~ix : ix)));+}++/**+ * A mesh geometry with normals and UVs, both per polygon-vertex — the mapping+ * an exporter uses when a vertex can carry different values per face.+ */+function geometry(id, name, { vertices, faces, normals, uvs, materials }) {+ const corners = faces.flat().length;+ return `\tGeometry: ${id}, "Geometry::${name}", "Mesh" {+${array('Vertices', vertices, 2)}${array('PolygonVertexIndex', polygons(faces), 2)}\t\tGeometryVersion: 124+\t\tLayerElementNormal: 0 {+\t\t\tVersion: 102+\t\t\tName: ""+\t\t\tMappingInformationType: "ByPolygonVertex"+\t\t\tReferenceInformationType: "Direct"+${array('Normals', normals, 3)}\t\t}+\t\tLayerElementUV: 0 {+\t\t\tVersion: 101+\t\t\tName: "UVMap"+\t\t\tMappingInformationType: "ByPolygonVertex"+\t\t\tReferenceInformationType: "Direct"+${array('UV', uvs, 3)}${array('UVIndex', Array.from({ length: corners }, (_, i) => i), 3)}\t\t}+${materials === undefined ? '' : `\t\tLayerElementMaterial: 0 {+\t\t\tVersion: 101+\t\t\tName: ""+\t\t\tMappingInformationType: "ByPolygon"+\t\t\tReferenceInformationType: "IndexToDirect"+${array('Materials', materials, 3)}\t\t}+`}\t\tLayer: 0 {+\t\t\tVersion: 100+\t\t\tLayerElement: {+\t\t\t\tType: "LayerElementNormal"+\t\t\t\tTypedIndex: 0+\t\t\t}+\t\t\tLayerElement: {+\t\t\t\tType: "LayerElementUV"+\t\t\t\tTypedIndex: 0+\t\t\t}+${materials === undefined ? '' : `\t\t\tLayerElement: {+\t\t\t\tType: "LayerElementMaterial"+\t\t\t\tTypedIndex: 0+\t\t\t}+`}\t\t}+\t}+`;+}++/** A scene node. `kind` is "Mesh", "LimbNode" or "Null" — what FBX calls it. */+function model(id, name, kind, { translation, rotation, scale } = {}) {+ const props = [+ translation && `\t\t\tP: "Lcl Translation", "Lcl Translation", "", "A",${translation.join(',')}`,+ rotation && `\t\t\tP: "Lcl Rotation", "Lcl Rotation", "", "A",${rotation.join(',')}`,+ scale && `\t\t\tP: "Lcl Scaling", "Lcl Scaling", "", "A",${scale.join(',')}`,+ ].filter(Boolean);+ return `\tModel: ${id}, "Model::${name}", "${kind}" {+\t\tVersion: 232+\t\tProperties70: {+${props.join('\n')}${props.length ? '\n' : ''}\t\t}+\t}+`;+}++/**+ * A Phong material — what the overwhelming majority of FBX files carry, and the+ * shading model ufbx derives roughness from (out of the specular exponent).+ */+function material(id, name, { diffuse = [0.8, 0.8, 0.8], emissive, shininess = 20, opacity = 1 } = {}) {+ return `\tMaterial: ${id}, "Material::${name}", "" {+\t\tVersion: 102+\t\tShadingModel: "phong"+\t\tMultiLayer: 0+\t\tProperties70: {+\t\t\tP: "DiffuseColor", "Color", "", "A",${diffuse.join(',')}+\t\t\tP: "ShininessExponent", "double", "Number", "",${shininess}+\t\t\tP: "Opacity", "double", "Number", "",${opacity}+${emissive ? `\t\t\tP: "EmissiveColor", "Color", "", "A",${emissive.join(',')}+\t\t\tP: "EmissiveFactor", "double", "Number", "",1+` : ''}\t\t}+\t}+`;+}++/** A file texture. `relative` is the path as the FBX stores it. */+function texture(id, name, relative) {+ return `\tTexture: ${id}, "Texture::${name}", "" {+\t\tType: "TextureVideoClip"+\t\tVersion: 202+\t\tTextureName: "Texture::${name}"+\t\tFileName: "C:/art/${relative}"+\t\tRelativeFilename: "${relative.split('/').join('\\')}"+\t\tModelUVTranslation: 0,0+\t\tModelUVScaling: 1,1+\t\tTexture_Alpha_Source: "None"+\t\tCropping: 0,0,0,0+\t}+`;+}++/**+ * One animation curve. The flag/attribute arrays are run-length encoded against+ * `KeyAttrRefCount`, so one entry covering every key is a whole curve of linear+ * keyframes.+ */+function animCurve(id, times, values) {+ return `\tAnimationCurve: ${id}, "AnimCurve::", "" {+\t\tDefault: ${values[0] ?? 0}+\t\tKeyVer: 4009+${array('KeyTime', times.map((t) => Math.round(t * TICKS_PER_SECOND)), 2)}${array('KeyValueFloat', values, 2)}${array('KeyAttrFlags', [KEY_LINEAR], 2)}${array('KeyAttrDataFloat', [0, 0, 0, 0], 2)}${array('KeyAttrRefCount', [times.length], 2)}\t}+`;+}++const connect = (child, parent) => `\tC: "OO",${child},${parent}\n`;+const connectProp = (child, parent, property) => `\tC: "OP",${child},${parent}, "${property}"\n`;++const encode = (text) => new TextEncoder().encode(text);++/**+ * A right triangle at the origin, drawn with a red Phong material that samples+ * an image beside the FBX. The node carrying it is moved to (1,2,3), so a test+ * can tell geometry from placement; the uvs are the unit corners in FBX's own+ * convention, where (0,0) is the image's BOTTOM left.+ */+export function texturedTriangle() {+ const objects = [+ geometry(1000, 'tri', {+ vertices: [0, 0, 0, 2, 0, 0, 0, 2, 0],+ faces: [[0, 1, 2]],+ normals: [0, 0, 1, 0, 0, 1, 0, 0, 1],+ uvs: [0, 0, 1, 0, 0, 1],+ materials: [0],+ }),+ model(2000, 'Tri', 'Mesh', { translation: [1, 2, 3] }),+ material(3000, 'Red', { diffuse: [1, 0, 0], emissive: [0, 0.5, 0] }),+ texture(4000, 'Brick', 'textures/brick.png'),+ ].join('');+ const connections = [+ connect(2000, 0),+ connect(1000, 2000),+ connect(3000, 2000),+ connectProp(4000, 3000, 'DiffuseColor'),+ ].join('');+ return encode(`${header('estella fbxFixtures')}Objects: {\n${objects}}\nConnections: {\n${connections}}\n`);+}++/**+ * Two bones and a quad bound to them, the upper bone turning a quarter circle+ * about Z over one second. The bind pose is deliberately plain — mesh and lower+ * bone at the origin, upper bone one unit up — so the inverse bind matrix a test+ * reads back is a translation it can check by eye.+ */+export function skinnedBar() {+ const objects = [+ geometry(1000, 'bar', {+ vertices: [-1, 0, 0, 1, 0, 0, 1, 2, 0, -1, 2, 0],+ faces: [[0, 1, 2, 3]],+ normals: Array.from({ length: 4 }, () => [0, 0, 1]).flat(),+ uvs: [0, 0, 1, 0, 1, 1, 0, 1],+ }),+ model(2000, 'Bar', 'Mesh'),+ model(2100, 'Bone1', 'LimbNode'),+ model(2200, 'Bone2', 'LimbNode', { translation: [0, 1, 0] }),+ `\tDeformer: 5000, "Deformer::Skin", "Skin" {+\t\tVersion: 101+\t\tLink_DeformAcuracy: 50+\t}+`,+ // Transform is the mesh-node-to-bone matrix — the bind pose, already+ // inverted — and TransformLink is where the bone stood when it was bound.+ cluster(5100, 'Bone1', [0, 1], [1, 1], IDENTITY, IDENTITY),+ cluster(5200, 'Bone2', [2, 3], [1, 1], translation(0, -1, 0), translation(0, 1, 0)),+ // Both ends of the range: a reader takes the pair or neither.+ `\tAnimationStack: 6000, "AnimStack::Take 001", "" {+\t\tProperties70: {+\t\t\tP: "LocalStart", "KTime", "Time", "",0+\t\t\tP: "LocalStop", "KTime", "Time", "",${TICKS_PER_SECOND}+\t\t\tP: "ReferenceStart", "KTime", "Time", "",0+\t\t\tP: "ReferenceStop", "KTime", "Time", "",${TICKS_PER_SECOND}+\t\t}+\t}+`,+ `\tAnimationLayer: 6100, "AnimLayer::BaseLayer", "" {+\t}+`,+ `\tAnimationCurveNode: 6200, "AnimCurveNode::R", "" {+\t\tProperties70: {+\t\t\tP: "d", "Compound", "", ""+\t\t\tP: "d|X", "Number", "", "A",0+\t\t\tP: "d|Y", "Number", "", "A",0+\t\t\tP: "d|Z", "Number", "", "A",0+\t\t}+\t}+`,+ animCurve(6300, [0, 1], [0, 90]),+ ].join('');+ const connections = [+ connect(2000, 0),+ connect(2100, 0),+ connect(2200, 2100),+ connect(1000, 2000),+ connect(5000, 1000),+ connect(5100, 5000),+ connect(5200, 5000),+ connect(2100, 5100),+ connect(2200, 5200),+ connect(6100, 6000),+ connect(6200, 6100),+ connectProp(6200, 2200, 'Lcl Rotation'),+ connectProp(6300, 6200, 'd|Z'),+ ].join('');+ return encode(`${header('estella fbxFixtures')}Objects: {\n${objects}}\nConnections: {\n${connections}}\n`);+}++/** A 4x4 matrix as FBX writes one: sixteen numbers, translation in the last row. */+const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];+const translation = (x, y, z) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];++function cluster(id, bone, indexes, weights, transform, transformLink) {+ return `\tDeformer: ${id}, "SubDeformer::Cluster ${bone}", "Cluster" {+\t\tVersion: 100+\t\tUserData: "", ""+${array('Indexes', indexes, 2)}${array('Weights', weights, 2)}${array('Transform', transform, 2)}${array('TransformLink', transformLink, 2)}\t}+`;+}diff --git a/desktop/src/plugins/importers.ts b/desktop/src/plugins/importers.tsindex a3bda4cb7..b5479d87f 100644--- a/desktop/src/plugins/importers.ts+++ b/desktop/src/plugins/importers.ts@@ -66,7 +66,7 @@ export async function runImporters(paths: readonly string[]): Promise<void> {// like any other and are registered rather than special-cased — Reimport and the// source watcher reach them by the one rule.for (const [id, extensions] of [- ['core:model', ['gltf', 'glb']],+ ['core:model', ['gltf', 'glb', 'fbx']],['core:panorama', ['hdr']],] as const) {importerRegistry.register('core', {diff --git a/desktop/src/project/assetTypes.ts b/desktop/src/project/assetTypes.tsindex 565287126..d3dcd3730 100644--- a/desktop/src/project/assetTypes.ts+++ b/desktop/src/project/assetTypes.ts@@ -75,7 +75,7 @@ export const ASSET_TYPES: Record<BuiltinAssetType, AssetTypeDef> = {// The model a mesh was imported FROM. Its own type, because the engine loads// none of these — offering one where a mesh is asked for is offering a ref// that cannot resolve.- model: { extensions: ['gltf', 'glb'], badge: 'MDL', icon: Boxes, tint: '#8fa9b5' },+ model: { extensions: ['gltf', 'glb', 'fbx'], badge: 'MDL', icon: Boxes, tint: '#8fa9b5' },// A baked environment (.esenv) and, in the same relation as model/mesh, the// panorama it was baked from — which the engine also cannot load.environment: { extensions: ['esenv'], badge: 'ENV', icon: Globe, tint: '#8fb5b0' },diff --git a/desktop/tests/fbx-import.test.ts b/desktop/tests/fbx-import.test.tsnew file mode 100644index 000000000..7996d50dd--- /dev/null+++ b/desktop/tests/fbx-import.test.ts@@ -0,0 +1,230 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file FBX import: what the products say, from geometry to bind pose to clip.+ *+ * The claims here are the ones a format conversion gets wrong quietly — units,+ * the uv origin, which matrix is the bind pose, which entity a track drives —+ * so each is asserted against a fixture whose numbers are written out in+ * `scripts/lib/fbxFixtures.mjs` rather than hidden in a binary.+ */+import { describe, it, expect } from 'vitest';+import { importFbxMeshes } from '../../pipeline/src/assets/fbxImport';+import { assembleModelPrefab, materialProducts,+ type ImportedMesh, type ImportedNode } from '../../pipeline/src/assets/modelImport';+import { MeshChannel } from 'esengine';+import { texturedTriangle, skinnedBar } from '../scripts/lib/fbxFixtures.mjs';++/** One channel's floats for vertex `index`, read back out of the packed buffer. */+function attribute(mesh: ImportedMesh, semantic: number, index: number, comps: number): number[] {+ const channel = mesh.data.channels.find(c => c.semantic === semantic)!;+ const view = new DataView(mesh.data.vertices.buffer, mesh.data.vertices.byteOffset);+ const at = index * mesh.data.vertexStride + channel.offset;+ return Array.from({ length: comps }, (_, c) => view.getFloat32(at + c * 4, true));+}++/** Every node of the tree, flattened, so a test can find one by name. */+function flatten(nodes: ImportedNode[]): ImportedNode[] {+ return nodes.flatMap(node => [node, ...flatten(node.children)]);+}++describe('fbx geometry', () => {+ it('keeps the source units — a metre stays a world unit', async () => {+ const { meshes, warnings } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');+ expect(warnings).toEqual([]);+ expect(meshes).toHaveLength(1);+ const mesh = meshes[0]!;+ expect(mesh.vertexCount).toBe(3);+ expect(mesh.triangleCount).toBe(1);+ // The fixture's UnitScaleFactor is 100 (centimetres to a metre), so the+ // vertices arrive as authored rather than a hundredth of that.+ expect(mesh.data.aabbMin).toEqual([0, 0, 0]);+ expect(mesh.data.aabbMax).toEqual([2, 2, 0]);+ });++ it('reads uvs with the origin FBX puts them in', async () => {+ const { meshes } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');+ const mesh = meshes[0]!;+ // (0,0), (1,0), (0,1) as authored. A glTF would arrive flipped in v — its+ // origin is the image's top left — and flipping these too would put the+ // texture on upside down.+ const uvs = [0, 1, 2].map(i => attribute(mesh, MeshChannel.TexCoord0, i, 2));+ const corner = (u: number, v: number): number[] | undefined =>+ uvs.find(([a, b]) => Math.abs(a! - u) < 1e-6 && Math.abs(b! - v) < 1e-6);+ expect(corner(0, 0)).toBeDefined();+ expect(corner(1, 0)).toBeDefined();+ expect(corner(0, 1)).toBeDefined();+ });++ it('carries the normals the source declares', async () => {+ const { meshes } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');+ expect(attribute(meshes[0]!, MeshChannel.Normal, 0, 3)).toEqual([0, 0, 1]);+ });++ it('triangulates a quad', async () => {+ const { meshes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');+ expect(meshes[0]!.triangleCount).toBe(2);+ expect(meshes[0]!.vertexCount).toBe(4);+ });+});++describe('fbx hierarchy', () => {+ it('places geometry by its node, not by the geometry', async () => {+ const { nodes, meshes } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');+ expect(nodes).toHaveLength(1);+ const node = nodes[0]!;+ expect(node.name).toBe('Tri');+ expect(node.translation).toEqual([1, 2, 3]);+ expect(node.meshes).toEqual([0]);+ // The vertices themselves stay at the origin: moving them AND the node+ // would place the triangle twice.+ expect(meshes[0]!.data.aabbMin).toEqual([0, 0, 0]);+ });++ it('drops the scene root, which is ufbx\'s and not the artist\'s', async () => {+ const { nodes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');+ expect(nodes.map(n => n.name)).toEqual(['Bar', 'Bone1']);+ expect(flatten(nodes).map(n => n.name)).toContain('Bone2');+ });+});++describe('fbx materials', () => {+ it('reads a Phong material as the engine\'s own terms', async () => {+ const { meshes } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');+ const material = meshes[0]!.material!;+ expect(material.baseColor).toEqual([1, 0, 0, 1]);+ expect(material.emissive).toEqual([0, 0.5, 0]);+ // A Phong material has no metalness; reporting one would invent a surface.+ expect(material.metallic).toBe(0);+ // Its roughness IS derived, from the specular exponent the fixture sets.+ expect(material.roughness).toBeGreaterThan(0);+ expect(material.roughness).toBeLessThan(1);+ expect(material.opaque).toBe(true);+ });++ it('references an image beside the source instead of copying it', async () => {+ const { meshes, textures, externalFiles } = await importFbxMeshes(+ texturedTriangle(), 'tri', 'tri.fbx');+ const image = meshes[0]!.material!.baseColorTexture!;+ expect(image).toMatchObject({ file: 'textures/brick.png', external: true });+ // Windows-authored paths reach the project with the separators every other+ // reader here resolves.+ expect(image.file).not.toContain('\\');+ expect(textures).toEqual([]);+ expect(externalFiles).toEqual(['textures/brick.png']);+ });++ it('writes an .esmaterial for what a Mesh2D cannot say', async () => {+ const { meshes } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');+ const products = materialProducts(meshes, 'tri');+ expect(products).toHaveLength(1);+ expect(products[0]!.data.properties).toMatchObject({+ u_metallic: 0,+ u_emissive: { r: 0, g: 0.5, b: 0, a: 1 },+ });+ });+});++describe('fbx skinning', () => {+ it('binds the mesh to the bone entities the prefab will hold', async () => {+ const { meshes, nodes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');+ const mesh = meshes[0]!;+ const named = new Map(flatten(nodes).map(n => [n.name, n.index]));+ expect(mesh.skinJoints).toEqual([named.get('Bone1'), named.get('Bone2')]);++ const prefab = assembleModelPrefab('bar', meshes, { nodes });+ const skin = prefab.entities.flatMap(e => e.components)+ .find(c => c.type === 'MeshSkin')!;+ const joints = (skin.data as { joints: string[] }).joints;+ const ids = new Set(prefab.entities.map(e => e.prefabEntityId));+ // Every joint names an entity this same prefab defines; a joint pointing at+ // nothing is a mesh that collapses to the origin at runtime.+ for (const joint of joints) expect(ids.has(joint)).toBe(true);+ });++ it('carries the bind pose as the inverse of where the bone was', async () => {+ const { meshes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');+ const matrices = meshes[0]!.data.inverseBindMatrices!;+ expect(matrices).toHaveLength(32);+ // Bone1 is bound at the origin, Bone2 one unit up — so undoing the bind+ // pose is identity for the first and a step DOWN for the second.+ expect([...matrices.slice(12, 15)]).toEqual([0, 0, 0]);+ expect([...matrices.slice(28, 31)].map(v => Math.round(v))).toEqual([0, -1, 0]);+ });++ it('normalizes the weights it keeps', async () => {+ const { meshes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');+ const mesh = meshes[0]!;+ for (let i = 0; i < mesh.vertexCount; i++) {+ const sum = attribute(mesh, MeshChannel.Weights, i, 4).reduce((a, b) => a + b, 0);+ expect(sum).toBeCloseTo(1, 5);+ }+ });+});++describe('fbx animation', () => {+ it('bakes the euler curves into a clip the runtime can play', async () => {+ const { animations, nodes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');+ expect(animations).toHaveLength(1);+ const clip = animations[0]!;+ expect(clip.name).toBe('bar_Take_001');+ const doc = clip.document as {+ duration: number;+ tracks: { name: string; childPath: string; component: string;+ channels: { property: string; keyframes: { time: number; value: number }[] }[] }[];+ };+ expect(doc.duration).toBeCloseTo(1, 6);+ expect(doc.tracks).toHaveLength(1);+ const track = doc.tracks[0]!;+ expect(track.name).toBe('Bone2');+ expect(track.component).toBe('Transform');+ // The path the clip addresses has to be the one the prefab builds, or the+ // track resolves to nothing and the model stands still.+ const prefab = assembleModelPrefab('bar', [], { nodes });+ const byId = new Map(prefab.entities.map(e => [e.prefabEntityId, e]));+ let entity = byId.get(prefab.rootEntityId)!;+ for (const step of track.childPath.split('/')) {+ entity = entity.children.map(id => byId.get(id)!).find(e => e.name === step)!;+ expect(entity).toBeDefined();+ }+ expect(entity.name).toBe('Bone2');+ });++ it('turns a quarter circle about Z, as the source says', async () => {+ const { animations } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');+ const doc = animations[0]!.document as {+ tracks: { channels: { property: string; keyframes: { time: number; value: number }[] }[] }[];+ };+ const channels = new Map(doc.tracks[0]!.channels.map(c => [c.property, c.keyframes]));+ const last = (property: string): number => {+ const keys = channels.get(property)!;+ return keys[keys.length - 1]!.value;+ };+ // 90° about Z is (0, 0, sin45, cos45) — the components a Transform holds.+ expect(last('rotation.x')).toBeCloseTo(0, 5);+ expect(last('rotation.y')).toBeCloseTo(0, 5);+ expect(Math.abs(last('rotation.z'))).toBeCloseTo(Math.SQRT1_2, 4);+ expect(Math.abs(last('rotation.w'))).toBeCloseTo(Math.SQRT1_2, 4);+ // Every keyframe is a unit quaternion; a track that drifts off the unit+ // sphere scales the model as it turns.+ const keys = channels.get('rotation.x')!.length;+ for (let k = 0; k < keys; k++) {+ const q = ['x', 'y', 'z', 'w'].map(a => channels.get(`rotation.${a}`)![k]!.value);+ expect(Math.hypot(...q)).toBeCloseTo(1, 5);+ }+ });+});++describe('fbx reporting', () => {+ it('says what a file carries that this import has no place for', async () => {+ const { warnings } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');+ // The fixture is entirely importable; a warning here would mean the reader+ // is complaining about something it did in fact carry.+ expect(warnings).toEqual([]);+ });++ it('refuses a file that is not an FBX at all', async () => {+ await expect(importFbxMeshes(new TextEncoder().encode('not an fbx'), 'x', 'x.fbx'))+ .rejects.toThrow();+ });+});diff --git a/desktop/tests/gltf-import.test.ts b/desktop/tests/gltf-import.test.tsindex 9c57ea40f..ff965215c 100644--- a/desktop/tests/gltf-import.test.ts+++ b/desktop/tests/gltf-import.test.ts@@ -8,10 +8,11 @@* already on disk, a node given as a matrix, a file with no node tree at all.*/import { describe, it, expect } from 'vitest';+import { importGltfMeshes } from '../../pipeline/src/assets/gltfImport';import {- importGltfMeshes, assembleGltfPrefab, materialProducts,+ assembleModelPrefab, materialProducts,type ImportedMesh, type PrefabAssembly, type ProductRefs,-} from '../../pipeline/src/assets/gltfImport';+} from '../../pipeline/src/assets/modelImport';import { BlendMode, CullMode, MeshChannel } from 'esengine';import { plainTriangle, meshoptTriangle, dracoTriangle } from '../scripts/lib/gltfFixtures.mjs';@@ -362,7 +363,7 @@ describe('glTF material products', () => {shaded({ normalTexture: { index: 0 }, emissiveFactor: [1, 1, 1] }),{ prefix: 'assets/models/' });expect(products[0]!.data.properties.u_normalMap).toBe('model_0.png');- const prefab = assembleGltfPrefab('model', meshes, { refs: { prefix: 'assets/models/' } });+ const prefab = assembleModelPrefab('model', meshes, { refs: { prefix: 'assets/models/' } });const mesh2d = prefab.entities[1]!.components[1]!.data;expect(mesh2d.material).toBe('assets/models/model_m0.esmaterial');expect(mesh2d.normalMap).toBeUndefined();@@ -391,7 +392,7 @@ describe('glTF material products', () => {]), 'model');const refs = { prefix: 'assets/models/' };expect(materialProducts(meshes, 'model', refs)).toHaveLength(1);- const prefab = assembleGltfPrefab('model', meshes, { refs });+ const prefab = assembleModelPrefab('model', meshes, { refs });const refsUsed = prefab.entities.flatMap(e => e.components.filter(c => c.type === 'Mesh2D').map(c => c.data.material));expect(refsUsed).toEqual(['assets/models/model_m0.esmaterial',@@ -417,7 +418,7 @@ describe('glTF material products', () => {describe('glTF prefab assembly', () => {const assemble = async (bytes: Uint8Array, options: Partial<PrefabAssembly> = {}) => {const { meshes, nodes } = await importGltfMeshes(bytes, 'model');- return assembleGltfPrefab('model', meshes, { nodes, ...options });+ return assembleModelPrefab('model', meshes, { nodes, ...options });};const oneNode = { nodes: [{ mesh: 0 }], scenes: [{ nodes: [0] }], scene: 0 };@@ -777,7 +778,7 @@ describe('glTF skinning import', () => {it('names the joint entities the prefab gives those nodes', async () => {const { meshes, nodes } = await importGltfMeshes(skinnedGltf(), 'rig');- const prefab = assembleGltfPrefab('rig', meshes, { nodes });+ const prefab = assembleModelPrefab('rig', meshes, { nodes });const body = prefab.entities.find((e) => e.name === 'Body')!;const skin = body.components.find((c) => c.type === 'MeshSkin');expect(skin?.data).toEqual({ joints: ['n1', 'n2'] });diff --git a/desktop/vite.config.ts b/desktop/vite.config.tsindex 895715898..bdde629bb 100644--- a/desktop/vite.config.ts+++ b/desktop/vite.config.ts@@ -104,7 +104,8 @@ export default defineConfig({vite: {build: {rolldownOptions: {- external: ['esbuild', 'typescript', 'ffmpeg-static', 'draco3dgltf', 'electron-updater', /[\\/]build-tools[\\/]basis[\\/]/],+ external: ['esbuild', 'typescript', 'ffmpeg-static', 'draco3dgltf', 'electron-updater',+ /[\\/]build-tools[\\/](basis|ufbx)[\\/]/],},} as never,},diff --git a/docs/astro/src/content/docs/assets/models.mdx b/docs/astro/src/content/docs/assets/models.mdxindex c09bda49c..1703e2081 100644--- a/docs/astro/src/content/docs/assets/models.mdx+++ b/docs/astro/src/content/docs/assets/models.mdx@@ -1,13 +1,16 @@---title: Models-description: Importing glTF/GLB — what the import writes, how a model reaches a scene, the Scale setting, re-importing, which material channels become an .esmaterial, Draco and meshopt, and what is reported rather than imported.+description: Importing glTF/GLB and FBX — what the import writes, how a model reaches a scene, the Scale setting, re-importing, which material channels become an .esmaterial, Draco and meshopt, and what is reported rather than imported.---import { Aside } from '@astrojs/starlight/components';-The engine draws meshes, and it loads exactly one mesh format: `.esmesh`. A `.gltf` or-`.glb` is a **source**, not an asset — bringing one into a project runs an import that-writes the assets a scene can actually reference.+The engine draws meshes, and it loads exactly one mesh format: `.esmesh`. A `.gltf`,+`.glb` or `.fbx` is a **source**, not an asset — bringing one into a project runs an import+that writes the assets a scene can actually reference.++Both formats produce the same products and go through the same settings; where FBX differs+is its [own section](#fbx) below.That import is the subject of this page. For the component that draws the result see[the component reference](/docs/reference/components/graphics/); for materials in general see@@ -19,9 +22,9 @@ Three doors, one import:| How | What happens ||---|---|-| Drag a `.gltf`/`.glb` onto the Content Browser | The source is copied in (with the files it points at) and imported. |+| Drag a `.gltf`/`.glb`/`.fbx` onto the Content Browser | The source is copied in (with the files it points at) and imported. || Put one in the project folder | The editor notices and imports it — a `git checkout`, a copy in Finder, a re-export from Blender. |-| `estella import-gltf <file> [outDir] --project <dir>` | The same import, on the command line. `--scale <n>` sizes it. |+| `estella import-model <file> [outDir] --project <dir>` | The same import, on the command line. `--scale <n>` sizes it. |Products land **beside the source**, not in whatever folder the browser is showing:re-importing has to overwrite the same files.@@ -48,11 +51,12 @@ place an instance in a scene and edit that instead.## Scale-A glTF is authored in **metres**. A world unit is a **design pixel**. A 1.7 m character+Models are authored in **metres** — an FBX authored in centimetres is converted on the way+in. A world unit is a **design pixel**. A 1.7 m charactertherefore arrives 1.7 units tall — a couple of pixels — unless you say otherwise.The import does not guess a factor. It tells you when a model came in small, and the-number that fixes it is `Scale` in the source's Import Settings (select the `.gltf` in the+number that fixes it is `Scale` in the source's Import Settings (select the source in theContent Browser). Saving it re-imports the model.`Scale` lands on the prefab root's `Transform`, never baked into the geometry — the@@ -129,7 +133,38 @@ joints.| 64 joints per mesh | The pose is a uniform block, which is 4KB at that size — inside what a WebGL2 block is guaranteed. A mesh wanting more draws undeformed. || Joint count must match the bind pose | A mesh whose `MeshSkin` names a different number of joints draws undeformed rather than with vertices resolved against the wrong matrices. |-## Compressed geometry+## FBX++FBX is read by [ufbx](https://github.com/ufbx/ufbx), built into the editor — no Autodesk+FBX SDK, nothing to install. Binary and ASCII, and every version from the 5000-series up,+go through the same reader.++What the format needs that glTF does not, the import settles before anything downstream+sees it:++| FBX says | What arrives |+|---|---|+| Its own up axis and unit (centimetres, Z-up, …) | Converted to the engine's: +Y up, one unit is one metre. |+| Polygons of any size | Triangles. |+| Geometry offset from its node with no node to hold it | A child entity holding that offset, named `GeometryTransform`. |+| A mesh split across several materials | One `.esmesh` per material run — the same split glTF calls a primitive. |+| Rotations as Euler angles around pivots, with pre- and post-rotation | Baked into position/rotation/scale keyframes (resampled at 30 fps where the curves are not already linear). |++Materials are read through ufbx's own mapping, so Phong, Lambert, Maya's Standard Surface,+3ds Max's Physical and Blender's Principled all arrive as the same parameters listed under+[Materials](#materials) — a Phong material's roughness is derived from its specular+exponent, and it reports **no** metalness rather than a made-up zero-metal surface.++Two things about FBX materials are worth knowing before you author for it:++- **Metalness and roughness maps are only carried when they are one image**, packed the way+ glTF packs them (roughness in green, metal in blue) — which is what the engine's Model+ shader samples. Exporters normally write two separate images; when they do, the import+ says so and the constants are used. Pack them into one image, or set the map by hand on+ the `.esmaterial`.+- **An opacity map is not carried.** Alpha comes from the base colour image's own channel.++## Compressed geometry (glTF)`EXT_meshopt_compression` and `KHR_draco_mesh_compression` are decoded during import, so acompressed export produces the same `.esmesh` as an uncompressed one. Nothing about the@@ -142,10 +177,12 @@ when it runs.| Not imported | Why ||---|---|-| Morph targets, `weights` animation channels | Blending between shapes needs the targets themselves, which are not carried. |-| A second UV set (`TEXCOORD_1`), `KHR_texture_transform` | UVs are used as authored. |+| Morph targets / blend shapes, `weights` animation channels | Blending between shapes needs the targets themselves, which are not carried. |+| A second UV set (`TEXCOORD_1`), `KHR_texture_transform`, an FBX uv transform | UVs are used as authored. || Non-triangle primitives (`mode` ≠ 4) | The renderer draws triangle lists. || `normalTexture.scale` | The map is applied at full strength. |+| Cameras and lights in an FBX | A scene's camera and lighting are the scene's, not the model's. |+| Separate FBX metalness/roughness maps, an FBX opacity map | See [FBX](#fbx). |## Limits worth knowingdiff --git a/docs/astro/src/content/docs/zh-cn/assets/models.mdx b/docs/astro/src/content/docs/zh-cn/assets/models.mdxindex 46b51777f..2c9438996 100644--- a/docs/astro/src/content/docs/zh-cn/assets/models.mdx+++ b/docs/astro/src/content/docs/zh-cn/assets/models.mdx@@ -1,12 +1,14 @@---title: 模型-description: glTF/GLB 导入 —— 导入写出什么、模型怎么进场景、Scale 设置、重新导入、哪些材质通道会变成 .esmaterial、Draco 与 meshopt、以及哪些东西只报告不导入。+description: glTF/GLB 与 FBX 导入 —— 导入写出什么、模型怎么进场景、Scale 设置、重新导入、哪些材质通道会变成 .esmaterial、Draco 与 meshopt、以及哪些东西只报告不导入。---import { Aside } from '@astrojs/starlight/components';-引擎画 mesh,而它只加载一种 mesh 格式:`.esmesh`。`.gltf` / `.glb` 是**源文件**,不是资源-——把它带进项目会跑一次导入,写出场景真正能引用的那些资源。+引擎画 mesh,而它只加载一种 mesh 格式:`.esmesh`。`.gltf` / `.glb` / `.fbx` 是**源文件**,+不是资源——把它带进项目会跑一次导入,写出场景真正能引用的那些资源。++两种格式产出同样的产物、走同样的设置;FBX 独有的部分在下面[单独一节](#fbx)。本页讲的就是这次导入。画出结果的那个组件见[组件参考](/docs/zh-cn/reference/components/graphics/);材质整体见[材质](/docs/zh-cn/graphics/materials/)。@@ -17,9 +19,9 @@ import { Aside } from '@astrojs/starlight/components';| 方式 | 会发生什么 ||---|---|-| 把 `.gltf`/`.glb` 拖进内容浏览器 | 源文件(连同它引用的文件)被拷进项目并导入。 |+| 把 `.gltf`/`.glb`/`.fbx` 拖进内容浏览器 | 源文件(连同它引用的文件)被拷进项目并导入。 || 直接放进项目目录 | 编辑器会发现并导入它 —— `git checkout`、访达里拷贝、Blender 重新导出,都算。 |-| `estella import-gltf <file> [outDir] --project <dir>` | 命令行里的同一次导入。`--scale <n>` 决定大小。 |+| `estella import-model <file> [outDir] --project <dir>` | 命令行里的同一次导入。`--scale <n>` 决定大小。 |产物落在**源文件旁边**,而不是内容浏览器当前显示的目录:重新导入必须覆盖同一批文件。@@ -44,11 +46,12 @@ import { Aside } from '@astrojs/starlight/components';## Scale-glTF 以**米**为单位。一个世界单位是一个**设计像素**。所以一个 1.7 米高的角色进来只有+模型以**米**为单位——以厘米创作的 FBX 会在进来的路上换算好。一个世界单位是一个**设计像素**。+所以一个 1.7 米高的角色进来只有1.7 个单位高 —— 几个像素 —— 除非你另行指定。导入器不猜这个系数。模型进来很小的时候它会说出来,而修正它的那个数字就是源文件导入设置里的-`Scale`(在内容浏览器里选中 `.gltf`)。保存它会重新导入这个模型。+`Scale`(在内容浏览器里选中源文件)。保存它会重新导入这个模型。`Scale` 落在 prefab 根节点的 `Transform` 上,**不会烘进几何** —— `.esmesh` 保持与源一致,而那个数字始终看得见、改得动。@@ -121,7 +124,33 @@ mesh 就会变形。| 每个 mesh 最多 64 根骨骼 | 姿态走 uniform 块,64 根是 4KB —— 在 WebGL2 对一个块的保证范围内。超过的 mesh 按不变形绘制。 || 骨骼数必须与绑定姿态一致 | `MeshSkin` 列出的骨骼数对不上时按不变形绘制,而不是让顶点去解析错误的矩阵。 |-## 压缩几何+## FBX++FBX 由编译进编辑器的 [ufbx](https://github.com/ufbx/ufbx) 读取——不需要 Autodesk FBX+SDK,也没有任何东西要装。二进制与 ASCII、从 5000 系列往上的每个版本,都走同一个读取器。++FBX 需要而 glTF 不需要的那些事,导入在下游看到之前就已经了结:++| FBX 说 | 进来的是 |+|---|---|+| 它自己的 up 轴与单位(厘米、Z 朝上……) | 换算成引擎的:+Y 朝上,一个单位一米。 |+| 任意边数的多边形 | 三角形。 |+| 几何相对节点有偏移,却没有节点承载它 | 一个承载该偏移的子实体,名叫 `GeometryTransform`。 |+| 一个 mesh 分给多个材质 | 每段材质一个 `.esmesh`——正是 glTF 叫做 primitive 的那种切分。 |+| 旋转是绕 pivot 的欧拉角,还带 pre/post rotation | 烘焙成位置/旋转/缩放关键帧(曲线本来就不是线性的地方按 30 fps 重采样)。 |++材质走 ufbx 自己的映射,所以 Phong、Lambert、Maya 的 Standard Surface、3ds Max 的+Physical、Blender 的 Principled 最终都落到[材质](#材质)那一节列的同一组参数上——Phong+材质的粗糙度由它的高光指数换算而来,而它的金属度会被报告为**没有**,而不是编一个非金属表面出来。++为 FBX 创作之前,有两件关于它材质的事值得先知道:++- **金属度与粗糙度贴图只有在是同一张图时才带得过来**,且要按 glTF 的方式打包(粗糙度在绿+ 通道、金属度在蓝通道)——引擎的 Model shader 采样的就是这一张。导出器通常写成两张独立的+ 图;那种情况导入会说出来,并改用常量。要么把它们打包成一张,要么在 `.esmaterial` 上手工指定。+- **不透明度贴图不会带过来。** alpha 来自 base color 图自己的通道。++## 压缩几何(glTF)`EXT_meshopt_compression` 与 `KHR_draco_mesh_compression` 在导入时解码,所以压缩过的导出件产出与未压缩件相同的 `.esmesh`。运行时什么都不变:压缩是源文件的属性,不是产物的属性。@@ -132,10 +161,12 @@ mesh 就会变形。| 不导入 | 为什么 ||---|---|-| morph target、`weights` 动画通道 | 在多个形状之间混合需要那些 target 本身,而它们没有被带过来。 |-| 第二套 UV(`TEXCOORD_1`)、`KHR_texture_transform` | UV 按作者写的原样使用。 |+| morph target / blend shape、`weights` 动画通道 | 在多个形状之间混合需要那些 target 本身,而它们没有被带过来。 |+| 第二套 UV(`TEXCOORD_1`)、`KHR_texture_transform`、FBX 的 uv transform | UV 按作者写的原样使用。 || 非三角形 primitive(`mode` ≠ 4) | 渲染器画的是三角形列表。 || `normalTexture.scale` | 法线贴图按全强度应用。 |+| FBX 里的相机与灯光 | 场景的相机与灯光属于场景,不属于模型。 |+| FBX 分离的金属度/粗糙度贴图、FBX 的不透明度贴图 | 见 [FBX](#fbx)。 |## 值得知道的限制diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjsindex 80d3e778e..bf41365d9 100644--- a/pipeline/bin/estella.mjs+++ b/pipeline/bin/estella.mjs@@ -13,7 +13,7 @@ const PIPELINE = path.join(HERE, '..');const REPO = path.join(PIPELINE, '..');const USAGE = `usage: node pipeline/bin/estella.mjs export <projectDir> [options]- node pipeline/bin/estella.mjs import-gltf <file.gltf|file.glb> [outDir]+ node pipeline/bin/estella.mjs import-model <file.gltf|file.glb|file.fbx> [outDir][--project <dir>] [--scale <n>]node pipeline/bin/estella.mjs import-hdr <file.hdr> [outDir] [--face-size <n>]@@ -35,9 +35,9 @@ against the limits in force. The size report rides the result rather than beingsecond file — \`result.size\` carries the verdicts the build dialog draws, so CIand the editor cannot disagree about whether a build fits.-import-gltf writes one \`.esmesh\` per triangle primitive next to the source (or+import-model writes one \`.esmesh\` per triangle primitive next to the source (orinto outDir), the images the file carries inline, and one \`.esprefab\` placing-each piece where the source's node tree puts it, with its image and tint. A glTF+each piece where the source's node tree puts it, with its image and tint. A modelholds many primitives, so it is a source that PRODUCES assets rather than one theengine loads — the products are what a scene references. Asset refs areproject-relative, so the project is found above the source unless --project says@@ -58,7 +58,7 @@ function parseArgs(argv) {console.log(USAGE);process.exit(0);}- if (command === 'import-gltf' || command === 'import-hdr') {+ if (command === 'import-model' || command === 'import-gltf' || command === 'import-hdr') {if (!projectDir) {console.error(USAGE);process.exit(2);@@ -119,7 +119,8 @@ async function loadPipeline(entry, outName) {format: 'esm',platform: 'node',target: 'node20',- external: ['esbuild', 'electron', 'sharp', 'draco3dgltf', '../../../build-tools/basis/encoder.mjs'],+ external: ['esbuild', 'electron', 'sharp', 'draco3dgltf',+ '../../../build-tools/basis/encoder.mjs', '../../../build-tools/ufbx/reader.mjs'],logLevel: 'error',banner: {js: "import { createRequire as __esCreateRequire } from 'node:module';\n"@@ -170,9 +171,13 @@ function engineRuntimeDir(platform) {const opts = parseArgs(process.argv.slice(2));-if (opts.command === 'import-gltf') {+// `import-gltf` is the name this command shipped under; it reads any of the+// model sources now, and the old spelling keeps working.+if (opts.command === 'import-model' || opts.command === 'import-gltf') {+ const { mod: reader, cleanup: cleanupReader } = await loadPipeline(+ path.join(PIPELINE, 'src', 'assets', 'readModelSource.ts'), 'readModelSource.mjs');const { mod: importer, cleanup } = await loadPipeline(- path.join(PIPELINE, 'src', 'assets', 'gltfImport.ts'), 'gltfImport.mjs');+ path.join(PIPELINE, 'src', 'assets', 'modelImport.ts'), 'modelImport.mjs');// The products are project assets, so they get their `.meta` here rather than// waiting for a scan — which is also the only moment the source's own import// settings (a sampler's filter and wrap) are still in hand.@@ -182,7 +187,7 @@ if (opts.command === 'import-gltf') {try {const sourceDir = path.dirname(opts.source);const dir = opts.out ?? sourceDir;- const stem = path.basename(opts.source).replace(/\.(gltf|glb)$/i, '');+ const stem = reader.modelStem(opts.source);// A component's asset ref is project-relative, so the products can only be// named once the project root is known; without one they are bare names.const root = opts.project ?? findProjectRoot(sourceDir);@@ -192,11 +197,14 @@ if (opts.command === 'import-gltf') {external: (uri) => projectRef(path.resolve(sourceDir, uri)) }: {};- const { meshes, textures, nodes, animations, warnings } = await importer.importGltfMeshes(+ const { meshes, textures, nodes, animations, warnings } = await reader.readModelSource(new Uint8Array(readFileSync(opts.source)), stem,- (uri) => {- const abs = path.join(sourceDir, uri);- return existsSync(abs) ? new Uint8Array(readFileSync(abs)) : null;+ {+ filename: opts.source,+ externalBuffers: (uri) => {+ const abs = path.join(sourceDir, uri);+ return existsSync(abs) ? new Uint8Array(readFileSync(abs)) : null;+ },},);for (const w of warnings) console.warn(` ! ${w}`);@@ -245,7 +253,7 @@ if (opts.command === 'import-gltf') {}if (meshes.length > 0) {const outFile = path.join(dir, `${stem}.esprefab`);- const prefab = importer.assembleGltfPrefab(+ const prefab = importer.assembleModelPrefab(stem, meshes, { refs, nodes, scale: opts.scale, timeline: firstClip });writeFileSync(outFile, `${JSON.stringify(prefab, null, 2)}\n`);await adopt(outFile);@@ -256,12 +264,13 @@ if (opts.command === 'import-gltf') {const extent = Math.max(...meshes.flatMap((m) => m.data.aabbMax.map((v, i) => v - m.data.aabbMin[i])));if (opts.scale === 1 && extent < 8) {- console.warn(` ! the model is ${extent.toFixed(2)} units across — a glTF is in metres`- + ' and a world unit is a design pixel; pass --scale if it should be bigger');+ console.warn(` ! the model is ${extent.toFixed(2)} units across — models are authored`+ + ' in metres and a world unit is a design pixel; pass --scale if it should be bigger');}}imported = meshes.length;} finally {+ cleanupReader();cleanup();cleanupMeta();}diff --git a/pipeline/src/assets/fbxImport.ts b/pipeline/src/assets/fbxImport.tsnew file mode 100644index 000000000..15674cbfb--- /dev/null+++ b/pipeline/src/assets/fbxImport.ts@@ -0,0 +1,581 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Reads an FBX into what @ref modelImport writes, the same shape a glTF+ * arrives as.+ *+ * FBX is a closed binary format with thirty years of dialects behind it, so the+ * parsing is ufbx's (vendored, built to wasm by tools/ufbx-wasm/build.mjs) and+ * what happens here is only the translation: ufbx's scene, already converted to+ * the engine's axes and units, becomes meshes, materials, nodes and timelines.+ *+ * The wasm hands over one self-describing blob — a JSON header plus a payload of+ * arrays — rather than a heap this side would walk. @ref tools/ufbx-wasm/bridge.c+ * is the other half of that contract.+ */+import { MeshChannel, MeshChannelType, packChannels } from 'esengine';+import {+ alignQuaternionSigns, animationProductName, ANIMATED_PATHS, disambiguateNodes,+ nodeChildPaths, nodeNameFor, samplerKeyframes, timelineDocument,+ type AnimatedNode, type ImportedAnimation, type ImportedImageRef, type ImportedMaterial,+ type ImportedMesh, type ImportedNode, type ImportedTexture, type ModelImportResult,+} from './modelImport';++/** A `[byteOffset, byteLength]` pair addressing the blob's payload. */+type Slice = [number, number];++interface FbxTextureRef {+ /** Index into @ref FbxScene.textures. */+ file: number;+ wrapU: number;+ wrapV: number;+ uvTransform: boolean;+}++interface FbxMaterialMap {+ value: number | number[];+ hasValue: boolean;+ texture: FbxTextureRef | null;+}++interface FbxMaterial {+ name: string;+ shader: number;+ pbr: boolean;+ twoSided: boolean;+ baseColor: FbxMaterialMap | null;+ baseFactor: FbxMaterialMap | null;+ roughness: FbxMaterialMap | null;+ glossiness: FbxMaterialMap | null;+ metalness: FbxMaterialMap | null;+ emissionColor: FbxMaterialMap | null;+ emissionFactor: FbxMaterialMap | null;+ opacity: FbxMaterialMap | null;+ normalMap: FbxMaterialMap | null;+ occlusion: FbxMaterialMap | null;+}++interface FbxNode {+ name: string;+ /** Index into @ref FbxScene.nodes, or -1 for the scene root. */+ parent: number;+ translation: [number, number, number];+ rotation: [number, number, number, number];+ scale: [number, number, number];+ /** ufbx mesh id this node draws, or -1. */+ mesh: number;+ /** ufbx invented this node to hold a geometry transform or an inherit mode. */+ helper: boolean;+}++interface FbxMeshPart {+ name: string;+ /** ufbx mesh id — several parts of one mesh share it. */+ mesh: number;+ /** Which material run of that mesh this is. */+ part: number;+ /** Index into @ref FbxScene.materials, or -1. */+ material: number;+ vertexCount: number;+ positions: Slice;+ normals: Slice | null;+ uvs: Slice | null;+ colors: Slice | null;+ joints: Slice | null;+ weights: Slice | null;+ indices: Slice;+ /** Source node index per bone, in the order the `Joints` channel indexes them. */+ skinJoints?: number[];+ inverseBindMatrices?: Slice;+}++interface FbxTextureFile {+ /** Path relative to the FBX, separators already normalized. */+ filename: string;+ relativeFilename: string;+ /** Bytes the FBX carries for it, when it embeds them. */+ content: Slice | null;+}++interface FbxAnimationNode {+ node: number;+ translation: { times: Slice; values: Slice } | null;+ rotation: { times: Slice; values: Slice } | null;+ scale: { times: Slice; values: Slice } | null;+}++interface FbxAnimation {+ name: string;+ duration: number;+ nodes: FbxAnimationNode[];+}++interface FbxScene {+ fileFormat: number;+ creator: string;+ nodes: FbxNode[];+ meshes: FbxMeshPart[];+ materials: FbxMaterial[];+ textures: FbxTextureFile[];+ animations: FbxAnimation[];+ warnings: string[];+}++const BLOB_MAGIC = 0x42465345;+const BLOB_VERSION = 1;++/**+ * Runs the FBX through ufbx and splits the blob into its two halves. The wasm+ * wrapper stays OUT of every bundle (see the externals in desktop/vite.config.ts+ * and pipeline/bin/estella.mjs): it finds its `.wasm` beside itself on disk,+ * which bundling breaks.+ */+async function readScene(bytes: Uint8Array, filename: string):+ Promise<{ scene: FbxScene; payload: Uint8Array }> {+ const { readFbxScene } = await import('../../../build-tools/ufbx/reader.mjs');+ const blob = await readFbxScene(bytes, filename);++ const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength);+ if (blob.byteLength < 16 || view.getUint32(0, true) !== BLOB_MAGIC) {+ throw new Error('the FBX reader returned something that is not a scene blob');+ }+ if (view.getUint32(4, true) !== BLOB_VERSION) {+ throw new Error(`the FBX reader speaks blob version ${view.getUint32(4, true)},`+ + ` this importer speaks ${BLOB_VERSION} — rebuild build-tools/ufbx`);+ }+ const jsonLength = view.getUint32(8, true);+ const scene = JSON.parse(+ new TextDecoder().decode(blob.subarray(16, 16 + jsonLength))) as FbxScene;+ const payloadAt = 16 + jsonLength + ((4 - (jsonLength % 4)) % 4);+ return { scene, payload: blob.subarray(payloadAt) };+}++/** Payload readers. A slice is always 4-byte aligned, so these never copy. */+function floats(payload: Uint8Array, slice: Slice): Float32Array {+ return new Float32Array(payload.buffer, payload.byteOffset + slice[0], slice[1] / 4);+}++function uints(payload: Uint8Array, slice: Slice): Uint32Array {+ return new Uint32Array(payload.buffer, payload.byteOffset + slice[0], slice[1] / 4);+}++function ushorts(payload: Uint8Array, slice: Slice): Uint16Array {+ return new Uint16Array(payload.buffer, payload.byteOffset + slice[0], slice[1] / 2);+}++/* -- Textures ----------------------------------------------------------- */++/**+ * What an embedded image is, read from its own first bytes. An FBX says nothing+ * about the type of the blob it carries, and the extension a product is written+ * with is what decides whether anything can load it.+ */+function imageExtension(bytes: Uint8Array): string | null {+ if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50) return '.png';+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8) return '.jpg';+ if (bytes.length >= 12 && bytes[8] === 0x57 && bytes[9] === 0x45+ && bytes[10] === 0x42 && bytes[11] === 0x50) return '.webp';+ return null;+}++interface TextureContext {+ scene: FbxScene;+ payload: Uint8Array;+ stem: string;+ textures: ImportedTexture[];+ externalFiles: string[];+ warnings: string[];+ cache: Map<number, ImportedImageRef | null>;+}++const WRAP_REPEAT = 0;++/**+ * Resolves one texture reference to the file a draw will sample, extracting the+ * image when the FBX embeds it. An image already on disk is REFERENCED, never+ * copied: a second copy is a second thing to keep in sync with the file the+ * artist edits.+ */+function readTexture(ctx: TextureContext, ref: FbxTextureRef, label: string): ImportedImageRef | null {+ if (ref.uvTransform) {+ ctx.warnings.push(`${label}: a uv transform on its texture is not imported`+ + ' (uvs are sampled as authored)');+ }+ const cached = ctx.cache.get(ref.file);+ if (cached !== undefined) return withWrap(cached, ref, ctx, label);++ const resolved = resolveTexture(ctx, ref, label);+ ctx.cache.set(ref.file, resolved);+ return withWrap(resolved, ref, ctx, label);+}++/**+ * The wrapping the texture asked for, as an import setting. It rides the+ * REFERENCE rather than the file because two materials can sample one image+ * differently, and only one of them can win when the `.meta` is minted.+ */+function withWrap(image: ImportedImageRef | null, ref: FbxTextureRef,+ ctx: TextureContext, label: string): ImportedImageRef | null {+ if (!image) return null;+ if (ref.wrapU !== ref.wrapV) {+ ctx.warnings.push(`${label}: its texture wraps u and v differently; using u`);+ }+ return { ...image, settings: { wrapMode: ref.wrapU === WRAP_REPEAT ? 'repeat' : 'clamp' } };+}++function resolveTexture(ctx: TextureContext, ref: FbxTextureRef,+ label: string): ImportedImageRef | null {+ const file = ctx.scene.textures[ref.file];+ if (!file) {+ ctx.warnings.push(`${label}: texture ${ref.file} is missing — skipped`);+ return null;+ }+ if (file.content) {+ const bytes = ctx.payload.subarray(file.content[0], file.content[0] + file.content[1]);+ const ext = imageExtension(bytes) ?? extensionOf(file.filename);+ if (!ext) {+ ctx.warnings.push(`${label}: the embedded image "${file.filename}" is not a PNG,`+ + ' JPEG or WebP — skipped');+ return null;+ }+ const name = `${ctx.stem}_${ref.file}${ext}`;+ if (!ctx.textures.some(t => t.name === name)) {+ ctx.textures.push({ name, bytes: bytes.slice() });+ }+ return { file: name, external: false };+ }+ const path = file.filename || file.relativeFilename;+ if (!path) {+ ctx.warnings.push(`${label}: its texture names no file — skipped`);+ return null;+ }+ if (!ctx.externalFiles.includes(path)) ctx.externalFiles.push(path);+ return { file: path, external: true };+}++/** The extension an image path carries, when the engine can load it. */+function extensionOf(path: string): string | null {+ const match = /\.(png|jpg|jpeg|webp|ktx2)$/i.exec(path);+ if (!match) return null;+ const ext = match[0].toLowerCase();+ return ext === '.jpeg' ? '.jpg' : ext;+}++/* -- Materials ---------------------------------------------------------- */++/** A map's scalar value, or `fallback` where the file said nothing. */+function scalar(map: FbxMaterialMap | null, fallback: number): number {+ if (!map?.hasValue) return fallback;+ return typeof map.value === 'number' ? map.value : (map.value[0] ?? fallback);+}++function rgb(map: FbxMaterialMap | null, fallback: number): [number, number, number] {+ if (!map?.hasValue) return [fallback, fallback, fallback];+ const value = map.value;+ if (typeof value === 'number') return [value, value, value];+ return [value[0] ?? fallback, value[1] ?? fallback, value[2] ?? fallback];+}++/**+ * One FBX material as the two things that can carry it. ufbx has already mapped+ * whatever shading model the file used — Phong, Maya's Standard Surface, 3ds+ * Max's Physical, Blender's Principled — onto one set of PBR maps, so what is+ * left here is the engine's own reading of those.+ */+function readMaterial(ctx: TextureContext, source: FbxMaterial, index: number): ImportedMaterial {+ const label = source.name ? `material "${source.name}"` : `material ${index}`;+ const texture = (map: FbxMaterialMap | null): ImportedImageRef | null =>+ map?.texture ? readTexture(ctx, map.texture, label) : null;++ const base = rgb(source.baseColor, 1);+ const baseFactor = scalar(source.baseFactor, 1);+ // Opacity is a scalar in FBX and the alpha of a tint here. A map for it is+ // not the same thing — the engine reads alpha from the base color image —+ // so it is reported rather than bound to a sampler that would ignore it.+ const opacity = scalar(source.opacity, 1);+ if (source.opacity?.texture) {+ ctx.warnings.push(`${label}: its opacity map is not imported`+ + " (the engine reads alpha from the base color image's own channel)");+ }++ // A Phong or Lambert material has no metalness at all; reporting ufbx's+ // zero as a value the file gave would be inventing a surface. Its roughness+ // IS derived — from specular exponent — and that conversion is ufbx's.+ const metallic = source.pbr ? scalar(source.metalness, 0) : 0;+ const roughness = source.glossiness?.hasValue && !source.roughness?.hasValue+ ? 1 - scalar(source.glossiness, 0)+ : scalar(source.roughness, 1);++ const metalMap = source.metalness?.texture ?? null;+ const roughMap = source.roughness?.texture ?? null;+ // The engine samples ONE map packed glTF's way (roughness in green, metal in+ // blue), and FBX exporters normally write two separate images. There is no+ // single image to bind when they do, so the import says so.+ const packed = metalMap && roughMap && metalMap.file === roughMap.file+ ? readTexture(ctx, metalMap, label) : null;+ if (!packed && (metalMap || roughMap)) {+ ctx.warnings.push(`${label}: its separate metalness/roughness maps are not imported —`+ + ' the engine samples one image packed as glTF does (roughness in green, metal in'+ + ` blue); the constants ${metallic.toFixed(2)}/${roughness.toFixed(2)} are used instead`);+ }++ const emissionFactor = scalar(source.emissionFactor, 1);+ const emissionColor = rgb(source.emissionColor, 0);+ const emissive = emissionColor.map(v => v * emissionFactor) as [number, number, number];+ const emits = emissive.some(v => v > 0);++ const baseTexture = texture(source.baseColor);+ const normalTexture = texture(source.normalMap);+ const occlusionTexture = texture(source.occlusion);+ // An emissive map multiplied by black emits nothing, and binding it would be+ // a sampler read per pixel for a result that is always zero.+ const emissiveTexture = emits ? texture(source.emissionColor) : null;++ return {+ index,+ name: source.name || `material_${index}`,+ baseColor: [base[0] * baseFactor, base[1] * baseFactor, base[2] * baseFactor, opacity],+ // FBX has no alpha mode: a material is transparent when it says it is+ // less than fully opaque, and opaque otherwise.+ opaque: opacity >= 1,+ cullBackfaces: !source.twoSided,+ ...(baseTexture ? { baseColorTexture: baseTexture } : {}),+ ...(normalTexture ? { normalTexture } : {}),+ ...(emits ? { emissive } : {}),+ ...(emissiveTexture ? { emissiveTexture } : {}),+ ...(occlusionTexture ? { occlusionTexture, occlusionStrength: 1 } : {}),+ metallic,+ roughness,+ ...(packed ? { metallicRoughnessTexture: packed } : {}),+ };+}++/* -- Nodes -------------------------------------------------------------- */++const IDENTITY_TRS = (node: FbxNode): boolean =>+ node.translation.every(v => v === 0) && node.scale.every(v => v === 1)+ && node.rotation[0] === 0 && node.rotation[1] === 0 && node.rotation[2] === 0+ && Math.abs(node.rotation[3]) === 1;++/**+ * The scene's hierarchy as the prefab will hold it. ufbx's root node is the scene+ * itself rather than anything the artist made, so its children are the roots —+ * unless it carries a transform, since dropping one would move the whole model.+ */+function buildNodes(scene: FbxScene, meshIndexOf: Map<string, number[]>): ImportedNode[] {+ const childrenOf = new Map<number, number[]>();+ scene.nodes.forEach((node, index) => {+ if (node.parent < 0) return;+ const siblings = childrenOf.get(node.parent) ?? [];+ siblings.push(index);+ childrenOf.set(node.parent, siblings);+ });++ const build = (index: number): ImportedNode => {+ const node = scene.nodes[index]!;+ return {+ index,+ name: node.name || (node.helper ? 'Helper' : `node_${index}`),+ translation: node.translation,+ rotation: node.rotation,+ scale: node.scale,+ meshes: node.mesh >= 0 ? meshIndexOf.get(`${node.mesh}`) ?? [] : [],+ children: (childrenOf.get(index) ?? []).map(build),+ };+ };++ const root = scene.nodes[0];+ const roots = !root || (IDENTITY_TRS(root) && root.mesh < 0)+ ? (childrenOf.get(0) ?? []).map(build)+ : [build(0)];+ disambiguateNodes(roots);+ return roots;+}++/* -- Geometry ----------------------------------------------------------- */++/** One material run of one FBX mesh as the `.esmesh` payload it becomes. */+function buildMesh(part: FbxMeshPart, name: string, payload: Uint8Array,+ material: ImportedMaterial | undefined): ImportedMesh {+ const positions = floats(payload, part.positions);+ const normals = part.normals ? floats(payload, part.normals) : null;+ const uvs = part.uvs ? floats(payload, part.uvs) : null;+ const colors = part.colors ? floats(payload, part.colors) : null;+ const joints = part.joints ? ushorts(payload, part.joints) : null;+ const weights = part.weights ? floats(payload, part.weights) : null;+ const indices = uints(payload, part.indices);+ const vertexCount = part.vertexCount;+ const skinned = !!(joints && weights && part.skinJoints?.length);++ const { channels, vertexStride } = packChannels([+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },+ ...(normals ? [{ semantic: MeshChannel.Normal, components: 3,+ type: MeshChannelType.Float32 }] : []),+ ...(skinned ? [+ { semantic: MeshChannel.Joints, components: 4, type: MeshChannelType.UInt16 },+ { semantic: MeshChannel.Weights, components: 4, type: MeshChannelType.Float32 },+ ] : []),+ ]);+ const jointsChannel = skinned ? channels[channels.length - 2]! : null;+ const weightsChannel = skinned ? channels[channels.length - 1]! : null;++ const vertices = new Uint8Array(vertexCount * vertexStride);+ const dv = new DataView(vertices.buffer);+ const min: [number, number, number] = [Infinity, Infinity, Infinity];+ const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];+ for (let i = 0; i < vertexCount; i++) {+ const at = i * vertexStride;+ for (let c = 0; c < 3; c++) {+ const v = positions[i * 3 + c] ?? 0;+ dv.setFloat32(at + channels[0]!.offset + c * 4, v, true);+ if (v < min[c]!) min[c] = v;+ if (v > max[c]!) max[c] = v;+ }+ // No v flip here, unlike glTF: FBX puts uv (0,0) at the image's BOTTOM+ // left, which is where the engine's textures start too.+ dv.setFloat32(at + channels[1]!.offset, uvs ? uvs[i * 2] ?? 0 : 0, true);+ dv.setFloat32(at + channels[1]!.offset + 4, uvs ? uvs[i * 2 + 1] ?? 0 : 0, true);+ for (let c = 0; c < 4; c++) {+ const v = colors ? colors[i * 4 + c] ?? 1 : 1;+ dv.setUint8(at + channels[2]!.offset + c,+ Math.max(0, Math.min(255, Math.round(v * 255))));+ }+ if (normals && channels[3]) {+ for (let c = 0; c < 3; c++) {+ dv.setFloat32(at + channels[3].offset + c * 4, normals[i * 3 + c] ?? 0, true);+ }+ }+ if (jointsChannel && weightsChannel) {+ for (let c = 0; c < 4; c++) {+ dv.setUint16(at + jointsChannel.offset + c * 2, joints![i * 4 + c] ?? 0, true);+ dv.setFloat32(at + weightsChannel.offset + c * 4, weights![i * 4 + c] ?? 0, true);+ }+ }+ }++ return {+ name,+ data: {+ channels, vertexStride, vertexCount,+ vertices, indices, aabbMin: min, aabbMax: max,+ ...(skinned && part.inverseBindMatrices+ ? { inverseBindMatrices: floats(payload, part.inverseBindMatrices).slice() }+ : {}),+ },+ vertexCount,+ triangleCount: indices.length / 3,+ ...(material ? { material } : {}),+ ...(skinned ? { skinJoints: part.skinJoints } : {}),+ };+}++/* -- Animation ---------------------------------------------------------- */++/**+ * The file's animation stacks as `.estimeline` documents. ufbx has already baked+ * them into TRS keyframes: FBX rotates in Euler angles around pivots the engine's+ * Transform has no field for, and reading those curves as authored would place a+ * limb where the source never put it.+ */+function buildAnimations(scene: FbxScene, payload: Uint8Array, nodes: ImportedNode[],+ stem: string, warnings: string[]): ImportedAnimation[] {+ if (scene.animations.length === 0) return [];+ const paths = nodeChildPaths(nodes);++ const out: ImportedAnimation[] = [];+ for (const [index, animation] of scene.animations.entries()) {+ const name = animation.name || `animation_${index}`;+ const byNode = new Map<string, AnimatedNode>();++ for (const target of animation.nodes) {+ const path = paths.get(target.node);+ if (path === undefined) continue;+ const entry = byNode.get(path)+ ?? { node: nodeNameFor(nodes, target.node), channels: new Map() };+ for (const property of ['translation', 'rotation', 'scale'] as const) {+ const channel = target[property];+ const spec = ANIMATED_PATHS[property]!;+ if (!channel) continue;+ const times = floats(payload, channel.times);+ const values = floats(payload, channel.values);+ if (times.length === 0) continue;+ const frames = samplerKeyframes(times, values, spec.channels.length, 'linear');+ if (property === 'rotation') alignQuaternionSigns(frames);+ spec.channels.forEach((key, c) => entry.channels.set(key, frames[c]!));+ }+ if (entry.channels.size > 0) byNode.set(path, entry);+ }++ if (byNode.size === 0) {+ warnings.push(`${name}: no channel targets a node this import produced`);+ continue;+ }+ out.push({+ name: animationProductName(stem, name),+ document: timelineDocument(animation.duration, byNode),+ });+ }+ return out;+}++/* -- Import ------------------------------------------------------------- */++/**+ * An FBX's triangle geometry, materials, hierarchy and animation as the products+ * a project can reference.+ *+ * @param bytes The `.fbx` file, binary or ASCII, any version ufbx reads.+ * @param stem Base name for the products.+ * @param filename What the source is called, so a texture path stored relative+ * to it resolves the way the file meant it to.+ */+export async function importFbxMeshes(bytes: Uint8Array, stem: string,+ filename = ''): Promise<ModelImportResult> {+ const { scene, payload } = await readScene(bytes, filename);+ const warnings = [...scene.warnings];+ const textures: ImportedTexture[] = [];+ const externalFiles: string[] = [];+ const ctx: TextureContext = {+ scene, payload, stem, textures, externalFiles, warnings, cache: new Map(),+ };++ const materialCache = new Map<number, ImportedMaterial>();+ const materialFor = (index: number): ImportedMaterial | undefined => {+ const source = scene.materials[index];+ if (!source) return undefined;+ let material = materialCache.get(index);+ if (!material) {+ material = readMaterial(ctx, source, index);+ materialCache.set(index, material);+ }+ return material;+ };++ // A node draws every part of its mesh, so the map holds a list — the same+ // relationship a glTF node has with its primitives.+ const meshIndexOf = new Map<string, number[]>();+ const single = scene.meshes.length === 1;+ const meshes: ImportedMesh[] = scene.meshes.map((part, index) => {+ const key = `${part.mesh}`;+ const products = meshIndexOf.get(key) ?? [];+ products.push(index);+ meshIndexOf.set(key, products);+ // An FBX mesh is often unnamed — the name is on the node that draws it —+ // so the product falls back to the source's own stem the way a glTF's+ // single primitive does.+ const name = single ? stem : `${stem}_${part.mesh}_${part.part}`;+ return buildMesh(part, name, payload, materialFor(part.material));+ });++ if (meshes.length === 0 && warnings.length === 0) {+ warnings.push('no triangle geometry found');+ }+ const nodes = buildNodes(scene, meshIndexOf);+ return {+ meshes, textures, externalFiles, nodes,+ animations: buildAnimations(scene, payload, nodes, stem, warnings),+ warnings,+ };+}diff --git a/pipeline/src/assets/gltfImport.ts b/pipeline/src/assets/gltfImport.tsindex e3c263ef1..32b83f8a0 100644--- a/pipeline/src/assets/gltfImport.ts+++ b/pipeline/src/assets/gltfImport.ts@@ -1,7 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file glTF geometry and baseColor → `.esmesh`, images, and one `.esprefab`.+ * @file Reads a glTF into what @ref modelImport writes: geometry, materials,+ * the node hierarchy and the animations.** An import, not a cook. A glTF holds MANY primitives, so it is a source* that produces several engine assets rather than one file becoming@@ -10,129 +11,15 @@* the cook then ships them as the engine format they already are.*//// <reference path="./draco3dgltf.d.ts" />-import {- MeshChannel, MeshChannelType, packChannels, encodeMesh, PREFAB_FORMAT_VERSION,- TIMELINE_FORMAT_VERSION,- MATERIAL_FORMAT_VERSION, BlendMode, CullMode,- type MeshData, type MaterialAssetData, type PrefabData, type PrefabEntityData,- type PrefabComponentData as ComponentData,-} from 'esengine';+import { MeshChannel, MeshChannelType, packChannels } from 'esengine';import { MeshoptDecoder } from 'meshoptimizer/decoder';--/** One primitive's worth of geometry, named for the file it will be written to. */-export interface ImportedMesh {- /** `<file stem>` for a single primitive, `<stem>_<mesh>_<primitive>` otherwise. */- name: string;- data: MeshData;- vertexCount: number;- triangleCount: number;- /** The primitive's baseColor, absent when it names no material. */- material?: ImportedMaterial;- /** Source node indices of the joints its `Joints` channel indexes, in order.- * Absent for geometry nothing skins. */- skinJoints?: number[];-}--/** Where a material's image comes from: a product this import writes, or a file already on disk. */-export interface ImportedImageRef {- /** Product name (no directory) when written, else the glTF's own uri. */- file: string;- /** True for a uri the glTF points at — an existing file is referenced, never copied. */- external: boolean;- /** Import settings the source's sampler asks for, in the engine's own words.- * Absent where the glTF names no sampler (its defaults are the engine's). */- settings?: { filterMode?: 'nearest' | 'linear'; wrapMode?: 'repeat' | 'clamp' | 'mirror' };-}--/**- * A glTF material, split by what can carry it: baseColor is `texture(uv) *- * vertexColor * tint`, which a Mesh2D's own fields say, and the shading around- * it becomes an `.esmaterial` (@ref materialProducts). What neither can express- * is reported, not dropped.- */-export interface ImportedMaterial {- /** The source's own material index — what its product is named after. */- index: number;- name: string;- /** baseColorFactor — the tint multiplied into the vertex colors. */- baseColor: [number, number, number, number];- baseColorTexture?: ImportedImageRef;- /** Tangent-space normal map; the engine derives its tangent frame per pixel. */- normalTexture?: ImportedImageRef;- /** emissiveFactor — light the surface makes, unaffected by the scene's lights. */- emissive?: [number, number, number];- emissiveTexture?: ImportedImageRef;- /** Ambient occlusion in the map's red channel, scaled by @ref occlusionStrength. */- occlusionTexture?: ImportedImageRef;- occlusionStrength?: number;- /** metallicFactor / roughnessFactor — glTF's defaults are 1 for both. */- metallic?: number;- roughness?: number;- /** glTF's packing: roughness in green, metal in blue, multiplying the factors. */- metallicRoughnessTexture?: ImportedImageRef;- /** alphaMode MASK: a fragment below this alpha is discarded (glTF default 0.5). */- alphaCutoff?: number;- /** Not BLEND: drawn without blending, and taking part in depth. */- opaque: boolean;- /** `doubleSided: false` (the glTF default): back faces are not drawn. */- cullBackfaces: boolean;-}--/** A material product: the shading a Mesh2D's own fields cannot say. */-export interface ImportedMaterialAsset {- /** `<stem>_m<material index>` — stable across re-imports, so overrides keep matching. */- name: string;- /** The `.esmaterial` document. */- data: MaterialAssetData;- /** Every image it references, so the caller can carry the sampler settings over. */- images: ImportedImageRef[];-}--/** An image the glTF carries inline (GLB chunk or data uri), to be written beside the meshes. */-export interface ImportedTexture {- /** `<stem>_<image index>.<ext>` — named for the source, since an inline image has no name. */- name: string;- bytes: Uint8Array;-}--/**- * A node of the source's own hierarchy: where its geometry sits, and what hangs- * off it. Without this every primitive of a model lands on the origin.- */-export interface ImportedNode {- /** The node's own index in the source, so a re-import addresses the same entity. */- index: number;- name: string;- translation: [number, number, number];- /** Quaternion, glTF's (x, y, z, w) order — the same components a Transform holds. */- rotation: [number, number, number, number];- scale: [number, number, number];- /** Indices into @ref GltfImportResult.meshes; one node can draw several primitives. */- meshes: number[];- children: ImportedNode[];-}--/** One glTF animation as the `.estimeline` document it will be written to. */-export interface ImportedAnimation {- /** `<stem>_<animation name>` — named for the file it will be written to. */- name: string;- document: Record<string, unknown>;-}--export interface GltfImportResult {- meshes: ImportedMesh[];- /** Images extracted from the file itself; external ones stay where they are. */- textures: ImportedTexture[];- /** Every uri the source points OUT to (buffers and images), in file order.- * Bringing a model into a project means bringing these with it. */- externalFiles: string[];- /** The scene's node roots. Empty for a file with no nodes, whose meshes then sit flat. */- nodes: ImportedNode[];- /** The file's animations, each addressing nodes by their path under the prefab. */- animations: ImportedAnimation[];- /** What was skipped and why — a silent drop is how half a model goes missing. */- warnings: string[];-}+import {+ ANIMATED_PATHS, alignQuaternionSigns, animationProductName, disambiguateNodes,+ nodeChildPaths, nodeNameFor, samplerKeyframes, timelineDocument,+ type AnimatedNode, type ImportedAnimation, type ImportedImageRef, type ImportedMaterial,+ type ImportedMesh, type ImportedNode, type ImportedTexture, type ModelImportResult,+ type OutKeyframe, type Trs,+} from './modelImport';const GLB_MAGIC = 0x46546c67;const CHUNK_JSON = 0x4e4f534a;@@ -656,8 +543,6 @@ function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedIm};}-type Trs = Pick<ImportedNode, 'translation' | 'rotation' | 'scale'>;-/*** A node's local transform. A glTF gives either TRS or a column-major matrix,* and the engine's Transform holds TRS — so a matrix is decomposed here rather@@ -741,46 +626,10 @@ function readNodes(json: GltfJson, meshIndexOf: Map<string, number>,};const built = roots.map(build).filter((n): n is ImportedNode => n !== null);- disambiguate(built);+ disambiguateNodes(built);return built;}-/**- * Make sibling names unique. An animation channel addresses its node by the path- * of names from the root, so two siblings called "Arm" would leave a track- * driving whichever the walk reached first — the wrong half of the model. glTF- * allows the duplicate, so the import settles it and the products agree.- */-function disambiguate(nodes: ImportedNode[]): void {- const used = new Set<string>();- for (const node of nodes) {- if (used.has(node.name)) node.name = `${node.name}_${node.index}`;- used.add(node.name);- disambiguate(node.children);- }-}--/**- * Each node's path of names from the prefab root, matching what- * {@link assembleGltfPrefab} builds: a lone root node IS the prefab root (empty- * path), while several roots hang under a holder and so carry their own name.- */-export function nodeChildPaths(nodes: ImportedNode[]): Map<number, string> {- const paths = new Map<number, string>();- const walk = (node: ImportedNode, prefix: string): void => {- const path = prefix ? `${prefix}/${node.name}` : node.name;- paths.set(node.index, path);- for (const child of node.children) walk(child, path);- };- if (nodes.length === 1 && nodes[0]) {- paths.set(nodes[0].index, '');- for (const child of nodes[0].children) walk(child, '');- } else {- for (const node of nodes) walk(node, '');- }- return paths;-}-/*** A skin's inverse bind matrices, one 4x4 per joint. The accessor is optional* per spec and its absence means identity — a bind pose already at the origin,@@ -812,63 +661,6 @@ const INTERPOLATION: Record<string, string> = {LINEAR: 'linear', STEP: 'step', CUBICSPLINE: 'hermite',};-/** Which Transform channels a glTF animation path writes, in component order. */-const ANIMATED_PATHS: Record<string, { property: string; channels: string[] }> = {- translation: { property: 'position', channels: ['position.x', 'position.y', 'position.z'] },- scale: { property: 'scale', channels: ['scale.x', 'scale.y', 'scale.z'] },- // glTF stores a rotation as (x, y, z, w) — the components, in that order.- rotation: { property: 'rotation', channels: ['rotation.x', 'rotation.y', 'rotation.z', 'rotation.w'] },-};--interface OutKeyframe { time: number; value: number; inTangent: number; outTangent: number; interpolation: string }--/**- * A quaternion and its negation are the same rotation, and interpolating the- * four numbers takes the LONG way round whenever consecutive keyframes point- * apart. Flipping the sign here means the products already describe the short- * arc, so nothing downstream has to decide it per frame.- */-function alignQuaternionSigns(frames: OutKeyframe[][]): void {- if (frames.length !== 4) return;- for (let k = 1; k < (frames[0]?.length ?? 0); k++) {- let dot = 0;- for (let c = 0; c < 4; c++) dot += frames[c]![k]!.value * frames[c]![k - 1]!.value;- if (dot >= 0) continue;- for (let c = 0; c < 4; c++) {- const kf = frames[c]![k]!;- kf.value = -kf.value;- kf.inTangent = -kf.inTangent;- kf.outTangent = -kf.outTangent;- }- }-}--/**- * One sampler's keyframes, split into one list per component. CUBICSPLINE stores- * each key as `[inTangent, value, outTangent]`, and its tangents are already per- * second — the units the evaluator multiplies by the segment length — so the- * three land in the three fields a keyframe has with no conversion.- */-function samplerKeyframes(times: Float32Array, values: Float32Array,- comps: number, interpolation: string): OutKeyframe[][] {- const cubic = interpolation === 'CUBICSPLINE';- const interp = INTERPOLATION[interpolation] ?? 'linear';- const out: OutKeyframe[][] = Array.from({ length: comps }, () => []);- for (let k = 0; k < times.length; k++) {- for (let c = 0; c < comps; c++) {- const at = cubic ? (3 * k + 1) * comps + c : k * comps + c;- out[c]!.push({- time: times[k] ?? 0,- value: values[at] ?? 0,- inTangent: cubic ? (values[3 * k * comps + c] ?? 0) : 0,- outTangent: cubic ? (values[(3 * k + 2) * comps + c] ?? 0) : 0,- interpolation: interp,- });- }- }- return out;-}-/*** A glTF animation as an `.estimeline` document. Channels are grouped per target* node, since a track drives one component on one entity and the runtime reads@@ -886,7 +678,7 @@ function readAnimations(json: GltfJson, src: GltfBytes, nodes: ImportedNode[],for (const [index, animation] of animations.entries()) {const name = animation.name || `animation_${index}`;// childPath -> property -> keyframes, so one node's channels form one track.- const byNode = new Map<string, { node: string; channels: Map<string, OutKeyframe[]> }>();+ const byNode = new Map<string, AnimatedNode>();let duration = 0;let drivesSkin = false;@@ -907,7 +699,8 @@ function readAnimations(json: GltfJson, src: GltfBytes, nodes: ImportedNode[],if (skinned.has(target)) drivesSkin = true;const comps = spec.channels.length;- const frames = samplerKeyframes(times, values, comps, sampler.interpolation ?? 'LINEAR');+ const frames = samplerKeyframes(times, values, comps,+ INTERPOLATION[sampler.interpolation ?? 'LINEAR'] ?? 'linear');if (spec.property === 'rotation') alignQuaternionSigns(frames);duration = Math.max(duration, times[times.length - 1] ?? 0);@@ -930,35 +723,13 @@ function readAnimations(json: GltfJson, src: GltfBytes, nodes: ImportedNode[],+ ' ignored (glTF requires it) — this channel moves nothing. Animate its joints.');}out.push({- // A source's animation name is whatever the tool wrote (spaces, dots,- // a slash), and it becomes a file name here.- name: `${stem}_${name.replace(/[^\w.-]+/g, '_')}`,- document: {- version: TIMELINE_FORMAT_VERSION,- type: 'timeline',- duration,- // glTF says nothing about looping, and the import does not guess.- wrapMode: 'once',- tracks: [...byNode].map(([childPath, entry]) => ({- type: 'property', name: entry.node, childPath, component: 'Transform',- channels: [...entry.channels].map(([property, keyframes]) => ({ property, keyframes })),- })),- },+ name: animationProductName(stem, name),+ document: timelineDocument(duration, byNode),});}return out;}-/** A node's own name, for the track label. */-function nodeNameFor(nodes: ImportedNode[], index: number): string {- for (const node of nodes) {- if (node.index === index) return node.name;- const hit = nodeNameFor(node.children, index);- if (hit) return hit;- }- return '';-}-/*** A glTF's triangle geometry as `.esmesh` payloads. NORMAL is carried when the* source has it: the engine then draws the mesh with its lit variant, and the@@ -972,7 +743,7 @@ function nodeNameFor(nodes: ImportedNode[], index: number): string {export async function importGltfMeshes(bytes: Uint8Array, stem: string,externalBuffers?: (uri: string) => Uint8Array | null,-): Promise<GltfImportResult> {+): Promise<ModelImportResult> {// Compressed views decode synchronously once this resolves; awaiting it// unconditionally keeps "is the decoder up" from being a per-file question.await MeshoptDecoder.ready;@@ -1220,255 +991,4 @@ export async function importGltfMeshes(meshes, textures, externalFiles, nodes, warnings,animations: readAnimations(json, src, nodes, stem, warnings),};-}--/** The bytes to write for an imported mesh. */-export function encodeImportedMesh(mesh: ImportedMesh): Uint8Array {- return encodeMesh(mesh.data);-}--/** How a product is spelled where a component refers to it. */-export interface ProductRefs {- /** Prepended to every product name, e.g. `assets/models/` — the project-relative dir. */- prefix?: string;- /** An external image uri (relative to the glTF) → the ref a component carries. */- external?: (uri: string) => string;-}--/** How the products go together. */-export interface PrefabAssembly {- refs?: ProductRefs;- /** The source's hierarchy; without it every mesh sits at the origin. */- nodes?: ImportedNode[];- /** Uniform scale on the root: a glTF is in metres, a world unit is a design pixel. */- scale?: number;- /** The clip the root's player points at — the products say what they have,- * and it is left stopped because what to play is the scene's decision. */- timeline?: string;-}--/** How a component spells a reference to an image: a project-relative path. */-function imageRef(image: ImportedImageRef, refs: ProductRefs): string {- return image.external- ? refs.external?.(image.file) ?? image.file- : (refs.prefix ?? '') + image.file;-}--/**- * How a MATERIAL spells the same reference. It resolves a relative ref against- * its own directory, and every product lands beside it, so a product is its bare- * name; a file already in the project takes a logical path instead — the one- * other spelling that resolver passes through (as `rewriteMaterialRefs` writes).- */-function materialImageRef(image: ImportedImageRef, refs: ProductRefs): string {- const dir = refs.prefix ?? '';- const ref = imageRef(image, refs);- if (ref.startsWith(dir)) {- const beside = ref.slice(dir.length);- if (beside.length > 0 && !beside.includes('/')) return beside;- }- return ref.startsWith('assets/') || ref.startsWith('/') ? ref : `/${ref}`;-}--/**- * Whether this material says anything a Mesh2D's own fields cannot. Shading —- * normal map, emission, occlusion, an alpha cutoff — is per-material constants- * and samplers, and the component has neither: its per-object attributes end at- * location 15, the ceiling both backends guarantee.- */-// A metal-roughness pair the engine's own defaults already are (dielectric, fully-// rough) needs nothing written; glTF's defaults are 1 and 1, so most materials do.-function needsMaterial(material: ImportedMaterial | undefined): material is ImportedMaterial {- return !!material && !!(material.normalTexture || material.emissive || material.emissiveTexture- || material.occlusionTexture || material.alphaCutoff || material.metallicRoughnessTexture- || (material.metallic ?? 0) !== 0 || (material.roughness ?? 1) !== 1);-}--/** `<stem>_m<source material index>` — the product a material becomes. */-function materialName(stem: string, material: ImportedMaterial): string {- return `${stem}_m${material.index}`;-}--/**- * The `.esmaterial` documents an import writes, one per source material that- * needs one. The render state is written out because a material REPLACES the- * draw's own — a model told to occlude itself would start blending the moment- * it gained a material.- */-export function materialProducts(meshes: ImportedMesh[], stem: string,- refs: ProductRefs = {}): ImportedMaterialAsset[] {- const out: ImportedMaterialAsset[] = [];- const seen = new Set<number>();- for (const mesh of meshes) {- const material = mesh.material;- if (!needsMaterial(material) || seen.has(material.index)) continue;- seen.add(material.index);-- const images: ImportedImageRef[] = [];- const properties: Record<string, unknown> = {};- const bind = (name: string, image?: ImportedImageRef): void => {- if (!image) return;- images.push(image);- properties[name] = materialImageRef(image, refs);- };- bind('u_normalMap', material.normalTexture);- bind('u_emissiveMap', material.emissiveTexture);- bind('u_occlusionMap', material.occlusionTexture);- bind('u_metallicRoughnessMap', material.metallicRoughnessTexture);- // Written even at the engine's own defaults: glTF's are 1 and 1, so a- // product that left them out would read as a surface it is not.- if (material.metallic !== undefined) properties.u_metallic = material.metallic;- if (material.roughness !== undefined) properties.u_roughness = material.roughness;- if (material.emissive) {- const [r, g, b] = material.emissive;- properties.u_emissive = { r, g, b, a: 1 };- }- if (material.occlusionStrength !== undefined) {- properties.u_occlusionStrength = material.occlusionStrength;- }- if (material.alphaCutoff !== undefined) properties.u_alphaCutoff = material.alphaCutoff;-- out.push({- name: materialName(stem, material),- data: {- version: MATERIAL_FORMAT_VERSION,- type: 'material',- shader: 'builtin:model',- blendMode: material.opaque ? BlendMode.None : BlendMode.Normal,- depthTest: material.opaque,- depthWrite: material.opaque,- cull: material.cullBackfaces ? CullMode.Back : CullMode.None,- properties,- },- images,- });- }- return out;-}--function meshComponent(mesh: ImportedMesh, stem: string, refs: ProductRefs): ComponentData {- const prefix = refs.prefix ?? '';- const texture = mesh.material?.baseColorTexture- ? imageRef(mesh.material.baseColorTexture, refs) : null;- const hasNormals = mesh.data.channels.some(c => c.semantic === MeshChannel.Normal);- const color = mesh.material?.baseColor;- // Shading moves WHOLE to the material when there is one: a material shader- // reads its own samplers, so a normal map left on the component would be a- // map nothing samples.- const material = needsMaterial(mesh.material)- ? `${prefix}${materialName(stem, mesh.material)}.esmaterial` : null;- // A normal map needs normals to perturb; without them the engine draws the- // unlit variant and the map would be a reference to nothing.- const normalMap = !material && hasNormals && mesh.material?.normalTexture- ? imageRef(mesh.material.normalTexture, refs) : null;- return { type: 'Mesh2D', data: {- mesh: `${prefix}${mesh.name}.esmesh`,- // Geometry that carries normals was authored to be shaded, so the product- // says so. Written rather than assumed: `lit` is a field a user can turn- // off, and an import that left it out would be one the engine had to guess.- ...(hasNormals ? { lit: true } : {}),- ...(texture ? { texture } : {}),- ...(normalMap ? { normalMap } : {}),- ...(material ? { material } : {}),- ...(color ? { color: { r: color[0], g: color[1], b: color[2], a: color[3] } } : {}),- ...(mesh.material?.opaque ? { opaque: true } : {}),- ...(mesh.material?.cullBackfaces ? { cullBackfaces: true } : {}),- enabled: true,- } };-}--/**- * The joints that deform this mesh, named by the prefab entity each source node- * became — the same `n<index>` ids {@link assembleGltfPrefab} emits, so a- * re-import keeps pointing at the same entities.- */-function skinComponent(mesh: ImportedMesh): ComponentData[] {- if (!mesh.skinJoints) return [];- return [{ type: 'MeshSkin', data: { joints: mesh.skinJoints.map(i => `n${i}`) } }];-}--/** Only what differs from a Transform's defaults, so a diff shows the placement. */-function transformComponent(trs?: Trs, scale?: number): ComponentData {- const s = trs?.scale ?? [1, 1, 1];- const k = scale ?? 1;- const [x, y, z] = trs?.translation ?? [0, 0, 0];- const [rx, ry, rz, rw] = trs?.rotation ?? [0, 0, 0, 1];- return { type: 'Transform', data: {- ...(x || y || z ? { position: { x, y, z } } : {}),- ...(rx || ry || rz || rw !== 1 ? { rotation: { w: rw, x: rx, y: ry, z: rz } } : {}),- ...(s[0] * k !== 1 || s[1] * k !== 1 || s[2] * k !== 1- ? { scale: { x: s[0] * k, y: s[1] * k, z: s[2] * k } } : {}),- } };-}--function entity(id: string, name: string, parent: string | null,- components: ComponentData[]): PrefabEntityData {- return { prefabEntityId: id, name, parent, children: [], visible: true, components };-}--/**- * The import's assembly: where each piece of geometry sits, and which image and- * tint it is drawn with. The products are separate files and nothing else- * records how they go together, so without this a model arrives as a pile of- * parts to be re-connected by hand.- */-export function assembleGltfPrefab(name: string, meshes: ImportedMesh[],- options: PrefabAssembly = {}): PrefabData {- const refs = options.refs ?? {};- const entities: PrefabEntityData[] = [];- const nodes = options.nodes ?? [];-- const emitNode = (node: ImportedNode, parent: string | null, rootScale?: number): string => {- const id = `n${node.index}`;- const drawn = node.meshes.map(i => meshes[i]).filter((m): m is ImportedMesh => !!m);- // One primitive rides the node itself; several cannot, since a Mesh2D- // draws one mesh — they become its children, at its own origin.- const own = drawn.length === 1 && drawn[0]- ? [meshComponent(drawn[0], name, refs), ...skinComponent(drawn[0])] : [];- const self = entity(id, node.name, parent,- [transformComponent(node, rootScale), ...own]);- entities.push(self);- if (own.length === 0) {- drawn.forEach((mesh, i) => {- const childId = `${id}_p${i}`;- self.children.push(childId);- entities.push(entity(childId, mesh.name, id,- [transformComponent(), meshComponent(mesh, name, refs),- ...skinComponent(mesh)]));- });- }- for (const child of node.children) self.children.push(emitNode(child, id));- return id;- };-- if (nodes.length === 1 && nodes[0]) {- emitNode(nodes[0], null, options.scale);- } else if (nodes.length > 1) {- // Several roots are one model all the same, so they get a holder to be- // placed by — and it is where the import's own scale belongs.- const root = entity('root', name, null, [transformComponent(undefined, options.scale)]);- entities.push(root);- for (const node of nodes) root.children.push(emitNode(node, 'root'));- } else {- // No node tree: the meshes are all there is to place.- const root = entity('root', name, null, [transformComponent(undefined, options.scale)]);- entities.push(root);- meshes.forEach((mesh, i) => {- const id = `m${i}`;- root.children.push(id);- entities.push(entity(id, mesh.name, 'root',- [transformComponent(), meshComponent(mesh, name, refs)]));- });- }- // The player rides the root, which is the entity a clip's childPaths are- // resolved from — the same root the tracks were addressed against.- if (options.timeline && entities[0]) {- entities[0].components.push({ type: 'TimelinePlayer', data: {- timeline: options.timeline, playing: false,- } });- }- return {- version: PREFAB_FORMAT_VERSION, name,- rootEntityId: entities[0]!.prefabEntityId, entities,- };-}+}\ No newline at end of filediff --git a/pipeline/src/assets/modelImport.ts b/pipeline/src/assets/modelImport.tsnew file mode 100644index 000000000..75f37214b--- /dev/null+++ b/pipeline/src/assets/modelImport.ts@@ -0,0 +1,529 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What a model becomes, and how its products go together — the half of+ * the import that has nothing to do with the format it arrived in.+ *+ * A reader (glTF, FBX) produces a {@link ModelImportResult}; everything+ * below that — the `.esmesh` bytes, the `.esmaterial` documents, the+ * `.estimeline` tracks and the `.esprefab` that assembles them — is+ * written here, once. A second format that wrote its own would be a+ * second set of rules for what a model IS in this engine.+ */+import {+ MeshChannel, encodeMesh, PREFAB_FORMAT_VERSION, TIMELINE_FORMAT_VERSION,+ MATERIAL_FORMAT_VERSION, BlendMode, CullMode,+ type MeshData, type MaterialAssetData, type PrefabData, type PrefabEntityData,+ type PrefabComponentData as ComponentData,+} from 'esengine';++/** One primitive's worth of geometry, named for the file it will be written to. */+export interface ImportedMesh {+ /** `<file stem>` for a single primitive, `<stem>_<mesh>_<primitive>` otherwise. */+ name: string;+ data: MeshData;+ vertexCount: number;+ triangleCount: number;+ /** The primitive's baseColor, absent when it names no material. */+ material?: ImportedMaterial;+ /** Source node indices of the joints its `Joints` channel indexes, in order.+ * Absent for geometry nothing skins. */+ skinJoints?: number[];+}++/** Where a material's image comes from: a product this import writes, or a file already on disk. */+export interface ImportedImageRef {+ /** Product name (no directory) when written, else the source's own uri. */+ file: string;+ /** True for a uri the source points at — an existing file is referenced, never copied. */+ external: boolean;+ /** Import settings the source's sampler asks for, in the engine's own words.+ * Absent where the source names no sampler (its defaults are the engine's). */+ settings?: { filterMode?: 'nearest' | 'linear'; wrapMode?: 'repeat' | 'clamp' | 'mirror' };+}++/**+ * A material, split by what can carry it: baseColor is `texture(uv) *+ * vertexColor * tint`, which a Mesh2D's own fields say, and the shading around+ * it becomes an `.esmaterial` (@ref materialProducts). What neither can express+ * is reported, not dropped.+ */+export interface ImportedMaterial {+ /** The source's own material index — what its product is named after. */+ index: number;+ name: string;+ /** The tint multiplied into the vertex colors. */+ baseColor: [number, number, number, number];+ baseColorTexture?: ImportedImageRef;+ /** Tangent-space normal map; the engine derives its tangent frame per pixel. */+ normalTexture?: ImportedImageRef;+ /** Light the surface makes, unaffected by the scene's lights. */+ emissive?: [number, number, number];+ emissiveTexture?: ImportedImageRef;+ /** Ambient occlusion in the map's red channel, scaled by @ref occlusionStrength. */+ occlusionTexture?: ImportedImageRef;+ occlusionStrength?: number;+ /** How metal and how rough the surface is, as constants. */+ metallic?: number;+ roughness?: number;+ /** glTF's packing: roughness in green, metal in blue, multiplying the factors. */+ metallicRoughnessTexture?: ImportedImageRef;+ /** A fragment below this alpha is discarded. */+ alphaCutoff?: number;+ /** Drawn without blending, and taking part in depth. */+ opaque: boolean;+ /** Back faces are not drawn. */+ cullBackfaces: boolean;+}++/** A material product: the shading a Mesh2D's own fields cannot say. */+export interface ImportedMaterialAsset {+ /** `<stem>_m<material index>` — stable across re-imports, so overrides keep matching. */+ name: string;+ /** The `.esmaterial` document. */+ data: MaterialAssetData;+ /** Every image it references, so the caller can carry the sampler settings over. */+ images: ImportedImageRef[];+}++/** An image the source carries inline, to be written beside the meshes. */+export interface ImportedTexture {+ /** `<stem>_<image index>.<ext>` — named for the source, since an inline image has no name. */+ name: string;+ bytes: Uint8Array;+}++/**+ * A node of the source's own hierarchy: where its geometry sits, and what hangs+ * off it. Without this every primitive of a model lands on the origin.+ */+export interface ImportedNode {+ /** The node's own index in the source, so a re-import addresses the same entity. */+ index: number;+ name: string;+ translation: [number, number, number];+ /** Quaternion in (x, y, z, w) order — the same components a Transform holds. */+ rotation: [number, number, number, number];+ scale: [number, number, number];+ /** Indices into @ref ModelImportResult.meshes; one node can draw several primitives. */+ meshes: number[];+ children: ImportedNode[];+}++/** One of the source's animations as the `.estimeline` document it will be written to. */+export interface ImportedAnimation {+ /** `<stem>_<animation name>` — named for the file it will be written to. */+ name: string;+ document: Record<string, unknown>;+}++/** What a reader hands over: one file's worth of model, in the engine's terms. */+export interface ModelImportResult {+ meshes: ImportedMesh[];+ /** Images extracted from the file itself; external ones stay where they are. */+ textures: ImportedTexture[];+ /** Every uri the source points OUT to (buffers and images), in file order.+ * Bringing a model into a project means bringing these with it. */+ externalFiles: string[];+ /** The scene's node roots. Empty for a file with no nodes, whose meshes then sit flat. */+ nodes: ImportedNode[];+ /** The file's animations, each addressing nodes by their path under the prefab. */+ animations: ImportedAnimation[];+ /** What was skipped and why — a silent drop is how half a model goes missing. */+ warnings: string[];+}++export type Trs = Pick<ImportedNode, 'translation' | 'rotation' | 'scale'>;++/**+ * Make sibling names unique. An animation channel addresses its node by the path+ * of names from the root, so two siblings called "Arm" would leave a track+ * driving whichever the walk reached first — the wrong half of the model. Both+ * formats allow the duplicate, so the import settles it and the products agree.+ */+export function disambiguateNodes(nodes: ImportedNode[]): void {+ const used = new Set<string>();+ for (const node of nodes) {+ if (used.has(node.name)) node.name = `${node.name}_${node.index}`;+ used.add(node.name);+ disambiguateNodes(node.children);+ }+}++/**+ * Each node's path of names from the prefab root, matching what+ * {@link assembleModelPrefab} builds: a lone root node IS the prefab root (empty+ * path), while several roots hang under a holder and so carry their own name.+ */+export function nodeChildPaths(nodes: ImportedNode[]): Map<number, string> {+ const paths = new Map<number, string>();+ const walk = (node: ImportedNode, prefix: string): void => {+ const path = prefix ? `${prefix}/${node.name}` : node.name;+ paths.set(node.index, path);+ for (const child of node.children) walk(child, path);+ };+ if (nodes.length === 1 && nodes[0]) {+ paths.set(nodes[0].index, '');+ for (const child of nodes[0].children) walk(child, '');+ } else {+ for (const node of nodes) walk(node, '');+ }+ return paths;+}++/** A node's own name, for the track label. */+export function nodeNameFor(nodes: ImportedNode[], index: number): string {+ for (const node of nodes) {+ if (node.index === index) return node.name;+ const hit = nodeNameFor(node.children, index);+ if (hit) return hit;+ }+ return '';+}++/* -- Animation ---------------------------------------------------------- */++export interface OutKeyframe {+ time: number; value: number; inTangent: number; outTangent: number; interpolation: string;+}++/** Which Transform channels a source's animation path writes, in component order. */+export const ANIMATED_PATHS: Record<string, { property: string; channels: string[] }> = {+ translation: { property: 'position', channels: ['position.x', 'position.y', 'position.z'] },+ scale: { property: 'scale', channels: ['scale.x', 'scale.y', 'scale.z'] },+ // A rotation is stored as (x, y, z, w) — the components, in that order.+ rotation: { property: 'rotation', channels: ['rotation.x', 'rotation.y', 'rotation.z', 'rotation.w'] },+};++/**+ * A quaternion and its negation are the same rotation, and interpolating the+ * four numbers takes the LONG way round whenever consecutive keyframes point+ * apart. Flipping the sign here means the products already describe the short+ * arc, so nothing downstream has to decide it per frame.+ */+export function alignQuaternionSigns(frames: OutKeyframe[][]): void {+ if (frames.length !== 4) return;+ for (let k = 1; k < (frames[0]?.length ?? 0); k++) {+ let dot = 0;+ for (let c = 0; c < 4; c++) dot += frames[c]![k]!.value * frames[c]![k - 1]!.value;+ if (dot >= 0) continue;+ for (let c = 0; c < 4; c++) {+ const kf = frames[c]![k]!;+ kf.value = -kf.value;+ kf.inTangent = -kf.inTangent;+ kf.outTangent = -kf.outTangent;+ }+ }+}++/**+ * One sampler's keyframes, split into one list per component. CUBICSPLINE stores+ * each key as `[inTangent, value, outTangent]`, and its tangents are already per+ * second — the units the evaluator multiplies by the segment length — so the+ * three land in the three fields a keyframe has with no conversion.+ */+export function samplerKeyframes(times: ArrayLike<number>, values: ArrayLike<number>,+ comps: number, interpolation: string): OutKeyframe[][] {+ const cubic = interpolation === 'hermite';+ const out: OutKeyframe[][] = Array.from({ length: comps }, () => []);+ for (let k = 0; k < times.length; k++) {+ for (let c = 0; c < comps; c++) {+ const at = cubic ? (3 * k + 1) * comps + c : k * comps + c;+ out[c]!.push({+ time: times[k] ?? 0,+ value: values[at] ?? 0,+ inTangent: cubic ? (values[3 * k * comps + c] ?? 0) : 0,+ outTangent: cubic ? (values[(3 * k + 2) * comps + c] ?? 0) : 0,+ interpolation: cubic ? 'hermite' : interpolation,+ });+ }+ }+ return out;+}++/** One animated node: the entity a track addresses, and the channels driving it. */+export interface AnimatedNode {+ /** The node's own name — the track's label. */+ node: string;+ channels: Map<string, OutKeyframe[]>;+}++/**+ * An animation as an `.estimeline` document. Channels are grouped per target+ * node, since a track drives one component on one entity and the runtime reads+ * and writes that component once per track.+ *+ * @param byNode childPath → the node's channels, in the order tracks are written.+ */+export function timelineDocument(duration: number,+ byNode: Map<string, AnimatedNode>): Record<string, unknown> {+ return {+ version: TIMELINE_FORMAT_VERSION,+ type: 'timeline',+ duration,+ // Neither format says anything about looping, and the import does not guess.+ wrapMode: 'once',+ tracks: [...byNode].map(([childPath, entry]) => ({+ type: 'property', name: entry.node, childPath, component: 'Transform',+ channels: [...entry.channels].map(([property, keyframes]) => ({ property, keyframes })),+ })),+ };+}++/** A source's animation name is whatever the tool wrote (spaces, dots, a slash),+ * and it becomes a file name here. */+export function animationProductName(stem: string, name: string): string {+ return `${stem}_${name.replace(/[^\w.-]+/g, '_')}`;+}++/* -- Products ----------------------------------------------------------- */++/** The bytes to write for an imported mesh. */+export function encodeImportedMesh(mesh: ImportedMesh): Uint8Array {+ return encodeMesh(mesh.data);+}++/** How a product is spelled where a component refers to it. */+export interface ProductRefs {+ /** Prepended to every product name, e.g. `assets/models/` — the project-relative dir. */+ prefix?: string;+ /** An external image uri (relative to the source) → the ref a component carries. */+ external?: (uri: string) => string;+}++/** How the products go together. */+export interface PrefabAssembly {+ refs?: ProductRefs;+ /** The source's hierarchy; without it every mesh sits at the origin. */+ nodes?: ImportedNode[];+ /** Uniform scale on the root: a model is authored in metres, a world unit is+ * a design pixel. */+ scale?: number;+ /** The clip the root's player points at — the products say what they have,+ * and it is left stopped because what to play is the scene's decision. */+ timeline?: string;+}++/** How a component spells a reference to an image: a project-relative path. */+function imageRef(image: ImportedImageRef, refs: ProductRefs): string {+ return image.external+ ? refs.external?.(image.file) ?? image.file+ : (refs.prefix ?? '') + image.file;+}++/**+ * How a MATERIAL spells the same reference. It resolves a relative ref against+ * its own directory, and every product lands beside it, so a product is its bare+ * name; a file already in the project takes a logical path instead — the one+ * other spelling that resolver passes through (as `rewriteMaterialRefs` writes).+ */+function materialImageRef(image: ImportedImageRef, refs: ProductRefs): string {+ const dir = refs.prefix ?? '';+ const ref = imageRef(image, refs);+ if (ref.startsWith(dir)) {+ const beside = ref.slice(dir.length);+ if (beside.length > 0 && !beside.includes('/')) return beside;+ }+ return ref.startsWith('assets/') || ref.startsWith('/') ? ref : `/${ref}`;+}++/**+ * Whether this material says anything a Mesh2D's own fields cannot: shading is+ * per-material constants and samplers, and the component has neither. A metal-+ * roughness pair the engine's defaults already are needs nothing written — but+ * glTF defaults both factors to 1, so most materials do.+ */+function needsMaterial(material: ImportedMaterial | undefined): material is ImportedMaterial {+ return !!material && !!(material.normalTexture || material.emissive || material.emissiveTexture+ || material.occlusionTexture || material.alphaCutoff || material.metallicRoughnessTexture+ || (material.metallic ?? 0) !== 0 || (material.roughness ?? 1) !== 1);+}++/** `<stem>_m<source material index>` — the product a material becomes. */+function materialName(stem: string, material: ImportedMaterial): string {+ return `${stem}_m${material.index}`;+}++/**+ * The `.esmaterial` documents an import writes, one per source material that+ * needs one. The render state is written out because a material REPLACES the+ * draw's own — a model told to occlude itself would start blending the moment+ * it gained a material.+ */+export function materialProducts(meshes: ImportedMesh[], stem: string,+ refs: ProductRefs = {}): ImportedMaterialAsset[] {+ const out: ImportedMaterialAsset[] = [];+ const seen = new Set<number>();+ for (const mesh of meshes) {+ const material = mesh.material;+ if (!needsMaterial(material) || seen.has(material.index)) continue;+ seen.add(material.index);++ const images: ImportedImageRef[] = [];+ const properties: Record<string, unknown> = {};+ const bind = (name: string, image?: ImportedImageRef): void => {+ if (!image) return;+ images.push(image);+ properties[name] = materialImageRef(image, refs);+ };+ bind('u_normalMap', material.normalTexture);+ bind('u_emissiveMap', material.emissiveTexture);+ bind('u_occlusionMap', material.occlusionTexture);+ bind('u_metallicRoughnessMap', material.metallicRoughnessTexture);+ // Written even at the engine's own defaults: glTF's are 1 and 1, so a+ // product that left them out would read as a surface it is not.+ if (material.metallic !== undefined) properties.u_metallic = material.metallic;+ if (material.roughness !== undefined) properties.u_roughness = material.roughness;+ if (material.emissive) {+ const [r, g, b] = material.emissive;+ properties.u_emissive = { r, g, b, a: 1 };+ }+ if (material.occlusionStrength !== undefined) {+ properties.u_occlusionStrength = material.occlusionStrength;+ }+ if (material.alphaCutoff !== undefined) properties.u_alphaCutoff = material.alphaCutoff;++ out.push({+ name: materialName(stem, material),+ data: {+ version: MATERIAL_FORMAT_VERSION,+ type: 'material',+ shader: 'builtin:model',+ blendMode: material.opaque ? BlendMode.None : BlendMode.Normal,+ depthTest: material.opaque,+ depthWrite: material.opaque,+ cull: material.cullBackfaces ? CullMode.Back : CullMode.None,+ properties,+ },+ images,+ });+ }+ return out;+}++function meshComponent(mesh: ImportedMesh, stem: string, refs: ProductRefs): ComponentData {+ const prefix = refs.prefix ?? '';+ const texture = mesh.material?.baseColorTexture+ ? imageRef(mesh.material.baseColorTexture, refs) : null;+ const hasNormals = mesh.data.channels.some(c => c.semantic === MeshChannel.Normal);+ const color = mesh.material?.baseColor;+ // Shading moves WHOLE to the material when there is one: a material shader+ // reads its own samplers, so a normal map left on the component would be a+ // map nothing samples.+ const material = needsMaterial(mesh.material)+ ? `${prefix}${materialName(stem, mesh.material)}.esmaterial` : null;+ // A normal map needs normals to perturb; without them the engine draws the+ // unlit variant and the map would be a reference to nothing.+ const normalMap = !material && hasNormals && mesh.material?.normalTexture+ ? imageRef(mesh.material.normalTexture, refs) : null;+ return { type: 'Mesh2D', data: {+ mesh: `${prefix}${mesh.name}.esmesh`,+ // Geometry that carries normals was authored to be shaded, so the product+ // says so. Written rather than assumed: `lit` is a field a user can turn+ // off, and an import that left it out would be one the engine had to guess.+ ...(hasNormals ? { lit: true } : {}),+ ...(texture ? { texture } : {}),+ ...(normalMap ? { normalMap } : {}),+ ...(material ? { material } : {}),+ ...(color ? { color: { r: color[0], g: color[1], b: color[2], a: color[3] } } : {}),+ ...(mesh.material?.opaque ? { opaque: true } : {}),+ ...(mesh.material?.cullBackfaces ? { cullBackfaces: true } : {}),+ enabled: true,+ } };+}++/**+ * The joints that deform this mesh, named by the prefab entity each source node+ * became — the same `n<index>` ids {@link assembleModelPrefab} emits, so a+ * re-import keeps pointing at the same entities.+ */+function skinComponent(mesh: ImportedMesh): ComponentData[] {+ if (!mesh.skinJoints) return [];+ return [{ type: 'MeshSkin', data: { joints: mesh.skinJoints.map(i => `n${i}`) } }];+}++/** Only what differs from a Transform's defaults, so a diff shows the placement. */+function transformComponent(trs?: Trs, scale?: number): ComponentData {+ const s = trs?.scale ?? [1, 1, 1];+ const k = scale ?? 1;+ const [x, y, z] = trs?.translation ?? [0, 0, 0];+ const [rx, ry, rz, rw] = trs?.rotation ?? [0, 0, 0, 1];+ return { type: 'Transform', data: {+ ...(x || y || z ? { position: { x, y, z } } : {}),+ ...(rx || ry || rz || rw !== 1 ? { rotation: { w: rw, x: rx, y: ry, z: rz } } : {}),+ ...(s[0] * k !== 1 || s[1] * k !== 1 || s[2] * k !== 1+ ? { scale: { x: s[0] * k, y: s[1] * k, z: s[2] * k } } : {}),+ } };+}++function entity(id: string, name: string, parent: string | null,+ components: ComponentData[]): PrefabEntityData {+ return { prefabEntityId: id, name, parent, children: [], visible: true, components };+}++/**+ * The import's assembly: where each piece of geometry sits, and which image and+ * tint it is drawn with. The products are separate files and nothing else+ * records how they go together, so without this a model arrives as a pile of+ * parts to be re-connected by hand.+ */+export function assembleModelPrefab(name: string, meshes: ImportedMesh[],+ options: PrefabAssembly = {}): PrefabData {+ const refs = options.refs ?? {};+ const entities: PrefabEntityData[] = [];+ const nodes = options.nodes ?? [];++ const emitNode = (node: ImportedNode, parent: string | null, rootScale?: number): string => {+ const id = `n${node.index}`;+ const drawn = node.meshes.map(i => meshes[i]).filter((m): m is ImportedMesh => !!m);+ // One primitive rides the node itself; several cannot, since a Mesh2D+ // draws one mesh — they become its children, at its own origin.+ const own = drawn.length === 1 && drawn[0]+ ? [meshComponent(drawn[0], name, refs), ...skinComponent(drawn[0])] : [];+ const self = entity(id, node.name, parent,+ [transformComponent(node, rootScale), ...own]);+ entities.push(self);+ if (own.length === 0) {+ drawn.forEach((mesh, i) => {+ const childId = `${id}_p${i}`;+ self.children.push(childId);+ entities.push(entity(childId, mesh.name, id,+ [transformComponent(), meshComponent(mesh, name, refs),+ ...skinComponent(mesh)]));+ });+ }+ for (const child of node.children) self.children.push(emitNode(child, id));+ return id;+ };++ if (nodes.length === 1 && nodes[0]) {+ emitNode(nodes[0], null, options.scale);+ } else if (nodes.length > 1) {+ // Several roots are one model all the same, so they get a holder to be+ // placed by — and it is where the import's own scale belongs.+ const root = entity('root', name, null, [transformComponent(undefined, options.scale)]);+ entities.push(root);+ for (const node of nodes) root.children.push(emitNode(node, 'root'));+ } else {+ // No node tree: the meshes are all there is to place.+ const root = entity('root', name, null, [transformComponent(undefined, options.scale)]);+ entities.push(root);+ meshes.forEach((mesh, i) => {+ const id = `m${i}`;+ root.children.push(id);+ entities.push(entity(id, mesh.name, 'root',+ [transformComponent(), meshComponent(mesh, name, refs)]));+ });+ }+ // The player rides the root, which is the entity a clip's childPaths are+ // resolved from — the same root the tracks were addressed against.+ if (options.timeline && entities[0]) {+ entities[0].components.push({ type: 'TimelinePlayer', data: {+ timeline: options.timeline, playing: false,+ } });+ }+ return {+ version: PREFAB_FORMAT_VERSION, name,+ rootEntityId: entities[0]!.prefabEntityId, entities,+ };+}diff --git a/pipeline/src/assets/readModelSource.ts b/pipeline/src/assets/readModelSource.tsnew file mode 100644index 000000000..6ad318a7d--- /dev/null+++ b/pipeline/src/assets/readModelSource.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Which reader a model source gets — the one place a format is named.+ *+ * Both import doors (the editor's and the CLI's) go through here, so adding a+ * format is adding a reader rather than a branch in every caller.+ */+import type { ModelImportResult } from './modelImport';++/** Source formats a project can import. The engine loads none of them. */+export const MODEL_EXTENSIONS = ['.gltf', '.glb', '.fbx'];++/** The extension of `file`, lowercased, or `''`. */+function extensionOf(file: string): string {+ const dot = file.lastIndexOf('.');+ return dot < 0 ? '' : file.slice(dot).toLowerCase();+}++export function isModelSource(file: string): boolean {+ return MODEL_EXTENSIONS.includes(extensionOf(file));+}++/** The products' base name: the source's own file name without its extension. */+export function modelStem(file: string): string {+ const name = file.split(/[\\/]/).pop() ?? file;+ const ext = extensionOf(name);+ return ext ? name.slice(0, -ext.length) : name;+}++export interface ModelSourceOptions {+ /** What the source is called — how a reader resolves the paths inside it. */+ filename?: string;+ /** Resolver for a glTF's `buffers[].uri` that are not data URIs. */+ externalBuffers?: (uri: string) => Uint8Array | null;+}++/**+ * Reads a model source into the products a project can reference.+ *+ * @param bytes The file, whichever of {@link MODEL_EXTENSIONS} it is.+ * @param stem Base name for the products.+ */+export async function readModelSource(bytes: Uint8Array, stem: string,+ options: ModelSourceOptions = {}): Promise<ModelImportResult> {+ if (extensionOf(options.filename ?? '') === '.fbx') {+ const { importFbxMeshes } = await import('./fbxImport');+ return importFbxMeshes(bytes, stem, options.filename);+ }+ const { importGltfMeshes } = await import('./gltfImport');+ return importGltfMeshes(bytes, stem, options.externalBuffers);+}diff --git a/pipeline/src/index.ts b/pipeline/src/index.tsindex aeead1988..2a8912328 100644--- a/pipeline/src/index.ts+++ b/pipeline/src/index.ts@@ -15,7 +15,10 @@ export * from './project/pluginPaths';export * from './project/readProject';export * from './fs/pathSandbox';export * from './assets/contentPolicy';+export * from './assets/modelImport';+export * from './assets/readModelSource';export * from './assets/gltfImport';+export * from './assets/fbxImport';export * from './assets/assetMeta';export * from './assets/assetDb';export * from './assets/cookAssets';diff --git a/pipeline/src/project/importSettings.ts b/pipeline/src/project/importSettings.tsindex 0843e0216..d380006d6 100644--- a/pipeline/src/project/importSettings.ts+++ b/pipeline/src/project/importSettings.ts@@ -132,7 +132,7 @@ const MODEL: ImporterFieldSpec[] = [{key: 'scale', label: 'Scale', type: 'number', default: 1, min: 0.0001, step: 0.1,category: 'Import',- tooltip: 'Uniform scale on the imported prefab\u0027s root. A glTF is authored in metres '+ tooltip: 'Uniform scale on the imported prefab\u0027s root. A model is authored in metres '+ 'and a world unit is a design pixel, so a real-world model arrives a few pixels across.',},];diff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.tsindex ad888adfe..8c463a952 100644--- a/sdk/src/assetTypes.ts+++ b/sdk/src/assetTypes.ts@@ -71,7 +71,7 @@ const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [{ extensions: ['esscene'], contentType: 'json', editorType: 'scene', addressableType: null, wechatPackInclude: false, hasTransitiveDeps: false },// GPU geometry (MeshAssetLoader). Its own channel table makes it// self-describing, so it names no other asset; the source it was imported- // from (.gltf/.glb) is not shipped and is deliberately absent here.+ // from (.gltf/.glb/.fbx) is not shipped and is deliberately absent here.{ extensions: ['esmesh'], contentType: 'binary', editorType: 'mesh', addressableType: 'binary', wechatPackInclude: true, hasTransitiveDeps: false },{ extensions: ['esanim'], contentType: 'json', editorType: 'anim-clip', addressableType: null, wechatPackInclude: true, hasTransitiveDeps: true },{ extensions: ['tmj'], contentType: 'json', editorType: 'tilemap', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.jsindex d43190e71..6dc95da13 100644--- a/tools/assetMetaTable.js+++ b/tools/assetMetaTable.js@@ -66,6 +66,7 @@ export const EXT_TO_TYPE = Object.freeze({// products for that reason — the engine loads no model format.'.gltf': 'model','.glb': 'model',+ '.fbx': 'model',// The same shape for lighting: a `.hdr` panorama is import-only and produces// the `.esenv` + atlas a scene references.'.hdr': 'panorama',