/examples/jsm/loaders/FBXLoader.js

http://github.com/mrdoob/three.js · JavaScript · 4120 lines · 2677 code · 1272 blank · 171 comment · 355 complexity · ef03a275993d99891e8257c7976f0a63 MD5 · raw file

Large files are truncated click here to view the full file

  1. import {
  2. AmbientLight,
  3. AnimationClip,
  4. Bone,
  5. BufferGeometry,
  6. ClampToEdgeWrapping,
  7. Color,
  8. DirectionalLight,
  9. EquirectangularReflectionMapping,
  10. Euler,
  11. FileLoader,
  12. Float32BufferAttribute,
  13. Group,
  14. Line,
  15. LineBasicMaterial,
  16. Loader,
  17. LoaderUtils,
  18. MathUtils,
  19. Matrix3,
  20. Matrix4,
  21. Mesh,
  22. MeshLambertMaterial,
  23. MeshPhongMaterial,
  24. NumberKeyframeTrack,
  25. Object3D,
  26. OrthographicCamera,
  27. PerspectiveCamera,
  28. PointLight,
  29. PropertyBinding,
  30. Quaternion,
  31. QuaternionKeyframeTrack,
  32. RepeatWrapping,
  33. Skeleton,
  34. SkinnedMesh,
  35. SpotLight,
  36. Texture,
  37. TextureLoader,
  38. Uint16BufferAttribute,
  39. Vector3,
  40. Vector4,
  41. VectorKeyframeTrack,
  42. sRGBEncoding
  43. } from '../../../build/three.module.js';
  44. import * as fflate from '../libs/fflate.module.js';
  45. import { NURBSCurve } from '../curves/NURBSCurve.js';
  46. /**
  47. * Loader loads FBX file and generates Group representing FBX scene.
  48. * Requires FBX file to be >= 7.0 and in ASCII or >= 6400 in Binary format
  49. * Versions lower than this may load but will probably have errors
  50. *
  51. * Needs Support:
  52. * Morph normals / blend shape normals
  53. *
  54. * FBX format references:
  55. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  56. * http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_index_html (C++ SDK reference)
  57. *
  58. * Binary format specification:
  59. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  60. */
  61. let fbxTree;
  62. let connections;
  63. let sceneGraph;
  64. class FBXLoader extends Loader {
  65. constructor( manager ) {
  66. super( manager );
  67. }
  68. load( url, onLoad, onProgress, onError ) {
  69. const scope = this;
  70. const path = ( scope.path === '' ) ? LoaderUtils.extractUrlBase( url ) : scope.path;
  71. const loader = new FileLoader( this.manager );
  72. loader.setPath( scope.path );
  73. loader.setResponseType( 'arraybuffer' );
  74. loader.setRequestHeader( scope.requestHeader );
  75. loader.setWithCredentials( scope.withCredentials );
  76. loader.load( url, function ( buffer ) {
  77. try {
  78. onLoad( scope.parse( buffer, path ) );
  79. } catch ( e ) {
  80. if ( onError ) {
  81. onError( e );
  82. } else {
  83. console.error( e );
  84. }
  85. scope.manager.itemError( url );
  86. }
  87. }, onProgress, onError );
  88. }
  89. parse( FBXBuffer, path ) {
  90. if ( isFbxFormatBinary( FBXBuffer ) ) {
  91. fbxTree = new BinaryParser().parse( FBXBuffer );
  92. } else {
  93. const FBXText = convertArrayBufferToString( FBXBuffer );
  94. if ( ! isFbxFormatASCII( FBXText ) ) {
  95. throw new Error( 'THREE.FBXLoader: Unknown format.' );
  96. }
  97. if ( getFbxVersion( FBXText ) < 7000 ) {
  98. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
  99. }
  100. fbxTree = new TextParser().parse( FBXText );
  101. }
  102. // console.log( fbxTree );
  103. const textureLoader = new TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  104. return new FBXTreeParser( textureLoader, this.manager ).parse( fbxTree );
  105. }
  106. }
  107. // Parse the FBXTree object returned by the BinaryParser or TextParser and return a Group
  108. class FBXTreeParser {
  109. constructor( textureLoader, manager ) {
  110. this.textureLoader = textureLoader;
  111. this.manager = manager;
  112. }
  113. parse() {
  114. connections = this.parseConnections();
  115. const images = this.parseImages();
  116. const textures = this.parseTextures( images );
  117. const materials = this.parseMaterials( textures );
  118. const deformers = this.parseDeformers();
  119. const geometryMap = new GeometryParser().parse( deformers );
  120. this.parseScene( deformers, geometryMap, materials );
  121. return sceneGraph;
  122. }
  123. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  124. // and details the connection type
  125. parseConnections() {
  126. const connectionMap = new Map();
  127. if ( 'Connections' in fbxTree ) {
  128. const rawConnections = fbxTree.Connections.connections;
  129. rawConnections.forEach( function ( rawConnection ) {
  130. const fromID = rawConnection[ 0 ];
  131. const toID = rawConnection[ 1 ];
  132. const relationship = rawConnection[ 2 ];
  133. if ( ! connectionMap.has( fromID ) ) {
  134. connectionMap.set( fromID, {
  135. parents: [],
  136. children: []
  137. } );
  138. }
  139. const parentRelationship = { ID: toID, relationship: relationship };
  140. connectionMap.get( fromID ).parents.push( parentRelationship );
  141. if ( ! connectionMap.has( toID ) ) {
  142. connectionMap.set( toID, {
  143. parents: [],
  144. children: []
  145. } );
  146. }
  147. const childRelationship = { ID: fromID, relationship: relationship };
  148. connectionMap.get( toID ).children.push( childRelationship );
  149. } );
  150. }
  151. return connectionMap;
  152. }
  153. // Parse FBXTree.Objects.Video for embedded image data
  154. // These images are connected to textures in FBXTree.Objects.Textures
  155. // via FBXTree.Connections.
  156. parseImages() {
  157. const images = {};
  158. const blobs = {};
  159. if ( 'Video' in fbxTree.Objects ) {
  160. const videoNodes = fbxTree.Objects.Video;
  161. for ( const nodeID in videoNodes ) {
  162. const videoNode = videoNodes[ nodeID ];
  163. const id = parseInt( nodeID );
  164. images[ id ] = videoNode.RelativeFilename || videoNode.Filename;
  165. // raw image data is in videoNode.Content
  166. if ( 'Content' in videoNode ) {
  167. const arrayBufferContent = ( videoNode.Content instanceof ArrayBuffer ) && ( videoNode.Content.byteLength > 0 );
  168. const base64Content = ( typeof videoNode.Content === 'string' ) && ( videoNode.Content !== '' );
  169. if ( arrayBufferContent || base64Content ) {
  170. const image = this.parseImage( videoNodes[ nodeID ] );
  171. blobs[ videoNode.RelativeFilename || videoNode.Filename ] = image;
  172. }
  173. }
  174. }
  175. }
  176. for ( const id in images ) {
  177. const filename = images[ id ];
  178. if ( blobs[ filename ] !== undefined ) images[ id ] = blobs[ filename ];
  179. else images[ id ] = images[ id ].split( '\\' ).pop();
  180. }
  181. return images;
  182. }
  183. // Parse embedded image data in FBXTree.Video.Content
  184. parseImage( videoNode ) {
  185. const content = videoNode.Content;
  186. const fileName = videoNode.RelativeFilename || videoNode.Filename;
  187. const extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  188. let type;
  189. switch ( extension ) {
  190. case 'bmp':
  191. type = 'image/bmp';
  192. break;
  193. case 'jpg':
  194. case 'jpeg':
  195. type = 'image/jpeg';
  196. break;
  197. case 'png':
  198. type = 'image/png';
  199. break;
  200. case 'tif':
  201. type = 'image/tiff';
  202. break;
  203. case 'tga':
  204. if ( this.manager.getHandler( '.tga' ) === null ) {
  205. console.warn( 'FBXLoader: TGA loader not found, skipping ', fileName );
  206. }
  207. type = 'image/tga';
  208. break;
  209. default:
  210. console.warn( 'FBXLoader: Image type "' + extension + '" is not supported.' );
  211. return;
  212. }
  213. if ( typeof content === 'string' ) { // ASCII format
  214. return 'data:' + type + ';base64,' + content;
  215. } else { // Binary Format
  216. const array = new Uint8Array( content );
  217. return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
  218. }
  219. }
  220. // Parse nodes in FBXTree.Objects.Texture
  221. // These contain details such as UV scaling, cropping, rotation etc and are connected
  222. // to images in FBXTree.Objects.Video
  223. parseTextures( images ) {
  224. const textureMap = new Map();
  225. if ( 'Texture' in fbxTree.Objects ) {
  226. const textureNodes = fbxTree.Objects.Texture;
  227. for ( const nodeID in textureNodes ) {
  228. const texture = this.parseTexture( textureNodes[ nodeID ], images );
  229. textureMap.set( parseInt( nodeID ), texture );
  230. }
  231. }
  232. return textureMap;
  233. }
  234. // Parse individual node in FBXTree.Objects.Texture
  235. parseTexture( textureNode, images ) {
  236. const texture = this.loadTexture( textureNode, images );
  237. texture.ID = textureNode.id;
  238. texture.name = textureNode.attrName;
  239. const wrapModeU = textureNode.WrapModeU;
  240. const wrapModeV = textureNode.WrapModeV;
  241. const valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  242. const valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  243. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  244. // 0: repeat(default), 1: clamp
  245. texture.wrapS = valueU === 0 ? RepeatWrapping : ClampToEdgeWrapping;
  246. texture.wrapT = valueV === 0 ? RepeatWrapping : ClampToEdgeWrapping;
  247. if ( 'Scaling' in textureNode ) {
  248. const values = textureNode.Scaling.value;
  249. texture.repeat.x = values[ 0 ];
  250. texture.repeat.y = values[ 1 ];
  251. }
  252. return texture;
  253. }
  254. // load a texture specified as a blob or data URI, or via an external URL using TextureLoader
  255. loadTexture( textureNode, images ) {
  256. let fileName;
  257. const currentPath = this.textureLoader.path;
  258. const children = connections.get( textureNode.id ).children;
  259. if ( children !== undefined && children.length > 0 && images[ children[ 0 ].ID ] !== undefined ) {
  260. fileName = images[ children[ 0 ].ID ];
  261. if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
  262. this.textureLoader.setPath( undefined );
  263. }
  264. }
  265. let texture;
  266. const extension = textureNode.FileName.slice( - 3 ).toLowerCase();
  267. if ( extension === 'tga' ) {
  268. const loader = this.manager.getHandler( '.tga' );
  269. if ( loader === null ) {
  270. console.warn( 'FBXLoader: TGA loader not found, creating placeholder texture for', textureNode.RelativeFilename );
  271. texture = new Texture();
  272. } else {
  273. loader.setPath( this.textureLoader.path );
  274. texture = loader.load( fileName );
  275. }
  276. } else if ( extension === 'psd' ) {
  277. console.warn( 'FBXLoader: PSD textures are not supported, creating placeholder texture for', textureNode.RelativeFilename );
  278. texture = new Texture();
  279. } else {
  280. texture = this.textureLoader.load( fileName );
  281. }
  282. this.textureLoader.setPath( currentPath );
  283. return texture;
  284. }
  285. // Parse nodes in FBXTree.Objects.Material
  286. parseMaterials( textureMap ) {
  287. const materialMap = new Map();
  288. if ( 'Material' in fbxTree.Objects ) {
  289. const materialNodes = fbxTree.Objects.Material;
  290. for ( const nodeID in materialNodes ) {
  291. const material = this.parseMaterial( materialNodes[ nodeID ], textureMap );
  292. if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
  293. }
  294. }
  295. return materialMap;
  296. }
  297. // Parse single node in FBXTree.Objects.Material
  298. // Materials are connected to texture maps in FBXTree.Objects.Textures
  299. // FBX format currently only supports Lambert and Phong shading models
  300. parseMaterial( materialNode, textureMap ) {
  301. const ID = materialNode.id;
  302. const name = materialNode.attrName;
  303. let type = materialNode.ShadingModel;
  304. // Case where FBX wraps shading model in property object.
  305. if ( typeof type === 'object' ) {
  306. type = type.value;
  307. }
  308. // Ignore unused materials which don't have any connections.
  309. if ( ! connections.has( ID ) ) return null;
  310. const parameters = this.parseParameters( materialNode, textureMap, ID );
  311. let material;
  312. switch ( type.toLowerCase() ) {
  313. case 'phong':
  314. material = new MeshPhongMaterial();
  315. break;
  316. case 'lambert':
  317. material = new MeshLambertMaterial();
  318. break;
  319. default:
  320. console.warn( 'THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type );
  321. material = new MeshPhongMaterial();
  322. break;
  323. }
  324. material.setValues( parameters );
  325. material.name = name;
  326. return material;
  327. }
  328. // Parse FBX material and return parameters suitable for a three.js material
  329. // Also parse the texture map and return any textures associated with the material
  330. parseParameters( materialNode, textureMap, ID ) {
  331. const parameters = {};
  332. if ( materialNode.BumpFactor ) {
  333. parameters.bumpScale = materialNode.BumpFactor.value;
  334. }
  335. if ( materialNode.Diffuse ) {
  336. parameters.color = new Color().fromArray( materialNode.Diffuse.value );
  337. } else if ( materialNode.DiffuseColor && ( materialNode.DiffuseColor.type === 'Color' || materialNode.DiffuseColor.type === 'ColorRGB' ) ) {
  338. // The blender exporter exports diffuse here instead of in materialNode.Diffuse
  339. parameters.color = new Color().fromArray( materialNode.DiffuseColor.value );
  340. }
  341. if ( materialNode.DisplacementFactor ) {
  342. parameters.displacementScale = materialNode.DisplacementFactor.value;
  343. }
  344. if ( materialNode.Emissive ) {
  345. parameters.emissive = new Color().fromArray( materialNode.Emissive.value );
  346. } else if ( materialNode.EmissiveColor && ( materialNode.EmissiveColor.type === 'Color' || materialNode.EmissiveColor.type === 'ColorRGB' ) ) {
  347. // The blender exporter exports emissive color here instead of in materialNode.Emissive
  348. parameters.emissive = new Color().fromArray( materialNode.EmissiveColor.value );
  349. }
  350. if ( materialNode.EmissiveFactor ) {
  351. parameters.emissiveIntensity = parseFloat( materialNode.EmissiveFactor.value );
  352. }
  353. if ( materialNode.Opacity ) {
  354. parameters.opacity = parseFloat( materialNode.Opacity.value );
  355. }
  356. if ( parameters.opacity < 1.0 ) {
  357. parameters.transparent = true;
  358. }
  359. if ( materialNode.ReflectionFactor ) {
  360. parameters.reflectivity = materialNode.ReflectionFactor.value;
  361. }
  362. if ( materialNode.Shininess ) {
  363. parameters.shininess = materialNode.Shininess.value;
  364. }
  365. if ( materialNode.Specular ) {
  366. parameters.specular = new Color().fromArray( materialNode.Specular.value );
  367. } else if ( materialNode.SpecularColor && materialNode.SpecularColor.type === 'Color' ) {
  368. // The blender exporter exports specular color here instead of in materialNode.Specular
  369. parameters.specular = new Color().fromArray( materialNode.SpecularColor.value );
  370. }
  371. const scope = this;
  372. connections.get( ID ).children.forEach( function ( child ) {
  373. const type = child.relationship;
  374. switch ( type ) {
  375. case 'Bump':
  376. parameters.bumpMap = scope.getTexture( textureMap, child.ID );
  377. break;
  378. case 'Maya|TEX_ao_map':
  379. parameters.aoMap = scope.getTexture( textureMap, child.ID );
  380. break;
  381. case 'DiffuseColor':
  382. case 'Maya|TEX_color_map':
  383. parameters.map = scope.getTexture( textureMap, child.ID );
  384. if ( parameters.map !== undefined ) {
  385. parameters.map.encoding = sRGBEncoding;
  386. }
  387. break;
  388. case 'DisplacementColor':
  389. parameters.displacementMap = scope.getTexture( textureMap, child.ID );
  390. break;
  391. case 'EmissiveColor':
  392. parameters.emissiveMap = scope.getTexture( textureMap, child.ID );
  393. if ( parameters.emissiveMap !== undefined ) {
  394. parameters.emissiveMap.encoding = sRGBEncoding;
  395. }
  396. break;
  397. case 'NormalMap':
  398. case 'Maya|TEX_normal_map':
  399. parameters.normalMap = scope.getTexture( textureMap, child.ID );
  400. break;
  401. case 'ReflectionColor':
  402. parameters.envMap = scope.getTexture( textureMap, child.ID );
  403. if ( parameters.envMap !== undefined ) {
  404. parameters.envMap.mapping = EquirectangularReflectionMapping;
  405. parameters.envMap.encoding = sRGBEncoding;
  406. }
  407. break;
  408. case 'SpecularColor':
  409. parameters.specularMap = scope.getTexture( textureMap, child.ID );
  410. if ( parameters.specularMap !== undefined ) {
  411. parameters.specularMap.encoding = sRGBEncoding;
  412. }
  413. break;
  414. case 'TransparentColor':
  415. case 'TransparencyFactor':
  416. parameters.alphaMap = scope.getTexture( textureMap, child.ID );
  417. parameters.transparent = true;
  418. break;
  419. case 'AmbientColor':
  420. case 'ShininessExponent': // AKA glossiness map
  421. case 'SpecularFactor': // AKA specularLevel
  422. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  423. default:
  424. console.warn( 'THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type );
  425. break;
  426. }
  427. } );
  428. return parameters;
  429. }
  430. // get a texture from the textureMap for use by a material.
  431. getTexture( textureMap, id ) {
  432. // if the texture is a layered texture, just use the first layer and issue a warning
  433. if ( 'LayeredTexture' in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture ) {
  434. console.warn( 'THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.' );
  435. id = connections.get( id ).children[ 0 ].ID;
  436. }
  437. return textureMap.get( id );
  438. }
  439. // Parse nodes in FBXTree.Objects.Deformer
  440. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  441. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  442. parseDeformers() {
  443. const skeletons = {};
  444. const morphTargets = {};
  445. if ( 'Deformer' in fbxTree.Objects ) {
  446. const DeformerNodes = fbxTree.Objects.Deformer;
  447. for ( const nodeID in DeformerNodes ) {
  448. const deformerNode = DeformerNodes[ nodeID ];
  449. const relationships = connections.get( parseInt( nodeID ) );
  450. if ( deformerNode.attrType === 'Skin' ) {
  451. const skeleton = this.parseSkeleton( relationships, DeformerNodes );
  452. skeleton.ID = nodeID;
  453. if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: skeleton attached to more than one geometry is not supported.' );
  454. skeleton.geometryID = relationships.parents[ 0 ].ID;
  455. skeletons[ nodeID ] = skeleton;
  456. } else if ( deformerNode.attrType === 'BlendShape' ) {
  457. const morphTarget = {
  458. id: nodeID,
  459. };
  460. morphTarget.rawTargets = this.parseMorphTargets( relationships, DeformerNodes );
  461. morphTarget.id = nodeID;
  462. if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: morph target attached to more than one geometry is not supported.' );
  463. morphTargets[ nodeID ] = morphTarget;
  464. }
  465. }
  466. }
  467. return {
  468. skeletons: skeletons,
  469. morphTargets: morphTargets,
  470. };
  471. }
  472. // Parse single nodes in FBXTree.Objects.Deformer
  473. // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
  474. // Each skin node represents a skeleton and each cluster node represents a bone
  475. parseSkeleton( relationships, deformerNodes ) {
  476. const rawBones = [];
  477. relationships.children.forEach( function ( child ) {
  478. const boneNode = deformerNodes[ child.ID ];
  479. if ( boneNode.attrType !== 'Cluster' ) return;
  480. const rawBone = {
  481. ID: child.ID,
  482. indices: [],
  483. weights: [],
  484. transformLink: new Matrix4().fromArray( boneNode.TransformLink.a ),
  485. // transform: new Matrix4().fromArray( boneNode.Transform.a ),
  486. // linkMode: boneNode.Mode,
  487. };
  488. if ( 'Indexes' in boneNode ) {
  489. rawBone.indices = boneNode.Indexes.a;
  490. rawBone.weights = boneNode.Weights.a;
  491. }
  492. rawBones.push( rawBone );
  493. } );
  494. return {
  495. rawBones: rawBones,
  496. bones: []
  497. };
  498. }
  499. // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
  500. parseMorphTargets( relationships, deformerNodes ) {
  501. const rawMorphTargets = [];
  502. for ( let i = 0; i < relationships.children.length; i ++ ) {
  503. const child = relationships.children[ i ];
  504. const morphTargetNode = deformerNodes[ child.ID ];
  505. const rawMorphTarget = {
  506. name: morphTargetNode.attrName,
  507. initialWeight: morphTargetNode.DeformPercent,
  508. id: morphTargetNode.id,
  509. fullWeights: morphTargetNode.FullWeights.a
  510. };
  511. if ( morphTargetNode.attrType !== 'BlendShapeChannel' ) return;
  512. rawMorphTarget.geoID = connections.get( parseInt( child.ID ) ).children.filter( function ( child ) {
  513. return child.relationship === undefined;
  514. } )[ 0 ].ID;
  515. rawMorphTargets.push( rawMorphTarget );
  516. }
  517. return rawMorphTargets;
  518. }
  519. // create the main Group() to be returned by the loader
  520. parseScene( deformers, geometryMap, materialMap ) {
  521. sceneGraph = new Group();
  522. const modelMap = this.parseModels( deformers.skeletons, geometryMap, materialMap );
  523. const modelNodes = fbxTree.Objects.Model;
  524. const scope = this;
  525. modelMap.forEach( function ( model ) {
  526. const modelNode = modelNodes[ model.ID ];
  527. scope.setLookAtProperties( model, modelNode );
  528. const parentConnections = connections.get( model.ID ).parents;
  529. parentConnections.forEach( function ( connection ) {
  530. const parent = modelMap.get( connection.ID );
  531. if ( parent !== undefined ) parent.add( model );
  532. } );
  533. if ( model.parent === null ) {
  534. sceneGraph.add( model );
  535. }
  536. } );
  537. this.bindSkeleton( deformers.skeletons, geometryMap, modelMap );
  538. this.createAmbientLight();
  539. sceneGraph.traverse( function ( node ) {
  540. if ( node.userData.transformData ) {
  541. if ( node.parent ) {
  542. node.userData.transformData.parentMatrix = node.parent.matrix;
  543. node.userData.transformData.parentMatrixWorld = node.parent.matrixWorld;
  544. }
  545. const transform = generateTransform( node.userData.transformData );
  546. node.applyMatrix4( transform );
  547. node.updateWorldMatrix();
  548. }
  549. } );
  550. const animations = new AnimationParser().parse();
  551. // if all the models where already combined in a single group, just return that
  552. if ( sceneGraph.children.length === 1 && sceneGraph.children[ 0 ].isGroup ) {
  553. sceneGraph.children[ 0 ].animations = animations;
  554. sceneGraph = sceneGraph.children[ 0 ];
  555. }
  556. sceneGraph.animations = animations;
  557. }
  558. // parse nodes in FBXTree.Objects.Model
  559. parseModels( skeletons, geometryMap, materialMap ) {
  560. const modelMap = new Map();
  561. const modelNodes = fbxTree.Objects.Model;
  562. for ( const nodeID in modelNodes ) {
  563. const id = parseInt( nodeID );
  564. const node = modelNodes[ nodeID ];
  565. const relationships = connections.get( id );
  566. let model = this.buildSkeleton( relationships, skeletons, id, node.attrName );
  567. if ( ! model ) {
  568. switch ( node.attrType ) {
  569. case 'Camera':
  570. model = this.createCamera( relationships );
  571. break;
  572. case 'Light':
  573. model = this.createLight( relationships );
  574. break;
  575. case 'Mesh':
  576. model = this.createMesh( relationships, geometryMap, materialMap );
  577. break;
  578. case 'NurbsCurve':
  579. model = this.createCurve( relationships, geometryMap );
  580. break;
  581. case 'LimbNode':
  582. case 'Root':
  583. model = new Bone();
  584. break;
  585. case 'Null':
  586. default:
  587. model = new Group();
  588. break;
  589. }
  590. model.name = node.attrName ? PropertyBinding.sanitizeNodeName( node.attrName ) : '';
  591. model.ID = id;
  592. }
  593. this.getTransformData( model, node );
  594. modelMap.set( id, model );
  595. }
  596. return modelMap;
  597. }
  598. buildSkeleton( relationships, skeletons, id, name ) {
  599. let bone = null;
  600. relationships.parents.forEach( function ( parent ) {
  601. for ( const ID in skeletons ) {
  602. const skeleton = skeletons[ ID ];
  603. skeleton.rawBones.forEach( function ( rawBone, i ) {
  604. if ( rawBone.ID === parent.ID ) {
  605. const subBone = bone;
  606. bone = new Bone();
  607. bone.matrixWorld.copy( rawBone.transformLink );
  608. // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  609. bone.name = name ? PropertyBinding.sanitizeNodeName( name ) : '';
  610. bone.ID = id;
  611. skeleton.bones[ i ] = bone;
  612. // In cases where a bone is shared between multiple meshes
  613. // duplicate the bone here and and it as a child of the first bone
  614. if ( subBone !== null ) {
  615. bone.add( subBone );
  616. }
  617. }
  618. } );
  619. }
  620. } );
  621. return bone;
  622. }
  623. // create a PerspectiveCamera or OrthographicCamera
  624. createCamera( relationships ) {
  625. let model;
  626. let cameraAttribute;
  627. relationships.children.forEach( function ( child ) {
  628. const attr = fbxTree.Objects.NodeAttribute[ child.ID ];
  629. if ( attr !== undefined ) {
  630. cameraAttribute = attr;
  631. }
  632. } );
  633. if ( cameraAttribute === undefined ) {
  634. model = new Object3D();
  635. } else {
  636. let type = 0;
  637. if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
  638. type = 1;
  639. }
  640. let nearClippingPlane = 1;
  641. if ( cameraAttribute.NearPlane !== undefined ) {
  642. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  643. }
  644. let farClippingPlane = 1000;
  645. if ( cameraAttribute.FarPlane !== undefined ) {
  646. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  647. }
  648. let width = window.innerWidth;
  649. let height = window.innerHeight;
  650. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  651. width = cameraAttribute.AspectWidth.value;
  652. height = cameraAttribute.AspectHeight.value;
  653. }
  654. const aspect = width / height;
  655. let fov = 45;
  656. if ( cameraAttribute.FieldOfView !== undefined ) {
  657. fov = cameraAttribute.FieldOfView.value;
  658. }
  659. const focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
  660. switch ( type ) {
  661. case 0: // Perspective
  662. model = new PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  663. if ( focalLength !== null ) model.setFocalLength( focalLength );
  664. break;
  665. case 1: // Orthographic
  666. model = new OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  667. break;
  668. default:
  669. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  670. model = new Object3D();
  671. break;
  672. }
  673. }
  674. return model;
  675. }
  676. // Create a DirectionalLight, PointLight or SpotLight
  677. createLight( relationships ) {
  678. let model;
  679. let lightAttribute;
  680. relationships.children.forEach( function ( child ) {
  681. const attr = fbxTree.Objects.NodeAttribute[ child.ID ];
  682. if ( attr !== undefined ) {
  683. lightAttribute = attr;
  684. }
  685. } );
  686. if ( lightAttribute === undefined ) {
  687. model = new Object3D();
  688. } else {
  689. let type;
  690. // LightType can be undefined for Point lights
  691. if ( lightAttribute.LightType === undefined ) {
  692. type = 0;
  693. } else {
  694. type = lightAttribute.LightType.value;
  695. }
  696. let color = 0xffffff;
  697. if ( lightAttribute.Color !== undefined ) {
  698. color = new Color().fromArray( lightAttribute.Color.value );
  699. }
  700. let intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
  701. // light disabled
  702. if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
  703. intensity = 0;
  704. }
  705. let distance = 0;
  706. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  707. if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
  708. distance = 0;
  709. } else {
  710. distance = lightAttribute.FarAttenuationEnd.value;
  711. }
  712. }
  713. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  714. const decay = 1;
  715. switch ( type ) {
  716. case 0: // Point
  717. model = new PointLight( color, intensity, distance, decay );
  718. break;
  719. case 1: // Directional
  720. model = new DirectionalLight( color, intensity );
  721. break;
  722. case 2: // Spot
  723. let angle = Math.PI / 3;
  724. if ( lightAttribute.InnerAngle !== undefined ) {
  725. angle = MathUtils.degToRad( lightAttribute.InnerAngle.value );
  726. }
  727. let penumbra = 0;
  728. if ( lightAttribute.OuterAngle !== undefined ) {
  729. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  730. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  731. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  732. penumbra = MathUtils.degToRad( lightAttribute.OuterAngle.value );
  733. penumbra = Math.max( penumbra, 1 );
  734. }
  735. model = new SpotLight( color, intensity, distance, angle, penumbra, decay );
  736. break;
  737. default:
  738. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a PointLight.' );
  739. model = new PointLight( color, intensity );
  740. break;
  741. }
  742. if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
  743. model.castShadow = true;
  744. }
  745. }
  746. return model;
  747. }
  748. createMesh( relationships, geometryMap, materialMap ) {
  749. let model;
  750. let geometry = null;
  751. let material = null;
  752. const materials = [];
  753. // get geometry and materials(s) from connections
  754. relationships.children.forEach( function ( child ) {
  755. if ( geometryMap.has( child.ID ) ) {
  756. geometry = geometryMap.get( child.ID );
  757. }
  758. if ( materialMap.has( child.ID ) ) {
  759. materials.push( materialMap.get( child.ID ) );
  760. }
  761. } );
  762. if ( materials.length > 1 ) {
  763. material = materials;
  764. } else if ( materials.length > 0 ) {
  765. material = materials[ 0 ];
  766. } else {
  767. material = new MeshPhongMaterial( { color: 0xcccccc } );
  768. materials.push( material );
  769. }
  770. if ( 'color' in geometry.attributes ) {
  771. materials.forEach( function ( material ) {
  772. material.vertexColors = true;
  773. } );
  774. }
  775. if ( geometry.FBX_Deformer ) {
  776. model = new SkinnedMesh( geometry, material );
  777. model.normalizeSkinWeights();
  778. } else {
  779. model = new Mesh( geometry, material );
  780. }
  781. return model;
  782. }
  783. createCurve( relationships, geometryMap ) {
  784. const geometry = relationships.children.reduce( function ( geo, child ) {
  785. if ( geometryMap.has( child.ID ) ) geo = geometryMap.get( child.ID );
  786. return geo;
  787. }, null );
  788. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  789. const material = new LineBasicMaterial( { color: 0x3300ff, linewidth: 1 } );
  790. return new Line( geometry, material );
  791. }
  792. // parse the model node for transform data
  793. getTransformData( model, modelNode ) {
  794. const transformData = {};
  795. if ( 'InheritType' in modelNode ) transformData.inheritType = parseInt( modelNode.InheritType.value );
  796. if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = getEulerOrder( modelNode.RotationOrder.value );
  797. else transformData.eulerOrder = 'ZYX';
  798. if ( 'Lcl_Translation' in modelNode ) transformData.translation = modelNode.Lcl_Translation.value;
  799. if ( 'PreRotation' in modelNode ) transformData.preRotation = modelNode.PreRotation.value;
  800. if ( 'Lcl_Rotation' in modelNode ) transformData.rotation = modelNode.Lcl_Rotation.value;
  801. if ( 'PostRotation' in modelNode ) transformData.postRotation = modelNode.PostRotation.value;
  802. if ( 'Lcl_Scaling' in modelNode ) transformData.scale = modelNode.Lcl_Scaling.value;
  803. if ( 'ScalingOffset' in modelNode ) transformData.scalingOffset = modelNode.ScalingOffset.value;
  804. if ( 'ScalingPivot' in modelNode ) transformData.scalingPivot = modelNode.ScalingPivot.value;
  805. if ( 'RotationOffset' in modelNode ) transformData.rotationOffset = modelNode.RotationOffset.value;
  806. if ( 'RotationPivot' in modelNode ) transformData.rotationPivot = modelNode.RotationPivot.value;
  807. model.userData.transformData = transformData;
  808. }
  809. setLookAtProperties( model, modelNode ) {
  810. if ( 'LookAtProperty' in modelNode ) {
  811. const children = connections.get( model.ID ).children;
  812. children.forEach( function ( child ) {
  813. if ( child.relationship === 'LookAtProperty' ) {
  814. const lookAtTarget = fbxTree.Objects.Model[ child.ID ];
  815. if ( 'Lcl_Translation' in lookAtTarget ) {
  816. const pos = lookAtTarget.Lcl_Translation.value;
  817. // DirectionalLight, SpotLight
  818. if ( model.target !== undefined ) {
  819. model.target.position.fromArray( pos );
  820. sceneGraph.add( model.target );
  821. } else { // Cameras and other Object3Ds
  822. model.lookAt( new Vector3().fromArray( pos ) );
  823. }
  824. }
  825. }
  826. } );
  827. }
  828. }
  829. bindSkeleton( skeletons, geometryMap, modelMap ) {
  830. const bindMatrices = this.parsePoseNodes();
  831. for ( const ID in skeletons ) {
  832. const skeleton = skeletons[ ID ];
  833. const parents = connections.get( parseInt( skeleton.ID ) ).parents;
  834. parents.forEach( function ( parent ) {
  835. if ( geometryMap.has( parent.ID ) ) {
  836. const geoID = parent.ID;
  837. const geoRelationships = connections.get( geoID );
  838. geoRelationships.parents.forEach( function ( geoConnParent ) {
  839. if ( modelMap.has( geoConnParent.ID ) ) {
  840. const model = modelMap.get( geoConnParent.ID );
  841. model.bind( new Skeleton( skeleton.bones ), bindMatrices[ geoConnParent.ID ] );
  842. }
  843. } );
  844. }
  845. } );
  846. }
  847. }
  848. parsePoseNodes() {
  849. const bindMatrices = {};
  850. if ( 'Pose' in fbxTree.Objects ) {
  851. const BindPoseNode = fbxTree.Objects.Pose;
  852. for ( const nodeID in BindPoseNode ) {
  853. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' && BindPoseNode[ nodeID ].NbPoseNodes > 0 ) {
  854. const poseNodes = BindPoseNode[ nodeID ].PoseNode;
  855. if ( Array.isArray( poseNodes ) ) {
  856. poseNodes.forEach( function ( poseNode ) {
  857. bindMatrices[ poseNode.Node ] = new Matrix4().fromArray( poseNode.Matrix.a );
  858. } );
  859. } else {
  860. bindMatrices[ poseNodes.Node ] = new Matrix4().fromArray( poseNodes.Matrix.a );
  861. }
  862. }
  863. }
  864. }
  865. return bindMatrices;
  866. }
  867. // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  868. createAmbientLight() {
  869. if ( 'GlobalSettings' in fbxTree && 'AmbientColor' in fbxTree.GlobalSettings ) {
  870. const ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
  871. const r = ambientColor[ 0 ];
  872. const g = ambientColor[ 1 ];
  873. const b = ambientColor[ 2 ];
  874. if ( r !== 0 || g !== 0 || b !== 0 ) {
  875. const color = new Color( r, g, b );
  876. sceneGraph.add( new AmbientLight( color, 1 ) );
  877. }
  878. }
  879. }
  880. }
  881. // parse Geometry data from FBXTree and return map of BufferGeometries
  882. class GeometryParser {
  883. // Parse nodes in FBXTree.Objects.Geometry
  884. parse( deformers ) {
  885. const geometryMap = new Map();
  886. if ( 'Geometry' in fbxTree.Objects ) {
  887. const geoNodes = fbxTree.Objects.Geometry;
  888. for ( const nodeID in geoNodes ) {
  889. const relationships = connections.get( parseInt( nodeID ) );
  890. const geo = this.parseGeometry( relationships, geoNodes[ nodeID ], deformers );
  891. geometryMap.set( parseInt( nodeID ), geo );
  892. }
  893. }
  894. return geometryMap;
  895. }
  896. // Parse single node in FBXTree.Objects.Geometry
  897. parseGeometry( relationships, geoNode, deformers ) {
  898. switch ( geoNode.attrType ) {
  899. case 'Mesh':
  900. return this.parseMeshGeometry( relationships, geoNode, deformers );
  901. break;
  902. case 'NurbsCurve':
  903. return this.parseNurbsGeometry( geoNode );
  904. break;
  905. }
  906. }
  907. // Parse single node mesh geometry in FBXTree.Objects.Geometry
  908. parseMeshGeometry( relationships, geoNode, deformers ) {
  909. const skeletons = deformers.skeletons;
  910. const morphTargets = [];
  911. const modelNodes = relationships.parents.map( function ( parent ) {
  912. return fbxTree.Objects.Model[ parent.ID ];
  913. } );
  914. // don't create geometry if it is not associated with any models
  915. if ( modelNodes.length === 0 ) return;
  916. const skeleton = relationships.children.reduce( function ( skeleton, child ) {
  917. if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ];
  918. return skeleton;
  919. }, null );
  920. relationships.children.forEach( function ( child ) {
  921. if ( deformers.morphTargets[ child.ID ] !== undefined ) {
  922. morphTargets.push( deformers.morphTargets[ child.ID ] );
  923. }
  924. } );
  925. // Assume one model and get the preRotation from that
  926. // if there is more than one model associated with the geometry this may cause problems
  927. const modelNode = modelNodes[ 0 ];
  928. const transformData = {};
  929. if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = getEulerOrder( modelNode.RotationOrder.value );
  930. if ( 'InheritType' in modelNode ) transformData.inheritType = parseInt( modelNode.InheritType.value );
  931. if ( 'GeometricTranslation' in modelNode ) transformData.translation = modelNode.GeometricTranslation.value;
  932. if ( 'GeometricRotation' in modelNode ) transformData.rotation = modelNode.GeometricRotation.value;
  933. if ( 'GeometricScaling' in modelNode ) transformData.scale = modelNode.GeometricScaling.value;
  934. const transform = generateTransform( transformData );
  935. return this.genGeometry( geoNode, skeleton, morphTargets, transform );
  936. }
  937. // Generate a BufferGeometry from a node in FBXTree.Objects.Geometry
  938. genGeometry( geoNode, skeleton, morphTargets, preTransform ) {
  939. const geo = new BufferGeometry();
  940. if ( geoNode.attrName ) geo.name = geoNode.attrName;
  941. const geoInfo = this.parseGeoNode( geoNode, skeleton );
  942. const buffers = this.genBuffers( geoInfo );
  943. const positionAttribute = new Float32BufferAttribute( buffers.vertex, 3 );
  944. positionAttribute.applyMatrix4( preTransform );
  945. geo.setAttribute( 'position', positionAttribute );
  946. if ( buffers.colors.length > 0 ) {
  947. geo.setAttribute( 'color', new Float32BufferAttribute( buffers.colors, 3 ) );
  948. }
  949. if ( skeleton ) {
  950. geo.setAttribute( 'skinIndex', new Uint16BufferAttribute( buffers.weightsIndices, 4 ) );
  951. geo.setAttribute( 'skinWeight', new Float32BufferAttribute( buffers.vertexWeights, 4 ) );
  952. // used later to bind the skeleton to the model
  953. geo.FBX_Deformer = skeleton;
  954. }
  955. if ( buffers.normal.length > 0 ) {
  956. const normalMatrix = new Matrix3().getNormalMatrix( preTransform );
  957. const normalAttribute = new Float32BufferAttribute( buffers.normal, 3 );
  958. normalAttribute.applyNormalMatrix( normalMatrix );
  959. geo.setAttribute( 'normal', normalAttribute );
  960. }
  961. buffers.uvs.forEach( function ( uvBuffer, i ) {
  962. // subsequent uv buffers are called 'uv1', 'uv2', ...
  963. let name = 'uv' + ( i + 1 ).toString();
  964. // the first uv buffer is just called 'uv'
  965. if ( i === 0 ) {
  966. name = 'uv';
  967. }
  968. geo.setAttribute( name, new Float32BufferAttribute( buffers.uvs[ i ], 2 ) );
  969. } );
  970. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  971. // Convert the material indices of each vertex into rendering groups on the geometry.
  972. let prevMaterialIndex = buffers.materialIndex[ 0 ];
  973. let startIndex = 0;
  974. buffers.materialIndex.forEach( function ( currentIndex, i ) {
  975. if ( currentIndex !== prevMaterialIndex ) {
  976. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  977. prevMaterialIndex = currentIndex;
  978. startIndex = i;
  979. }
  980. } );
  981. // the loop above doesn't add the last group, do that here.
  982. if ( geo.groups.length > 0 ) {
  983. const lastGroup = geo.groups[ geo.groups.length - 1 ];
  984. const lastIndex = lastGroup.start + lastGroup.count;
  985. if ( lastIndex !== buffers.materialIndex.length ) {
  986. geo.addGroup( lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex );
  987. }
  988. }
  989. // case where there are multiple materials but the whole geometry is only
  990. // using one of them
  991. if ( geo.groups.length === 0 ) {
  992. geo.addGroup( 0, buffers.materialIndex.length, buffers.materialIndex[ 0 ] );
  993. }
  994. }
  995. this.addMorphTargets( geo, geoNode, morphTargets, preTransform );
  996. return geo;
  997. }
  998. parseGeoNode( geoNode, skeleton ) {
  999. const geoInfo = {};
  1000. geoInfo.vertexPositions = ( geoNode.Vertices !== undefined ) ? geoNode.Vertices.a : [];
  1001. geoInfo.vertexIndices = ( geoNode.PolygonVertexIndex !== undefined ) ? geoNode.PolygonVertexIndex.a : [];
  1002. if ( geoNode.LayerElementColor ) {
  1003. geoInfo.color = this.parseVertexColors( geoNode.LayerElementColor[ 0 ] );
  1004. }
  1005. if ( geoNode.LayerElementMaterial ) {
  1006. geoInfo.material = this.parseMaterialIndices( geoNode.LayerElementMaterial[ 0 ] );
  1007. }
  1008. if ( geoNode.LayerElementNormal ) {
  1009. geoInfo.normal = this.parseNormals( geoNode.LayerElementNormal[ 0 ] );
  1010. }
  1011. if ( geoNode.LayerElementUV ) {
  1012. geoInfo.uv = [];
  1013. let i = 0;
  1014. while ( geoNode.LayerElementUV[ i ] ) {
  1015. if ( geoNode.LayerElementUV[ i ].UV ) {
  1016. geoInfo.uv.push( this.parseUVs( geoNode.LayerElementUV[ i ] ) );
  1017. }
  1018. i ++;
  1019. }
  1020. }
  1021. geoInfo.weightTable = {};
  1022. if ( skeleton !== null ) {
  1023. geoInfo.skeleton = skeleton;
  1024. skeleton.rawBones.forEach( function ( rawBone, i ) {
  1025. // loop over the bone's vertex indices and weights
  1026. rawBone.indices.forEach( function ( index, j ) {
  1027. if ( geoInfo.weightTable[ index ] === undefined ) geoInfo.weightTable[ index ] = [];
  1028. geoInfo.weightTable[ index ].push( {
  1029. id: i,
  1030. weight: rawBone.weights[ j ],
  1031. } );
  1032. } );
  1033. } );
  1034. }
  1035. return geoInfo;
  1036. }
  1037. genBuffers( geoInfo ) {
  1038. const buffers = {
  1039. vertex: [],
  1040. normal: [],
  1041. colors: [],
  1042. uvs: [],
  1043. materialIndex: [],
  1044. vertexWeights: [],
  1045. weightsIndices: [],
  1046. };
  1047. let polygonIndex = 0;
  1048. let faceLength = 0;
  1049. let displayedWeightsWarning = false;
  1050. // these will hold data for a single face
  1051. let facePositionIndexes = [];
  1052. let faceNormals = [];
  1053. let faceColors = [];
  1054. let faceUVs = [];
  1055. let faceWeights = [];
  1056. let faceWeightIndices = [];
  1057. const scope = this;
  1058. geoInfo.vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) {
  1059. let materialIndex;
  1060. let endOfFace = false;
  1061. // Face index and vertex index arrays are combined in a single array
  1062. // A cube with quad faces looks like this:
  1063. // PolygonVertexIndex: *24 {
  1064. // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5
  1065. // }
  1066. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  1067. // to find index of last vertex bit shift the index: ^ - 1
  1068. if ( vertexIndex < 0 ) {
  1069. vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
  1070. endOfFace = true;
  1071. }
  1072. let weightIndices = [];
  1073. let weights = [];
  1074. facePositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
  1075. if ( geoInfo.color ) {
  1076. const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color );
  1077. faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  1078. }
  1079. if ( geoInfo.skeleton ) {
  1080. if ( geoInfo.weightTable[ vertexIndex ] !== undefined ) {
  1081. geoInfo.weightTable[ vertexIndex ].forEach( function ( wt ) {
  1082. weights.push( wt.weight );
  1083. weightIndices.push( wt.id );
  1084. } );
  1085. }
  1086. if ( weights.length > 4 ) {
  1087. if ( ! displayedWeightsWarning ) {
  1088. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  1089. displayedWeightsWarning = true;
  1090. }
  1091. const wIndex = [ 0, 0, 0, 0 ];
  1092. const Weight = [ 0, 0, 0, 0 ];
  1093. weights.forEach( function ( weight, weightIndex ) {
  1094. let currentWeight = weight;
  1095. let currentIndex = weightIndices[ weightIndex ];
  1096. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  1097. if ( currentWeight > comparedWeight ) {
  1098. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  1099. currentWeight = comparedWeight;
  1100. const tmp = wIndex[ comparedWeightIndex ];
  1101. wIndex[ comparedWeightIndex ] = currentIndex;
  1102. currentIndex = tmp;
  1103. }
  1104. } );
  1105. } );
  1106. weightIndices = wIndex;
  1107. weights = Weight;
  1108. }
  1109. // if the weight array is shorter than 4 pad with 0s
  1110. while ( weights.length < 4 ) {
  1111. weights.push( 0 );
  1112. weightIndices.push( 0 );
  1113. }
  1114. for ( let i = 0; i < 4; ++ i ) {
  1115. faceWeights.push( weights[ i ] );
  1116. faceWeightIndices.push( weightIndices[ i ] );
  1117. }
  1118. }
  1119. if ( geoInfo.normal ) {
  1120. const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal );
  1121. faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  1122. }
  1123. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  1124. materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material )[ 0 ];
  1125. }
  1126. if ( geoInfo.uv ) {
  1127. geoInfo.uv.forEach( function ( uv, i ) {
  1128. const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv );
  1129. if ( faceUVs[ i ] === undefined ) {
  1130. faceUVs[ i ] = [];
  1131. }
  1132. faceUVs[ i ].push( data[ 0 ] );
  1133. faceUVs[ i ].push( data[ 1 ] );
  1134. } );
  1135. }
  1136. faceLength ++;
  1137. if ( endOfFace ) {
  1138. scope.genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength );
  1139. polygonIndex ++;
  1140. faceLength = 0;
  1141. // reset arrays for the next face
  1142. facePositionIndexes = [];
  1143. faceNormals = [];
  1144. faceColors = [];
  1145. faceUVs = [];
  1146. faceWeights = [];
  1147. faceWeightIndices = [];
  1148. }
  1149. } );
  1150. return buffers;
  1151. }
  1152. // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  1153. genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) {
  1154. for ( let i = 2; i < faceLength; i ++ ) {
  1155. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 0 ] ] );
  1156. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 1 ] ] );
  1157. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 2 ] ] );
  1158. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 ] ] );
  1159. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
  1160. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );
  1161. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 ] ] );
  1162. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 1 ] ] );
  1163. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 2 ] ] );
  1164. if ( geoInfo.skeleton ) {
  1165. buffers.vertexWeights.push( faceWeights[ 0 ] );
  1166. buffers.vertexWeights.push( faceWeights[ 1 ] );
  1167. buffers.vertexWeights.push( faceWeights[ 2 ] );
  1168. buffers.vertexWeights.push( faceWeights[ 3 ] );
  1169. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 ] );
  1170. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
  1171. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
  1172. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );
  1173. buffers.vertexWeights.push( faceWeights[ i * 4 ] );
  1174. buffers.vertexWeights.push( faceWeights[ i * 4 + 1 ] );
  1175. buffers.vertexWeights.push( faceWeights[ i * 4 + 2 ] );
  1176. buffers.vertexWeights.push( faceWeights[ i * 4 + 3 ] );
  1177. buffers.weightsIndices.push( faceWeightIndices[ 0 ] );
  1178. buffers.weightsIndices.push( faceWeightIndices[ 1 ] );
  1179. buffers.weightsIndices.push( faceWeightIndices[ 2 ] );
  1180. buffers.weightsIndices.push( faceWeightIndices[ 3 ] );
  1181. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
  1182. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
  1183. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
  1184. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );
  1185. buffers.weightsIndices.push( faceWeightIndices[ i * 4 ] );
  1186. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 1 ] );
  1187. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 2 ] );
  1188. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 3 ] );
  1189. }
  1190. if ( geoInfo.color ) {
  1191. buffers.colors.push( faceColors[ 0 ] );
  1192. buffers.colors.push( faceColors[ 1 ] );
  1193. buffers.colors.push( faceColors[ 2 ] );
  1194. buffers.colors.push( faceColors[ ( i - 1 ) * 3 ] );
  1195. buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
  1196. buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 2 ] );
  1197. buffers.colors.push( faceColors[ i * 3 ] );
  1198. buffers.colors.push( faceColors[ i * 3 + 1 ] );
  1199. buffers.colors.push( faceColors[ i * 3 + 2 ] );
  1200. }
  1201. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  1202. buffers.materialIndex.push( materialIndex );
  1203. buffers.materialIndex.push( materialIndex );
  1204. buffers.materialIndex.push( materialIndex );
  1205. }
  1206. if ( geoInfo.normal ) {
  1207. buffers.normal.push( faceNormals[ 0 ] );
  1208. buffers.normal.push( faceNormals[ 1 ] );
  1209. buffers.normal.push( faceNormals[ 2 ] );
  1210. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 ] );
  1211. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
  1212. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );
  1213. buffers.normal.push( faceNormals[ i * 3 ] );
  1214. buffers.normal.push( faceNormals[ i * 3 + 1 ] );
  1215. buffers.normal.push( faceNormals[ i * 3 + 2 ] );
  1216. }
  1217. if ( geoInfo.uv ) {
  1218. geoInfo.uv.forEach( function ( uv, j ) {
  1219. if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = [];
  1220. buffers.uvs[ j ].push( faceUVs[ j ][ 0 ] );
  1221. buffers.uvs[ j ].push( faceUVs[ j ][ 1 ] );
  1222. buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
  1223. buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );
  1224. buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 ] );
  1225. buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );
  1226. } );
  1227. }
  1228. }
  1229. }
  1230. addMorphTargets( parentGeo, parentGeoNode, morphTargets, preTransform ) {
  1231. if ( morphTargets.length === 0 ) return;
  1232. parentGeo.morphTargetsRelative = true;
  1233. parentGeo.morphAttributes.position = [];
  1234. // parentGeo.morphAttributes.normal = []; // not implemented
  1235. const scope = this;
  1236. morphTargets.forEach( function ( morphTarget ) {
  1237. morphTarget.rawTargets.forEach( function ( rawTarget ) {
  1238. const morphGeoNode = fbxTree.Objects.Geometry[ rawTarget.geoID ];
  1239. if ( morphGeoNode !== undefined ) {
  1240. scope.genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform, rawTarget.name );
  1241. }
  1242. } );
  1243. } );
  1244. }
  1245. // a morph geometry node is similar to a standard node, and the node is also contained
  1246. // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  1247. // and a special attribute Index defining which vertices of the original geometry are affected
  1248. // Normal and position attributes only have data for the vertices that are affected by the morph
  1249. genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform, name ) {
  1250. const vertexIndices = ( parentGeoNode.PolygonVertexIndex !== undefined ) ? parentGeoNode.PolygonVertexIndex.a : [];
  1251. const morphPositionsSparse = ( morphGeoNode.Vertices !== undefined ) ? morphGeoNode.Vertices.a : [];
  1252. const indices = ( morphGeoNode.Indexes !== undefined ) ? morphGeoNode.Indexes.a : [];
  1253. const length = parentGeo.attributes.position.count * 3;
  1254. const morphPositions = new Float32Array( le