FBXLoader.js 83 KB

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