2
0

FBXLoader.js 90 KB

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