FBXLoader.js 82 KB

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