FBXLoader.js 89 KB

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