FBXLoader.js 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582
  1. /**
  2. * @author Kyle-Larson https://github.com/Kyle-Larson
  3. * @author Takahiro https://github.com/takahirox
  4. * @author Lewy Blue https://github.com/looeee
  5. *
  6. * Loader loads FBX file and generates Group representing FBX scene.
  7. * Requires FBX file to be >= 7.0 and in ASCII or to be any version in Binary format.
  8. *
  9. * Supports:
  10. * Mesh Generation (Positional Data)
  11. * Normal Data (Per Vertex Drawing Instance)
  12. * UV Data (Per Vertex Drawing Instance)
  13. * Skinning
  14. * Animation
  15. * - Separated Animations based on stacks.
  16. * - Skeletal & Non-Skeletal Animations
  17. * NURBS (Open, Closed and Periodic forms)
  18. *
  19. * Needs Support:
  20. * Euler rotation order
  21. *
  22. *
  23. * FBX format references:
  24. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  25. *
  26. * Binary format specification:
  27. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  28. * https://wiki.rogiken.org/specifications/file-format/fbx/ (more detail but Japanese)
  29. */
  30. ( function () {
  31. THREE.FBXLoader = function ( manager ) {
  32. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  33. };
  34. Object.assign( THREE.FBXLoader.prototype, {
  35. load: function ( url, onLoad, onProgress, onError ) {
  36. var self = this;
  37. var resourceDirectory = THREE.LoaderUtils.extractUrlBase( url );
  38. var loader = new THREE.FileLoader( this.manager );
  39. loader.setResponseType( 'arraybuffer' );
  40. loader.load( url, function ( buffer ) {
  41. try {
  42. var scene = self.parse( buffer, resourceDirectory );
  43. onLoad( scene );
  44. } catch ( error ) {
  45. window.setTimeout( function () {
  46. if ( onError ) onError( error );
  47. self.manager.itemError( url );
  48. }, 0 );
  49. }
  50. }, onProgress, onError );
  51. },
  52. parse: function ( FBXBuffer, resourceDirectory ) {
  53. var FBXTree;
  54. if ( isFbxFormatBinary( FBXBuffer ) ) {
  55. FBXTree = new BinaryParser().parse( FBXBuffer );
  56. } else {
  57. var FBXText = convertArrayBufferToString( FBXBuffer );
  58. if ( ! isFbxFormatASCII( FBXText ) ) {
  59. throw new Error( 'THREE.FBXLoader: Unknown format.' );
  60. }
  61. if ( getFbxVersion( FBXText ) < 7000 ) {
  62. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
  63. }
  64. FBXTree = new TextParser().parse( FBXText );
  65. }
  66. console.log( FBXTree.Objects );
  67. var connections = parseConnections( FBXTree );
  68. var images = parseImages( FBXTree );
  69. var textures = parseTextures( FBXTree, new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ), images, connections );
  70. var materials = parseMaterials( FBXTree, textures, connections );
  71. var deformers = parseDeformers( FBXTree, connections );
  72. console.log( 'deformers', deformers );
  73. var geometryMap = parseGeometries( FBXTree, connections, deformers );
  74. var sceneGraph = parseScene( FBXTree, connections, deformers.skeletons, geometryMap, materials );
  75. return sceneGraph;
  76. }
  77. } );
  78. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  79. // and details the connection type
  80. function parseConnections( FBXTree ) {
  81. var connectionMap = new Map();
  82. if ( 'Connections' in FBXTree ) {
  83. var rawConnections = FBXTree.Connections.connections;
  84. rawConnections.forEach( function ( rawConnection ) {
  85. var fromID = rawConnection[ 0 ];
  86. var toID = rawConnection[ 1 ];
  87. var relationship = rawConnection[ 2 ];
  88. if ( ! connectionMap.has( fromID ) ) {
  89. connectionMap.set( fromID, {
  90. parents: [],
  91. children: []
  92. } );
  93. }
  94. var parentRelationship = { ID: toID, relationship: relationship };
  95. connectionMap.get( fromID ).parents.push( parentRelationship );
  96. if ( ! connectionMap.has( toID ) ) {
  97. connectionMap.set( toID, {
  98. parents: [],
  99. children: []
  100. } );
  101. }
  102. var childRelationship = { ID: fromID, relationship: relationship };
  103. connectionMap.get( toID ).children.push( childRelationship );
  104. } );
  105. }
  106. return connectionMap;
  107. }
  108. // Parse FBXTree.Objects.Video for embedded image data
  109. // These images are connected to textures in FBXTree.Objects.Textures
  110. // via FBXTree.Connections.
  111. function parseImages( FBXTree ) {
  112. var images = {};
  113. var blobs = {};
  114. if ( 'Video' in FBXTree.Objects ) {
  115. var videoNodes = FBXTree.Objects.Video;
  116. for ( var nodeID in videoNodes ) {
  117. var videoNode = videoNodes[ nodeID ];
  118. var id = parseInt( nodeID );
  119. images[ id ] = videoNode.Filename;
  120. // raw image data is in videoNode.Content
  121. if ( 'Content' in videoNode ) {
  122. var arrayBufferContent = ( videoNode.Content instanceof ArrayBuffer ) && ( videoNode.Content.byteLength > 0 );
  123. var base64Content = ( typeof videoNode.Content === 'string' ) && ( videoNode.Content !== '' );
  124. if ( arrayBufferContent || base64Content ) {
  125. var image = parseImage( videoNodes[ nodeID ] );
  126. blobs[ videoNode.Filename ] = image;
  127. }
  128. }
  129. }
  130. }
  131. for ( var id in images ) {
  132. var filename = images[ id ];
  133. if ( blobs[ filename ] !== undefined ) images[ id ] = blobs[ filename ];
  134. else images[ id ] = images[ id ].split( '\\' ).pop();
  135. }
  136. return images;
  137. }
  138. // Parse embedded image data in FBXTree.Video.Content
  139. function parseImage( videoNode ) {
  140. var content = videoNode.Content;
  141. var fileName = videoNode.RelativeFilename || videoNode.Filename;
  142. var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  143. var type;
  144. switch ( extension ) {
  145. case 'bmp':
  146. type = 'image/bmp';
  147. break;
  148. case 'jpg':
  149. case 'jpeg':
  150. type = 'image/jpeg';
  151. break;
  152. case 'png':
  153. type = 'image/png';
  154. break;
  155. case 'tif':
  156. type = 'image/tiff';
  157. break;
  158. default:
  159. console.warn( 'FBXLoader: Image type "' + extension + '" is not supported.' );
  160. return;
  161. }
  162. if ( typeof content === 'string' ) { // ASCII format
  163. return 'data:' + type + ';base64,' + content;
  164. } else { // Binary Format
  165. var array = new Uint8Array( content );
  166. return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
  167. }
  168. }
  169. // Parse nodes in FBXTree.Objects.Texture
  170. // These contain details such as UV scaling, cropping, rotation etc and are connected
  171. // to images in FBXTree.Objects.Video
  172. function parseTextures( FBXTree, loader, images, connections ) {
  173. var textureMap = new Map();
  174. if ( 'Texture' in FBXTree.Objects ) {
  175. var textureNodes = FBXTree.Objects.Texture;
  176. for ( var nodeID in textureNodes ) {
  177. var texture = parseTexture( textureNodes[ nodeID ], loader, images, connections );
  178. textureMap.set( parseInt( nodeID ), texture );
  179. }
  180. }
  181. return textureMap;
  182. }
  183. // Parse individual node in FBXTree.Objects.Texture
  184. function parseTexture( textureNode, loader, images, connections ) {
  185. var texture = loadTexture( textureNode, loader, images, connections );
  186. texture.ID = textureNode.id;
  187. texture.name = textureNode.attrName;
  188. var wrapModeU = textureNode.WrapModeU;
  189. var wrapModeV = textureNode.WrapModeV;
  190. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  191. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  192. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  193. // 0: repeat(default), 1: clamp
  194. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  195. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  196. if ( 'Scaling' in textureNode ) {
  197. var values = textureNode.Scaling.value;
  198. texture.repeat.x = values[ 0 ];
  199. texture.repeat.y = values[ 1 ];
  200. }
  201. return texture;
  202. }
  203. // load a texture specified as a blob or data URI, or via an external URL using THREE.TextureLoader
  204. function loadTexture( textureNode, loader, images, connections ) {
  205. var fileName;
  206. var currentPath = loader.path;
  207. var children = connections.get( textureNode.id ).children;
  208. if ( children !== undefined && children.length > 0 && images[ children[ 0 ].ID ] !== undefined ) {
  209. fileName = images[ children[ 0 ].ID ];
  210. if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
  211. loader.setPath( undefined );
  212. }
  213. }
  214. var texture = loader.load( fileName );
  215. loader.setPath( currentPath );
  216. return texture;
  217. }
  218. // Parse nodes in FBXTree.Objects.Material
  219. function parseMaterials( FBXTree, textureMap, connections ) {
  220. var materialMap = new Map();
  221. if ( 'Material' in FBXTree.Objects ) {
  222. var materialNodes = FBXTree.Objects.Material;
  223. for ( var nodeID in materialNodes ) {
  224. var material = parseMaterial( FBXTree, materialNodes[ nodeID ], textureMap, connections );
  225. if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
  226. }
  227. }
  228. return materialMap;
  229. }
  230. // Parse single node in FBXTree.Objects.Material
  231. // Materials are connected to texture maps in FBXTree.Objects.Textures
  232. // FBX format currently only supports Lambert and Phong shading models
  233. function parseMaterial( FBXTree, materialNode, textureMap, connections ) {
  234. var ID = materialNode.id;
  235. var name = materialNode.attrName;
  236. var type = materialNode.ShadingModel;
  237. //Case where FBX wraps shading model in property object.
  238. if ( typeof type === 'object' ) {
  239. type = type.value;
  240. }
  241. // Ignore unused materials which don't have any connections.
  242. if ( ! connections.has( ID ) ) return null;
  243. var parameters = parseParameters( FBXTree, materialNode, textureMap, ID, connections );
  244. var material;
  245. switch ( type.toLowerCase() ) {
  246. case 'phong':
  247. material = new THREE.MeshPhongMaterial();
  248. break;
  249. case 'lambert':
  250. material = new THREE.MeshLambertMaterial();
  251. break;
  252. default:
  253. console.warn( 'THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type );
  254. material = new THREE.MeshPhongMaterial( { color: 0x3300ff } );
  255. break;
  256. }
  257. material.setValues( parameters );
  258. material.name = name;
  259. return material;
  260. }
  261. // Parse FBX material and return parameters suitable for a three.js material
  262. // Also parse the texture map and return any textures associated with the material
  263. function parseParameters( FBXTree, properties, textureMap, ID, connections ) {
  264. var parameters = {};
  265. if ( properties.BumpFactor ) {
  266. parameters.bumpScale = properties.BumpFactor.value;
  267. }
  268. if ( properties.Diffuse ) {
  269. parameters.color = new THREE.Color().fromArray( properties.Diffuse.value );
  270. } else if ( properties.DiffuseColor && properties.DiffuseColor.type === 'Color' ) {
  271. // The blender exporter exports diffuse here instead of in properties.Diffuse
  272. parameters.color = new THREE.Color().fromArray( properties.DiffuseColor.value );
  273. }
  274. if ( properties.DisplacementFactor ) {
  275. parameters.displacementScale = properties.DisplacementFactor.value;
  276. }
  277. if ( properties.Emissive ) {
  278. parameters.emissive = new THREE.Color().fromArray( properties.Emissive.value );
  279. } else if ( properties.EmissiveColor && properties.EmissiveColor.type === 'Color' ) {
  280. // The blender exporter exports emissive color here instead of in properties.Emissive
  281. parameters.emissive = new THREE.Color().fromArray( properties.EmissiveColor.value );
  282. }
  283. if ( properties.EmissiveFactor ) {
  284. parameters.emissiveIntensity = parseFloat( properties.EmissiveFactor.value );
  285. }
  286. if ( properties.Opacity ) {
  287. parameters.opacity = parseFloat( properties.Opacity.value );
  288. }
  289. if ( parameters.opacity < 1.0 ) {
  290. parameters.transparent = true;
  291. }
  292. if ( properties.ReflectionFactor ) {
  293. parameters.reflectivity = properties.ReflectionFactor.value;
  294. }
  295. if ( properties.Shininess ) {
  296. parameters.shininess = properties.Shininess.value;
  297. }
  298. if ( properties.Specular ) {
  299. parameters.specular = new THREE.Color().fromArray( properties.Specular.value );
  300. } else if ( properties.SpecularColor && properties.SpecularColor.type === 'Color' ) {
  301. // The blender exporter exports specular color here instead of in properties.Specular
  302. parameters.specular = new THREE.Color().fromArray( properties.SpecularColor.value );
  303. }
  304. connections.get( ID ).children.forEach( function ( child ) {
  305. var type = child.relationship;
  306. switch ( type ) {
  307. case 'Bump':
  308. parameters.bumpMap = textureMap.get( child.ID );
  309. break;
  310. case 'DiffuseColor':
  311. parameters.map = getTexture( FBXTree, textureMap, child.ID, connections );
  312. break;
  313. case 'DisplacementColor':
  314. parameters.displacementMap = getTexture( FBXTree, textureMap, child.ID, connections );
  315. break;
  316. case 'EmissiveColor':
  317. parameters.emissiveMap = getTexture( FBXTree, textureMap, child.ID, connections );
  318. break;
  319. case 'NormalMap':
  320. parameters.normalMap = getTexture( FBXTree, textureMap, child.ID, connections );
  321. break;
  322. case 'ReflectionColor':
  323. parameters.envMap = getTexture( FBXTree, textureMap, child.ID, connections );
  324. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  325. break;
  326. case 'SpecularColor':
  327. parameters.specularMap = getTexture( FBXTree, textureMap, child.ID, connections );
  328. break;
  329. case 'TransparentColor':
  330. parameters.alphaMap = getTexture( FBXTree, textureMap, child.ID, connections );
  331. parameters.transparent = true;
  332. break;
  333. case 'AmbientColor':
  334. case 'ShininessExponent': // AKA glossiness map
  335. case 'SpecularFactor': // AKA specularLevel
  336. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  337. default:
  338. console.warn( 'THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type );
  339. break;
  340. }
  341. } );
  342. return parameters;
  343. }
  344. // get a texture from the textureMap for use by a material.
  345. function getTexture( FBXTree, textureMap, id, connections ) {
  346. // if the texture is a layered texture, just use the first layer and issue a warning
  347. if ( 'LayeredTexture' in FBXTree.Objects && id in FBXTree.Objects.LayeredTexture ) {
  348. console.warn( 'THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.' );
  349. id = connections.get( id ).children[ 0 ].ID;
  350. }
  351. return textureMap.get( id );
  352. }
  353. // Parse nodes in FBXTree.Objects.Deformer
  354. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  355. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  356. function parseDeformers( FBXTree, connections ) {
  357. var skeletons = {};
  358. var morphTargets = {};
  359. if ( 'Deformer' in FBXTree.Objects ) {
  360. var DeformerNodes = FBXTree.Objects.Deformer;
  361. for ( var nodeID in DeformerNodes ) {
  362. var deformerNode = DeformerNodes[ nodeID ];
  363. var relationships = connections.get( parseInt( nodeID ) );
  364. if ( deformerNode.attrType === 'Skin' ) {
  365. var skeleton = parseSkeleton( relationships, DeformerNodes );
  366. skeleton.ID = nodeID;
  367. if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: skeleton attached to more than one geometry is not supported.' );
  368. skeleton.geometryID = relationships.parents[ 0 ].ID;
  369. skeletons[ nodeID ] = skeleton;
  370. } else if ( deformerNode.attrType === 'BlendShape' ) {
  371. var morphTarget = parseMorphTargets( relationships, deformerNode, DeformerNodes, connections, FBXTree );
  372. morphTarget.id = nodeID;
  373. if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: morph target attached to more than one geometry is not supported.' );
  374. morphTarget.parentID = relationships.parents[ 0 ].ID;
  375. morphTargets[ nodeID ] = morphTarget;
  376. }
  377. }
  378. }
  379. return {
  380. skeletons: skeletons,
  381. morphTargets: morphTargets,
  382. };
  383. }
  384. // Parse single nodes in FBXTree.Objects.Deformer
  385. // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
  386. // Each skin node represents a skeleton and each cluster node represents a bone
  387. function parseSkeleton( connections, deformerNodes ) {
  388. var rawBones = [];
  389. connections.children.forEach( function ( child ) {
  390. var boneNode = deformerNodes[ child.ID ];
  391. if ( boneNode.attrType !== 'Cluster' ) return;
  392. var rawBone = {
  393. ID: child.ID,
  394. indices: [],
  395. weights: [],
  396. transform: new THREE.Matrix4().fromArray( boneNode.Transform.a ),
  397. transformLink: new THREE.Matrix4().fromArray( boneNode.TransformLink.a ),
  398. linkMode: boneNode.Mode,
  399. };
  400. if ( 'Indexes' in boneNode ) {
  401. rawBone.indices = boneNode.Indexes.a;
  402. rawBone.weights = boneNode.Weights.a;
  403. }
  404. rawBones.push( rawBone );
  405. } );
  406. return {
  407. rawBones: rawBones,
  408. bones: []
  409. };
  410. }
  411. // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
  412. function parseMorphTargets( relationships, deformerNode, deformerNodes, connections ) {
  413. var rawMorphTargets = [];
  414. relationships.children.forEach( function ( child ) {
  415. var morphTargetNode = deformerNodes[ child.ID ];
  416. var rawMorphTarget = {
  417. name: morphTargetNode.attrName,
  418. initialWeight: morphTargetNode.DeformPercent,
  419. id: morphTargetNode.id,
  420. fullWeights: morphTargetNode.FullWeights.a
  421. };
  422. if ( morphTargetNode.attrType !== 'BlendShapeChannel' ) return;
  423. var targetRelationships = connections.get( parseInt( child.ID ) );
  424. targetRelationships.children.forEach( function ( child ) {
  425. if ( child.relationship === 'DeformPercent' ) {
  426. rawMorphTarget.weightCurveID = child.ID;
  427. // FBXTree.Objects.AnimationCurveNode[ child.ID ];
  428. } else {
  429. rawMorphTarget.geoID = child.ID;
  430. // FBXTree.Objects.Geometry[ child.ID ];
  431. }
  432. } );
  433. rawMorphTargets.push( rawMorphTarget );
  434. } );
  435. return rawMorphTargets;
  436. }
  437. // Parse nodes in FBXTree.Objects.Geometry
  438. function parseGeometries( FBXTree, connections, deformers ) {
  439. var geometryMap = new Map();
  440. if ( 'Geometry' in FBXTree.Objects ) {
  441. var geometryNodes = FBXTree.Objects.Geometry;
  442. for ( var nodeID in geometryNodes ) {
  443. var relationships = connections.get( parseInt( nodeID ) );
  444. var geo = parseGeometry( FBXTree, relationships, geometryNodes[ nodeID ], deformers );
  445. geometryMap.set( parseInt( nodeID ), geo );
  446. }
  447. }
  448. return geometryMap;
  449. }
  450. // Parse single node in FBXTree.Objects.Geometry
  451. function parseGeometry( FBXTree, relationships, geometryNode, deformers ) {
  452. switch ( geometryNode.attrType ) {
  453. case 'Mesh':
  454. return parseMeshGeometry( FBXTree, relationships, geometryNode, deformers );
  455. break;
  456. case 'NurbsCurve':
  457. return parseNurbsGeometry( geometryNode );
  458. break;
  459. }
  460. }
  461. // Parse single node mesh geometry in FBXTree.Objects.Geometry
  462. function parseMeshGeometry( FBXTree, relationships, geometryNode, deformers ) {
  463. var skeletons = deformers.skeletons;
  464. var morphTargets = deformers.morphTargets;
  465. var modelNodes = relationships.parents.map( function ( parent ) {
  466. return FBXTree.Objects.Model[ parent.ID ];
  467. } );
  468. // don't create geometry if it is not associated with any models
  469. if ( modelNodes.length === 0 ) return;
  470. var skeleton = relationships.children.reduce( function ( skeleton, child ) {
  471. if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ];
  472. return skeleton;
  473. }, null );
  474. var morphTarget = relationships.children.reduce( function ( morphTarget, child ) {
  475. if ( morphTargets[ child.ID ] !== undefined ) morphTarget = morphTargets[ child.ID ];
  476. return morphTarget;
  477. }, null );
  478. var preTransform = new THREE.Matrix4();
  479. // TODO: if there is more than one model associated with the geometry, AND the models have
  480. // different geometric transforms, then this will cause problems
  481. // if ( modelNodes.length > 1 ) { }
  482. // For now just assume one model and get the preRotations from that
  483. var modelNode = modelNodes[ 0 ];
  484. if ( 'GeometricRotation' in modelNode ) {
  485. var array = modelNode.GeometricRotation.value.map( THREE.Math.degToRad );
  486. array[ 3 ] = 'ZYX';
  487. preTransform.makeRotationFromEuler( new THREE.Euler().fromArray( array ) );
  488. }
  489. if ( 'GeometricTranslation' in modelNode ) {
  490. preTransform.setPosition( new THREE.Vector3().fromArray( modelNode.GeometricTranslation.value ) );
  491. }
  492. if ( 'GeometricScaling' in modelNode ) {
  493. preTransform.scale( new THREE.Vector3().fromArray( modelNode.GeometricScaling.value ) );
  494. }
  495. return genGeometry( FBXTree, geometryNode, skeleton, morphTarget, preTransform );
  496. }
  497. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry
  498. function genGeometry( FBXTree, geometryNode, skeleton, morphTarget, preTransform ) {
  499. var vertexPositions = geometryNode.Vertices.a;
  500. var vertexIndices = geometryNode.PolygonVertexIndex.a;
  501. // create arrays to hold the final data used to build the buffergeometry
  502. var vertexBuffer = [];
  503. var normalBuffer = [];
  504. var colorsBuffer = [];
  505. var uvsBuffer = [];
  506. var materialIndexBuffer = [];
  507. var vertexWeightsBuffer = [];
  508. var weightsIndicesBuffer = [];
  509. if ( geometryNode.LayerElementColor ) {
  510. var colorInfo = getColors( geometryNode.LayerElementColor[ 0 ] );
  511. }
  512. if ( geometryNode.LayerElementMaterial ) {
  513. var materialInfo = getMaterials( geometryNode.LayerElementMaterial[ 0 ] );
  514. }
  515. if ( geometryNode.LayerElementNormal ) {
  516. var normalInfo = getNormals( geometryNode.LayerElementNormal[ 0 ] );
  517. }
  518. if ( geometryNode.LayerElementUV ) {
  519. var uvInfo = [];
  520. var i = 0;
  521. while ( geometryNode.LayerElementUV[ i ] ) {
  522. uvInfo.push( getUVs( geometryNode.LayerElementUV[ i ] ) );
  523. i ++;
  524. }
  525. }
  526. var weightTable = {};
  527. if ( skeleton !== null ) {
  528. skeleton.rawBones.forEach( function ( rawBone, i ) {
  529. // loop over the bone's vertex indices and weights
  530. rawBone.indices.forEach( function ( index, j ) {
  531. if ( weightTable[ index ] === undefined ) weightTable[ index ] = [];
  532. weightTable[ index ].push( {
  533. id: i,
  534. weight: rawBone.weights[ j ],
  535. } );
  536. } );
  537. } );
  538. }
  539. var polygonIndex = 0;
  540. var faceLength = 0;
  541. var displayedWeightsWarning = false;
  542. // these will hold data for a single face
  543. var vertexPositionIndexes = [];
  544. var faceNormals = [];
  545. var faceColors = [];
  546. var faceUVs = [];
  547. var faceWeights = [];
  548. var faceWeightIndices = [];
  549. vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) {
  550. var endOfFace = false;
  551. // Face index and vertex index arrays are combined in a single array
  552. // A cube with quad faces looks like this:
  553. // PolygonVertexIndex: *24 {
  554. // 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
  555. // }
  556. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  557. // to find index of last vertex multiply by -1 and subtract 1: -3 * - 1 - 1 = 2
  558. if ( vertexIndex < 0 ) {
  559. vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
  560. vertexIndices[ polygonVertexIndex ] = vertexIndex;
  561. endOfFace = true;
  562. }
  563. var weightIndices = [];
  564. var weights = [];
  565. vertexPositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
  566. if ( colorInfo ) {
  567. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, colorInfo );
  568. faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  569. }
  570. if ( skeleton ) {
  571. if ( weightTable[ vertexIndex ] !== undefined ) {
  572. weightTable[ vertexIndex ].forEach( function ( wt ) {
  573. weights.push( wt.weight );
  574. weightIndices.push( wt.id );
  575. } );
  576. }
  577. if ( weights.length > 4 ) {
  578. if ( ! displayedWeightsWarning ) {
  579. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  580. displayedWeightsWarning = true;
  581. }
  582. var wIndex = [ 0, 0, 0, 0 ];
  583. var Weight = [ 0, 0, 0, 0 ];
  584. weights.forEach( function ( weight, weightIndex ) {
  585. var currentWeight = weight;
  586. var currentIndex = weightIndices[ weightIndex ];
  587. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  588. if ( currentWeight > comparedWeight ) {
  589. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  590. currentWeight = comparedWeight;
  591. var tmp = wIndex[ comparedWeightIndex ];
  592. wIndex[ comparedWeightIndex ] = currentIndex;
  593. currentIndex = tmp;
  594. }
  595. } );
  596. } );
  597. weightIndices = wIndex;
  598. weights = Weight;
  599. }
  600. // if the weight array is shorter than 4 pad with 0s
  601. while ( weights.length < 4 ) {
  602. weights.push( 0 );
  603. weightIndices.push( 0 );
  604. }
  605. for ( var i = 0; i < 4; ++ i ) {
  606. faceWeights.push( weights[ i ] );
  607. faceWeightIndices.push( weightIndices[ i ] );
  608. }
  609. }
  610. if ( normalInfo ) {
  611. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo );
  612. faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  613. }
  614. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  615. var materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo )[ 0 ];
  616. }
  617. if ( uvInfo ) {
  618. uvInfo.forEach( function ( uv, i ) {
  619. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv );
  620. if ( faceUVs[ i ] === undefined ) {
  621. faceUVs[ i ] = [];
  622. }
  623. faceUVs[ i ].push( data[ 0 ] );
  624. faceUVs[ i ].push( data[ 1 ] );
  625. } );
  626. }
  627. faceLength ++;
  628. // we have reached the end of a face - it may have 4 sides though
  629. // in which case the data is split to represent two 3 sided faces
  630. if ( endOfFace ) {
  631. for ( var i = 2; i < faceLength; i ++ ) {
  632. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 0 ] ] );
  633. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 1 ] ] );
  634. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 2 ] ] );
  635. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 ] ] );
  636. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
  637. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );
  638. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 ] ] );
  639. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 + 1 ] ] );
  640. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 + 2 ] ] );
  641. if ( skeleton ) {
  642. vertexWeightsBuffer.push( faceWeights[ 0 ] );
  643. vertexWeightsBuffer.push( faceWeights[ 1 ] );
  644. vertexWeightsBuffer.push( faceWeights[ 2 ] );
  645. vertexWeightsBuffer.push( faceWeights[ 3 ] );
  646. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 ] );
  647. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
  648. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
  649. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );
  650. vertexWeightsBuffer.push( faceWeights[ i * 4 ] );
  651. vertexWeightsBuffer.push( faceWeights[ i * 4 + 1 ] );
  652. vertexWeightsBuffer.push( faceWeights[ i * 4 + 2 ] );
  653. vertexWeightsBuffer.push( faceWeights[ i * 4 + 3 ] );
  654. weightsIndicesBuffer.push( faceWeightIndices[ 0 ] );
  655. weightsIndicesBuffer.push( faceWeightIndices[ 1 ] );
  656. weightsIndicesBuffer.push( faceWeightIndices[ 2 ] );
  657. weightsIndicesBuffer.push( faceWeightIndices[ 3 ] );
  658. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
  659. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
  660. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
  661. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );
  662. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 ] );
  663. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 1 ] );
  664. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 2 ] );
  665. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 3 ] );
  666. }
  667. if ( colorInfo ) {
  668. colorsBuffer.push( faceColors[ 0 ] );
  669. colorsBuffer.push( faceColors[ 1 ] );
  670. colorsBuffer.push( faceColors[ 2 ] );
  671. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 ] );
  672. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
  673. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 + 2 ] );
  674. colorsBuffer.push( faceColors[ i * 3 ] );
  675. colorsBuffer.push( faceColors[ i * 3 + 1 ] );
  676. colorsBuffer.push( faceColors[ i * 3 + 2 ] );
  677. }
  678. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  679. materialIndexBuffer.push( materialIndex );
  680. materialIndexBuffer.push( materialIndex );
  681. materialIndexBuffer.push( materialIndex );
  682. }
  683. if ( normalInfo ) {
  684. normalBuffer.push( faceNormals[ 0 ] );
  685. normalBuffer.push( faceNormals[ 1 ] );
  686. normalBuffer.push( faceNormals[ 2 ] );
  687. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 ] );
  688. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
  689. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );
  690. normalBuffer.push( faceNormals[ i * 3 ] );
  691. normalBuffer.push( faceNormals[ i * 3 + 1 ] );
  692. normalBuffer.push( faceNormals[ i * 3 + 2 ] );
  693. }
  694. if ( uvInfo ) {
  695. uvInfo.forEach( function ( uv, j ) {
  696. if ( uvsBuffer[ j ] === undefined ) uvsBuffer[ j ] = [];
  697. uvsBuffer[ j ].push( faceUVs[ j ][ 0 ] );
  698. uvsBuffer[ j ].push( faceUVs[ j ][ 1 ] );
  699. uvsBuffer[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
  700. uvsBuffer[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );
  701. uvsBuffer[ j ].push( faceUVs[ j ][ i * 2 ] );
  702. uvsBuffer[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );
  703. } );
  704. }
  705. }
  706. polygonIndex ++;
  707. faceLength = 0;
  708. // reset arrays for the next face
  709. vertexPositionIndexes = [];
  710. faceNormals = [];
  711. faceColors = [];
  712. faceUVs = [];
  713. faceWeights = [];
  714. faceWeightIndices = [];
  715. }
  716. } );
  717. var geo = new THREE.BufferGeometry();
  718. geo.name = geometryNode.name;
  719. var positionAttribute = new THREE.Float32BufferAttribute( vertexBuffer, 3 );
  720. preTransform.applyToBufferAttribute( positionAttribute );
  721. geo.addAttribute( 'position', positionAttribute );
  722. if ( colorsBuffer.length > 0 ) {
  723. geo.addAttribute( 'color', new THREE.Float32BufferAttribute( colorsBuffer, 3 ) );
  724. }
  725. if ( skeleton ) {
  726. geo.addAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( weightsIndicesBuffer, 4 ) );
  727. geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( vertexWeightsBuffer, 4 ) );
  728. // used later to bind the skeleton to the model
  729. geo.FBX_Deformer = skeleton;
  730. }
  731. if ( normalBuffer.length > 0 ) {
  732. var normalAttribute = new THREE.Float32BufferAttribute( normalBuffer, 3 );
  733. var normalMatrix = new THREE.Matrix3().getNormalMatrix( preTransform );
  734. normalMatrix.applyToBufferAttribute( normalAttribute );
  735. geo.addAttribute( 'normal', normalAttribute );
  736. }
  737. uvsBuffer.forEach( function ( uvBuffer, i ) {
  738. // subsequent uv buffers are called 'uv1', 'uv2', ...
  739. var name = 'uv' + ( i + 1 ).toString();
  740. // the first uv buffer is just called 'uv'
  741. if ( i === 0 ) {
  742. name = 'uv';
  743. }
  744. geo.addAttribute( name, new THREE.Float32BufferAttribute( uvsBuffer[ i ], 2 ) );
  745. } );
  746. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  747. // Convert the material indices of each vertex into rendering groups on the geometry.
  748. var prevMaterialIndex = materialIndexBuffer[ 0 ];
  749. var startIndex = 0;
  750. materialIndexBuffer.forEach( function ( currentIndex, i ) {
  751. if ( currentIndex !== prevMaterialIndex ) {
  752. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  753. prevMaterialIndex = currentIndex;
  754. startIndex = i;
  755. }
  756. } );
  757. // the loop above doesn't add the last group, do that here.
  758. if ( geo.groups.length > 0 ) {
  759. var lastGroup = geo.groups[ geo.groups.length - 1 ];
  760. var lastIndex = lastGroup.start + lastGroup.count;
  761. if ( lastIndex !== materialIndexBuffer.length ) {
  762. geo.addGroup( lastIndex, materialIndexBuffer.length - lastIndex, prevMaterialIndex );
  763. }
  764. }
  765. // case where there are multiple materials but the whole geometry is only
  766. // using one of them
  767. if ( geo.groups.length === 0 ) {
  768. geo.addGroup( 0, materialIndexBuffer.length, materialIndexBuffer[ 0 ] );
  769. }
  770. }
  771. return geo;
  772. }
  773. // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  774. function getNormals( NormalNode ) {
  775. var mappingType = NormalNode.MappingInformationType;
  776. var referenceType = NormalNode.ReferenceInformationType;
  777. var buffer = NormalNode.Normals.a;
  778. var indexBuffer = [];
  779. if ( referenceType === 'IndexToDirect' ) {
  780. if ( 'NormalIndex' in NormalNode ) {
  781. indexBuffer = NormalNode.NormalIndex.a;
  782. } else if ( 'NormalsIndex' in NormalNode ) {
  783. indexBuffer = NormalNode.NormalsIndex.a;
  784. }
  785. }
  786. return {
  787. dataSize: 3,
  788. buffer: buffer,
  789. indices: indexBuffer,
  790. mappingType: mappingType,
  791. referenceType: referenceType
  792. };
  793. }
  794. // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  795. function getUVs( UVNode ) {
  796. var mappingType = UVNode.MappingInformationType;
  797. var referenceType = UVNode.ReferenceInformationType;
  798. var buffer = UVNode.UV.a;
  799. var indexBuffer = [];
  800. if ( referenceType === 'IndexToDirect' ) {
  801. indexBuffer = UVNode.UVIndex.a;
  802. }
  803. return {
  804. dataSize: 2,
  805. buffer: buffer,
  806. indices: indexBuffer,
  807. mappingType: mappingType,
  808. referenceType: referenceType
  809. };
  810. }
  811. // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  812. function getColors( ColorNode ) {
  813. var mappingType = ColorNode.MappingInformationType;
  814. var referenceType = ColorNode.ReferenceInformationType;
  815. var buffer = ColorNode.Colors.a;
  816. var indexBuffer = [];
  817. if ( referenceType === 'IndexToDirect' ) {
  818. indexBuffer = ColorNode.ColorIndex.a;
  819. }
  820. return {
  821. dataSize: 4,
  822. buffer: buffer,
  823. indices: indexBuffer,
  824. mappingType: mappingType,
  825. referenceType: referenceType
  826. };
  827. }
  828. // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  829. function getMaterials( MaterialNode ) {
  830. var mappingType = MaterialNode.MappingInformationType;
  831. var referenceType = MaterialNode.ReferenceInformationType;
  832. if ( mappingType === 'NoMappingInformation' ) {
  833. return {
  834. dataSize: 1,
  835. buffer: [ 0 ],
  836. indices: [ 0 ],
  837. mappingType: 'AllSame',
  838. referenceType: referenceType
  839. };
  840. }
  841. var materialIndexBuffer = MaterialNode.Materials.a;
  842. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  843. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  844. // for conforming with the other functions we've written for other data.
  845. var materialIndices = [];
  846. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  847. materialIndices.push( i );
  848. }
  849. return {
  850. dataSize: 1,
  851. buffer: materialIndexBuffer,
  852. indices: materialIndices,
  853. mappingType: mappingType,
  854. referenceType: referenceType
  855. };
  856. }
  857. var dataArray = [];
  858. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  859. var index;
  860. switch ( infoObject.mappingType ) {
  861. case 'ByPolygonVertex' :
  862. index = polygonVertexIndex;
  863. break;
  864. case 'ByPolygon' :
  865. index = polygonIndex;
  866. break;
  867. case 'ByVertice' :
  868. index = vertexIndex;
  869. break;
  870. case 'AllSame' :
  871. index = infoObject.indices[ 0 ];
  872. break;
  873. default :
  874. console.warn( 'THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType );
  875. }
  876. if ( infoObject.referenceType === 'IndexToDirect' ) index = infoObject.indices[ index ];
  877. var from = index * infoObject.dataSize;
  878. var to = from + infoObject.dataSize;
  879. return slice( dataArray, infoObject.buffer, from, to );
  880. }
  881. // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  882. function parseNurbsGeometry( geometryNode ) {
  883. if ( THREE.NURBSCurve === undefined ) {
  884. console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  885. return new THREE.BufferGeometry();
  886. }
  887. var order = parseInt( geometryNode.Order );
  888. if ( isNaN( order ) ) {
  889. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geometryNode.Order, geometryNode.id );
  890. return new THREE.BufferGeometry();
  891. }
  892. var degree = order - 1;
  893. var knots = geometryNode.KnotVector.a;
  894. var controlPoints = [];
  895. var pointsValues = geometryNode.Points.a;
  896. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  897. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  898. }
  899. var startKnot, endKnot;
  900. if ( geometryNode.Form === 'Closed' ) {
  901. controlPoints.push( controlPoints[ 0 ] );
  902. } else if ( geometryNode.Form === 'Periodic' ) {
  903. startKnot = degree;
  904. endKnot = knots.length - 1 - startKnot;
  905. for ( var i = 0; i < degree; ++ i ) {
  906. controlPoints.push( controlPoints[ i ] );
  907. }
  908. }
  909. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  910. var vertices = curve.getPoints( controlPoints.length * 7 );
  911. var positions = new Float32Array( vertices.length * 3 );
  912. vertices.forEach( function ( vertex, i ) {
  913. vertex.toArray( positions, i * 3 );
  914. } );
  915. var geometry = new THREE.BufferGeometry();
  916. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  917. return geometry;
  918. }
  919. // create the main THREE.Group() to be returned by the loader
  920. function parseScene( FBXTree, connections, skeletons, geometryMap, materialMap ) {
  921. var sceneGraph = new THREE.Group();
  922. var modelMap = parseModels( FBXTree, skeletons, geometryMap, materialMap, connections );
  923. var modelNodes = FBXTree.Objects.Model;
  924. modelMap.forEach( function ( model ) {
  925. var modelNode = modelNodes[ model.ID ];
  926. setLookAtProperties( FBXTree, model, modelNode, connections, sceneGraph );
  927. var parentConnections = connections.get( model.ID ).parents;
  928. parentConnections.forEach( function ( connection ) {
  929. var parent = modelMap.get( connection.ID );
  930. if ( parent !== undefined ) parent.add( model );
  931. } );
  932. if ( model.parent === null ) {
  933. sceneGraph.add( model );
  934. }
  935. } );
  936. bindSkeleton( FBXTree, skeletons, geometryMap, modelMap, connections );
  937. addAnimations( FBXTree, connections, sceneGraph );
  938. createAmbientLight( FBXTree, sceneGraph );
  939. return sceneGraph;
  940. }
  941. // parse nodes in FBXTree.Objects.Model
  942. function parseModels( FBXTree, skeletons, geometryMap, materialMap, connections ) {
  943. var modelMap = new Map();
  944. var modelNodes = FBXTree.Objects.Model;
  945. for ( var nodeID in modelNodes ) {
  946. var id = parseInt( nodeID );
  947. var node = modelNodes[ nodeID ];
  948. var relationships = connections.get( id );
  949. var model = buildSkeleton( relationships, skeletons, id, node.attrName );
  950. if ( ! model ) {
  951. switch ( node.attrType ) {
  952. case 'Camera':
  953. model = createCamera( FBXTree, relationships );
  954. break;
  955. case 'Light':
  956. model = createLight( FBXTree, relationships );
  957. break;
  958. case 'Mesh':
  959. model = createMesh( FBXTree, relationships, geometryMap, materialMap );
  960. break;
  961. case 'NurbsCurve':
  962. model = createCurve( relationships, geometryMap );
  963. break;
  964. case 'LimbNode': // usually associated with a Bone, however if a Bone was not created we'll make a Group instead
  965. case 'Null':
  966. default:
  967. model = new THREE.Group();
  968. break;
  969. }
  970. model.name = THREE.PropertyBinding.sanitizeNodeName( node.attrName );
  971. model.ID = id;
  972. }
  973. setModelTransforms( FBXTree, model, node );
  974. modelMap.set( id, model );
  975. }
  976. return modelMap;
  977. }
  978. function buildSkeleton( relationships, skeletons, id, name ) {
  979. var bone = null;
  980. relationships.parents.forEach( function ( parent ) {
  981. for ( var ID in skeletons ) {
  982. var skeleton = skeletons[ ID ];
  983. skeleton.rawBones.forEach( function ( rawBone, i ) {
  984. if ( rawBone.ID === parent.ID ) {
  985. var subBone = bone;
  986. bone = new THREE.Bone();
  987. bone.matrixWorld.copy( rawBone.transformLink );
  988. // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  989. bone.name = THREE.PropertyBinding.sanitizeNodeName( name );
  990. bone.ID = id;
  991. skeleton.bones[ i ] = bone;
  992. // In cases where a bone is shared between multiple meshes
  993. // duplicate the bone here and and it as a child of the first bone
  994. if ( subBone !== null ) {
  995. bone.add( subBone );
  996. }
  997. }
  998. } );
  999. }
  1000. } );
  1001. return bone;
  1002. }
  1003. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  1004. function createCamera( FBXTree, relationships ) {
  1005. var model;
  1006. var cameraAttribute;
  1007. relationships.children.forEach( function ( child ) {
  1008. var attr = FBXTree.Objects.NodeAttribute[ child.ID ];
  1009. if ( attr !== undefined ) {
  1010. cameraAttribute = attr;
  1011. }
  1012. } );
  1013. if ( cameraAttribute === undefined ) {
  1014. model = new THREE.Object3D();
  1015. } else {
  1016. var type = 0;
  1017. if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
  1018. type = 1;
  1019. }
  1020. var nearClippingPlane = 1;
  1021. if ( cameraAttribute.NearPlane !== undefined ) {
  1022. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  1023. }
  1024. var farClippingPlane = 1000;
  1025. if ( cameraAttribute.FarPlane !== undefined ) {
  1026. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  1027. }
  1028. var width = window.innerWidth;
  1029. var height = window.innerHeight;
  1030. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  1031. width = cameraAttribute.AspectWidth.value;
  1032. height = cameraAttribute.AspectHeight.value;
  1033. }
  1034. var aspect = width / height;
  1035. var fov = 45;
  1036. if ( cameraAttribute.FieldOfView !== undefined ) {
  1037. fov = cameraAttribute.FieldOfView.value;
  1038. }
  1039. var focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
  1040. switch ( type ) {
  1041. case 0: // Perspective
  1042. model = new THREE.PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  1043. if ( focalLength !== null ) model.setFocalLength( focalLength );
  1044. break;
  1045. case 1: // Orthographic
  1046. model = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  1047. break;
  1048. default:
  1049. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  1050. model = new THREE.Object3D();
  1051. break;
  1052. }
  1053. }
  1054. return model;
  1055. }
  1056. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  1057. function createLight( FBXTree, relationships ) {
  1058. var model;
  1059. var lightAttribute;
  1060. relationships.children.forEach( function ( child ) {
  1061. var attr = FBXTree.Objects.NodeAttribute[ child.ID ];
  1062. if ( attr !== undefined ) {
  1063. lightAttribute = attr;
  1064. }
  1065. } );
  1066. if ( lightAttribute === undefined ) {
  1067. model = new THREE.Object3D();
  1068. } else {
  1069. var type;
  1070. // LightType can be undefined for Point lights
  1071. if ( lightAttribute.LightType === undefined ) {
  1072. type = 0;
  1073. } else {
  1074. type = lightAttribute.LightType.value;
  1075. }
  1076. var color = 0xffffff;
  1077. if ( lightAttribute.Color !== undefined ) {
  1078. color = new THREE.Color().fromArray( lightAttribute.Color.value );
  1079. }
  1080. var intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
  1081. // light disabled
  1082. if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
  1083. intensity = 0;
  1084. }
  1085. var distance = 0;
  1086. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  1087. if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
  1088. distance = 0;
  1089. } else {
  1090. distance = lightAttribute.FarAttenuationEnd.value;
  1091. }
  1092. }
  1093. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  1094. var decay = 1;
  1095. switch ( type ) {
  1096. case 0: // Point
  1097. model = new THREE.PointLight( color, intensity, distance, decay );
  1098. break;
  1099. case 1: // Directional
  1100. model = new THREE.DirectionalLight( color, intensity );
  1101. break;
  1102. case 2: // Spot
  1103. var angle = Math.PI / 3;
  1104. if ( lightAttribute.InnerAngle !== undefined ) {
  1105. angle = THREE.Math.degToRad( lightAttribute.InnerAngle.value );
  1106. }
  1107. var penumbra = 0;
  1108. if ( lightAttribute.OuterAngle !== undefined ) {
  1109. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  1110. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  1111. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  1112. penumbra = THREE.Math.degToRad( lightAttribute.OuterAngle.value );
  1113. penumbra = Math.max( penumbra, 1 );
  1114. }
  1115. model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
  1116. break;
  1117. default:
  1118. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
  1119. model = new THREE.PointLight( color, intensity );
  1120. break;
  1121. }
  1122. if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
  1123. model.castShadow = true;
  1124. }
  1125. }
  1126. return model;
  1127. }
  1128. function createMesh( FBXTree, relationships, geometryMap, materialMap ) {
  1129. var model;
  1130. var geometry = null;
  1131. var material = null;
  1132. var materials = [];
  1133. // get geometry and materials(s) from connections
  1134. relationships.children.forEach( function ( child ) {
  1135. if ( geometryMap.has( child.ID ) ) {
  1136. geometry = geometryMap.get( child.ID );
  1137. }
  1138. if ( materialMap.has( child.ID ) ) {
  1139. materials.push( materialMap.get( child.ID ) );
  1140. }
  1141. } );
  1142. if ( materials.length > 1 ) {
  1143. material = materials;
  1144. } else if ( materials.length > 0 ) {
  1145. material = materials[ 0 ];
  1146. } else {
  1147. material = new THREE.MeshPhongMaterial( { color: 0xcccccc } );
  1148. materials.push( material );
  1149. }
  1150. if ( 'color' in geometry.attributes ) {
  1151. materials.forEach( function ( material ) {
  1152. material.vertexColors = THREE.VertexColors;
  1153. } );
  1154. }
  1155. if ( geometry.FBX_Deformer ) {
  1156. materials.forEach( function ( material ) {
  1157. material.skinning = true;
  1158. } );
  1159. model = new THREE.SkinnedMesh( geometry, material );
  1160. } else {
  1161. model = new THREE.Mesh( geometry, material );
  1162. }
  1163. return model;
  1164. }
  1165. function createCurve( relationships, geometryMap ) {
  1166. var geometry = relationships.children.reduce( function ( geo, child ) {
  1167. if ( geometryMap.has( child.ID ) ) geo = geometryMap.get( child.ID );
  1168. return geo;
  1169. }, null );
  1170. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  1171. var material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 1 } );
  1172. return new THREE.Line( geometry, material );
  1173. }
  1174. // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  1175. function createAmbientLight( FBXTree, sceneGraph ) {
  1176. if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings ) {
  1177. var ambientColor = FBXTree.GlobalSettings.AmbientColor.value;
  1178. var r = ambientColor[ 0 ];
  1179. var g = ambientColor[ 1 ];
  1180. var b = ambientColor[ 2 ];
  1181. if ( r !== 0 || g !== 0 || b !== 0 ) {
  1182. var color = new THREE.Color( r, g, b );
  1183. sceneGraph.add( new THREE.AmbientLight( color, 1 ) );
  1184. }
  1185. }
  1186. }
  1187. function setLookAtProperties( FBXTree, model, modelNode, connections, sceneGraph ) {
  1188. if ( 'LookAtProperty' in modelNode ) {
  1189. var children = connections.get( model.ID ).children;
  1190. children.forEach( function ( child ) {
  1191. if ( child.relationship === 'LookAtProperty' ) {
  1192. var lookAtTarget = FBXTree.Objects.Model[ child.ID ];
  1193. if ( 'Lcl_Translation' in lookAtTarget ) {
  1194. var pos = lookAtTarget.Lcl_Translation.value;
  1195. // DirectionalLight, SpotLight
  1196. if ( model.target !== undefined ) {
  1197. model.target.position.fromArray( pos );
  1198. sceneGraph.add( model.target );
  1199. } else { // Cameras and other Object3Ds
  1200. model.lookAt( new THREE.Vector3().fromArray( pos ) );
  1201. }
  1202. }
  1203. }
  1204. } );
  1205. }
  1206. }
  1207. // parse the model node for transform details and apply them to the model
  1208. function setModelTransforms( FBXTree, model, modelNode ) {
  1209. // http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  1210. if ( 'RotationOrder' in modelNode ) {
  1211. var enums = [
  1212. 'XYZ', // default
  1213. 'XZY',
  1214. 'YZX',
  1215. 'ZXY',
  1216. 'YXZ',
  1217. 'ZYX',
  1218. 'SphericXYZ',
  1219. ];
  1220. var value = parseInt( modelNode.RotationOrder.value, 10 );
  1221. if ( value > 0 && value < 6 ) {
  1222. // model.rotation.order = enums[ value ];
  1223. // Note: Euler order other than XYZ is currently not supported, so just display a warning for now
  1224. console.warn( 'THREE.FBXLoader: unsupported Euler Order: %s. Currently only XYZ order is supported. Animations and rotations may be incorrect.', enums[ value ] );
  1225. } else if ( value === 6 ) {
  1226. console.warn( 'THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.' );
  1227. }
  1228. }
  1229. if ( 'Lcl_Translation' in modelNode ) {
  1230. model.position.fromArray( modelNode.Lcl_Translation.value );
  1231. }
  1232. if ( 'Lcl_Rotation' in modelNode ) {
  1233. var rotation = modelNode.Lcl_Rotation.value.map( THREE.Math.degToRad );
  1234. rotation.push( 'ZYX' );
  1235. model.quaternion.setFromEuler( new THREE.Euler().fromArray( rotation ) );
  1236. }
  1237. if ( 'Lcl_Scaling' in modelNode ) {
  1238. model.scale.fromArray( modelNode.Lcl_Scaling.value );
  1239. }
  1240. if ( 'PreRotation' in modelNode ) {
  1241. var array = modelNode.PreRotation.value.map( THREE.Math.degToRad );
  1242. array[ 3 ] = 'ZYX';
  1243. var preRotations = new THREE.Euler().fromArray( array );
  1244. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1245. model.quaternion.premultiply( preRotations );
  1246. }
  1247. }
  1248. function bindSkeleton( FBXTree, skeletons, geometryMap, modelMap, connections ) {
  1249. var bindMatrices = parsePoseNodes( FBXTree );
  1250. for ( var ID in skeletons ) {
  1251. var skeleton = skeletons[ ID ];
  1252. var parents = connections.get( parseInt( skeleton.ID ) ).parents;
  1253. parents.forEach( function ( parent ) {
  1254. if ( geometryMap.has( parent.ID ) ) {
  1255. var geoID = parent.ID;
  1256. var geoRelationships = connections.get( geoID );
  1257. geoRelationships.parents.forEach( function ( geoConnParent ) {
  1258. if ( modelMap.has( geoConnParent.ID ) ) {
  1259. var model = modelMap.get( geoConnParent.ID );
  1260. model.bind( new THREE.Skeleton( skeleton.bones ), bindMatrices[ geoConnParent.ID ] );
  1261. }
  1262. } );
  1263. }
  1264. } );
  1265. }
  1266. }
  1267. function parsePoseNodes( FBXTree ) {
  1268. var bindMatrices = {};
  1269. if ( 'Pose' in FBXTree.Objects ) {
  1270. var BindPoseNode = FBXTree.Objects.Pose;
  1271. for ( var nodeID in BindPoseNode ) {
  1272. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  1273. var poseNodes = BindPoseNode[ nodeID ].PoseNode;
  1274. if ( Array.isArray( poseNodes ) ) {
  1275. poseNodes.forEach( function ( poseNode ) {
  1276. bindMatrices[ poseNode.Node ] = new THREE.Matrix4().fromArray( poseNode.Matrix.a );
  1277. } );
  1278. } else {
  1279. bindMatrices[ poseNodes.Node ] = new THREE.Matrix4().fromArray( poseNodes.Matrix.a );
  1280. }
  1281. }
  1282. }
  1283. }
  1284. return bindMatrices;
  1285. }
  1286. function parseAnimations( FBXTree, connections ) {
  1287. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  1288. // if this is undefined we can safely assume there are no animations
  1289. if ( FBXTree.Objects.AnimationCurve === undefined ) return undefined;
  1290. var curveNodesMap = parseAnimationCurveNodes( FBXTree );
  1291. parseAnimationCurves( FBXTree, connections, curveNodesMap );
  1292. var layersMap = parseAnimationLayers( FBXTree, connections, curveNodesMap );
  1293. var rawClips = parseAnimStacks( FBXTree, connections, layersMap );
  1294. return rawClips;
  1295. }
  1296. // parse nodes in FBXTree.Objects.AnimationCurveNode
  1297. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  1298. // and is referenced by an AnimationLayer
  1299. function parseAnimationCurveNodes( FBXTree ) {
  1300. var rawCurveNodes = FBXTree.Objects.AnimationCurveNode;
  1301. var curveNodesMap = new Map();
  1302. for ( var nodeID in rawCurveNodes ) {
  1303. var rawCurveNode = rawCurveNodes[ nodeID ];
  1304. if ( rawCurveNode.attrName.match( /S|R|T/ ) !== null ) {
  1305. var curveNode = {
  1306. id: rawCurveNode.id,
  1307. attr: rawCurveNode.attrName,
  1308. curves: {},
  1309. };
  1310. curveNodesMap.set( curveNode.id, curveNode );
  1311. }
  1312. }
  1313. return curveNodesMap;
  1314. }
  1315. // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  1316. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  1317. // axis ( e.g. times and values of x rotation)
  1318. function parseAnimationCurves( FBXTree, connections, curveNodesMap ) {
  1319. var rawCurves = FBXTree.Objects.AnimationCurve;
  1320. for ( var nodeID in rawCurves ) {
  1321. var animationCurve = {
  1322. id: rawCurves[ nodeID ].id,
  1323. times: rawCurves[ nodeID ].KeyTime.a.map( convertFBXTimeToSeconds ),
  1324. values: rawCurves[ nodeID ].KeyValueFloat.a,
  1325. };
  1326. var offset = animationCurve.times[ 0 ];
  1327. for ( var i = 0; i < animationCurve.times.length; i ++ ) {
  1328. animationCurve.times[ i ] -= offset;
  1329. }
  1330. var relationships = connections.get( animationCurve.id );
  1331. if ( relationships !== undefined ) {
  1332. var animationCurveID = relationships.parents[ 0 ].ID;
  1333. var animationCurveRelationship = relationships.parents[ 0 ].relationship;
  1334. var axis = '';
  1335. if ( animationCurveRelationship.match( /X/ ) ) {
  1336. axis = 'x';
  1337. } else if ( animationCurveRelationship.match( /Y/ ) ) {
  1338. axis = 'y';
  1339. } else if ( animationCurveRelationship.match( /Z/ ) ) {
  1340. axis = 'z';
  1341. } else {
  1342. continue;
  1343. }
  1344. curveNodesMap.get( animationCurveID ).curves[ axis ] = animationCurve;
  1345. }
  1346. }
  1347. }
  1348. // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  1349. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  1350. // note: theoretically a stack can multiple layers, however in practice there always seems to be one per stack
  1351. function parseAnimationLayers( FBXTree, connections, curveNodesMap ) {
  1352. var rawLayers = FBXTree.Objects.AnimationLayer;
  1353. var layersMap = new Map();
  1354. for ( var nodeID in rawLayers ) {
  1355. var layerCurveNodes = [];
  1356. var connection = connections.get( parseInt( nodeID ) );
  1357. if ( connection !== undefined ) {
  1358. // all the animationCurveNodes used in the layer
  1359. var children = connection.children;
  1360. children.forEach( function ( child, i ) {
  1361. if ( curveNodesMap.has( child.ID ) ) {
  1362. var curveNode = curveNodesMap.get( child.ID );
  1363. // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  1364. if ( curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined ) {
  1365. if ( layerCurveNodes[ i ] === undefined ) {
  1366. var modelID;
  1367. connections.get( child.ID ).parents.forEach( function ( parent ) {
  1368. if ( parent.relationship !== undefined ) modelID = parent.ID;
  1369. } );
  1370. var rawModel = FBXTree.Objects.Model[ modelID.toString() ];
  1371. var node = {
  1372. modelName: THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ),
  1373. initialPosition: [ 0, 0, 0 ],
  1374. initialRotation: [ 0, 0, 0 ],
  1375. initialScale: [ 1, 1, 1 ],
  1376. };
  1377. if ( 'Lcl_Translation' in rawModel ) node.initialPosition = rawModel.Lcl_Translation.value;
  1378. if ( 'Lcl_Rotation' in rawModel ) node.initialRotation = rawModel.Lcl_Rotation.value;
  1379. if ( 'Lcl_Scaling' in rawModel ) node.initialScale = rawModel.Lcl_Scaling.value;
  1380. // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  1381. // animation value as well
  1382. if ( 'PreRotation' in rawModel ) node.preRotations = rawModel.PreRotation.value;
  1383. layerCurveNodes[ i ] = node;
  1384. }
  1385. layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
  1386. }
  1387. }
  1388. } );
  1389. layersMap.set( parseInt( nodeID ), layerCurveNodes );
  1390. }
  1391. }
  1392. return layersMap;
  1393. }
  1394. // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  1395. // hierarchy. Each Stack node will be used to create a THREE.AnimationClip
  1396. function parseAnimStacks( FBXTree, connections, layersMap ) {
  1397. var rawStacks = FBXTree.Objects.AnimationStack;
  1398. // connect the stacks (clips) up to the layers
  1399. var rawClips = {};
  1400. for ( var nodeID in rawStacks ) {
  1401. var children = connections.get( parseInt( nodeID ) ).children;
  1402. if ( children.length > 1 ) {
  1403. // it seems like stacks will always be associated with a single layer. But just in case there are files
  1404. // where there are multiple layers per stack, we'll display a warning
  1405. console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' );
  1406. }
  1407. var layer = layersMap.get( children[ 0 ].ID );
  1408. rawClips[ nodeID ] = {
  1409. name: rawStacks[ nodeID ].attrName,
  1410. layer: layer,
  1411. };
  1412. }
  1413. return rawClips;
  1414. }
  1415. // take raw animation data from parseAnimations and connect it up to the loaded models
  1416. function addAnimations( FBXTree, connections, sceneGraph ) {
  1417. sceneGraph.animations = [];
  1418. var rawClips = parseAnimations( FBXTree, connections );
  1419. if ( rawClips === undefined ) return;
  1420. for ( var key in rawClips ) {
  1421. var rawClip = rawClips[ key ];
  1422. var clip = addClip( rawClip );
  1423. sceneGraph.animations.push( clip );
  1424. }
  1425. }
  1426. function addClip( rawClip ) {
  1427. var tracks = [];
  1428. rawClip.layer.forEach( function ( rawTracks ) {
  1429. tracks = tracks.concat( generateTracks( rawTracks ) );
  1430. } );
  1431. return new THREE.AnimationClip( rawClip.name, - 1, tracks );
  1432. }
  1433. function generateTracks( rawTracks ) {
  1434. var tracks = [];
  1435. if ( rawTracks.T !== undefined && Object.keys( rawTracks.T.curves ).length > 0 ) {
  1436. var positionTrack = generateVectorTrack( rawTracks.modelName, rawTracks.T.curves, rawTracks.initialPosition, 'position' );
  1437. if ( positionTrack !== undefined ) tracks.push( positionTrack );
  1438. }
  1439. if ( rawTracks.R !== undefined && Object.keys( rawTracks.R.curves ).length > 0 ) {
  1440. var rotationTrack = generateRotationTrack( rawTracks.modelName, rawTracks.R.curves, rawTracks.initialRotation, rawTracks.preRotations );
  1441. if ( rotationTrack !== undefined ) tracks.push( rotationTrack );
  1442. }
  1443. if ( rawTracks.S !== undefined && Object.keys( rawTracks.S.curves ).length > 0 ) {
  1444. var scaleTrack = generateVectorTrack( rawTracks.modelName, rawTracks.S.curves, rawTracks.initialScale, 'scale' );
  1445. if ( scaleTrack !== undefined ) tracks.push( scaleTrack );
  1446. }
  1447. return tracks;
  1448. }
  1449. function generateVectorTrack( modelName, curves, initialValue, type ) {
  1450. var times = getTimesForAllAxes( curves );
  1451. var values = getKeyframeTrackValues( times, curves, initialValue );
  1452. return new THREE.VectorKeyframeTrack( modelName + '.' + type, times, values );
  1453. }
  1454. function generateRotationTrack( modelName, curves, initialValue, preRotations ) {
  1455. if ( curves.x !== undefined ) curves.x.values = curves.x.values.map( THREE.Math.degToRad );
  1456. if ( curves.y !== undefined ) curves.y.values = curves.y.values.map( THREE.Math.degToRad );
  1457. if ( curves.z !== undefined ) curves.z.values = curves.z.values.map( THREE.Math.degToRad );
  1458. var times = getTimesForAllAxes( curves );
  1459. var values = getKeyframeTrackValues( times, curves, initialValue );
  1460. if ( preRotations !== undefined ) {
  1461. preRotations = preRotations.map( THREE.Math.degToRad );
  1462. preRotations.push( 'ZYX' );
  1463. preRotations = new THREE.Euler().fromArray( preRotations );
  1464. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1465. }
  1466. var quaternion = new THREE.Quaternion();
  1467. var euler = new THREE.Euler();
  1468. var quaternionValues = [];
  1469. for ( var i = 0; i < values.length; i += 3 ) {
  1470. euler.set( values[ i ], values[ i + 1 ], values[ i + 2 ], 'ZYX' );
  1471. quaternion.setFromEuler( euler );
  1472. if ( preRotations !== undefined )quaternion.premultiply( preRotations );
  1473. quaternion.toArray( quaternionValues, ( i / 3 ) * 4 );
  1474. }
  1475. return new THREE.QuaternionKeyframeTrack( modelName + '.quaternion', times, quaternionValues );
  1476. }
  1477. function getKeyframeTrackValues( times, curves, initialValue ) {
  1478. var prevValue = initialValue;
  1479. var values = [];
  1480. var xIndex = - 1;
  1481. var yIndex = - 1;
  1482. var zIndex = - 1;
  1483. times.forEach( function ( time ) {
  1484. if ( curves.x ) xIndex = curves.x.times.indexOf( time );
  1485. if ( curves.y ) yIndex = curves.y.times.indexOf( time );
  1486. if ( curves.z ) zIndex = curves.z.times.indexOf( time );
  1487. // if there is an x value defined for this frame, use that
  1488. if ( xIndex !== - 1 ) {
  1489. var xValue = curves.x.values[ xIndex ];
  1490. values.push( xValue );
  1491. prevValue[ 0 ] = xValue;
  1492. } else {
  1493. // otherwise use the x value from the previous frame
  1494. values.push( prevValue[ 0 ] );
  1495. }
  1496. if ( yIndex !== - 1 ) {
  1497. var yValue = curves.y.values[ yIndex ];
  1498. values.push( yValue );
  1499. prevValue[ 1 ] = yValue;
  1500. } else {
  1501. values.push( prevValue[ 1 ] );
  1502. }
  1503. if ( zIndex !== - 1 ) {
  1504. var zValue = curves.z.values[ zIndex ];
  1505. values.push( zValue );
  1506. prevValue[ 2 ] = zValue;
  1507. } else {
  1508. values.push( prevValue[ 2 ] );
  1509. }
  1510. } );
  1511. return values;
  1512. }
  1513. // For all animated objects, times are defined separately for each axis
  1514. // Here we'll combine the times into one sorted array without duplicates
  1515. function getTimesForAllAxes( curves ) {
  1516. var times = [];
  1517. // first join together the times for each axis, if defined
  1518. if ( curves.x !== undefined ) times = times.concat( curves.x.times );
  1519. if ( curves.y !== undefined ) times = times.concat( curves.y.times );
  1520. if ( curves.z !== undefined ) times = times.concat( curves.z.times );
  1521. // then sort them and remove duplicates
  1522. times = times.sort( function ( a, b ) {
  1523. return a - b;
  1524. } ).filter( function ( elem, index, array ) {
  1525. return array.indexOf( elem ) == index;
  1526. } );
  1527. return times;
  1528. }
  1529. // parse an FBX file in ASCII format
  1530. function TextParser() {}
  1531. Object.assign( TextParser.prototype, {
  1532. getPrevNode: function () {
  1533. return this.nodeStack[ this.currentIndent - 2 ];
  1534. },
  1535. getCurrentNode: function () {
  1536. return this.nodeStack[ this.currentIndent - 1 ];
  1537. },
  1538. getCurrentProp: function () {
  1539. return this.currentProp;
  1540. },
  1541. pushStack: function ( node ) {
  1542. this.nodeStack.push( node );
  1543. this.currentIndent += 1;
  1544. },
  1545. popStack: function () {
  1546. this.nodeStack.pop();
  1547. this.currentIndent -= 1;
  1548. },
  1549. setCurrentProp: function ( val, name ) {
  1550. this.currentProp = val;
  1551. this.currentPropName = name;
  1552. },
  1553. parse: function ( text ) {
  1554. this.currentIndent = 0;
  1555. this.allNodes = new FBXTree();
  1556. this.nodeStack = [];
  1557. this.currentProp = [];
  1558. this.currentPropName = '';
  1559. var self = this;
  1560. var split = text.split( '\n' );
  1561. split.forEach( function ( line, i ) {
  1562. var matchComment = line.match( /^[\s\t]*;/ );
  1563. var matchEmpty = line.match( /^[\s\t]*$/ );
  1564. if ( matchComment || matchEmpty ) return;
  1565. var matchBeginning = line.match( '^\\t{' + self.currentIndent + '}(\\w+):(.*){', '' );
  1566. var matchProperty = line.match( '^\\t{' + ( self.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  1567. var matchEnd = line.match( '^\\t{' + ( self.currentIndent - 1 ) + '}}' );
  1568. if ( matchBeginning ) {
  1569. self.parseNodeBegin( line, matchBeginning );
  1570. } else if ( matchProperty ) {
  1571. self.parseNodeProperty( line, matchProperty, split[ ++ i ] );
  1572. } else if ( matchEnd ) {
  1573. self.popStack();
  1574. } else if ( line.match( /^[^\s\t}]/ ) ) {
  1575. // large arrays are split over multiple lines terminated with a ',' character
  1576. // if this is encountered the line needs to be joined to the previous line
  1577. self.parseNodePropertyContinued( line );
  1578. }
  1579. } );
  1580. return this.allNodes;
  1581. },
  1582. parseNodeBegin: function ( line, property ) {
  1583. var nodeName = property[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  1584. var nodeAttrs = property[ 2 ].split( ',' ).map( function ( attr ) {
  1585. return attr.trim().replace( /^"/, '' ).replace( /"$/, '' );
  1586. } );
  1587. var node = { name: nodeName };
  1588. var attrs = this.parseNodeAttr( nodeAttrs );
  1589. var currentNode = this.getCurrentNode();
  1590. // a top node
  1591. if ( this.currentIndent === 0 ) {
  1592. this.allNodes.add( nodeName, node );
  1593. } else { // a subnode
  1594. // if the subnode already exists, append it
  1595. if ( nodeName in currentNode ) {
  1596. // special case Pose needs PoseNodes as an array
  1597. if ( nodeName === 'PoseNode' ) {
  1598. currentNode.PoseNode.push( node );
  1599. } else if ( currentNode[ nodeName ].id !== undefined ) {
  1600. currentNode[ nodeName ] = {};
  1601. currentNode[ nodeName ][ currentNode[ nodeName ].id ] = currentNode[ nodeName ];
  1602. }
  1603. if ( attrs.id !== '' ) currentNode[ nodeName ][ attrs.id ] = node;
  1604. } else if ( typeof attrs.id === 'number' ) {
  1605. currentNode[ nodeName ] = {};
  1606. currentNode[ nodeName ][ attrs.id ] = node;
  1607. } else if ( nodeName !== 'Properties70' ) {
  1608. if ( nodeName === 'PoseNode' ) currentNode[ nodeName ] = [ node ];
  1609. else currentNode[ nodeName ] = node;
  1610. }
  1611. }
  1612. if ( typeof attrs.id === 'number' ) node.id = attrs.id;
  1613. if ( attrs.name !== '' ) node.attrName = attrs.name;
  1614. if ( attrs.type !== '' ) node.attrType = attrs.type;
  1615. this.pushStack( node );
  1616. },
  1617. parseNodeAttr: function ( attrs ) {
  1618. var id = attrs[ 0 ];
  1619. if ( attrs[ 0 ] !== '' ) {
  1620. id = parseInt( attrs[ 0 ] );
  1621. if ( isNaN( id ) ) {
  1622. id = attrs[ 0 ];
  1623. }
  1624. }
  1625. var name = '', type = '';
  1626. if ( attrs.length > 1 ) {
  1627. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  1628. type = attrs[ 2 ];
  1629. }
  1630. return { id: id, name: name, type: type };
  1631. },
  1632. parseNodeProperty: function ( line, property, contentLine ) {
  1633. var propName = property[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1634. var propValue = property[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1635. // for special case: base64 image data follows "Content: ," line
  1636. // Content: ,
  1637. // "/9j/4RDaRXhpZgAATU0A..."
  1638. if ( propName === 'Content' && propValue === ',' ) {
  1639. propValue = contentLine.replace( /"/g, '' ).replace( /,$/, '' ).trim();
  1640. }
  1641. var currentNode = this.getCurrentNode();
  1642. var parentName = currentNode.name;
  1643. if ( parentName === 'Properties70' ) {
  1644. this.parseNodeSpecialProperty( line, propName, propValue );
  1645. return;
  1646. }
  1647. // Connections
  1648. if ( propName === 'C' ) {
  1649. var connProps = propValue.split( ',' ).slice( 1 );
  1650. var from = parseInt( connProps[ 0 ] );
  1651. var to = parseInt( connProps[ 1 ] );
  1652. var rest = propValue.split( ',' ).slice( 3 );
  1653. rest = rest.map( function ( elem ) {
  1654. return elem.trim().replace( /^"/, '' );
  1655. } );
  1656. propName = 'connections';
  1657. propValue = [ from, to ];
  1658. append( propValue, rest );
  1659. if ( currentNode[ propName ] === undefined ) {
  1660. currentNode[ propName ] = [];
  1661. }
  1662. }
  1663. // Node
  1664. if ( propName === 'Node' ) currentNode.id = propValue;
  1665. // connections
  1666. if ( propName in currentNode && Array.isArray( currentNode[ propName ] ) ) {
  1667. currentNode[ propName ].push( propValue );
  1668. } else {
  1669. if ( propName !== 'a' ) currentNode[ propName ] = propValue;
  1670. else currentNode.a = propValue;
  1671. }
  1672. this.setCurrentProp( currentNode, propName );
  1673. // convert string to array, unless it ends in ',' in which case more will be added to it
  1674. if ( propName === 'a' && propValue.slice( - 1 ) !== ',' ) {
  1675. currentNode.a = parseNumberArray( propValue );
  1676. }
  1677. },
  1678. parseNodePropertyContinued: function ( line ) {
  1679. var currentNode = this.getCurrentNode();
  1680. currentNode.a += line;
  1681. // if the line doesn't end in ',' we have reached the end of the property value
  1682. // so convert the string to an array
  1683. if ( line.slice( - 1 ) !== ',' ) {
  1684. currentNode.a = parseNumberArray( currentNode.a );
  1685. }
  1686. },
  1687. // parse "Property70"
  1688. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  1689. // split this
  1690. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  1691. // into array like below
  1692. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  1693. var props = propValue.split( '",' ).map( function ( prop ) {
  1694. return prop.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  1695. } );
  1696. var innerPropName = props[ 0 ];
  1697. var innerPropType1 = props[ 1 ];
  1698. var innerPropType2 = props[ 2 ];
  1699. var innerPropFlag = props[ 3 ];
  1700. var innerPropValue = props[ 4 ];
  1701. // cast values where needed, otherwise leave as strings
  1702. switch ( innerPropType1 ) {
  1703. case 'int':
  1704. case 'enum':
  1705. case 'bool':
  1706. case 'ULongLong':
  1707. case 'double':
  1708. case 'Number':
  1709. case 'FieldOfView':
  1710. innerPropValue = parseFloat( innerPropValue );
  1711. break;
  1712. case 'Color':
  1713. case 'ColorRGB':
  1714. case 'Vector3D':
  1715. case 'Lcl_Translation':
  1716. case 'Lcl_Rotation':
  1717. case 'Lcl_Scaling':
  1718. innerPropValue = parseNumberArray( innerPropValue );
  1719. break;
  1720. }
  1721. // CAUTION: these props must append to parent's parent
  1722. this.getPrevNode()[ innerPropName ] = {
  1723. 'type': innerPropType1,
  1724. 'type2': innerPropType2,
  1725. 'flag': innerPropFlag,
  1726. 'value': innerPropValue
  1727. };
  1728. this.setCurrentProp( this.getPrevNode(), innerPropName );
  1729. },
  1730. } );
  1731. // Parse an FBX file in Binary format
  1732. function BinaryParser() {}
  1733. Object.assign( BinaryParser.prototype, {
  1734. parse: function ( buffer ) {
  1735. var reader = new BinaryReader( buffer );
  1736. reader.skip( 23 ); // skip magic 23 bytes
  1737. var version = reader.getUint32();
  1738. console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
  1739. var allNodes = new FBXTree();
  1740. while ( ! this.endOfContent( reader ) ) {
  1741. var node = this.parseNode( reader, version );
  1742. if ( node !== null ) allNodes.add( node.name, node );
  1743. }
  1744. return allNodes;
  1745. },
  1746. // Check if reader has reached the end of content.
  1747. endOfContent: function ( reader ) {
  1748. // footer size: 160bytes + 16-byte alignment padding
  1749. // - 16bytes: magic
  1750. // - padding til 16-byte alignment (at least 1byte?)
  1751. // (seems like some exporters embed fixed 15 or 16bytes?)
  1752. // - 4bytes: magic
  1753. // - 4bytes: version
  1754. // - 120bytes: zero
  1755. // - 16bytes: magic
  1756. if ( reader.size() % 16 === 0 ) {
  1757. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  1758. } else {
  1759. return reader.getOffset() + 160 + 16 >= reader.size();
  1760. }
  1761. },
  1762. // recursively parse nodes until the end of the file is reached
  1763. parseNode: function ( reader, version ) {
  1764. var node = {};
  1765. // The first three data sizes depends on version.
  1766. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1767. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1768. // note: do not remove this even if you get a linter warning as it moves the buffer forward
  1769. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1770. var nameLen = reader.getUint8();
  1771. var name = reader.getString( nameLen );
  1772. // Regards this node as NULL-record if endOffset is zero
  1773. if ( endOffset === 0 ) return null;
  1774. var propertyList = [];
  1775. for ( var i = 0; i < numProperties; i ++ ) {
  1776. propertyList.push( this.parseProperty( reader ) );
  1777. }
  1778. // Regards the first three elements in propertyList as id, attrName, and attrType
  1779. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  1780. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  1781. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  1782. // check if this node represents just a single property
  1783. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  1784. node.singleProperty = ( numProperties === 1 && reader.getOffset() === endOffset ) ? true : false;
  1785. while ( endOffset > reader.getOffset() ) {
  1786. var subNode = this.parseNode( reader, version );
  1787. if ( subNode !== null ) this.parseSubNode( name, node, subNode );
  1788. }
  1789. node.propertyList = propertyList; // raw property list used by parent
  1790. if ( typeof id === 'number' ) node.id = id;
  1791. if ( attrName !== '' ) node.attrName = attrName;
  1792. if ( attrType !== '' ) node.attrType = attrType;
  1793. if ( name !== '' ) node.name = name;
  1794. return node;
  1795. },
  1796. parseSubNode: function ( name, node, subNode ) {
  1797. // special case: child node is single property
  1798. if ( subNode.singleProperty === true ) {
  1799. var value = subNode.propertyList[ 0 ];
  1800. if ( Array.isArray( value ) ) {
  1801. node[ subNode.name ] = subNode;
  1802. subNode.a = value;
  1803. } else {
  1804. node[ subNode.name ] = value;
  1805. }
  1806. } else if ( name === 'Connections' && subNode.name === 'C' ) {
  1807. var array = [];
  1808. subNode.propertyList.forEach( function ( property, i ) {
  1809. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  1810. if ( i !== 0 ) array.push( property );
  1811. } );
  1812. if ( node.connections === undefined ) {
  1813. node.connections = [];
  1814. }
  1815. node.connections.push( array );
  1816. } else if ( subNode.name === 'Properties70' ) {
  1817. var keys = Object.keys( subNode );
  1818. keys.forEach( function ( key ) {
  1819. node[ key ] = subNode[ key ];
  1820. } );
  1821. } else if ( name === 'Properties70' && subNode.name === 'P' ) {
  1822. var innerPropName = subNode.propertyList[ 0 ];
  1823. var innerPropType1 = subNode.propertyList[ 1 ];
  1824. var innerPropType2 = subNode.propertyList[ 2 ];
  1825. var innerPropFlag = subNode.propertyList[ 3 ];
  1826. var innerPropValue;
  1827. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  1828. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  1829. if ( innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  1830. innerPropValue = [
  1831. subNode.propertyList[ 4 ],
  1832. subNode.propertyList[ 5 ],
  1833. subNode.propertyList[ 6 ]
  1834. ];
  1835. } else {
  1836. innerPropValue = subNode.propertyList[ 4 ];
  1837. }
  1838. // this will be copied to parent, see above
  1839. node[ innerPropName ] = {
  1840. 'type': innerPropType1,
  1841. 'type2': innerPropType2,
  1842. 'flag': innerPropFlag,
  1843. 'value': innerPropValue
  1844. };
  1845. } else if ( node[ subNode.name ] === undefined ) {
  1846. if ( typeof subNode.id === 'number' ) {
  1847. node[ subNode.name ] = {};
  1848. node[ subNode.name ][ subNode.id ] = subNode;
  1849. } else {
  1850. node[ subNode.name ] = subNode;
  1851. }
  1852. } else {
  1853. if ( subNode.name === 'PoseNode' ) {
  1854. if ( ! Array.isArray( node[ subNode.name ] ) ) {
  1855. node[ subNode.name ] = [ node[ subNode.name ] ];
  1856. }
  1857. node[ subNode.name ].push( subNode );
  1858. } else if ( node[ subNode.name ][ subNode.id ] === undefined ) {
  1859. node[ subNode.name ][ subNode.id ] = subNode;
  1860. }
  1861. }
  1862. },
  1863. parseProperty: function ( reader ) {
  1864. var type = reader.getString( 1 );
  1865. switch ( type ) {
  1866. case 'C':
  1867. return reader.getBoolean();
  1868. case 'D':
  1869. return reader.getFloat64();
  1870. case 'F':
  1871. return reader.getFloat32();
  1872. case 'I':
  1873. return reader.getInt32();
  1874. case 'L':
  1875. return reader.getInt64();
  1876. case 'R':
  1877. var length = reader.getUint32();
  1878. return reader.getArrayBuffer( length );
  1879. case 'S':
  1880. var length = reader.getUint32();
  1881. return reader.getString( length );
  1882. case 'Y':
  1883. return reader.getInt16();
  1884. case 'b':
  1885. case 'c':
  1886. case 'd':
  1887. case 'f':
  1888. case 'i':
  1889. case 'l':
  1890. var arrayLength = reader.getUint32();
  1891. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  1892. var compressedLength = reader.getUint32();
  1893. if ( encoding === 0 ) {
  1894. switch ( type ) {
  1895. case 'b':
  1896. case 'c':
  1897. return reader.getBooleanArray( arrayLength );
  1898. case 'd':
  1899. return reader.getFloat64Array( arrayLength );
  1900. case 'f':
  1901. return reader.getFloat32Array( arrayLength );
  1902. case 'i':
  1903. return reader.getInt32Array( arrayLength );
  1904. case 'l':
  1905. return reader.getInt64Array( arrayLength );
  1906. }
  1907. }
  1908. if ( window.Zlib === undefined ) {
  1909. console.error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  1910. }
  1911. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  1912. var reader2 = new BinaryReader( inflate.decompress().buffer );
  1913. switch ( type ) {
  1914. case 'b':
  1915. case 'c':
  1916. return reader2.getBooleanArray( arrayLength );
  1917. case 'd':
  1918. return reader2.getFloat64Array( arrayLength );
  1919. case 'f':
  1920. return reader2.getFloat32Array( arrayLength );
  1921. case 'i':
  1922. return reader2.getInt32Array( arrayLength );
  1923. case 'l':
  1924. return reader2.getInt64Array( arrayLength );
  1925. }
  1926. default:
  1927. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  1928. }
  1929. }
  1930. } );
  1931. function BinaryReader( buffer, littleEndian ) {
  1932. this.dv = new DataView( buffer );
  1933. this.offset = 0;
  1934. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  1935. }
  1936. Object.assign( BinaryReader.prototype, {
  1937. getOffset: function () {
  1938. return this.offset;
  1939. },
  1940. size: function () {
  1941. return this.dv.buffer.byteLength;
  1942. },
  1943. skip: function ( length ) {
  1944. this.offset += length;
  1945. },
  1946. // seems like true/false representation depends on exporter.
  1947. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  1948. // then sees LSB.
  1949. getBoolean: function () {
  1950. return ( this.getUint8() & 1 ) === 1;
  1951. },
  1952. getBooleanArray: function ( size ) {
  1953. var a = [];
  1954. for ( var i = 0; i < size; i ++ ) {
  1955. a.push( this.getBoolean() );
  1956. }
  1957. return a;
  1958. },
  1959. getUint8: function () {
  1960. var value = this.dv.getUint8( this.offset );
  1961. this.offset += 1;
  1962. return value;
  1963. },
  1964. getInt16: function () {
  1965. var value = this.dv.getInt16( this.offset, this.littleEndian );
  1966. this.offset += 2;
  1967. return value;
  1968. },
  1969. getInt32: function () {
  1970. var value = this.dv.getInt32( this.offset, this.littleEndian );
  1971. this.offset += 4;
  1972. return value;
  1973. },
  1974. getInt32Array: function ( size ) {
  1975. var a = [];
  1976. for ( var i = 0; i < size; i ++ ) {
  1977. a.push( this.getInt32() );
  1978. }
  1979. return a;
  1980. },
  1981. getUint32: function () {
  1982. var value = this.dv.getUint32( this.offset, this.littleEndian );
  1983. this.offset += 4;
  1984. return value;
  1985. },
  1986. // JavaScript doesn't support 64-bit integer so calculate this here
  1987. // 1 << 32 will return 1 so using multiply operation instead here.
  1988. // There's a possibility that this method returns wrong value if the value
  1989. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  1990. // TODO: safely handle 64-bit integer
  1991. getInt64: function () {
  1992. var low, high;
  1993. if ( this.littleEndian ) {
  1994. low = this.getUint32();
  1995. high = this.getUint32();
  1996. } else {
  1997. high = this.getUint32();
  1998. low = this.getUint32();
  1999. }
  2000. // calculate negative value
  2001. if ( high & 0x80000000 ) {
  2002. high = ~ high & 0xFFFFFFFF;
  2003. low = ~ low & 0xFFFFFFFF;
  2004. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  2005. low = ( low + 1 ) & 0xFFFFFFFF;
  2006. return - ( high * 0x100000000 + low );
  2007. }
  2008. return high * 0x100000000 + low;
  2009. },
  2010. getInt64Array: function ( size ) {
  2011. var a = [];
  2012. for ( var i = 0; i < size; i ++ ) {
  2013. a.push( this.getInt64() );
  2014. }
  2015. return a;
  2016. },
  2017. // Note: see getInt64() comment
  2018. getUint64: function () {
  2019. var low, high;
  2020. if ( this.littleEndian ) {
  2021. low = this.getUint32();
  2022. high = this.getUint32();
  2023. } else {
  2024. high = this.getUint32();
  2025. low = this.getUint32();
  2026. }
  2027. return high * 0x100000000 + low;
  2028. },
  2029. getFloat32: function () {
  2030. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  2031. this.offset += 4;
  2032. return value;
  2033. },
  2034. getFloat32Array: function ( size ) {
  2035. var a = [];
  2036. for ( var i = 0; i < size; i ++ ) {
  2037. a.push( this.getFloat32() );
  2038. }
  2039. return a;
  2040. },
  2041. getFloat64: function () {
  2042. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  2043. this.offset += 8;
  2044. return value;
  2045. },
  2046. getFloat64Array: function ( size ) {
  2047. var a = [];
  2048. for ( var i = 0; i < size; i ++ ) {
  2049. a.push( this.getFloat64() );
  2050. }
  2051. return a;
  2052. },
  2053. getArrayBuffer: function ( size ) {
  2054. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  2055. this.offset += size;
  2056. return value;
  2057. },
  2058. getString: function ( size ) {
  2059. var a = new Uint8Array( size );
  2060. for ( var i = 0; i < size; i ++ ) {
  2061. a[ i ] = this.getUint8();
  2062. }
  2063. var nullByte = a.indexOf( 0 );
  2064. if ( nullByte >= 0 ) a = a.slice( 0, nullByte );
  2065. return THREE.LoaderUtils.decodeText( a );
  2066. }
  2067. } );
  2068. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2069. // and BinaryParser( FBX Binary format)
  2070. function FBXTree() {}
  2071. Object.assign( FBXTree.prototype, {
  2072. add: function ( key, val ) {
  2073. this[ key ] = val;
  2074. },
  2075. } );
  2076. function isFbxFormatBinary( buffer ) {
  2077. var CORRECT = 'Kaydara FBX Binary \0';
  2078. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  2079. }
  2080. function isFbxFormatASCII( text ) {
  2081. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  2082. var cursor = 0;
  2083. function read( offset ) {
  2084. var result = text[ offset - 1 ];
  2085. text = text.slice( cursor + offset );
  2086. cursor ++;
  2087. return result;
  2088. }
  2089. for ( var i = 0; i < CORRECT.length; ++ i ) {
  2090. var num = read( 1 );
  2091. if ( num === CORRECT[ i ] ) {
  2092. return false;
  2093. }
  2094. }
  2095. return true;
  2096. }
  2097. function getFbxVersion( text ) {
  2098. var versionRegExp = /FBXVersion: (\d+)/;
  2099. var match = text.match( versionRegExp );
  2100. if ( match ) {
  2101. var version = parseInt( match[ 1 ] );
  2102. return version;
  2103. }
  2104. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  2105. }
  2106. // Converts FBX ticks into real time seconds.
  2107. function convertFBXTimeToSeconds( time ) {
  2108. return time / 46186158000;
  2109. }
  2110. // Parses comma separated list of numbers and returns them an array.
  2111. // Used internally by the TextParser
  2112. function parseNumberArray( value ) {
  2113. var array = value.split( ',' ).map( function ( val ) {
  2114. return parseFloat( val );
  2115. } );
  2116. return array;
  2117. }
  2118. function convertArrayBufferToString( buffer, from, to ) {
  2119. if ( from === undefined ) from = 0;
  2120. if ( to === undefined ) to = buffer.byteLength;
  2121. return THREE.LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) );
  2122. }
  2123. function append( a, b ) {
  2124. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  2125. a[ j ] = b[ i ];
  2126. }
  2127. }
  2128. function slice( a, b, from, to ) {
  2129. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  2130. a[ j ] = b[ i ];
  2131. }
  2132. return a;
  2133. }
  2134. } )();