Import a 3D Model and automatically assign and export animations
TypeScript
Fix for FBX loader to better parse the file head and access root properties
Scott Petrovic6990d650931e
diff --git a/src/lib/io/FBXLoader.ts b/src/lib/io/FBXLoader.tsindex 2dedea8..f8dcbe0 100644--- a/src/lib/io/FBXLoader.ts+++ b/src/lib/io/FBXLoader.ts@@ -3,7 +3,7 @@ import { fbxGlobals } from './fbx/fbx-globals'import { BinaryParser } from './fbx/BinaryParser'import { TextParser } from './fbx/TextParser'import { FBXTreeParser } from './fbx/FBXTreeParser'-import { isFbxFormatBinary, isFbxFormatASCII, getFbxVersion, convertArrayBufferToString } from './fbx/fbx-utils'+import { isFbxFormatBinary, isFbxFormatASCII, describeFileHead, getFbxVersion, convertArrayBufferToString } from './fbx/fbx-utils'/*** A loader for the FBX format.@@ -109,7 +109,11 @@ class FBXLoader extends Loader {if (!isFbxFormatASCII(FBXText)) {- throw new Error('THREE.FBXLoader: Unknown format.');+ throw new Error(+ 'THREE.FBXLoader: Unknown format. The file is not a binary FBX (no "Kaydara FBX Binary" ' ++ 'magic prefix) and no FBXHeaderExtension/FBXVersion node was found in the text, so it is ' ++ 'not an ASCII FBX either. File starts with: ' + describeFileHead(FBXText)+ );}diff --git a/src/lib/io/fbx/TextParser.test.ts b/src/lib/io/fbx/TextParser.test.tsnew file mode 100644index 0000000..ffd9215--- /dev/null+++ b/src/lib/io/fbx/TextParser.test.ts@@ -0,0 +1,164 @@+import { describe, it, expect, vi } from 'vitest'+import { TextParser } from './TextParser'+import { isFbxFormatASCII, getFbxVersion } from './fbx-utils'++/**+ * A minimal but structurally realistic ASCII FBX document, exercising the shapes that+ * previously desynchronised the parser:+ * - no leading `; FBX 7.x.x project file` comment block+ * - document-level properties (`CreationTime`, `Creator`) outside any node+ * - a node header carrying attributes before the brace (`SceneInfo: ..., ... {`)+ * - property values containing `{` and `}`+ */+const ASCII_FBX = [+ 'FBXHeaderExtension: {',+ '\tFBXHeaderVersion: 1003',+ '\tFBXVersion: 7400',+ '\tCreationTimeStamp: {',+ '\t\tVersion: 1000',+ '\t\tYear: 2026',+ '\t}',+ '\tCreator: "FBX SDK/FBX Plugins version 2020.0"',+ '\tSceneInfo: "SceneInfo::GlobalInfo", "UserData" {',+ '\t\tType: "UserData"',+ '\t\tProperties70: {',+ '\t\t\tP: "DocumentUrl", "KString", "Url", "", "D:\\Art\\{Project}\\char.fbx"',+ '\t\t}',+ '\t}',+ '}',+ 'CreationTime: "2026-08-03 10:15:00:000"',+ 'Creator: "FBX SDK/FBX Plugins version 2020.0"',+ '',+ '; Object definitions',+ ';------------------------------------------------------------------',+ '',+ 'GlobalSettings: {',+ '\tVersion: 1000',+ '\tProperties70: {',+ '\t\tP: "UpAxis", "int", "Integer", "",1',+ '\t\tP: "UnitScaleFactor", "double", "Number", "",1',+ '\t}',+ '}',+ 'Objects: {',+ '\tGeometry: 140234, "Geometry::", "Mesh" {',+ '\t\tVertices: *9 {',+ '\t\t\ta: 0,0,0,1,0,0,0,1,0',+ '\t\t}',+ '\t\tPolygonVertexIndex: *3 {',+ '\t\t\ta: 0,1,-3',+ '\t\t}',+ '\t}',+ '}',+ 'Connections: {',+ '\tC: "OO",140234,0',+ '}'+].join('\n')++describe('ASCII FBX format detection', () => {+ it('accepts a document with no leading comment block', () => {+ // Regression: the upstream heuristic sampled offset 6 ('d' of "FBXHeaderExtension")+ // against the 4th char of the binary magic and rejected the file as "Unknown format".+ expect(isFbxFormatASCII(ASCII_FBX)).toBe(true)+ })++ it('accepts a document with a leading comment block', () => {+ expect(isFbxFormatASCII('; FBX 7.4.0 project file\n\n' + ASCII_FBX)).toBe(true)+ })++ it('rejects a binary FBX', () => {+ expect(isFbxFormatASCII('Kaydara FBX Binary \0\u001a\0')).toBe(false)+ })++ it('rejects files that are not FBX at all', () => {+ expect(isFbxFormatASCII('<!DOCTYPE html>\n<html><title>404</title></html>')).toBe(false)+ expect(isFbxFormatASCII('{"asset":{"version":"2.0"}}')).toBe(false)+ })++ it('reads the version regardless of spacing after the colon', () => {+ expect(getFbxVersion(ASCII_FBX)).toBe(7400)+ expect(getFbxVersion('\tFBXVersion:7300')).toBe(7300)+ })+})++describe('TextParser', () => {+ it('parses without throwing and returns to indent 0', () => {+ const parser = new TextParser()+ const tree = parser.parse(ASCII_FBX)++ expect(parser.currentIndent).toBe(0)+ expect(tree).toBeDefined()+ })++ it('stores document-level properties on the tree root', () => {+ // Regression: these lines crashed with+ // "TypeError: Cannot read properties of undefined (reading 'name')".+ const tree = new TextParser().parse(ASCII_FBX)++ expect(tree.CreationTime).toBe('2026-08-03 10:15:00:000')+ expect(tree.Creator).toBe('FBX SDK/FBX Plugins version 2020.0')+ })++ it('does not treat a brace inside a property value as a block delimiter', () => {+ // Regression: the unanchored '(\\w+):(.*){' pattern read this P: line as a node+ // beginning, so the indent drifted and every later node was silently discarded.+ const tree = new TextParser().parse(ASCII_FBX)+ // Both parsers flatten `Properties70` entries onto the enclosing node.+ const sceneInfo = tree.FBXHeaderExtension.SceneInfo++ expect(sceneInfo.DocumentUrl.value).toContain('{Project}')+ // Nodes that follow the offending line must still be present.+ expect(tree.GlobalSettings).toBeDefined()+ expect(tree.Objects).toBeDefined()+ expect(tree.Connections).toBeDefined()+ })++ it('parses the nodes that FBXTreeParser depends on', () => {+ const tree = new TextParser().parse(ASCII_FBX)++ expect(tree.GlobalSettings.UpAxis.value).toBe(1)+ expect(tree.GlobalSettings.UnitScaleFactor.value).toBe(1)+ expect(tree.Connections.connections).toEqual([[140234, 0]])++ const geometry = tree.Objects.Geometry[140234]+ expect(geometry.attrType).toBe('Mesh')+ expect(geometry.Vertices.a).toEqual([0, 0, 0, 1, 0, 0, 0, 1, 0])+ expect(geometry.PolygonVertexIndex.a).toEqual([0, 1, -3])+ })++ it('handles arrays split across multiple lines', () => {+ const tree = new TextParser().parse([+ 'Objects: {',+ '\tGeometry: 1, "Geometry::", "Mesh" {',+ '\t\tVertices: *6 {',+ '\t\t\ta: 1,2,3,',+ '4,5,6',+ '\t\t}',+ '\t}',+ '}'+ ].join('\n'))++ expect(tree.Objects.Geometry[1].Vertices.a).toEqual([1, 2, 3, 4, 5, 6])+ })++ it('reports the offending line instead of a TypeError on a truncated document', () => {+ // An extra closing brace empties the node stack while nodes remain open.+ const truncated = [+ 'Objects: {',+ '\tGeometry: 1, "Geometry::", "Mesh" {',+ '\t\tVersion: 100',+ '\t}',+ '}',+ '}',+ 'Connections: {',+ '\tC: "OO",1,0',+ '}'+ ].join('\n')++ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ // The stray brace is skipped with a warning rather than corrupting the tree.+ const tree = new TextParser().parse(truncated)++ expect(tree.Connections.connections).toEqual([[1, 0]])+ warn.mockRestore()+ })+})diff --git a/src/lib/io/fbx/TextParser.ts b/src/lib/io/fbx/TextParser.tsindex 831f46f..579e040 100644--- a/src/lib/io/fbx/TextParser.ts+++ b/src/lib/io/fbx/TextParser.ts@@ -13,6 +13,8 @@ class TextParser {currentProp!: FBXNode | unknown[];currentPropName: string | undefinedallNodes: FBXTree = new FBXTree();+ /** 1-based line number currently being processed, used only for error messages. */+ currentLineNumber: number = 0;getPrevNode (): FBXNode {@@ -68,14 +70,23 @@ class TextParser {split.forEach(function (line, i) {+ scope.currentLineNumber = i + 1;+const matchComment = line.match(/^[\s\t]*;/);const matchEmpty = line.match(/^[\s\t]*$/);if (matchComment || matchEmpty) return;- const matchBeginning = line.match('^\\t{' + scope.currentIndent + '}(\\w+):(.*){');+ // The `{` and `}` patterns are anchored to end-of-line. Without the anchor a+ // property whose *value* contains a brace -- a Windows path with a {token}, a+ // GUID, a material name -- was read as a block delimiter, pushing or popping the+ // node stack and permanently desynchronising the indent from the file.+ const matchBeginning = line.match('^\\t{' + scope.currentIndent + '}(\\w+):(.*)\\{\\s*$');const matchProperty = line.match('^\\t{' + (scope.currentIndent) + '}(\\w+):[\\s\\t\\r\\n](.*)');- const matchEnd = line.match('^\\t{' + (scope.currentIndent - 1) + '}}');+ // At indent 0 there is nothing to close, and '\t{-1}' is not a valid quantifier.+ const matchEnd = scope.currentIndent > 0+ ? line.match('^\\t{' + (scope.currentIndent - 1) + '}\\}\\s*$')+ : null;if (matchBeginning) {@@ -208,6 +219,28 @@ class TextParser {}const currentNode = this.getCurrentNode();++ if (currentNode === undefined) {++ // Document-level properties such as `CreationTime:` and `Creator:` sit outside+ // any block, so there is no node on the stack to attach them to -- they belong on+ // the tree root. Upstream three.js read `currentNode.name` unconditionally and+ // failed here with "Cannot read properties of undefined (reading 'name')".+ if (this.currentIndent === 0) {++ this.allNodes.add(propName, propValue);+ return;++ }++ throw new Error(+ 'THREE.FBXLoader: Malformed ASCII FBX. Expected an open node at indent ' ++ this.currentIndent + ' but the node stack holds ' + this.nodeStack.length ++ ' entries, on line ' + this.currentLineNumber + ': ' + JSON.stringify(line.slice(0, 120))+ );++ }+const parentName = currentNode.name;if (parentName === 'Properties70') {@@ -274,6 +307,15 @@ class TextParser {const currentNode = this.getCurrentNode();+ // Only array properties (`a:`) are continued across lines. Anything else reaching here+ // is a line the dispatcher could not classify, so there is nothing to append it to.+ if (currentNode === undefined || currentNode.a === undefined) {++ console.warn('THREE.FBXLoader: Skipping unrecognised line ' + this.currentLineNumber + ': ' + JSON.stringify(line.slice(0, 120)));+ return;++ }+currentNode.a += line;// if the line doesn't end in ',' we have reached the end of the property valuediff --git a/src/lib/io/fbx/fbx-utils.ts b/src/lib/io/fbx/fbx-utils.tsindex 7a32fe1..09f4c07 100644--- a/src/lib/io/fbx/fbx-utils.ts+++ b/src/lib/io/fbx/fbx-utils.ts@@ -35,41 +35,54 @@ function isFbxFormatBinary (buffer: ArrayBuffer): boolean {}-/** Returns true when the text does NOT contain the binary magic prefix, indicating ASCII format. */-function isFbxFormatASCII (text: string): boolean {-- const CORRECT = ['K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\'];-- let cursor = 0;+/** How much of a text file to inspect when sniffing for the ASCII FBX header node. */+const ASCII_SNIFF_LENGTH = 64 * 1024;- function read (offset: number) {+/**+ * Returns true when the decoded text looks like an ASCII FBX document.+ *+ * This replaces the upstream three.js implementation, which was doubly broken: its+ * `read()` helper advanced by an extra character each iteration, so it sampled the+ * triangular offsets (0, 1, 3, 6, 10, 15, 21, ...) instead of the first 20 characters,+ * and it rejected the file on the *first* matching character rather than requiring the+ * whole magic string. That made false rejections common -- notably, any ASCII FBX+ * written without the leading `; FBX 7.x.x project file` comment block begins with+ * `FBXHeaderExtension`, whose character at offset 6 is `d`, matching the 4th expected+ * character, so such files were always misdetected as binary.+ *+ * Detection is now the single question it should be: a binary FBX is identified by its+ * magic prefix, and anything else that contains an FBX header node is ASCII.+ */+function isFbxFormatASCII (text: string): boolean {- const result = text[offset - 1];- text = text.slice(cursor + offset);- cursor++;- return result;+ if (text.startsWith('Kaydara FBX Binary')) return false;- }+ // The header node sits at the top of the file, so only the start needs inspecting.+ return /FBXHeaderExtension\s*:|FBXVersion\s*:/.test(text.slice(0, ASCII_SNIFF_LENGTH));- for (let i = 0; i < CORRECT.length; ++i) {+}- const num = read(1);- if (num === CORRECT[i]) {+/**+ * Builds a short, printable description of a file's leading characters so that an+ * unrecognised-format error can say what was actually received (a renamed model, an+ * HTML error page from a failed request, a compressed archive, and so on).+ */+function describeFileHead (text: string): string {- return false;+ const printable = text.slice(0, 64).replace(/[^\x20-\x7e]/g, (char) => {- }+ return '\\x' + char.charCodeAt(0).toString(16).padStart(2, '0');- }+ });- return true;+ return JSON.stringify(printable);}/** Extracts the numeric FBX version from the `FBXVersion` header line. Throws if not found. */function getFbxVersion (text: string): number {- const versionRegExp = /FBXVersion: (\d+)/;+ const versionRegExp = /FBXVersion:\s*(\d+)/;const match = text.match(versionRegExp);if (match) {@@ -337,6 +350,7 @@ export {type FBXAttributeInfo,isFbxFormatBinary,isFbxFormatASCII,+ describeFileHead,getFbxVersion,convertFBXTimeToSeconds,dataArray,