Import a 3D Model and automatically assign and export animations
TypeScript
Add some stronger typing and return types for fbx loader
Scott Petrovic6d359e94408c
diff --git a/src/lib/io/fbx/AnimationParser.ts b/src/lib/io/fbx/AnimationParser.tsindex 9dd2cd1..4f972d6 100644--- a/src/lib/io/fbx/AnimationParser.ts+++ b/src/lib/io/fbx/AnimationParser.ts@@ -8,6 +8,7 @@ import {PropertyBinding,Quaternion,QuaternionKeyframeTrack,+ type KeyframeTrack,Vector3,VectorKeyframeTrack} from 'three'@@ -22,9 +23,9 @@ import { convertFBXTimeToSeconds, getEulerOrder } from './fbx-utils'class AnimationParser {// take raw animation clips and turn them into three.js animation clips- parse () {+ parse (): AnimationClip[] {- const animationClips = [];+ const animationClips: AnimationClip[] = [];const rawClips: any = this.parseClips();@@ -127,21 +128,21 @@ class AnimationParser {const animationCurveID = relationships.parents[0].ID;const animationCurveRelationship = relationships.parents[0].relationship;- if (animationCurveRelationship.match(/X/)) {+ if (animationCurveRelationship?.match(/X/)) {- curveNodesMap.get(animationCurveID).curves['x'] = animationCurve;+ curveNodesMap.get(animationCurveID)!.curves['x'] = animationCurve;- } else if (animationCurveRelationship.match(/Y/)) {+ } else if (animationCurveRelationship?.match(/Y/)) {- curveNodesMap.get(animationCurveID).curves['y'] = animationCurve;+ curveNodesMap.get(animationCurveID)!.curves['y'] = animationCurve;- } else if (animationCurveRelationship.match(/Z/)) {+ } else if (animationCurveRelationship?.match(/Z/)) {- curveNodesMap.get(animationCurveID).curves['z'] = animationCurve;+ curveNodesMap.get(animationCurveID)!.curves['z'] = animationCurve;- } else if (animationCurveRelationship.match(/DeformPercent/) && curveNodesMap.has(animationCurveID)) {+ } else if (animationCurveRelationship?.match(/DeformPercent/) && curveNodesMap.has(animationCurveID)) {- curveNodesMap.get(animationCurveID).curves['morph'] = animationCurve;+ curveNodesMap.get(animationCurveID)!.curves['morph'] = animationCurve;}@@ -182,7 +183,7 @@ class AnimationParser {if (layerCurveNodes[i] === undefined) {- const filteredParents = fbxGlobals.connections.get(child.ID).parents.filter(function (parent: any) {+ const filteredParents = fbxGlobals.connections.get(child.ID)!.parents.filter(function (parent: any) {return parent.relationship !== undefined;@@ -250,7 +251,7 @@ class AnimationParser {if (layerCurveNodes[i] === undefined) {- const filteredParents = fbxGlobals.connections.get(child.ID).parents.filter(function (parent: any) {+ const filteredParents = fbxGlobals.connections.get(child.ID)!.parents.filter(function (parent: any) {return parent.relationship !== undefined;@@ -260,11 +261,11 @@ class AnimationParser {const deformerID = filteredParents[0].ID;- const morpherID = fbxGlobals.connections.get(deformerID).parents[0].ID;- const geoID = fbxGlobals.connections.get(morpherID).parents[0].ID;+ const morpherID = fbxGlobals.connections.get(deformerID)!.parents[0].ID;+ const geoID = fbxGlobals.connections.get(morpherID)!.parents[0].ID;// assuming geometry is not used in more than one model- const modelID = fbxGlobals.connections.get(geoID).parents[0].ID;+ const modelID = fbxGlobals.connections.get(geoID)!.parents[0].ID;const rawModel = fbxGlobals.fbxTree.Objects.Model[modelID];@@ -308,7 +309,7 @@ class AnimationParser {for (const nodeID in rawStacks) {- const children = fbxGlobals.connections.get(parseInt(nodeID)).children;+ const children = fbxGlobals.connections.get(parseInt(nodeID))!.children;if (children.length > 1) {@@ -333,9 +334,9 @@ class AnimationParser {}- addClip (rawClip: any) {+ addClip (rawClip: any): AnimationClip {- let tracks: any[] = [];+ let tracks: KeyframeTrack[] = [];const scope = this;rawClip.layer.forEach(function (rawTracks: any) {@@ -348,17 +349,17 @@ class AnimationParser {}- generateTracks (rawTracks: any) {+ generateTracks (rawTracks: any): KeyframeTrack[] {- const tracks: any[] = [];+ const tracks: KeyframeTrack[] = [];- let initialPosition: any = new Vector3();- let initialScale: any = new Vector3();+ const initPositionVec = new Vector3();+ const initScaleVec = new Vector3();- if (rawTracks.transform) rawTracks.transform.decompose(initialPosition, new Quaternion(), initialScale);+ if (rawTracks.transform) rawTracks.transform.decompose(initPositionVec, new Quaternion(), initScaleVec);- initialPosition = initialPosition.toArray();- initialScale = initialScale.toArray();+ const initialPosition = initPositionVec.toArray();+ const initialScale = initScaleVec.toArray();if (rawTracks.T !== undefined && Object.keys(rawTracks.T.curves).length > 0) {@@ -392,7 +393,7 @@ class AnimationParser {}- generateVectorTrack (modelName: string, curves: any, initialValue: number[], type: string) {+ generateVectorTrack (modelName: string, curves: any, initialValue: number[], type: string): VectorKeyframeTrack {const times = this.getTimesForAllAxes(curves);const values = this.getKeyframeTrackValues(times, curves, initialValue);@@ -401,7 +402,7 @@ class AnimationParser {}- generateRotationTrack (modelName: string, curves: any, preRotation: any, postRotation: any, eulerOrder: EulerOrder | undefined, initialRotation: number[]) {+ generateRotationTrack (modelName: string, curves: any, preRotation: any, postRotation: any, eulerOrder: EulerOrder | undefined, initialRotation: number[]): QuaternionKeyframeTrack | undefined {let times;let values;@@ -493,7 +494,7 @@ class AnimationParser {}- generateMorphTrack (rawTracks: any) {+ generateMorphTrack (rawTracks: any): NumberKeyframeTrack {const curves = rawTracks.DeformPercent.curves.morph;const values = curves.values.map(function (val: any) {@@ -502,7 +503,7 @@ class AnimationParser {});- const morphNum = fbxGlobals.sceneGraph.getObjectByName(rawTracks.modelName).morphTargetDictionary[rawTracks.morphName];+ const morphNum = (fbxGlobals.sceneGraph.getObjectByName(rawTracks.modelName) as any)?.morphTargetDictionary[rawTracks.morphName];return new NumberKeyframeTrack(rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values);@@ -510,7 +511,7 @@ class AnimationParser {// For all animated objects, times are defined separately for each axis// Here we'll combine the times into one sorted array without duplicates- getTimesForAllAxes (curves: any) {+ getTimesForAllAxes (curves: any): number[] {let times: number[] = [];@@ -552,7 +553,7 @@ class AnimationParser {}- getKeyframeTrackValues (times: number[], curves: any, initialValue: number[]) {+ getKeyframeTrackValues (times: number[], curves: any, initialValue: number[]): number[] {const prevValue = initialValue;@@ -614,7 +615,7 @@ class AnimationParser {// Synchronize a curve to a target time array using linear interpolation.// If the curve is undefined (axis not animated), returns constant values from initialValue.- synchronizeCurve (curve: any, targetTimes: number[], initialValue: number) {+ synchronizeCurve (curve: any, targetTimes: number[], initialValue: number): { times: number[], values: number[] } {if (curve === undefined) {@@ -639,7 +640,7 @@ class AnimationParser {}// Sample a single value from a curve at a given time using linear interpolation- sampleCurveValue (curve: any, time: number, initialValue: number) {+ sampleCurveValue (curve: any, time: number, initialValue: number): number {const times = curve.times;const values = curve.values;@@ -671,7 +672,7 @@ class AnimationParser {// Rotations are defined as Euler angles which can have values of any size// These will be converted to quaternions which don't support values greater than// PI, so we'll interpolate large rotations- interpolateRotations (curvex: any, curvey: any, curvez: any, eulerOrder: any) {+ interpolateRotations (curvex: any, curvey: any, curvez: any, eulerOrder: EulerOrder | undefined): [number[], number[]] {const times: number[] = [];const values: number[] = [];@@ -730,8 +731,8 @@ class AnimationParser {const numSubIntervals = maxAbsSpan / 180;- const E1 = new Euler(...initialValueRad, eulerOrder);- const E2 = new Euler(...currentValueRad, eulerOrder);+ const E1 = new Euler(initialValueRad[0], initialValueRad[1], initialValueRad[2], eulerOrder);+ const E2 = new Euler(currentValueRad[0], currentValueRad[1], currentValueRad[2], eulerOrder);const Q1 = new Quaternion().setFromEuler(E1);const Q2 = new Quaternion().setFromEuler(E2);diff --git a/src/lib/io/fbx/BinaryParser.ts b/src/lib/io/fbx/BinaryParser.tsindex b1e2998..f45d2dd 100644--- a/src/lib/io/fbx/BinaryParser.ts+++ b/src/lib/io/fbx/BinaryParser.ts@@ -2,6 +2,21 @@ import { unzlibSync } from 'three/addons/libs/fflate.module.js'import { BinaryReader } from './BinaryReader'import { FBXTree } from './FBXTree'+/** Scalar or array property value stored in an FBX node's property list. */+type FBXPropertyValue = boolean | number | string | ArrayBuffer | boolean[] | number[]++/** A parsed FBX node with well-known fields and arbitrary dynamic children. */+interface FBXNode {+ name: string+ id?: number+ attrName?: string+ attrType?: string+ singleProperty?: boolean+ propertyList: FBXPropertyValue[]+ connections?: Array<Array<number | string>>+ [key: string]: any+}+/*** Parses an FBX file stored in binary format (version >= 6400).* Recursively reads nodes and their properties using a `BinaryReader`,@@ -36,7 +51,7 @@ class BinaryParser {}// Check if reader has reached the end of content.- endOfContent (reader: any) {+ endOfContent (reader: BinaryReader): boolean {// footer size: 160bytes + 16-byte alignment padding// - 16bytes: magic@@ -59,9 +74,9 @@ class BinaryParser {}// recursively parse nodes until the end of the file is reached- parseNode (reader: BinaryReader, version: number) {+ parseNode (reader: BinaryReader, version: number): FBXNode | null {- const node: any = {};+ const node: FBXNode = { name: '', propertyList: [] };// The first three data sizes depends on version.const endOffset = (version >= 7500) ? reader.getUint64() : reader.getUint32();@@ -75,18 +90,18 @@ class BinaryParser {// Regards this node as NULL-record if endOffset is zeroif (endOffset === 0) return null;- const propertyList: any[] = [];+ const propertyList: FBXPropertyValue[] = [];for (let i = 0; i < numProperties; i++) {- propertyList.push(this.parseProperty(reader));+ propertyList.push(this.parseProperty(reader)!);}// Regards the first three elements in propertyList as id, attrName, and attrTypeconst id = propertyList.length > 0 ? propertyList[0] : '';- const attrName = propertyList.length > 1 ? propertyList[1] : '';- const attrType = propertyList.length > 2 ? propertyList[2] : '';+ const attrName = propertyList.length > 1 ? propertyList[1] as string : '';+ const attrType = propertyList.length > 2 ? propertyList[2] as string : '';// check if this node represents just a single property// like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}@@ -111,7 +126,7 @@ class BinaryParser {}- parseSubNode (name: string, node: any, subNode: any) {+ parseSubNode (name: string, node: FBXNode, subNode: FBXNode): void {// special case: child node is single propertyif (subNode.singleProperty === true) {@@ -134,7 +149,7 @@ class BinaryParser {const array: any[] = [];- subNode.propertyList.forEach(function (property: any, i: number) {+ subNode.propertyList.forEach(function (property: FBXPropertyValue, i: number) {// first Connection is FBX type (OO, OP, etc.). We'll discard theseif (i !== 0) array.push(property);@@ -161,8 +176,8 @@ class BinaryParser {} else if (name === 'Properties70' && subNode.name === 'P') {- let innerPropName = subNode.propertyList[0];- let innerPropType1 = subNode.propertyList[1];+ let innerPropName = subNode.propertyList[0] as string;+ let innerPropType1 = subNode.propertyList[1] as string;const innerPropType2 = subNode.propertyList[2];const innerPropFlag = subNode.propertyList[3];let innerPropValue;@@ -219,7 +234,7 @@ class BinaryParser {node[subNode.name].push(subNode);- } else if (node[subNode.name][subNode.id] === undefined) {+ } else if (subNode.id !== undefined && node[subNode.name][subNode.id] === undefined) {node[subNode.name][subNode.id] = subNode;@@ -229,7 +244,7 @@ class BinaryParser {}- parseProperty (reader: BinaryReader) {+ parseProperty (reader: BinaryReader): FBXPropertyValue | undefined {const type = reader.getString(1);let length;@@ -331,4 +346,4 @@ class BinaryParser {}-export { BinaryParser }+export { BinaryParser, type FBXNode, type FBXPropertyValue }diff --git a/src/lib/io/fbx/BinaryReader.ts b/src/lib/io/fbx/BinaryReader.tsindex 2178abf..532c81f 100644--- a/src/lib/io/fbx/BinaryReader.ts+++ b/src/lib/io/fbx/BinaryReader.ts@@ -3,12 +3,12 @@* Wraps a `DataView` and advances an internal byte offset as typed values are read.*/class BinaryReader {- dv: DataView<any>;+ dv: DataView;offset: number;- littleEndian: any;+ littleEndian: boolean;_textDecoder: TextDecoder;- constructor (buffer: any, littleEndian?: any) {+ constructor (buffer: ArrayBuffer, littleEndian?: boolean) {this.dv = new DataView(buffer);this.offset = 0;@@ -17,19 +17,19 @@ class BinaryReader {}- getOffset () {+ getOffset (): number {return this.offset;}- size () {+ size (): number {return this.dv.buffer.byteLength;}- skip (length: number) {+ skip (length: number): void {this.offset += length;@@ -38,13 +38,13 @@ class BinaryReader {// seems like true/false representation depends on exporter.// true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)// then sees LSB.- getBoolean () {+ getBoolean (): boolean {return (this.getUint8() & 1) === 1;}- getBooleanArray (size: number) {+ getBooleanArray (size: number): boolean[] {const a: boolean[] = [];@@ -58,7 +58,7 @@ class BinaryReader {}- getUint8 () {+ getUint8 (): number {const value = this.dv.getUint8(this.offset);this.offset += 1;@@ -66,7 +66,7 @@ class BinaryReader {}- getInt16 () {+ getInt16 (): number {const value = this.dv.getInt16(this.offset, this.littleEndian);this.offset += 2;@@ -74,7 +74,7 @@ class BinaryReader {}- getInt32 () {+ getInt32 (): number {const value = this.dv.getInt32(this.offset, this.littleEndian);this.offset += 4;@@ -82,7 +82,7 @@ class BinaryReader {}- getInt32Array (size: number) {+ getInt32Array (size: number): number[] {const a: number[] = [];@@ -96,7 +96,7 @@ class BinaryReader {}- getUint32 () {+ getUint32 (): number {const value = this.dv.getUint32(this.offset, this.littleEndian);this.offset += 4;@@ -109,7 +109,7 @@ class BinaryReader {// There's a possibility that this method returns wrong value if the value// is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.// TODO: safely handle 64-bit integer- getInt64 () {+ getInt64 (): number {let low, high;@@ -143,9 +143,9 @@ class BinaryReader {}- getInt64Array (size: number) {+ getInt64Array (size: number): number[] {- const a = [];+ const a: number[] = [];for (let i = 0; i < size; i++) {@@ -158,7 +158,7 @@ class BinaryReader {}// Note: see getInt64() comment- getUint64 () {+ getUint64 (): number {let low, high;@@ -178,7 +178,7 @@ class BinaryReader {}- getFloat32 () {+ getFloat32 (): number {const value = this.dv.getFloat32(this.offset, this.littleEndian);this.offset += 4;@@ -186,7 +186,7 @@ class BinaryReader {}- getFloat32Array (size: number) {+ getFloat32Array (size: number): number[] {const a: number[] = [];@@ -200,7 +200,7 @@ class BinaryReader {}- getFloat64 () {+ getFloat64 (): number {const value = this.dv.getFloat64(this.offset, this.littleEndian);this.offset += 8;@@ -208,7 +208,7 @@ class BinaryReader {}- getFloat64Array (size: number) {+ getFloat64Array (size: number): number[] {const a: number[] = [];@@ -222,15 +222,15 @@ class BinaryReader {}- getArrayBuffer (size: number) {+ getArrayBuffer (size: number): ArrayBuffer {- const value = this.dv.buffer.slice(this.offset, this.offset + size);+ const value = this.dv.buffer.slice(this.offset, this.offset + size) as ArrayBuffer;this.offset += size;return value;}- getString (size: number) {+ getString (size: number): string {const start = this.offset;let a = new Uint8Array(this.dv.buffer, start, size);diff --git a/src/lib/io/fbx/FBXTree.ts b/src/lib/io/fbx/FBXTree.tsindex 9efc66b..e0fece0 100644--- a/src/lib/io/fbx/FBXTree.ts+++ b/src/lib/io/fbx/FBXTree.ts@@ -6,7 +6,7 @@class FBXTree {[key: string]: any- add (key: string, val: any) {+ add (key: string, val: unknown): void {this[key] = val;diff --git a/src/lib/io/fbx/FBXTreeParser.ts b/src/lib/io/fbx/FBXTreeParser.tsindex 125032b..03c0bf1 100644--- a/src/lib/io/fbx/FBXTreeParser.ts+++ b/src/lib/io/fbx/FBXTreeParser.ts@@ -10,6 +10,7 @@ import {Line,LineBasicMaterial,Loader,+ LoadingManager,MathUtils,Matrix4,Mesh,@@ -21,14 +22,15 @@ import {PropertyBinding,Quaternion,RepeatWrapping,- SRGBColorSpace,Skeleton,SkinnedMesh,SpotLight,+ SRGBColorSpace,Texture,+ TextureLoader,Vector3} from 'three'-import { fbxGlobals } from './fbx-globals'+import { fbxGlobals, type FBXConnectionEntry } from './fbx-globals'import { GeometryParser } from './GeometryParser'import { AnimationParser } from './AnimationParser'import { generateTransform, getEulerOrder } from './fbx-utils'@@ -39,16 +41,16 @@ import { generateTransform, getEulerOrder } from './fbx-utils'* cameras, meshes, skeletons, morph targets, and wiring up animations.*/class FBXTreeParser {- textureLoader: any;- manager: any;+ textureLoader: TextureLoader;+ manager: LoadingManager;- constructor (textureLoader: any, manager: any) {+ constructor (textureLoader: TextureLoader, manager: LoadingManager) {this.textureLoader = textureLoader;this.manager = manager;}- parse () {+ parse (): Group {fbxGlobals.connections = this.parseConnections();@@ -66,7 +68,7 @@ class FBXTreeParser {// Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )// and details the connection type- parseConnections () {+ parseConnections (): Map<number, FBXConnectionEntry> {const connectionMap = new Map();@@ -115,7 +117,7 @@ class FBXTreeParser {// Parse FBXTree.Objects.Video for embedded image data// These images are connected to textures in FBXTree.Objects.Textures// via FBXTree.Connections.- parseImages () {+ parseImages (): Record<number, string> {const images: any = {};const blobs: any = {};@@ -166,7 +168,7 @@ class FBXTreeParser {}// Parse embedded image data in FBXTree.Video.Content- parseImage (videoNode: any) {+ parseImage (videoNode: any): string | undefined {const content = videoNode.Content;const fileName = videoNode.RelativeFilename || videoNode.Filename;@@ -236,7 +238,7 @@ class FBXTreeParser {// Parse nodes in FBXTree.Objects.Texture// These contain details such as UV scaling, cropping, rotation etc and are connected// to images in FBXTree.Objects.Video- parseTextures (images: any) {+ parseTextures (images: Record<number, string>): Map<number, Texture> {const textureMap = new Map();@@ -257,11 +259,11 @@ class FBXTreeParser {}// Parse individual node in FBXTree.Objects.Texture- parseTexture (textureNode: any, images: any) {+ parseTexture (textureNode: any, images: Record<number, string>): Texture {const texture = this.loadTexture(textureNode, images);- texture.ID = textureNode.id;+ (texture as any).ID = textureNode.id;texture.name = textureNode.attrName;@@ -300,7 +302,7 @@ class FBXTreeParser {}// load a texture specified as a blob or data URI, or via an external URL using TextureLoader- loadTexture (textureNode: any, images: any) {+ loadTexture (textureNode: any, images: Record<number, string>): Texture {const extension = textureNode.FileName.split('.').pop().toLowerCase();@@ -315,7 +317,7 @@ class FBXTreeParser {}- const children = fbxGlobals.connections.get(textureNode.id).children;+ const children = fbxGlobals.connections.get(textureNode.id)!.children;let fileName;@@ -325,7 +327,7 @@ class FBXTreeParser {if (fileName.indexOf('blob:') === 0 || fileName.indexOf('data:') === 0) {- loader.setPath(undefined);+ loader.setPath(undefined as unknown as string);}@@ -338,17 +340,17 @@ class FBXTreeParser {}- const texture = loader.load(fileName);+ const texture = (loader as TextureLoader).load(fileName);// revert to initial path- loader.setPath(loaderPath);+ loader.setPath(loaderPath as string);return texture;}// Parse nodes in FBXTree.Objects.Material- parseMaterials (textureMap: any) {+ parseMaterials (textureMap: Map<number, Texture>): Map<number, MeshPhongMaterial | MeshLambertMaterial> {const materialMap = new Map();@@ -373,7 +375,7 @@ class FBXTreeParser {// Parse single node in FBXTree.Objects.Material// Materials are connected to texture maps in FBXTree.Objects.Textures// FBX format currently only supports Lambert and Phong shading models- parseMaterial (materialNode: any, textureMap: any) {+ parseMaterial (materialNode: any, textureMap: Map<number, Texture>): MeshPhongMaterial | MeshLambertMaterial | null {const ID = materialNode.id;const name = materialNode.attrName;@@ -417,7 +419,7 @@ class FBXTreeParser {// Parse FBX material and return parameters suitable for a three.js material// Also parse the texture map and return any textures associated with the material- parseParameters (materialNode: any, textureMap: any, ID: any) {+ parseParameters (materialNode: any, textureMap: Map<number, Texture>, ID: number): Record<string, unknown> {const parameters: any = {};@@ -511,7 +513,7 @@ class FBXTreeParser {}const scope = this;- fbxGlobals.connections.get(ID).children.forEach(function (child: any) {+ fbxGlobals.connections.get(ID)!.children.forEach(function (child: any) {const type = child.relationship;@@ -599,13 +601,13 @@ class FBXTreeParser {}// get a texture from the textureMap for use by a material.- getTexture (textureMap: any, id: any) {+ getTexture (textureMap: Map<number, Texture>, id: number): Texture | undefined {// if the texture is a layered texture, just use the first layer and issue a warningif ('LayeredTexture' in fbxGlobals.fbxTree.Objects && id in fbxGlobals.fbxTree.Objects.LayeredTexture) {console.warn('THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.');- id = fbxGlobals.connections.get(id).children[0].ID;+ id = fbxGlobals.connections.get(id)!.children[0].ID;}@@ -616,7 +618,7 @@ class FBXTreeParser {// Parse nodes in FBXTree.Objects.Deformer// Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here// Generates map of Skeleton-like objects for use later when generating and binding skeletons.- parseDeformers () {+ parseDeformers (): { skeletons: Record<string, any>; morphTargets: Record<string, any> } {const skeletons: any = {};const morphTargets: any = {};@@ -629,7 +631,7 @@ class FBXTreeParser {const deformerNode = DeformerNodes[nodeID];- const relationships = fbxGlobals.connections.get(parseInt(nodeID));+ const relationships = fbxGlobals.connections.get(parseInt(nodeID))!;if (deformerNode.attrType === 'Skin') {@@ -672,7 +674,7 @@ class FBXTreeParser {// Parse single nodes in FBXTree.Objects.Deformer// The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'// Each skin node represents a skeleton and each cluster node represents a bone- parseSkeleton (relationships: any, deformerNodes: any) {+ parseSkeleton (relationships: any, deformerNodes: any): { rawBones: any[]; bones: Bone[] } {const rawBones: any[] = [];@@ -712,7 +714,7 @@ class FBXTreeParser {}// The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"- parseMorphTargets (relationships: any, deformerNodes: any) {+ parseMorphTargets (relationships: any, deformerNodes: any): any[] {const rawMorphTargets: any[] = [];@@ -731,9 +733,9 @@ class FBXTreeParser {};- if (morphTargetNode.attrType !== 'BlendShapeChannel') return;+ if (morphTargetNode.attrType !== 'BlendShapeChannel') return rawMorphTargets;- rawMorphTarget.geoID = fbxGlobals.connections.get(parseInt(child.ID)).children.filter(function (child: any) {+ rawMorphTarget.geoID = fbxGlobals.connections.get(parseInt(child.ID))!.children.filter(function (child: any) {return child.relationship === undefined;@@ -748,7 +750,7 @@ class FBXTreeParser {}// create the main Group() to be returned by the loader- parseScene (deformers: any, geometryMap: any, materialMap: any) {+ parseScene (deformers: any, geometryMap: any, materialMap: any): void {fbxGlobals.sceneGraph = new Group();@@ -762,7 +764,7 @@ class FBXTreeParser {const modelNode = modelNodes[model.ID];scope.setLookAtProperties(model, modelNode);- const parentConnections = fbxGlobals.connections.get(model.ID).parents;+ const parentConnections = fbxGlobals.connections.get(model.ID)!.parents;parentConnections.forEach(function (connection: any) {@@ -863,7 +865,7 @@ class FBXTreeParser {const animations = new AnimationParser().parse();// if all the models where already combined in a single group, just return that- if (fbxGlobals.sceneGraph.children.length === 1 && fbxGlobals.sceneGraph.children[0].isGroup) {+ if (fbxGlobals.sceneGraph.children.length === 1 && fbxGlobals.sceneGraph.children[0] instanceof Group) {fbxGlobals.sceneGraph.children[0].animations = animations;fbxGlobals.sceneGraph = fbxGlobals.sceneGraph.children[0];@@ -893,7 +895,7 @@ class FBXTreeParser {}// parse nodes in FBXTree.Objects.Model- parseModels (skeletons: any, geometryMap: any, materialMap: any) {+ parseModels (skeletons: any, geometryMap: any, materialMap: any): Map<number, Object3D> {const modelMap = new Map();const modelNodes = fbxGlobals.fbxTree.Objects.Model;@@ -949,7 +951,7 @@ class FBXTreeParser {}- buildSkeleton (relationships: any, skeletons: any, id: any, name: any) {+ buildSkeleton (relationships: any, skeletons: any, id: number, name: any): Bone | null {let bone: any = null;@@ -997,7 +999,7 @@ class FBXTreeParser {}// create a PerspectiveCamera or OrthographicCamera- createCamera (relationships: any) {+ createCamera (relationships: any): Object3D {let model: any;let cameraAttribute: any;@@ -1089,7 +1091,7 @@ class FBXTreeParser {}// Create a DirectionalLight, PointLight or SpotLight- createLight (relationships: any) {+ createLight (relationships: any): Object3D {let model: any;let lightAttribute: any;@@ -1215,7 +1217,7 @@ class FBXTreeParser {}- createMesh (relationships: any, geometryMap: any, materialMap: any) {+ createMesh (relationships: any, geometryMap: any, materialMap: any): Mesh | SkinnedMesh {let model: any;let geometry: any = null;@@ -1311,7 +1313,7 @@ class FBXTreeParser {}- createCurve (relationships: any, geometryMap: any) {+ createCurve (relationships: any, geometryMap: any): Line {const geometry = relationships.children.reduce(function (geo: any, child: any) {@@ -1332,7 +1334,7 @@ class FBXTreeParser {}// parse the model node for transform data- getTransformData (model: any, modelNode: any) {+ getTransformData (model: any, modelNode: any): void {const transformData: any = {};@@ -1359,11 +1361,11 @@ class FBXTreeParser {}- setLookAtProperties (model: any, modelNode: any) {+ setLookAtProperties (model: any, modelNode: any): void {if ('LookAtProperty' in modelNode) {- const children = fbxGlobals.connections.get(model.ID).children;+ const children = fbxGlobals.connections.get(model.ID)!.children;children.forEach(function (child: any) {@@ -1397,7 +1399,7 @@ class FBXTreeParser {}- bindSkeleton (skeletons: any, geometryMap: any, modelMap: any) {+ bindSkeleton (skeletons: any, geometryMap: any, modelMap: any): void {for (const ID in skeletons) {@@ -1423,14 +1425,14 @@ class FBXTreeParser {}- const parents = fbxGlobals.connections.get(parseInt(skeleton.ID)).parents;+ const parents = fbxGlobals.connections.get(parseInt(skeleton.ID))!.parents;parents.forEach(function (parent: any) {if (geometryMap.has(parent.ID)) {const geoID = parent.ID;- const geoRelationships = fbxGlobals.connections.get(geoID);+ const geoRelationships = fbxGlobals.connections.get(geoID)!geoRelationships.parents.forEach(function (geoConnParent: any) {@@ -1500,7 +1502,7 @@ class FBXTreeParser {}- addGlobalSceneSettings () {+ addGlobalSceneSettings (): void {if ('GlobalSettings' in fbxGlobals.fbxTree) {diff --git a/src/lib/io/fbx/GeometryParser.ts b/src/lib/io/fbx/GeometryParser.tsindex 7a6fb6a..a992df9 100644--- a/src/lib/io/fbx/GeometryParser.ts+++ b/src/lib/io/fbx/GeometryParser.ts@@ -4,6 +4,7 @@ import {ColorManagement,Float32BufferAttribute,Matrix3,+ Matrix4,ShapeUtils,SRGBColorSpace,Uint16BufferAttribute,@@ -13,7 +14,7 @@ import {} from 'three'import { NURBSCurve } from 'three/addons/curves/NURBSCurve.js'import { fbxGlobals } from './fbx-globals'-import { generateTransform, getEulerOrder, getData } from './fbx-utils'+import { generateTransform, getEulerOrder, getData, type FBXAttributeInfo } from './fbx-utils'/*** Converts geometry nodes from the `FBXTree` into Three.js `BufferGeometry` objects.@@ -31,7 +32,7 @@ class GeometryParser {}// Parse nodes in FBXTree.Objects.Geometry- parse (deformers: any) {+ parse (deformers: any): Map<number, BufferGeometry | undefined> {const geometryMap = new Map();@@ -63,7 +64,7 @@ class GeometryParser {}// Parse single node in FBXTree.Objects.Geometry- parseGeometry (relationships: any, geoNode: any, deformers: any) {+ parseGeometry (relationships: any, geoNode: any, deformers: any): BufferGeometry | undefined {switch (geoNode.attrType) {@@ -78,7 +79,7 @@ class GeometryParser {}// Parse single node mesh geometry in FBXTree.Objects.Geometry- parseMeshGeometry (relationships: any, geoNode: any, deformers: any) {+ parseMeshGeometry (relationships: any, geoNode: any, deformers: any): BufferGeometry | undefined {const skeletons = deformers.skeletons;const morphTargets: any[] = [];@@ -130,7 +131,7 @@ class GeometryParser {}// Generate a BufferGeometry from a node in FBXTree.Objects.Geometry- genGeometry (geoNode: any, skeleton: any, morphTargets: any[], preTransform: any) {+ genGeometry (geoNode: any, skeleton: any, morphTargets: any[], preTransform: Matrix4): BufferGeometry {const geo: BufferGeometry = new BufferGeometry();if (geoNode.attrName) geo.name = geoNode.attrName;@@ -474,7 +475,7 @@ class GeometryParser {if (endOfFace) {- scope.genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength);+ scope.genFace(buffers, geoInfo, facePositionIndexes, materialIndex ?? 0, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength);polygonIndex++;faceLength = 0;@@ -496,7 +497,7 @@ class GeometryParser {}// See https://www.khronos.org/opengl/wiki/Calculating_a_Surface_Normal- getNormalNewell (vertices: Vector3[]) {+ getNormalNewell (vertices: Vector3[]): Vector3 {const normal = new Vector3(0.0, 0.0, 0.0);@@ -517,7 +518,7 @@ class GeometryParser {}- getNormalTangentAndBitangent (vertices: Vector3[]) {+ getNormalTangentAndBitangent (vertices: Vector3[]): { normal: Vector3; tangent: Vector3; bitangent: Vector3 } {const normalVector = this.getNormalNewell(vertices);// Avoid up being equal or almost equal to normalVector@@ -533,7 +534,7 @@ class GeometryParser {}- flattenVertex (vertex: Vector3, normalTangent: Vector3, normalBitangent: Vector3) {+ flattenVertex (vertex: Vector3, normalTangent: Vector3, normalBitangent: Vector3): Vector2 {return new Vector2(vertex.dot(normalTangent),@@ -781,7 +782,7 @@ class GeometryParser {}// Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists- parseNormals (NormalNode: any) {+ parseNormals (NormalNode: any): FBXAttributeInfo {const mappingType = NormalNode.MappingInformationType;const referenceType = NormalNode.ReferenceInformationType;@@ -812,7 +813,7 @@ class GeometryParser {}// Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists- parseUVs (UVNode: any) {+ parseUVs (UVNode: any): FBXAttributeInfo {const mappingType = UVNode.MappingInformationType;const referenceType = UVNode.ReferenceInformationType;@@ -835,7 +836,7 @@ class GeometryParser {}// Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists- parseVertexColors (ColorNode: any) {+ parseVertexColors (ColorNode: any): FBXAttributeInfo {const mappingType = ColorNode.MappingInformationType;const referenceType = ColorNode.ReferenceInformationType;@@ -866,7 +867,7 @@ class GeometryParser {}// Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists- parseMaterialIndices (MaterialNode: any) {+ parseMaterialIndices (MaterialNode: any): FBXAttributeInfo {const mappingType = MaterialNode.MappingInformationType;const referenceType = MaterialNode.ReferenceInformationType;@@ -907,7 +908,7 @@ class GeometryParser {}// Generate a NurbGeometry from a node in FBXTree.Objects.Geometry- parseNurbsGeometry (geoNode: any) {+ parseNurbsGeometry (geoNode: any): BufferGeometry {const order = parseInt(geoNode.Order);diff --git a/src/lib/io/fbx/TextParser.ts b/src/lib/io/fbx/TextParser.tsindex e318318..831f46f 100644--- a/src/lib/io/fbx/TextParser.ts+++ b/src/lib/io/fbx/TextParser.ts@@ -1,5 +1,6 @@import { FBXTree } from './FBXTree'import { append, parseNumberArray } from './fbx-utils'+import { type FBXNode } from './BinaryParser'/*** Parses an FBX file stored in ASCII (text) format.@@ -7,52 +8,52 @@ import { append, parseNumberArray } from './fbx-utils'* hierarchy, returning an `FBXTree` that mirrors the document structure.*/class TextParser {- nodeStack: any;+ nodeStack!: FBXNode[];currentIndent: number = 0;- currentProp: any;+ currentProp!: FBXNode | unknown[];currentPropName: string | undefinedallNodes: FBXTree = new FBXTree();- getPrevNode () {+ getPrevNode (): FBXNode {return this.nodeStack[this.currentIndent - 2];}- getCurrentNode () {+ getCurrentNode (): FBXNode {return this.nodeStack[this.currentIndent - 1];}- getCurrentProp () {+ getCurrentProp (): FBXNode | unknown[] {return this.currentProp;}- pushStack (node: any) {+ pushStack (node: FBXNode): void {this.nodeStack.push(node);this.currentIndent += 1;}- popStack () {+ popStack (): void {this.nodeStack.pop();this.currentIndent -= 1;}- setCurrentProp (val: any, name: string | undefined) {+ setCurrentProp (val: FBXNode | unknown[], name: string | undefined): void {this.currentProp = val;this.currentPropName = name;}- parse (text: string) {+ parse (text: string): FBXTree {this.currentIndent = 0;@@ -102,7 +103,7 @@ class TextParser {}- parseNodeBegin (_line: string, property: string[]) {+ parseNodeBegin (_line: string, property: string[]): void {const nodeName = property[1].trim().replace(/^"/, '').replace(/"$/, '');@@ -163,9 +164,9 @@ class TextParser {}- parseNodeAttr (attrs: any) {+ parseNodeAttr (attrs: string[]): { id: number | string; name: string; type: string } {- let id = attrs[0];+ let id: number | string = attrs[0];if (attrs[0] !== '') {@@ -192,9 +193,9 @@ class TextParser {}- parseNodeProperty (line: string, property: string[], contentLine: string) {+ parseNodeProperty (line: string, property: string[], contentLine: string): void {- let propName: any = property[1].replace(/^"/, '').replace(/"$/, '').trim();+ let propName: string = property[1].replace(/^"/, '').replace(/"$/, '').trim();let propValue: any = property[2].replace(/^"/, '').replace(/"$/, '').trim();// for special case: base64 image data follows "Content: ," line@@ -269,7 +270,7 @@ class TextParser {}- parseNodePropertyContinued (line: string) {+ parseNodePropertyContinued (line: string): void {const currentNode = this.getCurrentNode();@@ -286,7 +287,7 @@ class TextParser {}// parse "Property70"- parseNodeSpecialProperty (line: string, propName: string, propValue: any) {+ parseNodeSpecialProperty (line: string, propName: string, propValue: string): void {// split this// P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1diff --git a/src/lib/io/fbx/fbx-globals.ts b/src/lib/io/fbx/fbx-globals.tsindex c427997..d09cb41 100644--- a/src/lib/io/fbx/fbx-globals.ts+++ b/src/lib/io/fbx/fbx-globals.ts@@ -1,12 +1,17 @@+import { Group } from 'three'+import { FBXTree } from './FBXTree'++// Parent/child relationship entry stored in the FBX connections map+interface FBXConnectionEntry {+ parents: Array<{ ID: number; relationship: string | undefined }>+ children: Array<{ ID: number; relationship: string | undefined }>+}+// Shared mutable parse state passed implicitly between FBX parser classes-const fbxGlobals: {- fbxTree: any,- connections: any,- sceneGraph: any-} = {- fbxTree: undefined,- connections: undefined,- sceneGraph: undefined+const fbxGlobals = {+ fbxTree: undefined as unknown as FBXTree,+ connections: undefined as unknown as Map<number, FBXConnectionEntry>,+ sceneGraph: undefined as unknown as Group}-export { fbxGlobals }+export { fbxGlobals, type FBXConnectionEntry }diff --git a/src/lib/io/fbx/fbx-utils.ts b/src/lib/io/fbx/fbx-utils.tsindex c8e68f9..7a32fe1 100644--- a/src/lib/io/fbx/fbx-utils.ts+++ b/src/lib/io/fbx/fbx-utils.ts@@ -1,7 +1,33 @@-import { Euler, MathUtils, Matrix4, Vector3 } from 'three'+import { Euler, type EulerOrder, MathUtils, Matrix4, Vector3 } from 'three'++/** FBX transform pipeline properties used by generateTransform. */+interface FBXTransformData {+ translation?: number[]+ preRotation?: number[]+ rotation?: number[]+ postRotation?: number[]+ scale?: number[]+ scalingOffset?: number[]+ scalingPivot?: number[]+ rotationOffset?: number[]+ rotationPivot?: number[]+ parentMatrix?: Matrix4+ parentMatrixWorld?: Matrix4+ inheritType?: number+ eulerOrder?: EulerOrder+}++/** Describes a per-vertex attribute array as stored in FBX layer elements. */+interface FBXAttributeInfo {+ mappingType: string+ referenceType: string+ buffer: ArrayLike<number>+ indices: number[]+ dataSize: number+}/** Returns true when the buffer starts with the FBX binary magic string. */-function isFbxFormatBinary (buffer: ArrayBuffer) {+function isFbxFormatBinary (buffer: ArrayBuffer): boolean {const CORRECT = 'Kaydara\u0020FBX\u0020Binary\u0020\u0020\0';@@ -10,7 +36,7 @@ function isFbxFormatBinary (buffer: ArrayBuffer) {}/** Returns true when the text does NOT contain the binary magic prefix, indicating ASCII format. */-function isFbxFormatASCII (text: string) {+function isFbxFormatASCII (text: string): boolean {const CORRECT = ['K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\'];@@ -41,7 +67,7 @@ function isFbxFormatASCII (text: string) {}/** Extracts the numeric FBX version from the `FBXVersion` header line. Throws if not found. */-function getFbxVersion (text: string) {+function getFbxVersion (text: string): number {const versionRegExp = /FBXVersion: (\d+)/;const match = text.match(versionRegExp);@@ -58,14 +84,14 @@ function getFbxVersion (text: string) {}/** Converts an FBX time value (ticks at 46,186,158,000 per second) to seconds. */-function convertFBXTimeToSeconds (time: number) {+function convertFBXTimeToSeconds (time: number): number {return time / 46186158000;}/** Module-level scratch buffer reused by `getData` to avoid allocations per vertex. */-const dataArray: any[] = [];+const dataArray: number[] = [];/*** Reads one element from an FBX attribute array (normals, UVs, colours, etc.) at the@@ -73,7 +99,7 @@ const dataArray: any[] = [];* FBX stores per-vertex data in several ways (ByPolygonVertex, ByPolygon, ByVertice,* AllSame) and this function resolves all of them to a single flat index.*/-function getData (polygonVertexIndex: number, polygonIndex: number, vertexIndex: number, infoObject: any) {+function getData (polygonVertexIndex: number, polygonIndex: number, vertexIndex: number, infoObject: FBXAttributeInfo): number[] {let index;@@ -96,9 +122,9 @@ function getData (polygonVertexIndex: number, polygonIndex: number, vertexIndex:}- if (infoObject.referenceType === 'IndexToDirect') index = infoObject.indices[index];+ if (infoObject.referenceType === 'IndexToDirect') index = infoObject.indices[index!];- const from = index * infoObject.dataSize;+ const from = (index ?? 0) * infoObject.dataSize;const to = from + infoObject.dataSize;return slice(dataArray, infoObject.buffer, from, to);@@ -115,7 +141,7 @@ const tempVec = new Vector3();* algorithm described in the FBX SDK documentation.* @see https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm*/-function generateTransform (transformData: any) {+function generateTransform (transformData: FBXTransformData): Matrix4 {const lTranslationM = new Matrix4();const lPreRotationM = new Matrix4();@@ -141,25 +167,22 @@ function generateTransform (transformData: any) {if (transformData.preRotation) {- const array = transformData.preRotation.map(MathUtils.degToRad);- array.push(defaultEulerOrder);- lPreRotationM.makeRotationFromEuler(tempEuler.fromArray(array));+ const r = transformData.preRotation.map(MathUtils.degToRad);+ lPreRotationM.makeRotationFromEuler(tempEuler.set(r[0], r[1], r[2], defaultEulerOrder));}if (transformData.rotation) {- const array = transformData.rotation.map(MathUtils.degToRad);- array.push(transformData.eulerOrder || defaultEulerOrder);- lRotationM.makeRotationFromEuler(tempEuler.fromArray(array));+ const r = transformData.rotation.map(MathUtils.degToRad);+ lRotationM.makeRotationFromEuler(tempEuler.set(r[0], r[1], r[2], transformData.eulerOrder || defaultEulerOrder));}if (transformData.postRotation) {- const array = transformData.postRotation.map(MathUtils.degToRad);- array.push(defaultEulerOrder);- lPostRotationM.makeRotationFromEuler(tempEuler.fromArray(array));+ const r = transformData.postRotation.map(MathUtils.degToRad);+ lPostRotationM.makeRotationFromEuler(tempEuler.set(r[0], r[1], r[2], defaultEulerOrder));lPostRotationM.invert();}@@ -175,7 +198,7 @@ function generateTransform (transformData: any) {// parent transformif (transformData.parentMatrixWorld) {- lParentLX.copy(transformData.parentMatrix);+ lParentLX.copy(transformData.parentMatrix!);lParentGX.copy(transformData.parentMatrixWorld);}@@ -237,11 +260,11 @@ function generateTransform (transformData: any) {* intrinsic order string. Needed because FBX and Three.js use opposite conventions.* @see http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html*/-function getEulerOrder (order: any) {+function getEulerOrder (order: number): EulerOrder {order = order || 0;- const enums = [+ const enums: EulerOrder[] = ['ZYX', // -> XYZ extrinsic'YZX', // -> XZY extrinsic'XZY', // -> YZX extrinsic@@ -276,7 +299,7 @@ function parseNumberArray (value: string): number[] {}/** Decodes a byte range of an `ArrayBuffer` to a UTF-8 string. Used to read the FBX ASCII header and magic bytes. */-function convertArrayBufferToString (buffer: ArrayBuffer, from?: number, to?: number) {+function convertArrayBufferToString (buffer: ArrayBuffer, from?: number, to?: number): string {if (from === undefined) from = 0;if (to === undefined) to = buffer.byteLength;@@ -286,7 +309,7 @@ function convertArrayBufferToString (buffer: ArrayBuffer, from?: number, to?: nu}/** Appends all elements of `b` onto `a` in-place, avoiding the allocation overhead of `concat`. */-function append (a: any[], b: any[]) {+function append (a: unknown[], b: unknown[]): void {for (let i = 0, j = a.length, l = b.length; i < l; i++, j++) {@@ -297,7 +320,7 @@ function append (a: any[], b: any[]) {}/** Copies elements `[from, to)` of array `b` into `a` starting at index 0, reusing the `dataArray` scratch buffer. */-function slice (a: any[], b: any[], from: number, to: number) {+function slice (a: number[], b: ArrayLike<number>, from: number, to: number): number[] {for (let i = from, j = 0; i < to; i++, j++) {@@ -310,6 +333,8 @@ function slice (a: any[], b: any[], from: number, to: number) {}export {+ type FBXTransformData,+ type FBXAttributeInfo,isFbxFormatBinary,isFbxFormatASCII,getFbxVersion,